title
stringlengths 3
221
| text
stringlengths 17
477k
| parsed
listlengths 0
3.17k
|
|---|---|---|
SWING - JCheckBox Class
|
The class JCheckBox is an implementation of a check box - an item that can be selected or deselected, and which displays its state to the user.
Following is the declaration for javax.swing.JCheckBox class −
public class JCheckBox
extends JToggleButton
implements Accessible
Following are the fields for javax.swing.JCheckBox class −
static String BORDER_PAINTED_FLAT_CHANGED_PROPERTY − Identifies a change to the flat property.
JCheckBox()
Creates an initially unselected check box button with no text and no icon.
JCheckBox(Action a)
Creates a checkbox where the properties are taken from the Action supplied.
JCheckBox(Icon icon)
Creates an initially unselected checkbox with an icon.
JCheckBox(Icon icon, boolean selected)
Creates a checkbox with an icon and specifies whether or not it is initially selected.
JCheckBox(String text)
Creates an initially unselected checkbox with text.
JCheckBox(String text, boolean selected)
Creates a checkbox with the text and specifies whether or not it is initially selected.
JCheckBox(String text, Icon icon)
Creates an initially unselected checkbox with the specified text and icon.
JCheckBox(String text, Icon icon, boolean selected)
Creates a checkbox with text and icon, and specifies whether or not it is initially selected.
AccessibleContext getAccessibleContext()
Gets the AccessibleContext associated with this JCheckBox.
String getUIClassID()
Returns a string that specifies the name of the L&F class which renders this component.
boolean isBorderPaintedFlat()
Gets the value of the borderPaintedFlat property.
protected String paramString()
Returns a string representation of this JCheckBox.
void setBorderPaintedFlat(boolean b)
Sets the borderPaintedFlat property, which gives a hint to the look and feel as to the appearance of the checkbox border.
void updateUI()
Resets the UI property to a value from the current look and feel.
This class inherits methods from the following classes −
javax.swing.AbstractButton
javax.swing.JToggleButton
javax.swing.JComponent
java.awt.Container
java.awt.Component
java.lang.Object
Create the following Java program using any editor of your choice in say D:/ > SWING > com > tutorialspoint > gui >
SwingControlDemo.java
package com.tutorialspoint.gui;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class SwingControlDemo {
private JFrame mainFrame;
private JLabel headerLabel;
private JLabel statusLabel;
private JPanel controlPanel;
public SwingControlDemo(){
prepareGUI();
}
public static void main(String[] args){
SwingControlDemo swingControlDemo = new SwingControlDemo();
swingControlDemo.showCheckBoxDemo();
}
private void prepareGUI(){
mainFrame = new JFrame("Java Swing Examples");
mainFrame.setSize(400,400);
mainFrame.setLayout(new GridLayout(3, 1));
mainFrame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent windowEvent){
System.exit(0);
}
});
headerLabel = new JLabel("", JLabel.CENTER);
statusLabel = new JLabel("",JLabel.CENTER);
statusLabel.setSize(350,100);
controlPanel = new JPanel();
controlPanel.setLayout(new FlowLayout());
mainFrame.add(headerLabel);
mainFrame.add(controlPanel);
mainFrame.add(statusLabel);
mainFrame.setVisible(true);
}
private void showCheckBoxDemo(){
headerLabel.setText("Control in action: CheckBox");
final JCheckBox chkApple = new JCheckBox("Apple");
final JCheckBox chkMango = new JCheckBox("Mango");
final JCheckBox chkPeer = new JCheckBox("Peer");
chkApple.setMnemonic(KeyEvent.VK_C);
chkMango.setMnemonic(KeyEvent.VK_M);
chkPeer.setMnemonic(KeyEvent.VK_P);
chkApple.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
statusLabel.setText("Apple Checkbox: "
+ (e.getStateChange()==1?"checked":"unchecked"));
}
});
chkMango.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
statusLabel.setText("Mango Checkbox: "
+ (e.getStateChange()==1?"checked":"unchecked"));
}
});
chkPeer.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
statusLabel.setText("Peer Checkbox: "
+ (e.getStateChange()==1?"checked":"unchecked"));
}
});
controlPanel.add(chkApple);
controlPanel.add(chkMango);
controlPanel.add(chkPeer);
mainFrame.setVisible(true);
}
}
Compile the program using the command prompt. Go to D:/ > SWING and type the following command.
D:\SWING>javac com\tutorialspoint\gui\SwingControlDemo.java
If no error occurs, it means the compilation is successful. Run the program using the following command.
D:\SWING>java com.tutorialspoint.gui.SwingControlDemo
Verify the following output.
30 Lectures
3.5 hours
Pranjal Srivastava
13 Lectures
1 hours
Pranjal Srivastava
25 Lectures
4.5 hours
Emenwa Global, Ejike IfeanyiChukwu
14 Lectures
1.5 hours
Travis Rose
14 Lectures
1 hours
Travis Rose
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 1907,
"s": 1763,
"text": "The class JCheckBox is an implementation of a check box - an item that can be selected or deselected, and which displays its state to the user."
},
{
"code": null,
"e": 1970,
"s": 1907,
"text": "Following is the declaration for javax.swing.JCheckBox class −"
},
{
"code": null,
"e": 2047,
"s": 1970,
"text": "public class JCheckBox\n extends JToggleButton\n implements Accessible\n"
},
{
"code": null,
"e": 2106,
"s": 2047,
"text": "Following are the fields for javax.swing.JCheckBox class −"
},
{
"code": null,
"e": 2201,
"s": 2106,
"text": "static String BORDER_PAINTED_FLAT_CHANGED_PROPERTY − Identifies a change to the flat property."
},
{
"code": null,
"e": 2213,
"s": 2201,
"text": "JCheckBox()"
},
{
"code": null,
"e": 2288,
"s": 2213,
"text": "Creates an initially unselected check box button with no text and no icon."
},
{
"code": null,
"e": 2308,
"s": 2288,
"text": "JCheckBox(Action a)"
},
{
"code": null,
"e": 2384,
"s": 2308,
"text": "Creates a checkbox where the properties are taken from the Action supplied."
},
{
"code": null,
"e": 2405,
"s": 2384,
"text": "JCheckBox(Icon icon)"
},
{
"code": null,
"e": 2460,
"s": 2405,
"text": "Creates an initially unselected checkbox with an icon."
},
{
"code": null,
"e": 2499,
"s": 2460,
"text": "JCheckBox(Icon icon, boolean selected)"
},
{
"code": null,
"e": 2586,
"s": 2499,
"text": "Creates a checkbox with an icon and specifies whether or not it is initially selected."
},
{
"code": null,
"e": 2609,
"s": 2586,
"text": "JCheckBox(String text)"
},
{
"code": null,
"e": 2661,
"s": 2609,
"text": "Creates an initially unselected checkbox with text."
},
{
"code": null,
"e": 2702,
"s": 2661,
"text": "JCheckBox(String text, boolean selected)"
},
{
"code": null,
"e": 2790,
"s": 2702,
"text": "Creates a checkbox with the text and specifies whether or not it is initially selected."
},
{
"code": null,
"e": 2824,
"s": 2790,
"text": "JCheckBox(String text, Icon icon)"
},
{
"code": null,
"e": 2899,
"s": 2824,
"text": "Creates an initially unselected checkbox with the specified text and icon."
},
{
"code": null,
"e": 2951,
"s": 2899,
"text": "JCheckBox(String text, Icon icon, boolean selected)"
},
{
"code": null,
"e": 3046,
"s": 2951,
"text": "Creates a checkbox with text and icon, and specifies whether or not it is initially selected. "
},
{
"code": null,
"e": 3087,
"s": 3046,
"text": "AccessibleContext getAccessibleContext()"
},
{
"code": null,
"e": 3146,
"s": 3087,
"text": "Gets the AccessibleContext associated with this JCheckBox."
},
{
"code": null,
"e": 3168,
"s": 3146,
"text": "String getUIClassID()"
},
{
"code": null,
"e": 3256,
"s": 3168,
"text": "Returns a string that specifies the name of the L&F class which renders this component."
},
{
"code": null,
"e": 3286,
"s": 3256,
"text": "boolean isBorderPaintedFlat()"
},
{
"code": null,
"e": 3336,
"s": 3286,
"text": "Gets the value of the borderPaintedFlat property."
},
{
"code": null,
"e": 3368,
"s": 3336,
"text": "protected String paramString()"
},
{
"code": null,
"e": 3419,
"s": 3368,
"text": "Returns a string representation of this JCheckBox."
},
{
"code": null,
"e": 3456,
"s": 3419,
"text": "void setBorderPaintedFlat(boolean b)"
},
{
"code": null,
"e": 3578,
"s": 3456,
"text": "Sets the borderPaintedFlat property, which gives a hint to the look and feel as to the appearance of the checkbox border."
},
{
"code": null,
"e": 3594,
"s": 3578,
"text": "void updateUI()"
},
{
"code": null,
"e": 3660,
"s": 3594,
"text": "Resets the UI property to a value from the current look and feel."
},
{
"code": null,
"e": 3717,
"s": 3660,
"text": "This class inherits methods from the following classes −"
},
{
"code": null,
"e": 3744,
"s": 3717,
"text": "javax.swing.AbstractButton"
},
{
"code": null,
"e": 3770,
"s": 3744,
"text": "javax.swing.JToggleButton"
},
{
"code": null,
"e": 3793,
"s": 3770,
"text": "javax.swing.JComponent"
},
{
"code": null,
"e": 3812,
"s": 3793,
"text": "java.awt.Container"
},
{
"code": null,
"e": 3831,
"s": 3812,
"text": "java.awt.Component"
},
{
"code": null,
"e": 3848,
"s": 3831,
"text": "java.lang.Object"
},
{
"code": null,
"e": 3964,
"s": 3848,
"text": "Create the following Java program using any editor of your choice in say D:/ > SWING > com > tutorialspoint > gui >"
},
{
"code": null,
"e": 3986,
"s": 3964,
"text": "SwingControlDemo.java"
},
{
"code": null,
"e": 6535,
"s": 3986,
"text": "package com.tutorialspoint.gui;\n \nimport java.awt.*;\nimport java.awt.event.*;\nimport javax.swing.*;\n \npublic class SwingControlDemo {\n private JFrame mainFrame;\n private JLabel headerLabel;\n private JLabel statusLabel;\n private JPanel controlPanel;\n\n public SwingControlDemo(){\n prepareGUI();\n }\n public static void main(String[] args){\n SwingControlDemo swingControlDemo = new SwingControlDemo(); \n swingControlDemo.showCheckBoxDemo();\n }\n private void prepareGUI(){\n mainFrame = new JFrame(\"Java Swing Examples\");\n mainFrame.setSize(400,400);\n mainFrame.setLayout(new GridLayout(3, 1));\n \n mainFrame.addWindowListener(new WindowAdapter() {\n public void windowClosing(WindowEvent windowEvent){\n System.exit(0);\n } \n }); \n headerLabel = new JLabel(\"\", JLabel.CENTER); \n statusLabel = new JLabel(\"\",JLabel.CENTER); \n statusLabel.setSize(350,100);\n\n controlPanel = new JPanel();\n controlPanel.setLayout(new FlowLayout());\n\n mainFrame.add(headerLabel);\n mainFrame.add(controlPanel);\n mainFrame.add(statusLabel);\n mainFrame.setVisible(true); \n }\n private void showCheckBoxDemo(){\n headerLabel.setText(\"Control in action: CheckBox\"); \n\n final JCheckBox chkApple = new JCheckBox(\"Apple\");\n final JCheckBox chkMango = new JCheckBox(\"Mango\");\n final JCheckBox chkPeer = new JCheckBox(\"Peer\");\n\n chkApple.setMnemonic(KeyEvent.VK_C);\n chkMango.setMnemonic(KeyEvent.VK_M);\n chkPeer.setMnemonic(KeyEvent.VK_P);\n\n chkApple.addItemListener(new ItemListener() {\n public void itemStateChanged(ItemEvent e) { \n statusLabel.setText(\"Apple Checkbox: \" \n + (e.getStateChange()==1?\"checked\":\"unchecked\"));\n } \n });\n chkMango.addItemListener(new ItemListener() {\n public void itemStateChanged(ItemEvent e) { \n statusLabel.setText(\"Mango Checkbox: \" \n + (e.getStateChange()==1?\"checked\":\"unchecked\")); \n } \n });\n chkPeer.addItemListener(new ItemListener() {\n public void itemStateChanged(ItemEvent e) { \n statusLabel.setText(\"Peer Checkbox: \" \n + (e.getStateChange()==1?\"checked\":\"unchecked\"));\n } \n });\n controlPanel.add(chkApple);\n controlPanel.add(chkMango);\n controlPanel.add(chkPeer); \n\n mainFrame.setVisible(true); \n }\n}"
},
{
"code": null,
"e": 6631,
"s": 6535,
"text": "Compile the program using the command prompt. Go to D:/ > SWING and type the following command."
},
{
"code": null,
"e": 6692,
"s": 6631,
"text": "D:\\SWING>javac com\\tutorialspoint\\gui\\SwingControlDemo.java\n"
},
{
"code": null,
"e": 6797,
"s": 6692,
"text": "If no error occurs, it means the compilation is successful. Run the program using the following command."
},
{
"code": null,
"e": 6852,
"s": 6797,
"text": "D:\\SWING>java com.tutorialspoint.gui.SwingControlDemo\n"
},
{
"code": null,
"e": 6881,
"s": 6852,
"text": "Verify the following output."
},
{
"code": null,
"e": 6916,
"s": 6881,
"text": "\n 30 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 6936,
"s": 6916,
"text": " Pranjal Srivastava"
},
{
"code": null,
"e": 6969,
"s": 6936,
"text": "\n 13 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 6989,
"s": 6969,
"text": " Pranjal Srivastava"
},
{
"code": null,
"e": 7024,
"s": 6989,
"text": "\n 25 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 7060,
"s": 7024,
"text": " Emenwa Global, Ejike IfeanyiChukwu"
},
{
"code": null,
"e": 7095,
"s": 7060,
"text": "\n 14 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 7108,
"s": 7095,
"text": " Travis Rose"
},
{
"code": null,
"e": 7141,
"s": 7108,
"text": "\n 14 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 7154,
"s": 7141,
"text": " Travis Rose"
},
{
"code": null,
"e": 7161,
"s": 7154,
"text": " Print"
},
{
"code": null,
"e": 7172,
"s": 7161,
"text": " Add Notes"
}
] |
3 bit Synchronous Down Counter - GeeksforGeeks
|
19 May, 2021
Prerequisite : Counter , Synchronous counter.
3 bit Synchronous Down Counter :
In synchronous counter clock is provided to all the flip-flops simultaneously.
Circuit becomes complex as the number of states increases.
Speed is high.
Design : The steps involves in design are
1. Decide the number of Flip flops –
N number of Flip flop(FF) required for N bit counter.
For 3 bit counter we require 3 FF.
Maximum count = 2n-1, where n is a number of bits.
For n= 3, Maximum count = 7.
Here T FF is used.
2. Write excitation table of FF –
3. Draw State diagram and circuit excitation table – Number of states = 2n, where n is number of bits.
Here T = 1, then there is output state(next state changes from previous state) changes i.e Q changes from 0 to 1 or 1 to 0 T= 0 then, there is no state output state changes i.e Q remains same
4. Find simplified equation using k map –
K map for 3 bit synchronous down counter
5. Create circuit diagram –The clock is provided to every Flip flop at same instant of time. The toggle(T) input is provided to every Flip flop according to the simplified equation of K map.
Timing diagram of 3 bit synchronous Down counter.
Explanation : Here -ve edge triggered clock is used for toggling purpose.
As we see from characteristics table when T = 1, then toggling takes place and T =0 then it stores the output state.
Initially Q3 = 0, Q2= 0, Q1= 0.
In simplified equation of K map we get T1 = 1, therefore Flip flop 1 output Q1 is toggle for every negative edge(because clock is negative edge triggered). Flip-flop(FF) 2 toggle input(T2) is connected to Q’1. Therefore, Flip Flop 2 output state Q2 is toggle only when there is clock falling edge (i.e -ve edge triggering) and Q’1 =1.
Similarly, Flip flop 3 toggle input(T) is connected to Q’2 and Q’1. Therefore, Flip flop 3 output is toggle when there is clock falling edge and Q’2=1 and Q’1 = 1 .(as you can see from timing diagram)
Therefore, we get output(as down counting Q3(MSB) Q2 Q1(LSB) after 8th -ve edge triggered clock the output of the three Flip flops again becomes Q3 = 0, Q2 = 0, Q1 =0.
We get output(state changes) after every -ve edge clock pulse.
By 3 Flip flop we get output as 23-1= 7 to 0.
Digital Electronics & Logic Design
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
4-bit binary Adder-Subtractor
Multiplexers in Digital Logic
Magnitude Comparator in Digital Logic
BCD to 7 Segment Decoder
Full Subtractor in Digital Logic
Carry Look-Ahead Adder
Encoder in Digital Logic
Half Adder in Digital Logic
Difference between Unipolar, Polar and Bipolar Line Coding Schemes
Encoders and Decoders in Digital Logic
|
[
{
"code": null,
"e": 24035,
"s": 24007,
"text": "\n19 May, 2021"
},
{
"code": null,
"e": 24081,
"s": 24035,
"text": "Prerequisite : Counter , Synchronous counter."
},
{
"code": null,
"e": 24114,
"s": 24081,
"text": "3 bit Synchronous Down Counter :"
},
{
"code": null,
"e": 24193,
"s": 24114,
"text": "In synchronous counter clock is provided to all the flip-flops simultaneously."
},
{
"code": null,
"e": 24252,
"s": 24193,
"text": "Circuit becomes complex as the number of states increases."
},
{
"code": null,
"e": 24267,
"s": 24252,
"text": "Speed is high."
},
{
"code": null,
"e": 24310,
"s": 24267,
"text": "Design : The steps involves in design are "
},
{
"code": null,
"e": 24350,
"s": 24310,
"text": " 1. Decide the number of Flip flops – "
},
{
"code": null,
"e": 24404,
"s": 24350,
"text": "N number of Flip flop(FF) required for N bit counter."
},
{
"code": null,
"e": 24439,
"s": 24404,
"text": "For 3 bit counter we require 3 FF."
},
{
"code": null,
"e": 24490,
"s": 24439,
"text": "Maximum count = 2n-1, where n is a number of bits."
},
{
"code": null,
"e": 24519,
"s": 24490,
"text": "For n= 3, Maximum count = 7."
},
{
"code": null,
"e": 24538,
"s": 24519,
"text": "Here T FF is used."
},
{
"code": null,
"e": 24575,
"s": 24538,
"text": " 2. Write excitation table of FF –"
},
{
"code": null,
"e": 24684,
"s": 24575,
"text": " 3. Draw State diagram and circuit excitation table – Number of states = 2n, where n is number of bits."
},
{
"code": null,
"e": 24877,
"s": 24684,
"text": "Here T = 1, then there is output state(next state changes from previous state) changes i.e Q changes from 0 to 1 or 1 to 0 T= 0 then, there is no state output state changes i.e Q remains same "
},
{
"code": null,
"e": 24920,
"s": 24877,
"text": " 4. Find simplified equation using k map –"
},
{
"code": null,
"e": 24962,
"s": 24920,
"text": "K map for 3 bit synchronous down counter "
},
{
"code": null,
"e": 25155,
"s": 24962,
"text": " 5. Create circuit diagram –The clock is provided to every Flip flop at same instant of time. The toggle(T) input is provided to every Flip flop according to the simplified equation of K map."
},
{
"code": null,
"e": 25205,
"s": 25155,
"text": "Timing diagram of 3 bit synchronous Down counter."
},
{
"code": null,
"e": 25280,
"s": 25205,
"text": "Explanation : Here -ve edge triggered clock is used for toggling purpose."
},
{
"code": null,
"e": 25397,
"s": 25280,
"text": "As we see from characteristics table when T = 1, then toggling takes place and T =0 then it stores the output state."
},
{
"code": null,
"e": 25429,
"s": 25397,
"text": "Initially Q3 = 0, Q2= 0, Q1= 0."
},
{
"code": null,
"e": 25765,
"s": 25429,
"text": "In simplified equation of K map we get T1 = 1, therefore Flip flop 1 output Q1 is toggle for every negative edge(because clock is negative edge triggered). Flip-flop(FF) 2 toggle input(T2) is connected to Q’1. Therefore, Flip Flop 2 output state Q2 is toggle only when there is clock falling edge (i.e -ve edge triggering) and Q’1 =1."
},
{
"code": null,
"e": 25966,
"s": 25765,
"text": "Similarly, Flip flop 3 toggle input(T) is connected to Q’2 and Q’1. Therefore, Flip flop 3 output is toggle when there is clock falling edge and Q’2=1 and Q’1 = 1 .(as you can see from timing diagram)"
},
{
"code": null,
"e": 26134,
"s": 25966,
"text": "Therefore, we get output(as down counting Q3(MSB) Q2 Q1(LSB) after 8th -ve edge triggered clock the output of the three Flip flops again becomes Q3 = 0, Q2 = 0, Q1 =0."
},
{
"code": null,
"e": 26197,
"s": 26134,
"text": "We get output(state changes) after every -ve edge clock pulse."
},
{
"code": null,
"e": 26243,
"s": 26197,
"text": "By 3 Flip flop we get output as 23-1= 7 to 0."
},
{
"code": null,
"e": 26278,
"s": 26243,
"text": "Digital Electronics & Logic Design"
},
{
"code": null,
"e": 26376,
"s": 26278,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26385,
"s": 26376,
"text": "Comments"
},
{
"code": null,
"e": 26398,
"s": 26385,
"text": "Old Comments"
},
{
"code": null,
"e": 26428,
"s": 26398,
"text": "4-bit binary Adder-Subtractor"
},
{
"code": null,
"e": 26458,
"s": 26428,
"text": "Multiplexers in Digital Logic"
},
{
"code": null,
"e": 26496,
"s": 26458,
"text": "Magnitude Comparator in Digital Logic"
},
{
"code": null,
"e": 26521,
"s": 26496,
"text": "BCD to 7 Segment Decoder"
},
{
"code": null,
"e": 26554,
"s": 26521,
"text": "Full Subtractor in Digital Logic"
},
{
"code": null,
"e": 26577,
"s": 26554,
"text": "Carry Look-Ahead Adder"
},
{
"code": null,
"e": 26602,
"s": 26577,
"text": "Encoder in Digital Logic"
},
{
"code": null,
"e": 26630,
"s": 26602,
"text": "Half Adder in Digital Logic"
},
{
"code": null,
"e": 26697,
"s": 26630,
"text": "Difference between Unipolar, Polar and Bipolar Line Coding Schemes"
}
] |
ios good() function in C++ with Examples - GeeksforGeeks
|
02 Sep, 2019
The good() method of ios class in C++ is used to check if the stream is good enough to work. It means that this function will check if this stream has raised any error or not.
Syntax:
bool good() const;
Parameters: This method does not accept any parameter.
Return Value: This method returns true if the stream is good, else false.
Example 1:
// C++ code to demonstrate// the working of good() function #include <bits/stdc++.h>using namespace std; int main(){ // Stream stringstream ss; // Using good() function bool isGood = ss.good(); // print result cout << "is stream good: " << isGood << endl; return 0;}
is stream good: 1
Example 2:
// C++ code to demonstrate// the working of good() function #include <bits/stdc++.h>using namespace std; int main(){ // Stream stringstream ss; ss.clear(ss.eofbit); // Using good() function bool isGood = ss.good(); // print result cout << "is stream good: " << isGood << endl; return 0;}
is stream good: 0
Reference: hhttp://www.cplusplus.com/reference/ios/ios/good/
CPP-Functions
cpp-ios
C++
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Operator Overloading in C++
Sorting a vector in C++
Polymorphism in C++
Friend class and function in C++
List in C++ Standard Template Library (STL)
Convert string to char array in C++
new and delete operators in C++ for dynamic memory
Destructors in C++
Pair in C++ Standard Template Library (STL)
Inline Functions in C++
|
[
{
"code": null,
"e": 23707,
"s": 23679,
"text": "\n02 Sep, 2019"
},
{
"code": null,
"e": 23883,
"s": 23707,
"text": "The good() method of ios class in C++ is used to check if the stream is good enough to work. It means that this function will check if this stream has raised any error or not."
},
{
"code": null,
"e": 23891,
"s": 23883,
"text": "Syntax:"
},
{
"code": null,
"e": 23911,
"s": 23891,
"text": "bool good() const;\n"
},
{
"code": null,
"e": 23966,
"s": 23911,
"text": "Parameters: This method does not accept any parameter."
},
{
"code": null,
"e": 24040,
"s": 23966,
"text": "Return Value: This method returns true if the stream is good, else false."
},
{
"code": null,
"e": 24051,
"s": 24040,
"text": "Example 1:"
},
{
"code": "// C++ code to demonstrate// the working of good() function #include <bits/stdc++.h>using namespace std; int main(){ // Stream stringstream ss; // Using good() function bool isGood = ss.good(); // print result cout << \"is stream good: \" << isGood << endl; return 0;}",
"e": 24357,
"s": 24051,
"text": null
},
{
"code": null,
"e": 24376,
"s": 24357,
"text": "is stream good: 1\n"
},
{
"code": null,
"e": 24387,
"s": 24376,
"text": "Example 2:"
},
{
"code": "// C++ code to demonstrate// the working of good() function #include <bits/stdc++.h>using namespace std; int main(){ // Stream stringstream ss; ss.clear(ss.eofbit); // Using good() function bool isGood = ss.good(); // print result cout << \"is stream good: \" << isGood << endl; return 0;}",
"e": 24717,
"s": 24387,
"text": null
},
{
"code": null,
"e": 24736,
"s": 24717,
"text": "is stream good: 0\n"
},
{
"code": null,
"e": 24797,
"s": 24736,
"text": "Reference: hhttp://www.cplusplus.com/reference/ios/ios/good/"
},
{
"code": null,
"e": 24811,
"s": 24797,
"text": "CPP-Functions"
},
{
"code": null,
"e": 24819,
"s": 24811,
"text": "cpp-ios"
},
{
"code": null,
"e": 24823,
"s": 24819,
"text": "C++"
},
{
"code": null,
"e": 24827,
"s": 24823,
"text": "CPP"
},
{
"code": null,
"e": 24925,
"s": 24827,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 24934,
"s": 24925,
"text": "Comments"
},
{
"code": null,
"e": 24947,
"s": 24934,
"text": "Old Comments"
},
{
"code": null,
"e": 24975,
"s": 24947,
"text": "Operator Overloading in C++"
},
{
"code": null,
"e": 24999,
"s": 24975,
"text": "Sorting a vector in C++"
},
{
"code": null,
"e": 25019,
"s": 24999,
"text": "Polymorphism in C++"
},
{
"code": null,
"e": 25052,
"s": 25019,
"text": "Friend class and function in C++"
},
{
"code": null,
"e": 25096,
"s": 25052,
"text": "List in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 25132,
"s": 25096,
"text": "Convert string to char array in C++"
},
{
"code": null,
"e": 25183,
"s": 25132,
"text": "new and delete operators in C++ for dynamic memory"
},
{
"code": null,
"e": 25202,
"s": 25183,
"text": "Destructors in C++"
},
{
"code": null,
"e": 25246,
"s": 25202,
"text": "Pair in C++ Standard Template Library (STL)"
}
] |
Graph Theory | Rooting a Tree. Today, we are going to see how we can... | by Kelvin Jose | Towards Data Science
|
Today, we are going to see how we can root a tree. This is the 8th post of my ongoing series Graph Theory : Go Hero. You should definitely check out the index page to deep dive into Graphs and related problems. I mostly try to come up with new posts of this series in every weekends. Let’s see how rooting is done.
This is one of those very basic and fundamental transformations we need to have if we want to work with rooted trees. The motivation of rooting a tree is that often it can help to add a structure and simplify the problem. A rooted tree can convert an undirected tree into a directed one which lot easier to work with. Conceptually, rooting a tree is like picking up the tree by a specific node and having all the edges point downwards.
We can root a tree by using any of its nodes, however, be cautious about the node we are choosing because not all nodes would not generate well-balanced trees. So we need to be a bit selective.
In some situations, it’s always a good idea to have a route back to the parent node so that we can walk back. I have illustrated routes to parent nodes with red lines below.
Let’s see how we can root a tree.
Rooting a tree is easily done with a Depth First Search (DFS). I have created an animated version of the resultant DFS below. You would definitely understand it, for sure.
and that’s rooting a tree in a nutshell.
class Treenode: int id; Treenode parent; Treenode [] children;function rootTree(g, rootId = 0): root = Treenode(rootId, null, []) return buildTree(g, root, null)function buildTree(g, node, parent): for child in g[node.id]: if parent != null and childId == parent.id: continue child = Treenode(childId, node, []) node.children.add(child) buildTree(g, child, node) return node
We have a class defined with the name Treenode. Every node in the tree would have an unique id, that’s what we are storing in the id placeholder. As we discussed earlier, it’s always a best practice to save the parent node because it would help us to travel back. Also, we save some references to the children of the current node.
Then we define a function called rootTree which takes two parameters into it - a graph and the id of the node to get started. The graph g would be represented as an adjacency list with undirected edges. The first line of rootTree method creates a Treenode object with given rootId, parent reference and list of children. The rootTree function invokes another function named buildTree with parameters graph g, root node and reference to the parent node.
The buildTree method takes the exact three parameters we just talked about. As we enter into the function, we end up landing in a for loop which travels all over the children of the current node. We know the edges are undirected, so we absolutely need to manage the situation where we add a directed edge pointing towards the same node. If the above condition is not met, we are sure that we have a confirmed child in our hand. Then we create an object to the Treenode class and add the child to the list of children of the current node. Afterwards, it does DFS more into the tree using the newly created node. We return the current node as we visit all the neighbors of the node.
So, that’s how we root a tree. We will discuss Tree center(s) in the coming post. Let’s keep learning, together.
|
[
{
"code": null,
"e": 486,
"s": 171,
"text": "Today, we are going to see how we can root a tree. This is the 8th post of my ongoing series Graph Theory : Go Hero. You should definitely check out the index page to deep dive into Graphs and related problems. I mostly try to come up with new posts of this series in every weekends. Let’s see how rooting is done."
},
{
"code": null,
"e": 922,
"s": 486,
"text": "This is one of those very basic and fundamental transformations we need to have if we want to work with rooted trees. The motivation of rooting a tree is that often it can help to add a structure and simplify the problem. A rooted tree can convert an undirected tree into a directed one which lot easier to work with. Conceptually, rooting a tree is like picking up the tree by a specific node and having all the edges point downwards."
},
{
"code": null,
"e": 1116,
"s": 922,
"text": "We can root a tree by using any of its nodes, however, be cautious about the node we are choosing because not all nodes would not generate well-balanced trees. So we need to be a bit selective."
},
{
"code": null,
"e": 1290,
"s": 1116,
"text": "In some situations, it’s always a good idea to have a route back to the parent node so that we can walk back. I have illustrated routes to parent nodes with red lines below."
},
{
"code": null,
"e": 1324,
"s": 1290,
"text": "Let’s see how we can root a tree."
},
{
"code": null,
"e": 1496,
"s": 1324,
"text": "Rooting a tree is easily done with a Depth First Search (DFS). I have created an animated version of the resultant DFS below. You would definitely understand it, for sure."
},
{
"code": null,
"e": 1537,
"s": 1496,
"text": "and that’s rooting a tree in a nutshell."
},
{
"code": null,
"e": 1976,
"s": 1537,
"text": "class Treenode: int id; Treenode parent; Treenode [] children;function rootTree(g, rootId = 0): root = Treenode(rootId, null, []) return buildTree(g, root, null)function buildTree(g, node, parent): for child in g[node.id]: if parent != null and childId == parent.id: continue child = Treenode(childId, node, []) node.children.add(child) buildTree(g, child, node) return node"
},
{
"code": null,
"e": 2307,
"s": 1976,
"text": "We have a class defined with the name Treenode. Every node in the tree would have an unique id, that’s what we are storing in the id placeholder. As we discussed earlier, it’s always a best practice to save the parent node because it would help us to travel back. Also, we save some references to the children of the current node."
},
{
"code": null,
"e": 2760,
"s": 2307,
"text": "Then we define a function called rootTree which takes two parameters into it - a graph and the id of the node to get started. The graph g would be represented as an adjacency list with undirected edges. The first line of rootTree method creates a Treenode object with given rootId, parent reference and list of children. The rootTree function invokes another function named buildTree with parameters graph g, root node and reference to the parent node."
},
{
"code": null,
"e": 3441,
"s": 2760,
"text": "The buildTree method takes the exact three parameters we just talked about. As we enter into the function, we end up landing in a for loop which travels all over the children of the current node. We know the edges are undirected, so we absolutely need to manage the situation where we add a directed edge pointing towards the same node. If the above condition is not met, we are sure that we have a confirmed child in our hand. Then we create an object to the Treenode class and add the child to the list of children of the current node. Afterwards, it does DFS more into the tree using the newly created node. We return the current node as we visit all the neighbors of the node."
}
] |
Kotlin When Expressions
|
Instead of writing many if..else expressions, you can use the when
expression, which is much easier to read.
It is used to select one of many code blocks to be executed:
Use the weekday number to calculate the weekday name:
val day = 4
val result = when (day) {
1 -> "Monday"
2 -> "Tuesday"
3 -> "Wednesday"
4 -> "Thursday"
5 -> "Friday"
6 -> "Saturday"
7 -> "Sunday"
else -> "Invalid day."
}
println(result)
// Outputs "Thursday" (day 4)
The when expression is similar to the switch statement in Java.
This is how it works:
The when variable (day) is evaluated once
The value of the day variable is compared with the values of each "branch"
Each branch starts with a value, followed by an arrow (->) and a result
If there is a match, the associated block of code is executed
else is used to specify some code to run if there is no match
In the example above, the value of day is 4, meaning "Thursday" will be printed
We just launchedW3Schools videos
Get certifiedby completinga course today!
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
help@w3schools.com
Your message has been sent to W3Schools.
|
[
{
"code": null,
"e": 110,
"s": 0,
"text": "Instead of writing many if..else expressions, you can use the when \nexpression, which is much easier to read."
},
{
"code": null,
"e": 171,
"s": 110,
"text": "It is used to select one of many code blocks to be executed:"
},
{
"code": null,
"e": 225,
"s": 171,
"text": "Use the weekday number to calculate the weekday name:"
},
{
"code": null,
"e": 458,
"s": 225,
"text": "val day = 4\n\nval result = when (day) {\n 1 -> \"Monday\"\n 2 -> \"Tuesday\"\n 3 -> \"Wednesday\"\n 4 -> \"Thursday\"\n 5 -> \"Friday\"\n 6 -> \"Saturday\"\n 7 -> \"Sunday\"\n else -> \"Invalid day.\"\n}\nprintln(result)\n\n// Outputs \"Thursday\" (day 4)"
},
{
"code": null,
"e": 522,
"s": 458,
"text": "The when expression is similar to the switch statement in Java."
},
{
"code": null,
"e": 544,
"s": 522,
"text": "This is how it works:"
},
{
"code": null,
"e": 586,
"s": 544,
"text": "The when variable (day) is evaluated once"
},
{
"code": null,
"e": 661,
"s": 586,
"text": "The value of the day variable is compared with the values of each \"branch\""
},
{
"code": null,
"e": 733,
"s": 661,
"text": "Each branch starts with a value, followed by an arrow (->) and a result"
},
{
"code": null,
"e": 795,
"s": 733,
"text": "If there is a match, the associated block of code is executed"
},
{
"code": null,
"e": 857,
"s": 795,
"text": "else is used to specify some code to run if there is no match"
},
{
"code": null,
"e": 937,
"s": 857,
"text": "In the example above, the value of day is 4, meaning \"Thursday\" will be printed"
},
{
"code": null,
"e": 970,
"s": 937,
"text": "We just launchedW3Schools videos"
},
{
"code": null,
"e": 1012,
"s": 970,
"text": "Get certifiedby completinga course today!"
},
{
"code": null,
"e": 1119,
"s": 1012,
"text": "If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:"
},
{
"code": null,
"e": 1138,
"s": 1119,
"text": "help@w3schools.com"
}
] |
Matlab - Matrix - GeeksforGeeks
|
21 Feb, 2022
A Matrix is a two-dimensional array of elements. In MATLAB, the matrix is created by assigning the array elements that are delimited by spaces or commas and using semicolons to mark the end of each row. Now let’s have a glance at some examples to understand it better.
Syntax:
a = [elements; elements]
Example: Creating a Matrix
MATLAB
% MATLAB program to create% a matrix %Number Matrixx = [1 2 3;4 5 6;7 8 9] %String Matrixy = ['Geeks';'Geeks']
Output:
Example: Knowing the size of the Matrix
MATLAB
% MATLAB program to know% the size of a matrix % Creating matricesx = [1 2 3 4;4 5 6 7;7 8 9 10];xSize = size(x) y=['Geeks';'Geeks'];ySize = size(y)
Output:
To reference an element in a matrix, we write matrix(m, n). Here m and n are row and column indexes.
Example 1:
MATLAB
% MATLAB program to access% a particular element % Creating matricesx = [1 2 3 4;4 5 6 7;7 8 9 10];x(3,2) y=['Geeks';'Geeks'];y(1,2)
Output:
To access multiple elements in the matrix, we write
matrix(x:y;,xy)
Example 2:
MATLAB
% MATLAB program to access% a multiple elements % Creating matricesx = [1 2 3 4;4 5 6 7;7 8 9 10]; % Accessing all rows and columnsx(:,:) % Accessing all the elements% in the first two rowsx(1:2,:) % Accessing all the elements% from 2nd to last element% in every row.x(:,2:end) % Accessing elements from 2nd index% to 3rd index in the first two columnsx(1:2,2:3)
Output:
To add elements/dimension to a matrix we can use one of the following methods:
cat(dimension,A,B,....)
or
x = [A;B]
In the above syntax, A & B are matrices that we need to pass into the function cat() or concatenate by using square brackets. Here dimension parameter must be either 1 or 2 for table or timetable input.
Example 1:
MATLAB
% MATLAB program to add% dimensions to a matrix % Creating matricesx = [1 2 3 4;4 5 6 7];y = [7 8 9 10;11 12 13 14]; % Concatenating two matrices% or adding a rowa = [x;y]b = [x;11 12 13 14] %Adding a column to a matrixx(:,5)=[15 16]
Output:
Example 2:
MATLAB
% Matlab Program to% explain concatenation x = [1 2 3 4;4 5 6 7]; % Creating a new matrix by% concatenating multiple rows% of a matrixa = x([1,2,2,1],:) % Creating a new matrix by% concatenating multiple columns% of a matrixb = x(:,[1,3,2])
Output:
Example 3:
MATLAB
% MATLAB program to concatenate% two matrices using cat() function % Creating matricesx = [1 2 3 4;4 5 6 7];y = [1 2 3 4;4 5 6 7]; % Concatenating two matrices% Using cat() functiona = cat(1,x,y)b = cat(2,x,y)
Output:
Example 4: Deleting a row/column of a matrix
MATLAB
% MATLAB program to delete% a row or a column % Creating matricesx = [1 2 3 4;4 5 6 7;7 8 9 10]; % Deleting 3rd row of% a matrixx(3,:) = [] % Deleting 3rd column in% every row of a matrixx(:,3) = []
Output:
Note:
Unlike most of the programming languages, MATLAB array indexes start from 1.
To perform operations(almost all) on the matrices, dimensions must be the same.
A semicolon must be added at each end of the statement in order to avoid multiple outputs.
In MATLAB, a string is a character array.
In MATLAB, length() gives the length of an array, and size() gives the size of a matrix.
gabaa406
sagar0719kumar
germanshephered48
MATLAB
Advanced Computer Subject
Programming Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Decision Tree
ML | Linear Regression
Python | Decision tree implementation
System Design Tutorial
Decision Tree Introduction with example
Modulo Operator (%) in C/C++ with Examples
Differences between Procedural and Object Oriented Programming
Arrow operator -> in C/C++ with Examples
Structures in C++
Top 10 Programming Languages to Learn in 2022
|
[
{
"code": null,
"e": 24434,
"s": 24406,
"text": "\n21 Feb, 2022"
},
{
"code": null,
"e": 24704,
"s": 24434,
"text": "A Matrix is a two-dimensional array of elements. In MATLAB, the matrix is created by assigning the array elements that are delimited by spaces or commas and using semicolons to mark the end of each row. Now let’s have a glance at some examples to understand it better."
},
{
"code": null,
"e": 24712,
"s": 24704,
"text": "Syntax:"
},
{
"code": null,
"e": 24737,
"s": 24712,
"text": "a = [elements; elements]"
},
{
"code": null,
"e": 24764,
"s": 24737,
"text": "Example: Creating a Matrix"
},
{
"code": null,
"e": 24771,
"s": 24764,
"text": "MATLAB"
},
{
"code": "% MATLAB program to create% a matrix %Number Matrixx = [1 2 3;4 5 6;7 8 9] %String Matrixy = ['Geeks';'Geeks']",
"e": 24882,
"s": 24771,
"text": null
},
{
"code": null,
"e": 24895,
"s": 24885,
"text": " Output: "
},
{
"code": null,
"e": 24941,
"s": 24899,
"text": " Example: Knowing the size of the Matrix "
},
{
"code": null,
"e": 24950,
"s": 24943,
"text": "MATLAB"
},
{
"code": "% MATLAB program to know% the size of a matrix % Creating matricesx = [1 2 3 4;4 5 6 7;7 8 9 10];xSize = size(x) y=['Geeks';'Geeks'];ySize = size(y)",
"e": 25099,
"s": 24950,
"text": null
},
{
"code": null,
"e": 25111,
"s": 25102,
"text": "Output: "
},
{
"code": null,
"e": 25218,
"s": 25115,
"text": " To reference an element in a matrix, we write matrix(m, n). Here m and n are row and column indexes. "
},
{
"code": null,
"e": 25231,
"s": 25220,
"text": "Example 1:"
},
{
"code": null,
"e": 25240,
"s": 25233,
"text": "MATLAB"
},
{
"code": "% MATLAB program to access% a particular element % Creating matricesx = [1 2 3 4;4 5 6 7;7 8 9 10];x(3,2) y=['Geeks';'Geeks'];y(1,2)",
"e": 25373,
"s": 25240,
"text": null
},
{
"code": null,
"e": 25384,
"s": 25376,
"text": "Output:"
},
{
"code": null,
"e": 25441,
"s": 25388,
"text": "To access multiple elements in the matrix, we write "
},
{
"code": null,
"e": 25459,
"s": 25443,
"text": "matrix(x:y;,xy)"
},
{
"code": null,
"e": 25473,
"s": 25461,
"text": "Example 2: "
},
{
"code": null,
"e": 25482,
"s": 25475,
"text": "MATLAB"
},
{
"code": "% MATLAB program to access% a multiple elements % Creating matricesx = [1 2 3 4;4 5 6 7;7 8 9 10]; % Accessing all rows and columnsx(:,:) % Accessing all the elements% in the first two rowsx(1:2,:) % Accessing all the elements% from 2nd to last element% in every row.x(:,2:end) % Accessing elements from 2nd index% to 3rd index in the first two columnsx(1:2,2:3)",
"e": 25845,
"s": 25482,
"text": null
},
{
"code": null,
"e": 25857,
"s": 25848,
"text": "Output: "
},
{
"code": null,
"e": 25941,
"s": 25861,
"text": "To add elements/dimension to a matrix we can use one of the following methods: "
},
{
"code": null,
"e": 25967,
"s": 25943,
"text": "cat(dimension,A,B,....)"
},
{
"code": null,
"e": 25970,
"s": 25967,
"text": "or"
},
{
"code": null,
"e": 25980,
"s": 25970,
"text": "x = [A;B]"
},
{
"code": null,
"e": 26186,
"s": 25982,
"text": "In the above syntax, A & B are matrices that we need to pass into the function cat() or concatenate by using square brackets. Here dimension parameter must be either 1 or 2 for table or timetable input. "
},
{
"code": null,
"e": 26200,
"s": 26188,
"text": "Example 1: "
},
{
"code": null,
"e": 26209,
"s": 26202,
"text": "MATLAB"
},
{
"code": "% MATLAB program to add% dimensions to a matrix % Creating matricesx = [1 2 3 4;4 5 6 7];y = [7 8 9 10;11 12 13 14]; % Concatenating two matrices% or adding a rowa = [x;y]b = [x;11 12 13 14] %Adding a column to a matrixx(:,5)=[15 16]",
"e": 26443,
"s": 26209,
"text": null
},
{
"code": null,
"e": 26455,
"s": 26446,
"text": "Output: "
},
{
"code": null,
"e": 26471,
"s": 26459,
"text": "Example 2: "
},
{
"code": null,
"e": 26480,
"s": 26473,
"text": "MATLAB"
},
{
"code": "% Matlab Program to% explain concatenation x = [1 2 3 4;4 5 6 7]; % Creating a new matrix by% concatenating multiple rows% of a matrixa = x([1,2,2,1],:) % Creating a new matrix by% concatenating multiple columns% of a matrixb = x(:,[1,3,2])",
"e": 26723,
"s": 26480,
"text": null
},
{
"code": null,
"e": 26734,
"s": 26726,
"text": "Output:"
},
{
"code": null,
"e": 26751,
"s": 26738,
"text": " Example 3: "
},
{
"code": null,
"e": 26760,
"s": 26753,
"text": "MATLAB"
},
{
"code": "% MATLAB program to concatenate% two matrices using cat() function % Creating matricesx = [1 2 3 4;4 5 6 7];y = [1 2 3 4;4 5 6 7]; % Concatenating two matrices% Using cat() functiona = cat(1,x,y)b = cat(2,x,y)",
"e": 26970,
"s": 26760,
"text": null
},
{
"code": null,
"e": 26982,
"s": 26973,
"text": "Output: "
},
{
"code": null,
"e": 27032,
"s": 26986,
"text": "Example 4: Deleting a row/column of a matrix "
},
{
"code": null,
"e": 27041,
"s": 27034,
"text": "MATLAB"
},
{
"code": "% MATLAB program to delete% a row or a column % Creating matricesx = [1 2 3 4;4 5 6 7;7 8 9 10]; % Deleting 3rd row of% a matrixx(3,:) = [] % Deleting 3rd column in% every row of a matrixx(:,3) = []",
"e": 27240,
"s": 27041,
"text": null
},
{
"code": null,
"e": 27251,
"s": 27243,
"text": "Output:"
},
{
"code": null,
"e": 27262,
"s": 27255,
"text": "Note: "
},
{
"code": null,
"e": 27341,
"s": 27264,
"text": "Unlike most of the programming languages, MATLAB array indexes start from 1."
},
{
"code": null,
"e": 27421,
"s": 27341,
"text": "To perform operations(almost all) on the matrices, dimensions must be the same."
},
{
"code": null,
"e": 27512,
"s": 27421,
"text": "A semicolon must be added at each end of the statement in order to avoid multiple outputs."
},
{
"code": null,
"e": 27554,
"s": 27512,
"text": "In MATLAB, a string is a character array."
},
{
"code": null,
"e": 27643,
"s": 27554,
"text": "In MATLAB, length() gives the length of an array, and size() gives the size of a matrix."
},
{
"code": null,
"e": 27654,
"s": 27645,
"text": "gabaa406"
},
{
"code": null,
"e": 27669,
"s": 27654,
"text": "sagar0719kumar"
},
{
"code": null,
"e": 27687,
"s": 27669,
"text": "germanshephered48"
},
{
"code": null,
"e": 27694,
"s": 27687,
"text": "MATLAB"
},
{
"code": null,
"e": 27720,
"s": 27694,
"text": "Advanced Computer Subject"
},
{
"code": null,
"e": 27741,
"s": 27720,
"text": "Programming Language"
},
{
"code": null,
"e": 27839,
"s": 27741,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27848,
"s": 27839,
"text": "Comments"
},
{
"code": null,
"e": 27861,
"s": 27848,
"text": "Old Comments"
},
{
"code": null,
"e": 27875,
"s": 27861,
"text": "Decision Tree"
},
{
"code": null,
"e": 27898,
"s": 27875,
"text": "ML | Linear Regression"
},
{
"code": null,
"e": 27936,
"s": 27898,
"text": "Python | Decision tree implementation"
},
{
"code": null,
"e": 27959,
"s": 27936,
"text": "System Design Tutorial"
},
{
"code": null,
"e": 27999,
"s": 27959,
"text": "Decision Tree Introduction with example"
},
{
"code": null,
"e": 28042,
"s": 27999,
"text": "Modulo Operator (%) in C/C++ with Examples"
},
{
"code": null,
"e": 28105,
"s": 28042,
"text": "Differences between Procedural and Object Oriented Programming"
},
{
"code": null,
"e": 28146,
"s": 28105,
"text": "Arrow operator -> in C/C++ with Examples"
},
{
"code": null,
"e": 28164,
"s": 28146,
"text": "Structures in C++"
}
] |
Assertions in Python 3
|
An assertion is a sanity-check that you can turn on or turn off when you are done with your testing of the program.
The easiest way to think of an assertion is to liken it to a raise-if statement (or to be more accurate, a raise-if-not statement). An expression is tested, and if the result comes up false, an exception is raised.
Assertions are carried out by the assert statement, the newest keyword to Python, introduced in version 1.5.
Programmers often place assertions at the start of a function to check for valid input, and after a function call to check for valid output.
When it encounters an assert statement, Python evaluates the accompanying expression, which is hopefully true. If the expression is false, Python raises an AssertionError exception.
The syntax for assert is:
assert Expression[, Arguments]
If the assertion fails, Python uses ArgumentExpression as the argument for the AssertionError. AssertionError exceptions can be caught and handled like any other exception using the try-except statement, but if not handled, they will terminate the program and produce a traceback.
Here is a function that converts a temperature from degrees Kelvin to degrees Fahrenheit. Since zero degrees Kelvin is as cold as it gets, the function bails out if it sees a negative temperature:
#!/usr/bin/python3
def KelvinToFahrenheit(Temperature):
assert (Temperature >= 0),"Colder than absolute zero!"
return ((Temperature-273)*1.8)+32
print (KelvinToFahrenheit(273))
print (int(KelvinToFahrenheit(505.78)))
print (KelvinToFahrenheit(-5))
When the above code is executed, it produces the following result:
32.0
451
Traceback (most recent call last):
File "test.py", line 9, in <module>
print KelvinToFahrenheit(-5)
File "test.py", line 4, in KelvinToFahrenheit
assert (Temperature >= 0),"Colder than absolute zero!"
AssertionError: Colder than absolute zero!
187 Lectures
17.5 hours
Malhar Lathkar
55 Lectures
8 hours
Arnab Chakraborty
136 Lectures
11 hours
In28Minutes Official
75 Lectures
13 hours
Eduonix Learning Solutions
70 Lectures
8.5 hours
Lets Kode It
63 Lectures
6 hours
Abhilash Nelson
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2457,
"s": 2340,
"text": "An assertion is a sanity-check that you can turn on or turn off when you are done with your testing of the program."
},
{
"code": null,
"e": 2672,
"s": 2457,
"text": "The easiest way to think of an assertion is to liken it to a raise-if statement (or to be more accurate, a raise-if-not statement). An expression is tested, and if the result comes up false, an exception is raised."
},
{
"code": null,
"e": 2781,
"s": 2672,
"text": "Assertions are carried out by the assert statement, the newest keyword to Python, introduced in version 1.5."
},
{
"code": null,
"e": 2922,
"s": 2781,
"text": "Programmers often place assertions at the start of a function to check for valid input, and after a function call to check for valid output."
},
{
"code": null,
"e": 3104,
"s": 2922,
"text": "When it encounters an assert statement, Python evaluates the accompanying expression, which is hopefully true. If the expression is false, Python raises an AssertionError exception."
},
{
"code": null,
"e": 3130,
"s": 3104,
"text": "The syntax for assert is:"
},
{
"code": null,
"e": 3161,
"s": 3130,
"text": "assert Expression[, Arguments]"
},
{
"code": null,
"e": 3442,
"s": 3161,
"text": "If the assertion fails, Python uses ArgumentExpression as the argument for the AssertionError. AssertionError exceptions can be caught and handled like any other exception using the try-except statement, but if not handled, they will terminate the program and produce a traceback."
},
{
"code": null,
"e": 3639,
"s": 3442,
"text": "Here is a function that converts a temperature from degrees Kelvin to degrees Fahrenheit. Since zero degrees Kelvin is as cold as it gets, the function bails out if it sees a negative temperature:"
},
{
"code": null,
"e": 3895,
"s": 3639,
"text": "#!/usr/bin/python3\n\ndef KelvinToFahrenheit(Temperature):\n assert (Temperature >= 0),\"Colder than absolute zero!\"\n return ((Temperature-273)*1.8)+32\n\nprint (KelvinToFahrenheit(273))\nprint (int(KelvinToFahrenheit(505.78)))\nprint (KelvinToFahrenheit(-5))"
},
{
"code": null,
"e": 3963,
"s": 3895,
"text": "When the above code is executed, it produces the following result:"
},
{
"code": null,
"e": 4228,
"s": 3963,
"text": "32.0\n451\nTraceback (most recent call last):\n File \"test.py\", line 9, in <module>\n print KelvinToFahrenheit(-5)\n File \"test.py\", line 4, in KelvinToFahrenheit\n assert (Temperature >= 0),\"Colder than absolute zero!\"\nAssertionError: Colder than absolute zero!"
},
{
"code": null,
"e": 4265,
"s": 4228,
"text": "\n 187 Lectures \n 17.5 hours \n"
},
{
"code": null,
"e": 4281,
"s": 4265,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 4314,
"s": 4281,
"text": "\n 55 Lectures \n 8 hours \n"
},
{
"code": null,
"e": 4333,
"s": 4314,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 4368,
"s": 4333,
"text": "\n 136 Lectures \n 11 hours \n"
},
{
"code": null,
"e": 4390,
"s": 4368,
"text": " In28Minutes Official"
},
{
"code": null,
"e": 4424,
"s": 4390,
"text": "\n 75 Lectures \n 13 hours \n"
},
{
"code": null,
"e": 4452,
"s": 4424,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 4487,
"s": 4452,
"text": "\n 70 Lectures \n 8.5 hours \n"
},
{
"code": null,
"e": 4501,
"s": 4487,
"text": " Lets Kode It"
},
{
"code": null,
"e": 4534,
"s": 4501,
"text": "\n 63 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 4551,
"s": 4534,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 4558,
"s": 4551,
"text": " Print"
},
{
"code": null,
"e": 4569,
"s": 4558,
"text": " Add Notes"
}
] |
Absolute Difference of all pairwise consecutive elements in an array - GeeksforGeeks
|
26 Oct, 2021
Given an array of integers of N elements. The task is to print the absolute difference of all of the pairwise consecutive elements.Pairwise consecutive pairs of an array of size N are (a[i], a[i+1]) for all i ranging from 0 to N-2Examples:
Input: arr[] = {8, 5, 4, 3, 15, 20}
Output: 3, 1, 1, 12, 5
Input: arr[] = {5, 10, 15, 20}
Output: 5, 5, 5
Approach: The solution is to traverse the array and calculate and print the absolute difference of every pair (arr[i], arr[i+1]).Below is the implementation of the above approach:
C++
Java
Python 3
C#
PHP
Javascript
// C++ program to print the absolute// difference of the consecutive elements#include <iostream>using namespace std; // Function to print pairwise absolute// difference of consecutive elementsvoid pairwiseDifference(int arr[], int n){ int diff; for (int i = 0; i < n - 1; i++) { // absolute difference between // consecutive numbers diff = abs(arr[i] - arr[i + 1]); cout << diff << " "; }} // Driver Codeint main(){ int arr[] = { 4, 10, 15, 5, 6 }; int n = sizeof(arr) / sizeof(arr[0]); pairwiseDifference(arr, n); return 0;}
// Java program to print the absolute// difference of the consecutive elements class GFG{// Function to print pairwise absolute// difference of consecutive elementsstatic void pairwiseDifference(int arr[], int n){ int diff; for (int i = 0; i < n - 1; i++) { // absolute difference between // consecutive numbers diff = Math.abs(arr[i] - arr[i + 1]); System.out.print(diff+" "); }} // Driver Codepublic static void main(String[] args){ int arr[] = { 4, 10, 15, 5, 6 }; int n = arr.length; pairwiseDifference(arr, n);}}// This code is contributed by mits
# Python 3 program to print the absolute# difference of the consecutive elements # Function to print pairwise absolute# difference of consecutive elementsdef pairwiseDifference(arr, n): for i in range(n - 1) : # absolute difference between # consecutive numbers diff = abs(arr[i] - arr[i + 1]) print(diff , end = " ") # Driver Codeif __name__=="__main__": arr = [ 4, 10, 15, 5, 6 ] n = len(arr) pairwiseDifference(arr, n) # This code is contributed# by ChitraNayal
// C# program to print the absolute// difference of the consecutive elementsusing System; class GFG{// Function to print pairwise absolute// difference of consecutive elementsstatic void pairwiseDifference(int []arr, int n){ int diff; for (int i = 0; i < n - 1; i++) { // absolute difference between // consecutive numbers diff = Math.Abs(arr[i] - arr[i + 1]); Console.WriteLine(diff+" "); }} // Driver Codepublic static void Main(String[] args){ int []arr = { 4, 10, 15, 5, 6 }; int n = arr.Length; pairwiseDifference(arr, n);}}
<?php// PHP program to print the absolute// difference of the consecutive elements // Function to print pairwise absolute// difference of consecutive elementsfunction pairwiseDifference($arr, $n){ $diff = 0; for ($i = 0; $i < $n - 1; $i++) { // absolute difference between // consecutive numbers $diff = abs($arr[$i] - $arr[$i + 1]); echo $diff." "; }} // Driver Code$arr = array( 4, 10, 15, 5, 6 );$n = sizeof($arr); pairwiseDifference($arr, $n); // This code is contributed by mits?>
<script>// javascript program to print the absolute// difference of the consecutive elements // Function to print pairwise absolute // difference of consecutive elements function pairwiseDifference(arr , n) { var diff; for (i = 0; i < n - 1; i++) { // absolute difference between // consecutive numbers diff = Math.abs(arr[i] - arr[i + 1]); document.write(diff + " "); } } // Driver Code var arr = [ 4, 10, 15, 5, 6 ]; var n = arr.length; pairwiseDifference(arr, n); // This code contributed by umadevi9616</script>
6 5 10 1
Time complexity : O(n)
Mithun Kumar
ukasp
ankita_saini
VishalBachchas
umadevi9616
Kirti_Mangal
Technical Scripter 2018
Arrays
Mathematical
School Programming
Technical Scripter
Arrays
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Stack Data Structure (Introduction and Program)
Top 50 Array Coding Problems for Interviews
Introduction to Arrays
Multidimensional Arrays in Java
Linear Search
Program for Fibonacci numbers
C++ Data Types
Write a program to print all permutations of a given string
Set in C++ Standard Template Library (STL)
Coin Change | DP-7
|
[
{
"code": null,
"e": 24878,
"s": 24850,
"text": "\n26 Oct, 2021"
},
{
"code": null,
"e": 25120,
"s": 24878,
"text": "Given an array of integers of N elements. The task is to print the absolute difference of all of the pairwise consecutive elements.Pairwise consecutive pairs of an array of size N are (a[i], a[i+1]) for all i ranging from 0 to N-2Examples: "
},
{
"code": null,
"e": 25227,
"s": 25120,
"text": "Input: arr[] = {8, 5, 4, 3, 15, 20}\nOutput: 3, 1, 1, 12, 5\n\nInput: arr[] = {5, 10, 15, 20}\nOutput: 5, 5, 5"
},
{
"code": null,
"e": 25411,
"s": 25229,
"text": "Approach: The solution is to traverse the array and calculate and print the absolute difference of every pair (arr[i], arr[i+1]).Below is the implementation of the above approach: "
},
{
"code": null,
"e": 25415,
"s": 25411,
"text": "C++"
},
{
"code": null,
"e": 25420,
"s": 25415,
"text": "Java"
},
{
"code": null,
"e": 25429,
"s": 25420,
"text": "Python 3"
},
{
"code": null,
"e": 25432,
"s": 25429,
"text": "C#"
},
{
"code": null,
"e": 25436,
"s": 25432,
"text": "PHP"
},
{
"code": null,
"e": 25447,
"s": 25436,
"text": "Javascript"
},
{
"code": "// C++ program to print the absolute// difference of the consecutive elements#include <iostream>using namespace std; // Function to print pairwise absolute// difference of consecutive elementsvoid pairwiseDifference(int arr[], int n){ int diff; for (int i = 0; i < n - 1; i++) { // absolute difference between // consecutive numbers diff = abs(arr[i] - arr[i + 1]); cout << diff << \" \"; }} // Driver Codeint main(){ int arr[] = { 4, 10, 15, 5, 6 }; int n = sizeof(arr) / sizeof(arr[0]); pairwiseDifference(arr, n); return 0;}",
"e": 26025,
"s": 25447,
"text": null
},
{
"code": "// Java program to print the absolute// difference of the consecutive elements class GFG{// Function to print pairwise absolute// difference of consecutive elementsstatic void pairwiseDifference(int arr[], int n){ int diff; for (int i = 0; i < n - 1; i++) { // absolute difference between // consecutive numbers diff = Math.abs(arr[i] - arr[i + 1]); System.out.print(diff+\" \"); }} // Driver Codepublic static void main(String[] args){ int arr[] = { 4, 10, 15, 5, 6 }; int n = arr.length; pairwiseDifference(arr, n);}}// This code is contributed by mits",
"e": 26626,
"s": 26025,
"text": null
},
{
"code": "# Python 3 program to print the absolute# difference of the consecutive elements # Function to print pairwise absolute# difference of consecutive elementsdef pairwiseDifference(arr, n): for i in range(n - 1) : # absolute difference between # consecutive numbers diff = abs(arr[i] - arr[i + 1]) print(diff , end = \" \") # Driver Codeif __name__==\"__main__\": arr = [ 4, 10, 15, 5, 6 ] n = len(arr) pairwiseDifference(arr, n) # This code is contributed# by ChitraNayal",
"e": 27138,
"s": 26626,
"text": null
},
{
"code": "// C# program to print the absolute// difference of the consecutive elementsusing System; class GFG{// Function to print pairwise absolute// difference of consecutive elementsstatic void pairwiseDifference(int []arr, int n){ int diff; for (int i = 0; i < n - 1; i++) { // absolute difference between // consecutive numbers diff = Math.Abs(arr[i] - arr[i + 1]); Console.WriteLine(diff+\" \"); }} // Driver Codepublic static void Main(String[] args){ int []arr = { 4, 10, 15, 5, 6 }; int n = arr.Length; pairwiseDifference(arr, n);}}",
"e": 27716,
"s": 27138,
"text": null
},
{
"code": "<?php// PHP program to print the absolute// difference of the consecutive elements // Function to print pairwise absolute// difference of consecutive elementsfunction pairwiseDifference($arr, $n){ $diff = 0; for ($i = 0; $i < $n - 1; $i++) { // absolute difference between // consecutive numbers $diff = abs($arr[$i] - $arr[$i + 1]); echo $diff.\" \"; }} // Driver Code$arr = array( 4, 10, 15, 5, 6 );$n = sizeof($arr); pairwiseDifference($arr, $n); // This code is contributed by mits?>",
"e": 28243,
"s": 27716,
"text": null
},
{
"code": "<script>// javascript program to print the absolute// difference of the consecutive elements // Function to print pairwise absolute // difference of consecutive elements function pairwiseDifference(arr , n) { var diff; for (i = 0; i < n - 1; i++) { // absolute difference between // consecutive numbers diff = Math.abs(arr[i] - arr[i + 1]); document.write(diff + \" \"); } } // Driver Code var arr = [ 4, 10, 15, 5, 6 ]; var n = arr.length; pairwiseDifference(arr, n); // This code contributed by umadevi9616</script>",
"e": 28868,
"s": 28243,
"text": null
},
{
"code": null,
"e": 28877,
"s": 28868,
"text": "6 5 10 1"
},
{
"code": null,
"e": 28903,
"s": 28879,
"text": "Time complexity : O(n) "
},
{
"code": null,
"e": 28916,
"s": 28903,
"text": "Mithun Kumar"
},
{
"code": null,
"e": 28922,
"s": 28916,
"text": "ukasp"
},
{
"code": null,
"e": 28935,
"s": 28922,
"text": "ankita_saini"
},
{
"code": null,
"e": 28950,
"s": 28935,
"text": "VishalBachchas"
},
{
"code": null,
"e": 28962,
"s": 28950,
"text": "umadevi9616"
},
{
"code": null,
"e": 28975,
"s": 28962,
"text": "Kirti_Mangal"
},
{
"code": null,
"e": 28999,
"s": 28975,
"text": "Technical Scripter 2018"
},
{
"code": null,
"e": 29006,
"s": 28999,
"text": "Arrays"
},
{
"code": null,
"e": 29019,
"s": 29006,
"text": "Mathematical"
},
{
"code": null,
"e": 29038,
"s": 29019,
"text": "School Programming"
},
{
"code": null,
"e": 29057,
"s": 29038,
"text": "Technical Scripter"
},
{
"code": null,
"e": 29064,
"s": 29057,
"text": "Arrays"
},
{
"code": null,
"e": 29077,
"s": 29064,
"text": "Mathematical"
},
{
"code": null,
"e": 29175,
"s": 29077,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29184,
"s": 29175,
"text": "Comments"
},
{
"code": null,
"e": 29197,
"s": 29184,
"text": "Old Comments"
},
{
"code": null,
"e": 29245,
"s": 29197,
"text": "Stack Data Structure (Introduction and Program)"
},
{
"code": null,
"e": 29289,
"s": 29245,
"text": "Top 50 Array Coding Problems for Interviews"
},
{
"code": null,
"e": 29312,
"s": 29289,
"text": "Introduction to Arrays"
},
{
"code": null,
"e": 29344,
"s": 29312,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 29358,
"s": 29344,
"text": "Linear Search"
},
{
"code": null,
"e": 29388,
"s": 29358,
"text": "Program for Fibonacci numbers"
},
{
"code": null,
"e": 29403,
"s": 29388,
"text": "C++ Data Types"
},
{
"code": null,
"e": 29463,
"s": 29403,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 29506,
"s": 29463,
"text": "Set in C++ Standard Template Library (STL)"
}
] |
Essential guide to Impute Missing Values in a single line of Python code | by Satyam Kumar | Towards Data Science
|
A real-world dataset often has a lot of missing records that may be caused due to data corruption or failure to record the values. To train a robust machine learning model handling of missing values is essential during the feature engineering pipeline.
There are various imputation strategies that can be used to impute missing records for categorical, numerical, or time-series features. You can refer to one of my previous articles where I have discussed 7 strategies or techniques to handle missing records in the dataset.
In this article, we will discuss the implementation of an open-source Python library — missingpy that predicts missing values in a numerical feature using Random forest and k-NN based models.
missingpy is an open-source python library that imputes missing data using prediction-based Imputation strategies. It has an API similar to that of scikit-learn, so developers can find the interface familiar. As of now, missingpy only supports Random Forest and k-NN based Imputation strategies.
We will be using few features from the Credit card fraud detection dataset from Kaggle to impute the missing records and compare the performance of the missingpy library.
missingpy can be installed from PyPI using:
pip install missingpy
KNNImputer() and MissForest() are two API from the missingpy package.
We will be using only 8 features and 25,000 instances from the credit card detection dataset for further demonstration. As the dataset does not have missing records, we will create a copy of the ‘Amount’ feature and replace the actual values with NaN values.
After preparing the data, the copy of the ‘Amount’ feature ‘Amount_with_NaN’ has 4,512 null records out of a total sample data of 25,000 records.
missingpy comes with a Random Forest-based imputation model that can be implemented in a single line of Python code using MissForest() function.
from missingpy import MissForestimputer = MissForest()df_new = imputer.fit_transform(df)
After instantiating the MissForest model, fit the dataset having missing records. The fit_transform() the method returns the dataset along with the imputed values.
Now, let’s compare the Imputed values with the real values of the ‘Amount’ feature and see the deviation of the Imputation.
Concluding from the above plots,
Left Image: we can observe that the predicted missing data and actual amount have similar PDF plots.
Right Image: The PDF plot of the deviation between the actual values and predicted missing records is skewed and peaked at a value of 0. We have long tails that represent very few predictions that are deviated by more than 100 values.
Now, let's see some statistical figures to observe how the MissForest Imputation has performed.
The implementation of the KNNImputer is the same as that of MissForest Imputation. Now let's straight away jump to implementation and generating PDF plots.
from missingpy import KNNImputerimputer = KNNImputer()df_new = imputer.fit_transform(df)
The MissForest (Random Forest-based Imputation) and KNNImputer (k-NN based Imputation) perform almost similarly giving similar statistical figures for imputed values and deviation from its actual values. In terms of RMSE metrics, the KNNImputer seems to perform a bit better.
missingpy library is a very handy tool to predict the missing data in few lines of Python code. The API implementation of the package is similar to that of scikit-learn, which makes developers familiar with the interface.
Read my previous article, to know 7 techniques to handle missing values in your dataset
towardsdatascience.com
[1] missingpy documentation: https://pypi.org/project/missingpy/
Thank You for Reading
|
[
{
"code": null,
"e": 425,
"s": 172,
"text": "A real-world dataset often has a lot of missing records that may be caused due to data corruption or failure to record the values. To train a robust machine learning model handling of missing values is essential during the feature engineering pipeline."
},
{
"code": null,
"e": 698,
"s": 425,
"text": "There are various imputation strategies that can be used to impute missing records for categorical, numerical, or time-series features. You can refer to one of my previous articles where I have discussed 7 strategies or techniques to handle missing records in the dataset."
},
{
"code": null,
"e": 890,
"s": 698,
"text": "In this article, we will discuss the implementation of an open-source Python library — missingpy that predicts missing values in a numerical feature using Random forest and k-NN based models."
},
{
"code": null,
"e": 1186,
"s": 890,
"text": "missingpy is an open-source python library that imputes missing data using prediction-based Imputation strategies. It has an API similar to that of scikit-learn, so developers can find the interface familiar. As of now, missingpy only supports Random Forest and k-NN based Imputation strategies."
},
{
"code": null,
"e": 1357,
"s": 1186,
"text": "We will be using few features from the Credit card fraud detection dataset from Kaggle to impute the missing records and compare the performance of the missingpy library."
},
{
"code": null,
"e": 1401,
"s": 1357,
"text": "missingpy can be installed from PyPI using:"
},
{
"code": null,
"e": 1423,
"s": 1401,
"text": "pip install missingpy"
},
{
"code": null,
"e": 1493,
"s": 1423,
"text": "KNNImputer() and MissForest() are two API from the missingpy package."
},
{
"code": null,
"e": 1752,
"s": 1493,
"text": "We will be using only 8 features and 25,000 instances from the credit card detection dataset for further demonstration. As the dataset does not have missing records, we will create a copy of the ‘Amount’ feature and replace the actual values with NaN values."
},
{
"code": null,
"e": 1898,
"s": 1752,
"text": "After preparing the data, the copy of the ‘Amount’ feature ‘Amount_with_NaN’ has 4,512 null records out of a total sample data of 25,000 records."
},
{
"code": null,
"e": 2043,
"s": 1898,
"text": "missingpy comes with a Random Forest-based imputation model that can be implemented in a single line of Python code using MissForest() function."
},
{
"code": null,
"e": 2132,
"s": 2043,
"text": "from missingpy import MissForestimputer = MissForest()df_new = imputer.fit_transform(df)"
},
{
"code": null,
"e": 2296,
"s": 2132,
"text": "After instantiating the MissForest model, fit the dataset having missing records. The fit_transform() the method returns the dataset along with the imputed values."
},
{
"code": null,
"e": 2420,
"s": 2296,
"text": "Now, let’s compare the Imputed values with the real values of the ‘Amount’ feature and see the deviation of the Imputation."
},
{
"code": null,
"e": 2453,
"s": 2420,
"text": "Concluding from the above plots,"
},
{
"code": null,
"e": 2554,
"s": 2453,
"text": "Left Image: we can observe that the predicted missing data and actual amount have similar PDF plots."
},
{
"code": null,
"e": 2789,
"s": 2554,
"text": "Right Image: The PDF plot of the deviation between the actual values and predicted missing records is skewed and peaked at a value of 0. We have long tails that represent very few predictions that are deviated by more than 100 values."
},
{
"code": null,
"e": 2885,
"s": 2789,
"text": "Now, let's see some statistical figures to observe how the MissForest Imputation has performed."
},
{
"code": null,
"e": 3041,
"s": 2885,
"text": "The implementation of the KNNImputer is the same as that of MissForest Imputation. Now let's straight away jump to implementation and generating PDF plots."
},
{
"code": null,
"e": 3130,
"s": 3041,
"text": "from missingpy import KNNImputerimputer = KNNImputer()df_new = imputer.fit_transform(df)"
},
{
"code": null,
"e": 3406,
"s": 3130,
"text": "The MissForest (Random Forest-based Imputation) and KNNImputer (k-NN based Imputation) perform almost similarly giving similar statistical figures for imputed values and deviation from its actual values. In terms of RMSE metrics, the KNNImputer seems to perform a bit better."
},
{
"code": null,
"e": 3628,
"s": 3406,
"text": "missingpy library is a very handy tool to predict the missing data in few lines of Python code. The API implementation of the package is similar to that of scikit-learn, which makes developers familiar with the interface."
},
{
"code": null,
"e": 3716,
"s": 3628,
"text": "Read my previous article, to know 7 techniques to handle missing values in your dataset"
},
{
"code": null,
"e": 3739,
"s": 3716,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 3804,
"s": 3739,
"text": "[1] missingpy documentation: https://pypi.org/project/missingpy/"
}
] |
HSQLDB - Indexes
|
A database index is a data structure that improves the speed of operations in a table. Indexes can be created using one or more columns, providing the basis for both rapid random lookups and efficient ordering of access to the records.
While creating an index, it should be considered what are the columns which will be used to make SQL queries, and create one or more indexes on those columns.
Practically, indexes are also type of tables, which keep the primary key or the index field and a pointer to each record into the actual table.
The users cannot see the indexes. They are just used to speed up queries and will be used by the Database Search Engine to quickly locate records.
The INSERT and UPDATE statements take more time on tables having indexes, whereas SELECT statements run faster on those tables. The reason being while inserting or updating, the database needs to insert or update the index values as well.
You can create a unique index on a table. A unique index means that two rows cannot have the same index value. Following is the syntax to create an Index on a table.
CREATE UNIQUE INDEX index_name
ON table_name (column1, column2,...);
You can use one or more columns to create an index. For example, create an index on tutorials_tbl using tutorial_author.
CREATE UNIQUE INDEX AUTHOR_INDEX
ON tutorials_tbl (tutorial_author)
You can create a simple index on a table. Just omit the UNIQUE keyword from the query to create a simple index. A simple index allows duplicate values in a table.
If you want to index the values in a column in a descending order, you can add the reserved word DESC after the column name.
CREATE UNIQUE INDEX AUTHOR_INDEX
ON tutorials_tbl (tutorial_author DESC)
There are four types of statements for adding indexes to a table −
ALTER TABLE tbl_name ADD PRIMARY KEY (column_list) − This statement adds a PRIMARY KEY, which means that indexed values must be unique and cannot be NULL.
ALTER TABLE tbl_name ADD PRIMARY KEY (column_list) − This statement adds a PRIMARY KEY, which means that indexed values must be unique and cannot be NULL.
ALTER TABLE tbl_name ADD UNIQUE index_name (column_list) − This statement creates an index for which the values must be unique (with the exception of NULL values, which may appear multiple times).
ALTER TABLE tbl_name ADD UNIQUE index_name (column_list) − This statement creates an index for which the values must be unique (with the exception of NULL values, which may appear multiple times).
ALTER TABLE tbl_name ADD INDEX index_name (column_list) − This adds an ordinary index in which any value may appear more than once.
ALTER TABLE tbl_name ADD INDEX index_name (column_list) − This adds an ordinary index in which any value may appear more than once.
ALTER TABLE tbl_name ADD FULLTEXT index_name (column_list) − This creates a special FULLTEXT index that is used for text-searching purposes.
ALTER TABLE tbl_name ADD FULLTEXT index_name (column_list) − This creates a special FULLTEXT index that is used for text-searching purposes.
Following is the query to add index in an existing table.
ALTER TABLE testalter_tbl ADD INDEX (c);
You can drop any INDEX by using the DROP clause along with the ALTER command. Following is the query to drop the above-created index.
ALTER TABLE testalter_tbl DROP INDEX (c);
You can use the SHOW INDEX command to list out all the indexes associated with a table. Vertical-format output (specified by \G) often is useful with this statement, to avoid long line wraparound.
Following is the generic syntax to display the index information about a table.
SHOW INDEX FROM table_name\G
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2218,
"s": 1982,
"text": "A database index is a data structure that improves the speed of operations in a table. Indexes can be created using one or more columns, providing the basis for both rapid random lookups and efficient ordering of access to the records."
},
{
"code": null,
"e": 2377,
"s": 2218,
"text": "While creating an index, it should be considered what are the columns which will be used to make SQL queries, and create one or more indexes on those columns."
},
{
"code": null,
"e": 2521,
"s": 2377,
"text": "Practically, indexes are also type of tables, which keep the primary key or the index field and a pointer to each record into the actual table."
},
{
"code": null,
"e": 2668,
"s": 2521,
"text": "The users cannot see the indexes. They are just used to speed up queries and will be used by the Database Search Engine to quickly locate records."
},
{
"code": null,
"e": 2907,
"s": 2668,
"text": "The INSERT and UPDATE statements take more time on tables having indexes, whereas SELECT statements run faster on those tables. The reason being while inserting or updating, the database needs to insert or update the index values as well."
},
{
"code": null,
"e": 3073,
"s": 2907,
"text": "You can create a unique index on a table. A unique index means that two rows cannot have the same index value. Following is the syntax to create an Index on a table."
},
{
"code": null,
"e": 3143,
"s": 3073,
"text": "CREATE UNIQUE INDEX index_name\nON table_name (column1, column2,...);\n"
},
{
"code": null,
"e": 3264,
"s": 3143,
"text": "You can use one or more columns to create an index. For example, create an index on tutorials_tbl using tutorial_author."
},
{
"code": null,
"e": 3333,
"s": 3264,
"text": "CREATE UNIQUE INDEX AUTHOR_INDEX\nON tutorials_tbl (tutorial_author)\n"
},
{
"code": null,
"e": 3496,
"s": 3333,
"text": "You can create a simple index on a table. Just omit the UNIQUE keyword from the query to create a simple index. A simple index allows duplicate values in a table."
},
{
"code": null,
"e": 3621,
"s": 3496,
"text": "If you want to index the values in a column in a descending order, you can add the reserved word DESC after the column name."
},
{
"code": null,
"e": 3695,
"s": 3621,
"text": "CREATE UNIQUE INDEX AUTHOR_INDEX\nON tutorials_tbl (tutorial_author DESC)\n"
},
{
"code": null,
"e": 3762,
"s": 3695,
"text": "There are four types of statements for adding indexes to a table −"
},
{
"code": null,
"e": 3917,
"s": 3762,
"text": "ALTER TABLE tbl_name ADD PRIMARY KEY (column_list) − This statement adds a PRIMARY KEY, which means that indexed values must be unique and cannot be NULL."
},
{
"code": null,
"e": 4072,
"s": 3917,
"text": "ALTER TABLE tbl_name ADD PRIMARY KEY (column_list) − This statement adds a PRIMARY KEY, which means that indexed values must be unique and cannot be NULL."
},
{
"code": null,
"e": 4269,
"s": 4072,
"text": "ALTER TABLE tbl_name ADD UNIQUE index_name (column_list) − This statement creates an index for which the values must be unique (with the exception of NULL values, which may appear multiple times)."
},
{
"code": null,
"e": 4466,
"s": 4269,
"text": "ALTER TABLE tbl_name ADD UNIQUE index_name (column_list) − This statement creates an index for which the values must be unique (with the exception of NULL values, which may appear multiple times)."
},
{
"code": null,
"e": 4598,
"s": 4466,
"text": "ALTER TABLE tbl_name ADD INDEX index_name (column_list) − This adds an ordinary index in which any value may appear more than once."
},
{
"code": null,
"e": 4730,
"s": 4598,
"text": "ALTER TABLE tbl_name ADD INDEX index_name (column_list) − This adds an ordinary index in which any value may appear more than once."
},
{
"code": null,
"e": 4871,
"s": 4730,
"text": "ALTER TABLE tbl_name ADD FULLTEXT index_name (column_list) − This creates a special FULLTEXT index that is used for text-searching purposes."
},
{
"code": null,
"e": 5012,
"s": 4871,
"text": "ALTER TABLE tbl_name ADD FULLTEXT index_name (column_list) − This creates a special FULLTEXT index that is used for text-searching purposes."
},
{
"code": null,
"e": 5070,
"s": 5012,
"text": "Following is the query to add index in an existing table."
},
{
"code": null,
"e": 5112,
"s": 5070,
"text": "ALTER TABLE testalter_tbl ADD INDEX (c);\n"
},
{
"code": null,
"e": 5246,
"s": 5112,
"text": "You can drop any INDEX by using the DROP clause along with the ALTER command. Following is the query to drop the above-created index."
},
{
"code": null,
"e": 5289,
"s": 5246,
"text": "ALTER TABLE testalter_tbl DROP INDEX (c);\n"
},
{
"code": null,
"e": 5486,
"s": 5289,
"text": "You can use the SHOW INDEX command to list out all the indexes associated with a table. Vertical-format output (specified by \\G) often is useful with this statement, to avoid long line wraparound."
},
{
"code": null,
"e": 5566,
"s": 5486,
"text": "Following is the generic syntax to display the index information about a table."
},
{
"code": null,
"e": 5596,
"s": 5566,
"text": "SHOW INDEX FROM table_name\\G\n"
},
{
"code": null,
"e": 5603,
"s": 5596,
"text": " Print"
},
{
"code": null,
"e": 5614,
"s": 5603,
"text": " Add Notes"
}
] |
HTTP headers | Content-Language - GeeksforGeeks
|
23 Oct, 2019
HTTP headers are used to provide additional information in HTTP request and HTTP response. HTTP headers Content-Language is used to define, which language speaker document is intended to. It doesn’t define the language of the document. In case this header is not specified, it is assumed that the document is intended for all language speakers.
Syntax:
When only one language is specifiedContent-Language: <language-tag>
Content-Language: <language-tag>
When multiple languages are specifiedContent-Language: <language-tag>, <language-tag>, <language-tag>
Content-Language: <language-tag>, <language-tag>, <language-tag>
Directive:
language-tag: It is the case-insensitive directive which defines the language. Generally, it consists of two parts. First part defines the primary language which defines a broad family of related languages (e.g., “en” = English) and the optional second part which is separated by “-” and used to narrow the language range.
Example:
It says that English speakers are the intended audience of the page.Content-Language: en
Content-Language: en
It says that German and English speakers are the intended audience of the page.Content-Language: de, en
Content-Language: de, en
To check the Content-language in action go to Inspect Element -> Network check the request header for content-language like below.
Supported Browsers: The browsers compatible with HTTP headers Content-language are listed below:
Google Chrome
Internet Explorer
Firefox
Safari
Opera
HTTP-headers
Picked
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Top 10 Front End Developer Skills That You Need in 2022
How to fetch data from an API in ReactJS ?
Difference between var, let and const keywords in JavaScript
Convert a string to an integer in JavaScript
Differences between Functional Components and Class Components in React
How to set the default value for an HTML <select> element ?
How to create footer to stay at the bottom of a Web page?
Node.js fs.readFileSync() Method
File uploading in React.js
How to set input type date in dd-mm-yyyy format using HTML ?
|
[
{
"code": null,
"e": 24181,
"s": 24153,
"text": "\n23 Oct, 2019"
},
{
"code": null,
"e": 24526,
"s": 24181,
"text": "HTTP headers are used to provide additional information in HTTP request and HTTP response. HTTP headers Content-Language is used to define, which language speaker document is intended to. It doesn’t define the language of the document. In case this header is not specified, it is assumed that the document is intended for all language speakers."
},
{
"code": null,
"e": 24534,
"s": 24526,
"text": "Syntax:"
},
{
"code": null,
"e": 24603,
"s": 24534,
"text": "When only one language is specifiedContent-Language: <language-tag>\n"
},
{
"code": null,
"e": 24637,
"s": 24603,
"text": "Content-Language: <language-tag>\n"
},
{
"code": null,
"e": 24740,
"s": 24637,
"text": "When multiple languages are specifiedContent-Language: <language-tag>, <language-tag>, <language-tag>\n"
},
{
"code": null,
"e": 24806,
"s": 24740,
"text": "Content-Language: <language-tag>, <language-tag>, <language-tag>\n"
},
{
"code": null,
"e": 24817,
"s": 24806,
"text": "Directive:"
},
{
"code": null,
"e": 25140,
"s": 24817,
"text": "language-tag: It is the case-insensitive directive which defines the language. Generally, it consists of two parts. First part defines the primary language which defines a broad family of related languages (e.g., “en” = English) and the optional second part which is separated by “-” and used to narrow the language range."
},
{
"code": null,
"e": 25149,
"s": 25140,
"text": "Example:"
},
{
"code": null,
"e": 25238,
"s": 25149,
"text": "It says that English speakers are the intended audience of the page.Content-Language: en"
},
{
"code": null,
"e": 25259,
"s": 25238,
"text": "Content-Language: en"
},
{
"code": null,
"e": 25363,
"s": 25259,
"text": "It says that German and English speakers are the intended audience of the page.Content-Language: de, en"
},
{
"code": null,
"e": 25388,
"s": 25363,
"text": "Content-Language: de, en"
},
{
"code": null,
"e": 25519,
"s": 25388,
"text": "To check the Content-language in action go to Inspect Element -> Network check the request header for content-language like below."
},
{
"code": null,
"e": 25616,
"s": 25519,
"text": "Supported Browsers: The browsers compatible with HTTP headers Content-language are listed below:"
},
{
"code": null,
"e": 25630,
"s": 25616,
"text": "Google Chrome"
},
{
"code": null,
"e": 25648,
"s": 25630,
"text": "Internet Explorer"
},
{
"code": null,
"e": 25656,
"s": 25648,
"text": "Firefox"
},
{
"code": null,
"e": 25663,
"s": 25656,
"text": "Safari"
},
{
"code": null,
"e": 25669,
"s": 25663,
"text": "Opera"
},
{
"code": null,
"e": 25682,
"s": 25669,
"text": "HTTP-headers"
},
{
"code": null,
"e": 25689,
"s": 25682,
"text": "Picked"
},
{
"code": null,
"e": 25706,
"s": 25689,
"text": "Web Technologies"
},
{
"code": null,
"e": 25804,
"s": 25706,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25813,
"s": 25804,
"text": "Comments"
},
{
"code": null,
"e": 25826,
"s": 25813,
"text": "Old Comments"
},
{
"code": null,
"e": 25882,
"s": 25826,
"text": "Top 10 Front End Developer Skills That You Need in 2022"
},
{
"code": null,
"e": 25925,
"s": 25882,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 25986,
"s": 25925,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 26031,
"s": 25986,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 26103,
"s": 26031,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 26163,
"s": 26103,
"text": "How to set the default value for an HTML <select> element ?"
},
{
"code": null,
"e": 26221,
"s": 26163,
"text": "How to create footer to stay at the bottom of a Web page?"
},
{
"code": null,
"e": 26254,
"s": 26221,
"text": "Node.js fs.readFileSync() Method"
},
{
"code": null,
"e": 26281,
"s": 26254,
"text": "File uploading in React.js"
}
] |
Malware Classification using Machine Learning | by Arpan Das | Towards Data Science
|
If you love to explore large and challenging data sets, then probably you should give Microsoft Malware Classification a try. Before diving deep in to the problem let’s take few points on what can you expect to learn from this:
How to handle large scale data? Total train data set consist of 200 GB data out of which 50 GB of data is .bytes files and 150 GB of data is .asm files.What feature engineering should you do? If till now you have been working only on text and image data, this will surely boost your intuitions on feature engineering.How to approach a machine learning problem without domain knowledge? In the words of the 1st place winners of this challenge: “Cross Validation is more trust worthy than domain knowledge”.
How to handle large scale data? Total train data set consist of 200 GB data out of which 50 GB of data is .bytes files and 150 GB of data is .asm files.
What feature engineering should you do? If till now you have been working only on text and image data, this will surely boost your intuitions on feature engineering.
How to approach a machine learning problem without domain knowledge? In the words of the 1st place winners of this challenge: “Cross Validation is more trust worthy than domain knowledge”.
Business Problem
In the past few years, the malware industry has grown very rapidly that, the syndicates invest heavily in technologies to evade traditional protection, forcing the anti-malware groups/communities to build more robust software to detect and terminate these attacks. The major part of protecting a computer system from a malware attack is to identify whether a given piece of file/software is a malware.
Machine Learning Problem, KPI and constraints
We can map the business problem to a multi-class classification problem, where we need to predict the class for each given byte files among nine categories (Ramnit, Lollipop, Kelihos_ver3, Vundo, Simda,Tracur, Kelihos_ver1, Obfuscator.ACY, Gatak).
KPI: multi-class log loss, confusion matrix
Constrains: We need to provide the class probability, wrongly classified class labels should be penalized(that’s why log loss has been chosen as KPI) and there should some latency bound.
Handling the Large Size
Keeping the scale of data in mind, It is advised to go for cloud platforms like GCP, AWS or IBM Cloud. We have completed this case study in GCP with Linux based 1vCPU box with 30 GB RAM and 500 GB HDD. Follow this link to know how you can download the data directly in GCP from jupyter notebook itself with the help of CurlWidget. After downloading the data the next challenge will be to extract these files using python as the python support for 7z files are limited. Go for a package called ‘p7zip’ which provides a Linux command line tool to extract 7z files.
# command to install the package in Linuxsudo apt-get install p7zip-full# Sample Command to extract the data from terminal7za x yourfile.tar.7z
The total data set is consists of 10,868 .bytes files and 10,868 asm files total 21,736 files. Byte files are a combination of 256 hex numbers (decimal value ranging between 0 to 255) and a special character(??). Asm files are assembly files obtained using smart compilers.The data set is unbalanced.
The total data set is consists of 10,868 .bytes files and 10,868 asm files total 21,736 files. Byte files are a combination of 256 hex numbers (decimal value ranging between 0 to 255) and a special character(??). Asm files are assembly files obtained using smart compilers.
The data set is unbalanced.
The good thing of this case study is, it demands a lot of patience and experiments to obtain the useful features. We have tried out the following features based on our intuitions and previous works on this field
n-gram features of byte files: We have tried uni-gram, bi-gram and tri-gram features. Though the performance with these features is good but the main challenge lies in handling their large dimensionality. The number of features with uni-gram is 256, with bi-gram it is 65531 and leaving the number of tri-gram features for your exercise. Even with the 30 GB RAM it is not possible to load the total data with 65531 features, so we went for SVD in chunk. First we tried out elbow method with random samples and 3000 features to check the number of components needed to preserve the variance and we found out 1000 as a good number.
n-gram features of byte files: We have tried uni-gram, bi-gram and tri-gram features. Though the performance with these features is good but the main challenge lies in handling their large dimensionality. The number of features with uni-gram is 256, with bi-gram it is 65531 and leaving the number of tri-gram features for your exercise. Even with the 30 GB RAM it is not possible to load the total data with 65531 features, so we went for SVD in chunk. First we tried out elbow method with random samples and 3000 features to check the number of components needed to preserve the variance and we found out 1000 as a good number.
2. Size of byte and asm files: Size of bytes and asm files turned out be be good features. Let’s take a look at the box plots of file sizes
3. Size of byte array: As we mentioned earlier,the byte files are consists of hexadecimal digits. For each files we have taken an array and added each elements in to the array and used the length of these arrays as a feature.
4. Segment count and n-grams of asm files: asm files consists of various segments like prefixes(ex. HEADER,TEXT), opcodes(ex. jmp, hlt), keywords(ex. .dll, std::), registers(ex. edx,epi) etc. We have taken the count of segments as a feature. We have also considered uni-gram, bi-gram and tri-gram of asm files as feature.
5. Pixel intensity of byte and asm features: This is probably the most innovative features of the case this case study. We have borrowed the concept from the 1st place winner solution.As we mentioned earlier the value of each elements in byte files is between 0 to 255. We can easily convert these byte files along with the asm files in to gray scale images. It is observed that the first 800 pixel densities of asm files have significant impact over the final result.
Let’s take a look how a random asm file looks after the conversion
By now you must have observed the dimension of the features and get a sense of the dimensionality of the final features for training. To cope up with the problem we have used random forest to select the important features. Number of important features is a hyper-parameter. We have tried various numbers based of our experiences and obviously there are scope of improvements. Let’s look at a sample code on this and how we have selected best tri-gram asm features. We have also tried t-SNE for multivariate analysis.
We have tried various linear machine learning models like KNN, multi-class logistic regression and ensembles like random forest, XGBoost and LightGBM with various combination of features. We have trained the models with single features, and a combination of byte features and asm features. We have also tried out various CNN architectures over the images obtained from byte and asm files but the obtained result was poorer compared to fine tuned machine learning models. As we did not have any domain knowledge on malware industry we have completely relied on cross validation. As the number of features and files were high, we have chosen RandomizedCV for cross validation and there are scope of improvements. Another question may come to your mind that why we have used both XGBoost and LightGBM? Actually we have started with XGBoost but found out that the training latency of LightGBM is much lower than XGBoost along with similar or better performance. We started with a random model then added the complexity of the model gradually after keeping an eye on the performance.
Finally a use case does not worth anything if it does not provide a satisfactory result. Here let’s list down only the result we obtained after calibrating our final LightGBM model.
|
[
{
"code": null,
"e": 400,
"s": 172,
"text": "If you love to explore large and challenging data sets, then probably you should give Microsoft Malware Classification a try. Before diving deep in to the problem let’s take few points on what can you expect to learn from this:"
},
{
"code": null,
"e": 906,
"s": 400,
"text": "How to handle large scale data? Total train data set consist of 200 GB data out of which 50 GB of data is .bytes files and 150 GB of data is .asm files.What feature engineering should you do? If till now you have been working only on text and image data, this will surely boost your intuitions on feature engineering.How to approach a machine learning problem without domain knowledge? In the words of the 1st place winners of this challenge: “Cross Validation is more trust worthy than domain knowledge”."
},
{
"code": null,
"e": 1059,
"s": 906,
"text": "How to handle large scale data? Total train data set consist of 200 GB data out of which 50 GB of data is .bytes files and 150 GB of data is .asm files."
},
{
"code": null,
"e": 1225,
"s": 1059,
"text": "What feature engineering should you do? If till now you have been working only on text and image data, this will surely boost your intuitions on feature engineering."
},
{
"code": null,
"e": 1414,
"s": 1225,
"text": "How to approach a machine learning problem without domain knowledge? In the words of the 1st place winners of this challenge: “Cross Validation is more trust worthy than domain knowledge”."
},
{
"code": null,
"e": 1431,
"s": 1414,
"text": "Business Problem"
},
{
"code": null,
"e": 1833,
"s": 1431,
"text": "In the past few years, the malware industry has grown very rapidly that, the syndicates invest heavily in technologies to evade traditional protection, forcing the anti-malware groups/communities to build more robust software to detect and terminate these attacks. The major part of protecting a computer system from a malware attack is to identify whether a given piece of file/software is a malware."
},
{
"code": null,
"e": 1879,
"s": 1833,
"text": "Machine Learning Problem, KPI and constraints"
},
{
"code": null,
"e": 2127,
"s": 1879,
"text": "We can map the business problem to a multi-class classification problem, where we need to predict the class for each given byte files among nine categories (Ramnit, Lollipop, Kelihos_ver3, Vundo, Simda,Tracur, Kelihos_ver1, Obfuscator.ACY, Gatak)."
},
{
"code": null,
"e": 2171,
"s": 2127,
"text": "KPI: multi-class log loss, confusion matrix"
},
{
"code": null,
"e": 2358,
"s": 2171,
"text": "Constrains: We need to provide the class probability, wrongly classified class labels should be penalized(that’s why log loss has been chosen as KPI) and there should some latency bound."
},
{
"code": null,
"e": 2382,
"s": 2358,
"text": "Handling the Large Size"
},
{
"code": null,
"e": 2945,
"s": 2382,
"text": "Keeping the scale of data in mind, It is advised to go for cloud platforms like GCP, AWS or IBM Cloud. We have completed this case study in GCP with Linux based 1vCPU box with 30 GB RAM and 500 GB HDD. Follow this link to know how you can download the data directly in GCP from jupyter notebook itself with the help of CurlWidget. After downloading the data the next challenge will be to extract these files using python as the python support for 7z files are limited. Go for a package called ‘p7zip’ which provides a Linux command line tool to extract 7z files."
},
{
"code": null,
"e": 3089,
"s": 2945,
"text": "# command to install the package in Linuxsudo apt-get install p7zip-full# Sample Command to extract the data from terminal7za x yourfile.tar.7z"
},
{
"code": null,
"e": 3390,
"s": 3089,
"text": "The total data set is consists of 10,868 .bytes files and 10,868 asm files total 21,736 files. Byte files are a combination of 256 hex numbers (decimal value ranging between 0 to 255) and a special character(??). Asm files are assembly files obtained using smart compilers.The data set is unbalanced."
},
{
"code": null,
"e": 3664,
"s": 3390,
"text": "The total data set is consists of 10,868 .bytes files and 10,868 asm files total 21,736 files. Byte files are a combination of 256 hex numbers (decimal value ranging between 0 to 255) and a special character(??). Asm files are assembly files obtained using smart compilers."
},
{
"code": null,
"e": 3692,
"s": 3664,
"text": "The data set is unbalanced."
},
{
"code": null,
"e": 3904,
"s": 3692,
"text": "The good thing of this case study is, it demands a lot of patience and experiments to obtain the useful features. We have tried out the following features based on our intuitions and previous works on this field"
},
{
"code": null,
"e": 4534,
"s": 3904,
"text": "n-gram features of byte files: We have tried uni-gram, bi-gram and tri-gram features. Though the performance with these features is good but the main challenge lies in handling their large dimensionality. The number of features with uni-gram is 256, with bi-gram it is 65531 and leaving the number of tri-gram features for your exercise. Even with the 30 GB RAM it is not possible to load the total data with 65531 features, so we went for SVD in chunk. First we tried out elbow method with random samples and 3000 features to check the number of components needed to preserve the variance and we found out 1000 as a good number."
},
{
"code": null,
"e": 5164,
"s": 4534,
"text": "n-gram features of byte files: We have tried uni-gram, bi-gram and tri-gram features. Though the performance with these features is good but the main challenge lies in handling their large dimensionality. The number of features with uni-gram is 256, with bi-gram it is 65531 and leaving the number of tri-gram features for your exercise. Even with the 30 GB RAM it is not possible to load the total data with 65531 features, so we went for SVD in chunk. First we tried out elbow method with random samples and 3000 features to check the number of components needed to preserve the variance and we found out 1000 as a good number."
},
{
"code": null,
"e": 5304,
"s": 5164,
"text": "2. Size of byte and asm files: Size of bytes and asm files turned out be be good features. Let’s take a look at the box plots of file sizes"
},
{
"code": null,
"e": 5530,
"s": 5304,
"text": "3. Size of byte array: As we mentioned earlier,the byte files are consists of hexadecimal digits. For each files we have taken an array and added each elements in to the array and used the length of these arrays as a feature."
},
{
"code": null,
"e": 5852,
"s": 5530,
"text": "4. Segment count and n-grams of asm files: asm files consists of various segments like prefixes(ex. HEADER,TEXT), opcodes(ex. jmp, hlt), keywords(ex. .dll, std::), registers(ex. edx,epi) etc. We have taken the count of segments as a feature. We have also considered uni-gram, bi-gram and tri-gram of asm files as feature."
},
{
"code": null,
"e": 6321,
"s": 5852,
"text": "5. Pixel intensity of byte and asm features: This is probably the most innovative features of the case this case study. We have borrowed the concept from the 1st place winner solution.As we mentioned earlier the value of each elements in byte files is between 0 to 255. We can easily convert these byte files along with the asm files in to gray scale images. It is observed that the first 800 pixel densities of asm files have significant impact over the final result."
},
{
"code": null,
"e": 6388,
"s": 6321,
"text": "Let’s take a look how a random asm file looks after the conversion"
},
{
"code": null,
"e": 6905,
"s": 6388,
"text": "By now you must have observed the dimension of the features and get a sense of the dimensionality of the final features for training. To cope up with the problem we have used random forest to select the important features. Number of important features is a hyper-parameter. We have tried various numbers based of our experiences and obviously there are scope of improvements. Let’s look at a sample code on this and how we have selected best tri-gram asm features. We have also tried t-SNE for multivariate analysis."
},
{
"code": null,
"e": 7984,
"s": 6905,
"text": "We have tried various linear machine learning models like KNN, multi-class logistic regression and ensembles like random forest, XGBoost and LightGBM with various combination of features. We have trained the models with single features, and a combination of byte features and asm features. We have also tried out various CNN architectures over the images obtained from byte and asm files but the obtained result was poorer compared to fine tuned machine learning models. As we did not have any domain knowledge on malware industry we have completely relied on cross validation. As the number of features and files were high, we have chosen RandomizedCV for cross validation and there are scope of improvements. Another question may come to your mind that why we have used both XGBoost and LightGBM? Actually we have started with XGBoost but found out that the training latency of LightGBM is much lower than XGBoost along with similar or better performance. We started with a random model then added the complexity of the model gradually after keeping an eye on the performance."
}
] |
Voting System Project Using Django Framework - GeeksforGeeks
|
04 Sep, 2021
Project Title: Pollster (Voting System) web application using Django frameworkType of Application (Category): Web application.
Introduction: We will create a pollster (voting system) web application using Django. This application will conduct a series of questions along with many choices. A user will be allowed to give voting for that question by selecting a choice. Based on the answer the total votes will be calculated and it will be displayed to the user. Users can also check the result of the total votes for specific questions on the website directly. We will also build the admin part of this project. Admin user will be allowed to add questions and manage questions in the application.
Pre-requisite: Knowledge of Python and basics of Django Framework. Python should be installed in the system. Visual studio code or any code editor to work on the application.
Technologies used in the project: Django framework and SQLite database which comes by default with Django.
Step-1: Create an empty folder pollster_project in your directory.Step-2: Now switch to your folder and create a virtual environment in this folder using the following command.
pip install pipenv
pipenv shell
Step-3: A Pipfile will be created in your folder from the above step. Now install Django in your folder using the following command.
pipenv install django
Step-4: Now we need to establish the Django project. Run the following command in your folder and initiate a Django project.
django-admin startproject pollster
A New Folder with name pollster will be created. Switch to the pollster folder using the following command.
cd pollster
The folder structure will look something like this.
Here you can start the server using the following command and check if the application running or not using ur http://127.0.0.1:8000/ in your browser.
python manage.py runserver
Step-5: Create an app ‘polls‘ using the following command
python manage.py startapp polls
Below is the folder structure after creating ”polls’ app in the project.
Step-1: In your models.py file write the code given below to create two tables in your database. One is ‘Question‘ and the other one is ‘Choice‘. ‘Question’ will have two fields of ‘question_text’ and a ‘pub_date’. Choice has three fields: ‘question’, ‘choice_text’, and ‘votes’. Each Choice is associated with a Question.
Python3
from django.db import models # Create your models here. class Question(models.Model): question_text = models.CharField(max_length = 200) pub_date = models.DateTimeField('date published') def __str__(self): return self.question_text class Choice(models.Model): question = models.ForeignKey(Question, on_delete = models.CASCADE) choice_text = models.CharField(max_length = 200) votes = models.IntegerField(default = 0) def __str__(self): return self.choice_text
Step-2:Go to the settings.py file and in the list, INSTALLED_APPS write down the code below to include the app in our project. This will refer to the polls -> apps.py -> PollsConfig class.
Python3
INSTALLED_APPS = [ 'polls.apps.PollsConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles',]
Step-3: We have made changes in our database and created some tables but in order to reflect these changes we need to create migration here and then Django application will stores changes to our models. Run the following command given below to create migrations.
python manage.py makemigrations polls
Inside polls->migrations a file 0001_initial.py will be created where you can find the database tables which we have created in our models.py file. Now to insert all the tables in our database run the command given below...
python manage.py migrate
Step-1: Run the command given below to create a user who can login to the admin site.
python manage.py createsuperuser
It will prompt username which we need to enter.
Username: geeks123
Now it will prompt an email address which again we need to enter here.
Email address: xyz@example.com
The final step is to enter the password. We need to enter the password twice, the second time as a confirmation of the first.
Password: ******
Password (again): ******
Superuser created successfully.
Now we can run the server using the same command python manage.py runserver and we can check our admin panel browsing the URL http://127.0.0.1:8000/admin .
Step-2: In the admin.py file we will write the code given below to map each question with choices to select. Also, we will write the code to change the site header, site title, and index_title. Once this is done we can add questions and choices for the question from the admin panel.
Python3
from django.contrib import admin# Register your models here.from .models import Question, Choice # admin.site.register(Question)# admin.site.register(Choice) admin.site.site_header = "Pollster Admin"admin.site.site_title = "Pollster Admin Area"admin.site.index_title = "Welcome to the Pollster Admin Area" class ChoiceInLine(admin.TabularInline): model = Choice extra = 3 class QuestionAdmin(admin.ModelAdmin): fieldsets = [(None, {'fields': ['question_text']}), ('Date Information', { 'fields': ['pub_date'], 'classes': ['collapse']}), ] inlines = [ChoiceInLine] admin.site.register(Question, QuestionAdmin)
Note: We can test the application here by adding some questions and choices for those questions.
Now we will create the view of our application that will fetch the data from our database and will render the data in the ‘template‘ (we will create ‘template’ folder and the files inside this folder in the next section) of our application to display it to the user.
Step-1 Open views.py file and write down the code given below.
Python3
from django.template import loaderfrom django.http import HttpResponse, HttpResponseRedirectfrom django.shortcuts import get_object_or_404, renderfrom django.urls import reverse from .models import Question, Choice # Get questions and display them def index(request): latest_question_list = Question.objects.order_by('-pub_date')[:5] context = {'latest_question_list': latest_question_list} return render(request, 'polls / index.html', context) # Show specific question and choices def detail(request, question_id): try: question = Question.objects.get(pk = question_id) except Question.DoesNotExist: raise Http404("Question does not exist") return render(request, 'polls / detail.html', {'question': question}) # Get question and display results def results(request, question_id): question = get_object_or_404(Question, pk = question_id) return render(request, 'polls / results.html', {'question': question}) # Vote for a question choice def vote(request, question_id): # print(request.POST['choice']) question = get_object_or_404(Question, pk = question_id) try: selected_choice = question.choice_set.get(pk = request.POST['choice']) except (KeyError, Choice.DoesNotExist): # Redisplay the question voting form. return render(request, 'polls / detail.html', { 'question': question, 'error_message': "You didn't select a choice.", }) else: selected_choice.votes += 1 selected_choice.save() # Always return an HttpResponseRedirect after successfully dealing # with POST data. This prevents data from being posted twice if a # user hits the Back button. return HttpResponseRedirect(reverse('polls:results', args =(question.id, )))
Step-2: Create a file urls.py inside the pollster->polls folder to define the routing for all the methods we have implemented in views.py file (don’t get confused with the file inside the pollster->pollster->urls.py file). Below is the code of urls.py file...
Python3
from django.urls import pathfrom . import views app_name = 'polls'urlpatterns = [ path('', views.index, name ='index'), path('<int:question_id>/', views.detail, name ='detail'), path('<int:question_id>/results/', views.results, name ='results'), path('<int:question_id>/vote/', views.vote, name ='vote'),]
Step-1: Follow the steps given below to create the front layout of the page.
Create a folder ‘templates‘ in top-level pollster folder (alongside of polls and pollster) i.e. pollster-> templates.
Create ‘base.html‘ file inside the template folder. We will define the head, body and navigation bar of our application in this file.
In the ‘templates’ folder create another folder ‘polls‘. In ‘polls’ folder create three files ‘index.html‘, ‘results.html‘ and ‘detail.html‘.
The folder structure will look like the image given below (we have highlighted the files which we have created in ‘create views i.e urls.py’ and ‘create template’ section)...
Step-2: By default Django will search the ‘template’ inside the ‘polls’ app but we have created a global ‘template’ folder which is outside the polls app. So in order to make it work, we need to define the ‘template’ folder path inside the settings.py file. Open settings.py file and add the code given below in the list ‘TEMPLATES’.
Python3
TEMPLATES = [ { # make changes in DIRS[]. 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, },]
Step-3: Open index.html file and write the code given below. This file will display the list of questions which are stored in our database. Also, two buttons will be displayed to the user. One for the voting (we will create a detail.html file for voting) and the other one is to check the results (we will create results.html file for results).
Python3
{% extends 'base.html' %}{% block content %}<h1 class ="text-center mb-3">Poll Questions</h1>{% if latest_question_list %}{% for question in latest_question_list %}<div class ="card-mb-3"> <div class ="card-body"> <p class ="lead">{{ question.question_text }}</p> <a href ="{% url 'polls:detail' question.id %}" class ="btn btn-primary btn-sm">Vote Now</a> <a href ="{% url 'polls:results' question.id %}" class ="btn btn-secondary btn-sm">Results</a> </div></div>{% endfor %}{% else %} <p>No polls available</p> {% endif %}{% endblock %}
Step-4: Open detail.html file and write the code given below. This file will be responsible for voting on specific questions. Whatever question a user will select for voting from the list of the question (index.html file), that specific question and the choices for the question will be displayed on this page. A user will be allowed to select one choice and give voting by clicking on the vote button.
Python3
{% extends 'base.html' %}{% block content %}<a class ="btn btn-secondary btn-sm mb-3" href ="{% url 'polls:index' %}">Back To Polls</a><h1 class ="text-center mb-3">{{ question.question_text }}</h1> {% if error_message %}<p class ="alert alert-danger"> <strong>{{ error_message }}</strong></p> {% endif %} <form action ="{% url 'polls:vote' question.id %}" method ="post"> {% csrf_token %} {% for choice in question.choice_set.all %} <div class ="form-check"> <input type ="radio" name ="choice" class ="form-check-input" id ="choice{{ forloop.counter }}" value ="{{ choice.id }}" /> <label for ="choice{{ forloop.counter }}">{{ choice.choice_text }}</label> </div> {% endfor %} <input type ="submit" value ="Vote" class ="btn btn-success btn-lg btn-block mt-4" /></form>{% endblock %}
Step-5: Open results.html file and write the code given below. This file will display the result of total votes on a specific question whatever question the user will select (from the index.html file) to check the result.
Python3
{% extends 'base.html' %}{% block content %}<h1 class ="mb-5 text-center">{{ question.question_text }}</h1> <ul class ="list-group mb-5"> {% for choice in question.choice_set.all %} <li class ="list-group-item"> {{ choice.choice_text }} <span class ="badge badge-success float-right">{{ choice.votes }} vote{{ choice.votes | pluralize }}</span> </li> {% endfor %}</ul> <a class ="btn btn-secondary" href ="{% url 'polls:index' %}">Back To Polls</a><a class ="btn btn-dark" href ="{% url 'polls:detail' question.id %}">Vote again?</a>{% endblock %}
Step-6: Let’s create the navigation bar for our application. Create a folder ‘partials‘ inside the folder ‘templates’ and then create a file ‘_navbar.html‘ inside the ‘partial’ folder. File structure will be templates->partials->_navbar.html. Write the code given below in this file.
Python3
<nav class ="navbar navbar-dark bg-primary mb-4"> <div class ="container"> <a class ="navbar-brand" href ="/">Pollster</a> </div></nav>
Step-7: We haven’t included the head and body tag in every single HTML file we have created till now. We can write these codes in just one single file base.html and we can give the layout to our page. We will also bring our navigation bar(_navbar.html file) on this page. So open base.html file inside the ‘template’ folder and write down the code given below.
Python3
<! DOCTYPE html><html lang ="en"><head> <link rel ="stylesheet" href ="https://stackpath.bootstrapcdn.com / bootstrap / 4.4.1 / css / bootstrap.min.css" integrity ="sha384-Vkoo8x4CGsO3 + Hhxv8T / Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin ="anonymous"> <title>Pollster {% block title %}{% endblock %}</title></head> <body> <!--NavBar--> {% include 'partials/_navbar.html'%} <div class ="container"> <div class ="row"> <div class =".col-md-6 m-auto"> {% block content %}{% endblock %} </div> </div> </div></body> </html>
The URL http://127.0.0.1:8000/ should display a landing page for our web application. So to create a landing page we will follow the step given below.
Step-1 Switch to the top-level pollster folder and run the command given below to create an app ‘pages‘.
python manage.py startapp pages
Below is the folder structure once the ‘pages’ app will be created.
Step-2 Open ‘views.py‘ inside ‘pages’ folder i.e. pages->views.py. Write down the code given below to visit on landing page.
Python3
from django.shortcuts import render # Create your views here. def index(request): return render(request, 'pages / index.html')
Step-3 Create urls.py file inside the ‘pages’ folder i.e. pages->urls.py. Write the code given below to define the routing of pages->index.html file (check step-1).
Python3
from django.urls import path from . import views urlpatterns = [ path('', views.index, name ='index'),]
Step-4 Create a folder ‘pages‘ inside ‘template’ folder. Now inside ‘pages’ folder create a file index.html. Write down the code given below to display the landing page to the users.
Python3
{% extends 'base.html' %}{% block content %} <div class ="card text-center"> <div class ="card-body"> <h1>Welcome To Pollster</h1> <p>This is an example Django polling app</p> <a class ="btn btn-dark" href ="{% url 'polls:index' %}"> View Available Polls</a> </div></div>{% endblock %}
We have created two apps in our application ‘polls‘ and ‘pages‘. We need to define the routing of these two apps inside the main urls.py file which is pollster->pollster->urls.py file. So open the main urls.py file inside the pollster folder and write down the code give below to define the routing of these two apps(‘polls’ and ‘pages’).
Python3
from django.contrib import adminfrom django.urls import include, path urlpatterns = [ path('', include('pages.urls')), path('polls/', include('polls.urls')), path('admin/', admin.site.urls),]
Step-1 Run the server using the command python manage.py runserver and browse the URL http://127.0.0.1:8000/admin/. Now enter the username and password to login into the system.
Step-2 Click on ‘add’ button next to the ‘Questions’.
Step-2 Now add question and choices for those questions. Also, mention the date and time and then click on the ‘save’ button. You can add as many questions as you want. You will see a list of questions added in the database.
Step-1: Browse the URL http://127.0.0.1:8000/ and you will see the landing page of the application. Click on the “View Available Polls”
Step-2: You will see list of questions with two options ‘Vote Now’ and ‘Results’. From here you need to select one question and click on the ‘Vote Now’ button.
Step-3: Once this is done select any one choice and click on ‘Vote’ button. You can also go to the previous menu using the ‘Back to Polls’ button on the top.
You will see the total voting result for the question you have selected.
You can also check the total votes for any question using the option ‘Results’ from the ‘Poll Questions’ page.
This project can be used to conduct the online voting system in any field or industry. The project can be expanded and several other features can also be included based on the requirement. People can share the opinion and they can also check the total voting given by many users.
https://github.com/anuupadhyay/pollster-django-crash
simmytarika5
Python Django
Project
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Banking Transaction System using Java
E-commerce Website using Django
Student record management system using linked list
How to write a good SRS for your Project
Handling Ajax request in Django
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe
|
[
{
"code": null,
"e": 25807,
"s": 25779,
"text": "\n04 Sep, 2021"
},
{
"code": null,
"e": 25934,
"s": 25807,
"text": "Project Title: Pollster (Voting System) web application using Django frameworkType of Application (Category): Web application."
},
{
"code": null,
"e": 26505,
"s": 25934,
"text": "Introduction: We will create a pollster (voting system) web application using Django. This application will conduct a series of questions along with many choices. A user will be allowed to give voting for that question by selecting a choice. Based on the answer the total votes will be calculated and it will be displayed to the user. Users can also check the result of the total votes for specific questions on the website directly. We will also build the admin part of this project. Admin user will be allowed to add questions and manage questions in the application. "
},
{
"code": null,
"e": 26681,
"s": 26505,
"text": "Pre-requisite: Knowledge of Python and basics of Django Framework. Python should be installed in the system. Visual studio code or any code editor to work on the application. "
},
{
"code": null,
"e": 26790,
"s": 26681,
"text": "Technologies used in the project: Django framework and SQLite database which comes by default with Django. "
},
{
"code": null,
"e": 26968,
"s": 26790,
"text": "Step-1: Create an empty folder pollster_project in your directory.Step-2: Now switch to your folder and create a virtual environment in this folder using the following command. "
},
{
"code": null,
"e": 26987,
"s": 26968,
"text": "pip install pipenv"
},
{
"code": null,
"e": 27000,
"s": 26987,
"text": "pipenv shell"
},
{
"code": null,
"e": 27134,
"s": 27000,
"text": "Step-3: A Pipfile will be created in your folder from the above step. Now install Django in your folder using the following command. "
},
{
"code": null,
"e": 27156,
"s": 27134,
"text": "pipenv install django"
},
{
"code": null,
"e": 27282,
"s": 27156,
"text": "Step-4: Now we need to establish the Django project. Run the following command in your folder and initiate a Django project. "
},
{
"code": null,
"e": 27317,
"s": 27282,
"text": "django-admin startproject pollster"
},
{
"code": null,
"e": 27426,
"s": 27317,
"text": "A New Folder with name pollster will be created. Switch to the pollster folder using the following command. "
},
{
"code": null,
"e": 27438,
"s": 27426,
"text": "cd pollster"
},
{
"code": null,
"e": 27491,
"s": 27438,
"text": "The folder structure will look something like this. "
},
{
"code": null,
"e": 27643,
"s": 27491,
"text": "Here you can start the server using the following command and check if the application running or not using ur http://127.0.0.1:8000/ in your browser. "
},
{
"code": null,
"e": 27670,
"s": 27643,
"text": "python manage.py runserver"
},
{
"code": null,
"e": 27730,
"s": 27670,
"text": "Step-5: Create an app ‘polls‘ using the following command "
},
{
"code": null,
"e": 27762,
"s": 27730,
"text": "python manage.py startapp polls"
},
{
"code": null,
"e": 27837,
"s": 27762,
"text": "Below is the folder structure after creating ”polls’ app in the project. "
},
{
"code": null,
"e": 28161,
"s": 27837,
"text": "Step-1: In your models.py file write the code given below to create two tables in your database. One is ‘Question‘ and the other one is ‘Choice‘. ‘Question’ will have two fields of ‘question_text’ and a ‘pub_date’. Choice has three fields: ‘question’, ‘choice_text’, and ‘votes’. Each Choice is associated with a Question. "
},
{
"code": null,
"e": 28169,
"s": 28161,
"text": "Python3"
},
{
"code": "from django.db import models # Create your models here. class Question(models.Model): question_text = models.CharField(max_length = 200) pub_date = models.DateTimeField('date published') def __str__(self): return self.question_text class Choice(models.Model): question = models.ForeignKey(Question, on_delete = models.CASCADE) choice_text = models.CharField(max_length = 200) votes = models.IntegerField(default = 0) def __str__(self): return self.choice_text",
"e": 28667,
"s": 28169,
"text": null
},
{
"code": null,
"e": 28857,
"s": 28667,
"text": "Step-2:Go to the settings.py file and in the list, INSTALLED_APPS write down the code below to include the app in our project. This will refer to the polls -> apps.py -> PollsConfig class. "
},
{
"code": null,
"e": 28865,
"s": 28857,
"text": "Python3"
},
{
"code": "INSTALLED_APPS = [ 'polls.apps.PollsConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles',]",
"e": 29094,
"s": 28865,
"text": null
},
{
"code": null,
"e": 29358,
"s": 29094,
"text": "Step-3: We have made changes in our database and created some tables but in order to reflect these changes we need to create migration here and then Django application will stores changes to our models. Run the following command given below to create migrations. "
},
{
"code": null,
"e": 29396,
"s": 29358,
"text": "python manage.py makemigrations polls"
},
{
"code": null,
"e": 29622,
"s": 29396,
"text": "Inside polls->migrations a file 0001_initial.py will be created where you can find the database tables which we have created in our models.py file. Now to insert all the tables in our database run the command given below... "
},
{
"code": null,
"e": 29648,
"s": 29622,
"text": "python manage.py migrate "
},
{
"code": null,
"e": 29735,
"s": 29648,
"text": "Step-1: Run the command given below to create a user who can login to the admin site. "
},
{
"code": null,
"e": 29768,
"s": 29735,
"text": "python manage.py createsuperuser"
},
{
"code": null,
"e": 29817,
"s": 29768,
"text": "It will prompt username which we need to enter. "
},
{
"code": null,
"e": 29836,
"s": 29817,
"text": "Username: geeks123"
},
{
"code": null,
"e": 29909,
"s": 29836,
"text": "Now it will prompt an email address which again we need to enter here. "
},
{
"code": null,
"e": 29940,
"s": 29909,
"text": "Email address: xyz@example.com"
},
{
"code": null,
"e": 30068,
"s": 29940,
"text": "The final step is to enter the password. We need to enter the password twice, the second time as a confirmation of the first. "
},
{
"code": null,
"e": 30142,
"s": 30068,
"text": "Password: ******\nPassword (again): ******\nSuperuser created successfully."
},
{
"code": null,
"e": 30300,
"s": 30142,
"text": "Now we can run the server using the same command python manage.py runserver and we can check our admin panel browsing the URL http://127.0.0.1:8000/admin . "
},
{
"code": null,
"e": 30586,
"s": 30300,
"text": "Step-2: In the admin.py file we will write the code given below to map each question with choices to select. Also, we will write the code to change the site header, site title, and index_title. Once this is done we can add questions and choices for the question from the admin panel. "
},
{
"code": null,
"e": 30594,
"s": 30586,
"text": "Python3"
},
{
"code": "from django.contrib import admin# Register your models here.from .models import Question, Choice # admin.site.register(Question)# admin.site.register(Choice) admin.site.site_header = \"Pollster Admin\"admin.site.site_title = \"Pollster Admin Area\"admin.site.index_title = \"Welcome to the Pollster Admin Area\" class ChoiceInLine(admin.TabularInline): model = Choice extra = 3 class QuestionAdmin(admin.ModelAdmin): fieldsets = [(None, {'fields': ['question_text']}), ('Date Information', { 'fields': ['pub_date'], 'classes': ['collapse']}), ] inlines = [ChoiceInLine] admin.site.register(Question, QuestionAdmin)",
"e": 31225,
"s": 30594,
"text": null
},
{
"code": null,
"e": 31323,
"s": 31225,
"text": "Note: We can test the application here by adding some questions and choices for those questions. "
},
{
"code": null,
"e": 31591,
"s": 31323,
"text": "Now we will create the view of our application that will fetch the data from our database and will render the data in the ‘template‘ (we will create ‘template’ folder and the files inside this folder in the next section) of our application to display it to the user. "
},
{
"code": null,
"e": 31655,
"s": 31591,
"text": "Step-1 Open views.py file and write down the code given below. "
},
{
"code": null,
"e": 31663,
"s": 31655,
"text": "Python3"
},
{
"code": "from django.template import loaderfrom django.http import HttpResponse, HttpResponseRedirectfrom django.shortcuts import get_object_or_404, renderfrom django.urls import reverse from .models import Question, Choice # Get questions and display them def index(request): latest_question_list = Question.objects.order_by('-pub_date')[:5] context = {'latest_question_list': latest_question_list} return render(request, 'polls / index.html', context) # Show specific question and choices def detail(request, question_id): try: question = Question.objects.get(pk = question_id) except Question.DoesNotExist: raise Http404(\"Question does not exist\") return render(request, 'polls / detail.html', {'question': question}) # Get question and display results def results(request, question_id): question = get_object_or_404(Question, pk = question_id) return render(request, 'polls / results.html', {'question': question}) # Vote for a question choice def vote(request, question_id): # print(request.POST['choice']) question = get_object_or_404(Question, pk = question_id) try: selected_choice = question.choice_set.get(pk = request.POST['choice']) except (KeyError, Choice.DoesNotExist): # Redisplay the question voting form. return render(request, 'polls / detail.html', { 'question': question, 'error_message': \"You didn't select a choice.\", }) else: selected_choice.votes += 1 selected_choice.save() # Always return an HttpResponseRedirect after successfully dealing # with POST data. This prevents data from being posted twice if a # user hits the Back button. return HttpResponseRedirect(reverse('polls:results', args =(question.id, )))",
"e": 33442,
"s": 31663,
"text": null
},
{
"code": null,
"e": 33703,
"s": 33442,
"text": "Step-2: Create a file urls.py inside the pollster->polls folder to define the routing for all the methods we have implemented in views.py file (don’t get confused with the file inside the pollster->pollster->urls.py file). Below is the code of urls.py file... "
},
{
"code": null,
"e": 33711,
"s": 33703,
"text": "Python3"
},
{
"code": "from django.urls import pathfrom . import views app_name = 'polls'urlpatterns = [ path('', views.index, name ='index'), path('<int:question_id>/', views.detail, name ='detail'), path('<int:question_id>/results/', views.results, name ='results'), path('<int:question_id>/vote/', views.vote, name ='vote'),]",
"e": 34029,
"s": 33711,
"text": null
},
{
"code": null,
"e": 34107,
"s": 34029,
"text": "Step-1: Follow the steps given below to create the front layout of the page. "
},
{
"code": null,
"e": 34225,
"s": 34107,
"text": "Create a folder ‘templates‘ in top-level pollster folder (alongside of polls and pollster) i.e. pollster-> templates."
},
{
"code": null,
"e": 34359,
"s": 34225,
"text": "Create ‘base.html‘ file inside the template folder. We will define the head, body and navigation bar of our application in this file."
},
{
"code": null,
"e": 34501,
"s": 34359,
"text": "In the ‘templates’ folder create another folder ‘polls‘. In ‘polls’ folder create three files ‘index.html‘, ‘results.html‘ and ‘detail.html‘."
},
{
"code": null,
"e": 34677,
"s": 34501,
"text": "The folder structure will look like the image given below (we have highlighted the files which we have created in ‘create views i.e urls.py’ and ‘create template’ section)... "
},
{
"code": null,
"e": 35012,
"s": 34677,
"text": "Step-2: By default Django will search the ‘template’ inside the ‘polls’ app but we have created a global ‘template’ folder which is outside the polls app. So in order to make it work, we need to define the ‘template’ folder path inside the settings.py file. Open settings.py file and add the code given below in the list ‘TEMPLATES’. "
},
{
"code": null,
"e": 35020,
"s": 35012,
"text": "Python3"
},
{
"code": "TEMPLATES = [ { # make changes in DIRS[]. 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, },]",
"e": 35558,
"s": 35020,
"text": null
},
{
"code": null,
"e": 35904,
"s": 35558,
"text": "Step-3: Open index.html file and write the code given below. This file will display the list of questions which are stored in our database. Also, two buttons will be displayed to the user. One for the voting (we will create a detail.html file for voting) and the other one is to check the results (we will create results.html file for results). "
},
{
"code": null,
"e": 35912,
"s": 35904,
"text": "Python3"
},
{
"code": "{% extends 'base.html' %}{% block content %}<h1 class =\"text-center mb-3\">Poll Questions</h1>{% if latest_question_list %}{% for question in latest_question_list %}<div class =\"card-mb-3\"> <div class =\"card-body\"> <p class =\"lead\">{{ question.question_text }}</p> <a href =\"{% url 'polls:detail' question.id %}\" class =\"btn btn-primary btn-sm\">Vote Now</a> <a href =\"{% url 'polls:results' question.id %}\" class =\"btn btn-secondary btn-sm\">Results</a> </div></div>{% endfor %}{% else %} <p>No polls available</p> {% endif %}{% endblock %}",
"e": 36479,
"s": 35912,
"text": null
},
{
"code": null,
"e": 36883,
"s": 36479,
"text": "Step-4: Open detail.html file and write the code given below. This file will be responsible for voting on specific questions. Whatever question a user will select for voting from the list of the question (index.html file), that specific question and the choices for the question will be displayed on this page. A user will be allowed to select one choice and give voting by clicking on the vote button. "
},
{
"code": null,
"e": 36891,
"s": 36883,
"text": "Python3"
},
{
"code": "{% extends 'base.html' %}{% block content %}<a class =\"btn btn-secondary btn-sm mb-3\" href =\"{% url 'polls:index' %}\">Back To Polls</a><h1 class =\"text-center mb-3\">{{ question.question_text }}</h1> {% if error_message %}<p class =\"alert alert-danger\"> <strong>{{ error_message }}</strong></p> {% endif %} <form action =\"{% url 'polls:vote' question.id %}\" method =\"post\"> {% csrf_token %} {% for choice in question.choice_set.all %} <div class =\"form-check\"> <input type =\"radio\" name =\"choice\" class =\"form-check-input\" id =\"choice{{ forloop.counter }}\" value =\"{{ choice.id }}\" /> <label for =\"choice{{ forloop.counter }}\">{{ choice.choice_text }}</label> </div> {% endfor %} <input type =\"submit\" value =\"Vote\" class =\"btn btn-success btn-lg btn-block mt-4\" /></form>{% endblock %}",
"e": 37723,
"s": 36891,
"text": null
},
{
"code": null,
"e": 37946,
"s": 37723,
"text": "Step-5: Open results.html file and write the code given below. This file will display the result of total votes on a specific question whatever question the user will select (from the index.html file) to check the result. "
},
{
"code": null,
"e": 37954,
"s": 37946,
"text": "Python3"
},
{
"code": "{% extends 'base.html' %}{% block content %}<h1 class =\"mb-5 text-center\">{{ question.question_text }}</h1> <ul class =\"list-group mb-5\"> {% for choice in question.choice_set.all %} <li class =\"list-group-item\"> {{ choice.choice_text }} <span class =\"badge badge-success float-right\">{{ choice.votes }} vote{{ choice.votes | pluralize }}</span> </li> {% endfor %}</ul> <a class =\"btn btn-secondary\" href =\"{% url 'polls:index' %}\">Back To Polls</a><a class =\"btn btn-dark\" href =\"{% url 'polls:detail' question.id %}\">Vote again?</a>{% endblock %}",
"e": 38532,
"s": 37954,
"text": null
},
{
"code": null,
"e": 38817,
"s": 38532,
"text": "Step-6: Let’s create the navigation bar for our application. Create a folder ‘partials‘ inside the folder ‘templates’ and then create a file ‘_navbar.html‘ inside the ‘partial’ folder. File structure will be templates->partials->_navbar.html. Write the code given below in this file. "
},
{
"code": null,
"e": 38825,
"s": 38817,
"text": "Python3"
},
{
"code": "<nav class =\"navbar navbar-dark bg-primary mb-4\"> <div class =\"container\"> <a class =\"navbar-brand\" href =\"/\">Pollster</a> </div></nav>",
"e": 38974,
"s": 38825,
"text": null
},
{
"code": null,
"e": 39336,
"s": 38974,
"text": "Step-7: We haven’t included the head and body tag in every single HTML file we have created till now. We can write these codes in just one single file base.html and we can give the layout to our page. We will also bring our navigation bar(_navbar.html file) on this page. So open base.html file inside the ‘template’ folder and write down the code given below. "
},
{
"code": null,
"e": 39344,
"s": 39336,
"text": "Python3"
},
{
"code": "<! DOCTYPE html><html lang =\"en\"><head> <link rel =\"stylesheet\" href =\"https://stackpath.bootstrapcdn.com / bootstrap / 4.4.1 / css / bootstrap.min.css\" integrity =\"sha384-Vkoo8x4CGsO3 + Hhxv8T / Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh\" crossorigin =\"anonymous\"> <title>Pollster {% block title %}{% endblock %}</title></head> <body> <!--NavBar--> {% include 'partials/_navbar.html'%} <div class =\"container\"> <div class =\"row\"> <div class =\".col-md-6 m-auto\"> {% block content %}{% endblock %} </div> </div> </div></body> </html>",
"e": 39955,
"s": 39344,
"text": null
},
{
"code": null,
"e": 40107,
"s": 39955,
"text": "The URL http://127.0.0.1:8000/ should display a landing page for our web application. So to create a landing page we will follow the step given below. "
},
{
"code": null,
"e": 40213,
"s": 40107,
"text": "Step-1 Switch to the top-level pollster folder and run the command given below to create an app ‘pages‘. "
},
{
"code": null,
"e": 40245,
"s": 40213,
"text": "python manage.py startapp pages"
},
{
"code": null,
"e": 40314,
"s": 40245,
"text": "Below is the folder structure once the ‘pages’ app will be created. "
},
{
"code": null,
"e": 40440,
"s": 40314,
"text": "Step-2 Open ‘views.py‘ inside ‘pages’ folder i.e. pages->views.py. Write down the code given below to visit on landing page. "
},
{
"code": null,
"e": 40448,
"s": 40440,
"text": "Python3"
},
{
"code": "from django.shortcuts import render # Create your views here. def index(request): return render(request, 'pages / index.html')",
"e": 40578,
"s": 40448,
"text": null
},
{
"code": null,
"e": 40744,
"s": 40578,
"text": "Step-3 Create urls.py file inside the ‘pages’ folder i.e. pages->urls.py. Write the code given below to define the routing of pages->index.html file (check step-1). "
},
{
"code": null,
"e": 40752,
"s": 40744,
"text": "Python3"
},
{
"code": " from django.urls import path from . import views urlpatterns = [ path('', views.index, name ='index'),]",
"e": 40862,
"s": 40752,
"text": null
},
{
"code": null,
"e": 41046,
"s": 40862,
"text": "Step-4 Create a folder ‘pages‘ inside ‘template’ folder. Now inside ‘pages’ folder create a file index.html. Write down the code given below to display the landing page to the users. "
},
{
"code": null,
"e": 41054,
"s": 41046,
"text": "Python3"
},
{
"code": "{% extends 'base.html' %}{% block content %} <div class =\"card text-center\"> <div class =\"card-body\"> <h1>Welcome To Pollster</h1> <p>This is an example Django polling app</p> <a class =\"btn btn-dark\" href =\"{% url 'polls:index' %}\"> View Available Polls</a> </div></div>{% endblock %}",
"e": 41380,
"s": 41054,
"text": null
},
{
"code": null,
"e": 41720,
"s": 41380,
"text": "We have created two apps in our application ‘polls‘ and ‘pages‘. We need to define the routing of these two apps inside the main urls.py file which is pollster->pollster->urls.py file. So open the main urls.py file inside the pollster folder and write down the code give below to define the routing of these two apps(‘polls’ and ‘pages’). "
},
{
"code": null,
"e": 41728,
"s": 41720,
"text": "Python3"
},
{
"code": "from django.contrib import adminfrom django.urls import include, path urlpatterns = [ path('', include('pages.urls')), path('polls/', include('polls.urls')), path('admin/', admin.site.urls),]",
"e": 41929,
"s": 41728,
"text": null
},
{
"code": null,
"e": 42108,
"s": 41929,
"text": "Step-1 Run the server using the command python manage.py runserver and browse the URL http://127.0.0.1:8000/admin/. Now enter the username and password to login into the system. "
},
{
"code": null,
"e": 42163,
"s": 42108,
"text": "Step-2 Click on ‘add’ button next to the ‘Questions’. "
},
{
"code": null,
"e": 42389,
"s": 42163,
"text": "Step-2 Now add question and choices for those questions. Also, mention the date and time and then click on the ‘save’ button. You can add as many questions as you want. You will see a list of questions added in the database. "
},
{
"code": null,
"e": 42526,
"s": 42389,
"text": "Step-1: Browse the URL http://127.0.0.1:8000/ and you will see the landing page of the application. Click on the “View Available Polls” "
},
{
"code": null,
"e": 42687,
"s": 42526,
"text": "Step-2: You will see list of questions with two options ‘Vote Now’ and ‘Results’. From here you need to select one question and click on the ‘Vote Now’ button. "
},
{
"code": null,
"e": 42846,
"s": 42687,
"text": "Step-3: Once this is done select any one choice and click on ‘Vote’ button. You can also go to the previous menu using the ‘Back to Polls’ button on the top. "
},
{
"code": null,
"e": 42920,
"s": 42846,
"text": "You will see the total voting result for the question you have selected. "
},
{
"code": null,
"e": 43032,
"s": 42920,
"text": "You can also check the total votes for any question using the option ‘Results’ from the ‘Poll Questions’ page. "
},
{
"code": null,
"e": 43313,
"s": 43032,
"text": "This project can be used to conduct the online voting system in any field or industry. The project can be expanded and several other features can also be included based on the requirement. People can share the opinion and they can also check the total voting given by many users. "
},
{
"code": null,
"e": 43367,
"s": 43313,
"text": "https://github.com/anuupadhyay/pollster-django-crash "
},
{
"code": null,
"e": 43380,
"s": 43367,
"text": "simmytarika5"
},
{
"code": null,
"e": 43394,
"s": 43380,
"text": "Python Django"
},
{
"code": null,
"e": 43402,
"s": 43394,
"text": "Project"
},
{
"code": null,
"e": 43409,
"s": 43402,
"text": "Python"
},
{
"code": null,
"e": 43507,
"s": 43409,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 43545,
"s": 43507,
"text": "Banking Transaction System using Java"
},
{
"code": null,
"e": 43577,
"s": 43545,
"text": "E-commerce Website using Django"
},
{
"code": null,
"e": 43628,
"s": 43577,
"text": "Student record management system using linked list"
},
{
"code": null,
"e": 43669,
"s": 43628,
"text": "How to write a good SRS for your Project"
},
{
"code": null,
"e": 43701,
"s": 43669,
"text": "Handling Ajax request in Django"
},
{
"code": null,
"e": 43729,
"s": 43701,
"text": "Read JSON file using Python"
},
{
"code": null,
"e": 43779,
"s": 43729,
"text": "Adding new column to existing DataFrame in Pandas"
},
{
"code": null,
"e": 43801,
"s": 43779,
"text": "Python map() function"
}
] |
Kotlin if-else expression - GeeksforGeeks
|
09 Sep, 2021
Decision Making in programming is similar to decision making in real life. In programming too, a certain block of code needs to be executed when some condition is fulfilled.A programming language uses control statements to control the flow of execution of program based on certain conditions.If condition is true then it enters into the conditional block and executes the instructions. There are different types of if-else expressions in Kotlin:
if expression
if-else expression
if-else-if ladder expression
nested if expression
if statement: It is used to specify a block of statements to be executed or not i.e if a certain condition is true then the statement or block of statements to be executed otherwise fails to execute. Syntax:
if(condition) {
// code to run if condition is true
}
Flowchart:
Example:
Java
fun main(args: Array<String>) { var a = 3 if(a > 0){ print("Yes,number is positive") }}
Output:
Yes, number is positive
if-else statement: if-else statement contains two blocks of statements. ‘if’ statement is used to execute the block of code when the condition becomes true and ‘else’ statement is used to execute a block of code when the condition becomes false. Syntax:
if(condition) {
// code to run if condition is true
}
else {
// code to run if condition is false
}
Flowchart:
Here is the Kotlin program to find the larger value of two numbers.
Java
fun main(args: Array<String>) { var a = 5 var b = 10 if(a > b){ print("Number 5 is larger than 10") } else{ println("Number 10 is larger than 5") } }
Output:
Number 10 is larger than 5
Kotlin if-else expression as ternary operator – In Kotlin, if-else can be used as an expression because it returns a value. Unlike java, there is no ternary operator in Kotlin because if-else return the value according to the condition and works exactly similar to ternary. Below is the Kotlin program to find the greater value between two numbers using if-else expression.
Java
fun main(args: Array<String>) { var a = 50 var b = 40 // here if-else returns a value which // is to be stored in max variable var max = if(a > b){ print("Greater number is: ") a } else{ print("Greater number is:") b } print(max)}
Output:
Greater number is: 50
if-else-if ladder expression: Here, a user can put multiple conditions. All the ‘if’ statements are executed from the top to bottom. One by one all the conditions are checked and if any of the condition found to be true then the code associated with the if statement will be executed and all other statements bypassed to the end of the block. If none of the conditions is true, then by default the final else statement will be executed. Syntax:
if(Firstcondition) {
// code to run if condition is true
}
else if(Secondcondition) {
// code to run if condition is true
}
else{
}
Flowchart:
Below is the Kotlin program to determine the number is positive, negative or equal to zero.
Java
import java.util.Scanner fun main(args: Array<String>) { // create an object for scanner class val reader = Scanner(System.`in`) print("Enter any number: ") // read the next Integer value var num = reader.nextInt() var result = if ( num > 0){ "$num is positive number" } else if( num < 0){ "$num is negative number" } else{ "$num is equal to zero" } println(result) }
Output:
Enter any number: 12
12 is positive number
Enter any number: -11
-11 is negative number
Enter any number: 0
0 is zero
nested if expression: Nested if statements means an if statement inside another if statement.If first condition is true then code the associated block to be executed, and again check for the if condition nested in the first block and if it is also true then execute the code associated with it. It will go on until the last condition is true. Syntax:
if(condition1){
// code 1
if(condition2){
// code2
}
}
Flowchart:
Below is the Kotlin program to determine the largest value among three Integers.
Java
import java.util.Scanner fun main(args: Array<String>) { // create an object for scanner class val reader = Scanner(System.`in`) print("Enter three numbers: ") var num1 = reader.nextInt() var num2 = reader.nextInt() var num3 = reader.nextInt() var max = if ( num1 > num2) { if (num1 > num3) { "$num1 is the largest number" } else { "$num3 is the largest number" } } else if( num2 > num3){ "$num2 is the largest number" } else{ "$num3 is the largest number" } println(max) }
Output:
Enter three numbers: 123 231 321
321 is the largest number
Akanksha_Rai
rajeev0719singh
Kotlin
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Android RecyclerView in Kotlin
Retrofit with Kotlin Coroutine in Android
How to Get Current Location in Android?
Kotlin Higher-Order Functions
Android Menus
ImageView in Android with Example
Kotlin constructor
How to Build a Weather App in Android?
Android SQLite Database in Kotlin
MVP (Model View Presenter) Architecture Pattern in Android with Example
|
[
{
"code": null,
"e": 25447,
"s": 25419,
"text": "\n09 Sep, 2021"
},
{
"code": null,
"e": 25895,
"s": 25447,
"text": "Decision Making in programming is similar to decision making in real life. In programming too, a certain block of code needs to be executed when some condition is fulfilled.A programming language uses control statements to control the flow of execution of program based on certain conditions.If condition is true then it enters into the conditional block and executes the instructions. There are different types of if-else expressions in Kotlin: "
},
{
"code": null,
"e": 25909,
"s": 25895,
"text": "if expression"
},
{
"code": null,
"e": 25928,
"s": 25909,
"text": "if-else expression"
},
{
"code": null,
"e": 25957,
"s": 25928,
"text": "if-else-if ladder expression"
},
{
"code": null,
"e": 25978,
"s": 25957,
"text": "nested if expression"
},
{
"code": null,
"e": 26188,
"s": 25978,
"text": "if statement: It is used to specify a block of statements to be executed or not i.e if a certain condition is true then the statement or block of statements to be executed otherwise fails to execute. Syntax: "
},
{
"code": null,
"e": 26250,
"s": 26188,
"text": "if(condition) {\n\n // code to run if condition is true\n}"
},
{
"code": null,
"e": 26263,
"s": 26250,
"text": "Flowchart: "
},
{
"code": null,
"e": 26274,
"s": 26263,
"text": "Example: "
},
{
"code": null,
"e": 26279,
"s": 26274,
"text": "Java"
},
{
"code": "fun main(args: Array<String>) { var a = 3 if(a > 0){ print(\"Yes,number is positive\") }}",
"e": 26383,
"s": 26279,
"text": null
},
{
"code": null,
"e": 26393,
"s": 26383,
"text": "Output: "
},
{
"code": null,
"e": 26417,
"s": 26393,
"text": "Yes, number is positive"
},
{
"code": null,
"e": 26675,
"s": 26417,
"text": " if-else statement: if-else statement contains two blocks of statements. ‘if’ statement is used to execute the block of code when the condition becomes true and ‘else’ statement is used to execute a block of code when the condition becomes false. Syntax: "
},
{
"code": null,
"e": 26793,
"s": 26675,
"text": " if(condition) { \n // code to run if condition is true\n}\nelse { \n // code to run if condition is false\n}"
},
{
"code": null,
"e": 26806,
"s": 26793,
"text": "Flowchart: "
},
{
"code": null,
"e": 26876,
"s": 26806,
"text": "Here is the Kotlin program to find the larger value of two numbers. "
},
{
"code": null,
"e": 26881,
"s": 26876,
"text": "Java"
},
{
"code": "fun main(args: Array<String>) { var a = 5 var b = 10 if(a > b){ print(\"Number 5 is larger than 10\") } else{ println(\"Number 10 is larger than 5\") } }",
"e": 27098,
"s": 26881,
"text": null
},
{
"code": null,
"e": 27108,
"s": 27098,
"text": "Output: "
},
{
"code": null,
"e": 27135,
"s": 27108,
"text": "Number 10 is larger than 5"
},
{
"code": null,
"e": 27513,
"s": 27135,
"text": " Kotlin if-else expression as ternary operator – In Kotlin, if-else can be used as an expression because it returns a value. Unlike java, there is no ternary operator in Kotlin because if-else return the value according to the condition and works exactly similar to ternary. Below is the Kotlin program to find the greater value between two numbers using if-else expression. "
},
{
"code": null,
"e": 27518,
"s": 27513,
"text": "Java"
},
{
"code": "fun main(args: Array<String>) { var a = 50 var b = 40 // here if-else returns a value which // is to be stored in max variable var max = if(a > b){ print(\"Greater number is: \") a } else{ print(\"Greater number is:\") b } print(max)}",
"e": 27822,
"s": 27518,
"text": null
},
{
"code": null,
"e": 27832,
"s": 27822,
"text": "Output: "
},
{
"code": null,
"e": 27854,
"s": 27832,
"text": "Greater number is: 50"
},
{
"code": null,
"e": 28303,
"s": 27854,
"text": " if-else-if ladder expression: Here, a user can put multiple conditions. All the ‘if’ statements are executed from the top to bottom. One by one all the conditions are checked and if any of the condition found to be true then the code associated with the if statement will be executed and all other statements bypassed to the end of the block. If none of the conditions is true, then by default the final else statement will be executed. Syntax: "
},
{
"code": null,
"e": 28444,
"s": 28303,
"text": "if(Firstcondition) { \n // code to run if condition is true\n}\nelse if(Secondcondition) {\n // code to run if condition is true\n}\nelse{\n}"
},
{
"code": null,
"e": 28457,
"s": 28444,
"text": "Flowchart: "
},
{
"code": null,
"e": 28551,
"s": 28457,
"text": "Below is the Kotlin program to determine the number is positive, negative or equal to zero. "
},
{
"code": null,
"e": 28556,
"s": 28551,
"text": "Java"
},
{
"code": "import java.util.Scanner fun main(args: Array<String>) { // create an object for scanner class val reader = Scanner(System.`in`) print(\"Enter any number: \") // read the next Integer value var num = reader.nextInt() var result = if ( num > 0){ \"$num is positive number\" } else if( num < 0){ \"$num is negative number\" } else{ \"$num is equal to zero\" } println(result) }",
"e": 29005,
"s": 28556,
"text": null
},
{
"code": null,
"e": 29015,
"s": 29005,
"text": "Output: "
},
{
"code": null,
"e": 29135,
"s": 29015,
"text": "Enter any number: 12\n12 is positive number\n\nEnter any number: -11\n-11 is negative number\n\nEnter any number: 0\n0 is zero"
},
{
"code": null,
"e": 29490,
"s": 29135,
"text": " nested if expression: Nested if statements means an if statement inside another if statement.If first condition is true then code the associated block to be executed, and again check for the if condition nested in the first block and if it is also true then execute the code associated with it. It will go on until the last condition is true. Syntax: "
},
{
"code": null,
"e": 29587,
"s": 29490,
"text": "if(condition1){\n // code 1\n if(condition2){\n // code2\n }\n}"
},
{
"code": null,
"e": 29600,
"s": 29587,
"text": "Flowchart: "
},
{
"code": null,
"e": 29683,
"s": 29600,
"text": "Below is the Kotlin program to determine the largest value among three Integers. "
},
{
"code": null,
"e": 29688,
"s": 29683,
"text": "Java"
},
{
"code": "import java.util.Scanner fun main(args: Array<String>) { // create an object for scanner class val reader = Scanner(System.`in`) print(\"Enter three numbers: \") var num1 = reader.nextInt() var num2 = reader.nextInt() var num3 = reader.nextInt() var max = if ( num1 > num2) { if (num1 > num3) { \"$num1 is the largest number\" } else { \"$num3 is the largest number\" } } else if( num2 > num3){ \"$num2 is the largest number\" } else{ \"$num3 is the largest number\" } println(max) }",
"e": 30276,
"s": 29688,
"text": null
},
{
"code": null,
"e": 30286,
"s": 30276,
"text": "Output: "
},
{
"code": null,
"e": 30345,
"s": 30286,
"text": "Enter three numbers: 123 231 321\n321 is the largest number"
},
{
"code": null,
"e": 30360,
"s": 30347,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 30376,
"s": 30360,
"text": "rajeev0719singh"
},
{
"code": null,
"e": 30383,
"s": 30376,
"text": "Kotlin"
},
{
"code": null,
"e": 30481,
"s": 30383,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30512,
"s": 30481,
"text": "Android RecyclerView in Kotlin"
},
{
"code": null,
"e": 30554,
"s": 30512,
"text": "Retrofit with Kotlin Coroutine in Android"
},
{
"code": null,
"e": 30594,
"s": 30554,
"text": "How to Get Current Location in Android?"
},
{
"code": null,
"e": 30624,
"s": 30594,
"text": "Kotlin Higher-Order Functions"
},
{
"code": null,
"e": 30638,
"s": 30624,
"text": "Android Menus"
},
{
"code": null,
"e": 30672,
"s": 30638,
"text": "ImageView in Android with Example"
},
{
"code": null,
"e": 30691,
"s": 30672,
"text": "Kotlin constructor"
},
{
"code": null,
"e": 30730,
"s": 30691,
"text": "How to Build a Weather App in Android?"
},
{
"code": null,
"e": 30764,
"s": 30730,
"text": "Android SQLite Database in Kotlin"
}
] |
Need help selecting non-empty column values from MySQL?
|
Select non-empty column values using NOT IS NULL and TRIM() function. The syntax is as follows.
SELECT * FROM yourTableName WHERE yourColumnName IS NOT NULL AND TRIM(yourColumnName) <> ' ';
You can select non-empty value as well as whitespace from column using the same TRIM() function.
To understand the syntax we discussed above, let us create a table. The query to create a table is as follows −
mysql> create table SelectNonEmptyValues
-> (
-> Id int not null auto_increment,
-> Name varchar(30),
-> PRIMARY KEY(Id)
-> );
Query OK, 0 rows affected (0.62 sec)
Insert records in the table using insert command. The query is as follows −
mysql> insert into SelectNonEmptyValues(Name) values('John Smith');
Query OK, 1 row affected (0.20 sec)
mysql> insert into SelectNonEmptyValues(Name) values(NULL);
Query OK, 1 row affected (0.13 sec)
mysql> insert into SelectNonEmptyValues(Name) values('');
Query OK, 1 row affected (0.24 sec)
mysql> insert into SelectNonEmptyValues(Name) values('Carol Taylor');
Query OK, 1 row affected (0.13 sec)
mysql> insert into SelectNonEmptyValues(Name) values('DavidMiller');
Query OK, 1 row affected (0.28 sec)
mysql> insert into SelectNonEmptyValues(Name) values(' ');
Query OK, 1 row affected (0.18 sec)
Display all records from the table using select statement −
mysql> select *from SelectNonEmptyValues;
The following is the output −
+----+-----------------------+
| Id | Name |
+----+-----------------------+
| 1 | John Smith |
| 2 | NULL |
| 3 | |
| 4 | Carol Taylor |
| 5 | DavidMiller |
| 6 | |
+----+-----------------------+
6 rows in set (0.00 sec)
Here is the query to select non-empty values. The below query works for all cases − if the column has NULL, empty string or whitespaces −
mysql> SELECT * FROM SelectNonEmptyValues WHERE Name IS NOT NULL AND TRIM(Name) <> '';
The following is the output −
+----+--------------+
| Id | Name |
+----+--------------+
| 1 | John Smith |
| 4 | Carol Taylor |
| 5 | DavidMiller |
+----+--------------+
3 rows in set (0.00 sec)
|
[
{
"code": null,
"e": 1158,
"s": 1062,
"text": "Select non-empty column values using NOT IS NULL and TRIM() function. The syntax is as follows."
},
{
"code": null,
"e": 1252,
"s": 1158,
"text": "SELECT * FROM yourTableName WHERE yourColumnName IS NOT NULL AND TRIM(yourColumnName) <> ' ';"
},
{
"code": null,
"e": 1349,
"s": 1252,
"text": "You can select non-empty value as well as whitespace from column using the same TRIM() function."
},
{
"code": null,
"e": 1461,
"s": 1349,
"text": "To understand the syntax we discussed above, let us create a table. The query to create a table is as follows −"
},
{
"code": null,
"e": 1640,
"s": 1461,
"text": "mysql> create table SelectNonEmptyValues\n -> (\n -> Id int not null auto_increment,\n -> Name varchar(30),\n -> PRIMARY KEY(Id)\n -> );\nQuery OK, 0 rows affected (0.62 sec)"
},
{
"code": null,
"e": 1716,
"s": 1640,
"text": "Insert records in the table using insert command. The query is as follows −"
},
{
"code": null,
"e": 2321,
"s": 1716,
"text": "mysql> insert into SelectNonEmptyValues(Name) values('John Smith');\nQuery OK, 1 row affected (0.20 sec)\n\nmysql> insert into SelectNonEmptyValues(Name) values(NULL);\nQuery OK, 1 row affected (0.13 sec)\n\nmysql> insert into SelectNonEmptyValues(Name) values('');\nQuery OK, 1 row affected (0.24 sec)\n\nmysql> insert into SelectNonEmptyValues(Name) values('Carol Taylor');\nQuery OK, 1 row affected (0.13 sec)\n\nmysql> insert into SelectNonEmptyValues(Name) values('DavidMiller');\nQuery OK, 1 row affected (0.28 sec)\n\nmysql> insert into SelectNonEmptyValues(Name) values(' ');\nQuery OK, 1 row affected (0.18 sec)"
},
{
"code": null,
"e": 2381,
"s": 2321,
"text": "Display all records from the table using select statement −"
},
{
"code": null,
"e": 2423,
"s": 2381,
"text": "mysql> select *from SelectNonEmptyValues;"
},
{
"code": null,
"e": 2453,
"s": 2423,
"text": "The following is the output −"
},
{
"code": null,
"e": 2788,
"s": 2453,
"text": "+----+-----------------------+\n| Id | Name |\n+----+-----------------------+\n| 1 | John Smith |\n| 2 | NULL |\n| 3 | |\n| 4 | Carol Taylor |\n| 5 | DavidMiller |\n| 6 | |\n+----+-----------------------+\n6 rows in set (0.00 sec)"
},
{
"code": null,
"e": 2926,
"s": 2788,
"text": "Here is the query to select non-empty values. The below query works for all cases − if the column has NULL, empty string or whitespaces −"
},
{
"code": null,
"e": 3013,
"s": 2926,
"text": "mysql> SELECT * FROM SelectNonEmptyValues WHERE Name IS NOT NULL AND TRIM(Name) <> '';"
},
{
"code": null,
"e": 3043,
"s": 3013,
"text": "The following is the output −"
},
{
"code": null,
"e": 3222,
"s": 3043,
"text": "+----+--------------+\n| Id | Name |\n+----+--------------+\n| 1 | John Smith |\n| 4 | Carol Taylor |\n| 5 | DavidMiller |\n+----+--------------+\n3 rows in set (0.00 sec)"
}
] |
Remove Leading Zeros from a String in C#
|
Let’s say the following is our string with leading zeros.
String str ="000234";
Use the TrimStart() method and set the 0 to remove it.
TrimStart(new Char[] { '0' } )
The following is the complete code to remove leading zeros.
Live Demo
using System;
class Program {
static void Main() {
String str ="000234".TrimStart(new Char[] { '0' } );
Console.WriteLine(str);
}
}
234
|
[
{
"code": null,
"e": 1120,
"s": 1062,
"text": "Let’s say the following is our string with leading zeros."
},
{
"code": null,
"e": 1142,
"s": 1120,
"text": "String str =\"000234\";"
},
{
"code": null,
"e": 1197,
"s": 1142,
"text": "Use the TrimStart() method and set the 0 to remove it."
},
{
"code": null,
"e": 1228,
"s": 1197,
"text": "TrimStart(new Char[] { '0' } )"
},
{
"code": null,
"e": 1288,
"s": 1228,
"text": "The following is the complete code to remove leading zeros."
},
{
"code": null,
"e": 1299,
"s": 1288,
"text": " Live Demo"
},
{
"code": null,
"e": 1450,
"s": 1299,
"text": "using System;\nclass Program {\n static void Main() {\n\n String str =\"000234\".TrimStart(new Char[] { '0' } );\n Console.WriteLine(str);\n }\n}"
},
{
"code": null,
"e": 1454,
"s": 1450,
"text": "234"
}
] |
Find XOR of all elements in an Array - GeeksforGeeks
|
22 Mar, 2022
Given an array arr[] containing integers of size N, the task is to find the XOR of this array.Examples:
Input: arr[] = {2, 4, 7} Output: 1 Explanation: XOR of the array = 2 ^ 4 ^ 7 = 1Input: arr[] = { 3, 9, 12, 13, 15 } Output: 4
Approach: In order to find the XOR of all elements in the array, we simply iterate through the array and find the XOR using ‘^’ operator. Therefore, the following steps are followed to compute the answer:
Create a variable to store the XOR of the array as a result.For each element in the array, find the XOR of the element and the result variable using ‘^’ operator.Finally, the result variable stores the XOR of all elements in the array.
Create a variable to store the XOR of the array as a result.
For each element in the array, find the XOR of the element and the result variable using ‘^’ operator.
Finally, the result variable stores the XOR of all elements in the array.
Below is the implementation of the above approach:
CPP
C
Java
Python3
C#
Javascript
// C++ program to find the XOR of// all elements in the array #include <bits/stdc++.h>using namespace std; // Function to find the XOR of// all elements in the arrayint xorOfArray(int arr[], int n){ // Resultant variable int xor_arr = 0; // Iterating through every element in // the array for (int i = 0; i < n; i++) { // Find XOR with the result xor_arr = xor_arr ^ arr[i]; } // Return the XOR return xor_arr;} // Driver Codeint main(){ int arr[] = { 3, 9, 12, 13, 15 }; int n = sizeof(arr) / sizeof(arr[0]); // Function call cout << xorOfArray(arr, n) << endl; return 0;}
// C program to find the XOR of// all elements in the array#include <stdio.h> // Function to find the XOR of// all elements in the arrayint xorOfArray(int arr[], int n){ // Resultant variable int xor_arr = 0; // Iterating through every element in // the array for (int i = 0; i < n; i++) { // Find XOR with the result xor_arr = xor_arr ^ arr[i]; } // Return the XOR return xor_arr;} // Driver Codeint main(){ int arr[] = { 3, 9, 12, 13, 15 }; int n = sizeof(arr) / sizeof(arr[0]); // Function Call printf("%d\n", xorOfArray(arr, n)); return 0;} // This code is contributed by phalashi.
// Java program to find the XOR of// all elements in the arrayclass GFG { // Function to find the XOR of // all elements in the array static int xorOfArray(int arr[], int n) { // Resultant variable int xor_arr = 0; // Iterating through every element in // the array for (int i = 0; i < n; i++) { // Find XOR with the result xor_arr = xor_arr ^ arr[i]; } // Return the XOR return xor_arr; } // Driver Code public static void main (String[] args) { int arr[] = { 3, 9, 12, 13, 15 }; int n = arr.length; // Function call System.out.println(xorOfArray(arr, n)); }} // This code is contributed by Yash_R
# Python3 program to find the XOR of# all elements in the array # Function to find the XOR of# all elements in the arraydef xorOfArray(arr, n): # Resultant variable xor_arr = 0 # Iterating through every element in # the array for i in range(n): # Find XOR with the result xor_arr = xor_arr ^ arr[i] # Return the XOR return xor_arr # Driver Codeif __name__ == '__main__': arr = [3, 9, 12, 13, 15] n = len(arr) # Function call print(xorOfArray(arr, n)) # This code is contributed by mohit kumar 29
// C# program to find the XOR of// all elements in the arrayusing System; class GFG { // Function to find the XOR of // all elements in the array static int xorOfArray(int []arr, int n) { // Resultant variable int xor_arr = 0; // Iterating through every element in // the array for (int i = 0; i < n; i++) { // Find XOR with the result xor_arr = xor_arr ^ arr[i]; } // Return the XOR return xor_arr; } // Driver Code public static void Main (string[] args) { int []arr = { 3, 9, 12, 13, 15 }; int n = arr.Length; // Function call Console.WriteLine(xorOfArray(arr, n)); }} // This code is contributed by AnkitRai01
<script> // JavaScript program to find the XOR of// all elements in the array // Function to find the XOR of// all elements in the arrayfunction xorOfArray(arr, n){ // Resultant variable let xor_arr = 0; // Iterating through every element in // the array for (let i = 0; i < n; i++) { // Find XOR with the result xor_arr = xor_arr ^ arr[i]; } // Return the XOR return xor_arr;} // Driver Code let arr = [ 3, 9, 12, 13, 15 ]; let n = arr.length; // Function call document.write(xorOfArray(arr, n) + "<br>"); // This code is contributed by Surbhi Tyagi. </script>
4
Time Complexity: O(N), where N is the size of the array.
mohit kumar 29
Yash_R
ankthon
surbhityagi15
phasing17
Bitwise-XOR
number-digits
Arrays
Bit Magic
Arrays
Bit Magic
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Maximum and minimum of an array using minimum number of comparisons
Top 50 Array Coding Problems for Interviews
Introduction to Arrays
Multidimensional Arrays in Java
Linear Search
Bitwise Operators in C/C++
Left Shift and Right Shift Operators in C/C++
Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)
Count set bits in an integer
How to swap two numbers without using a temporary variable?
|
[
{
"code": null,
"e": 26608,
"s": 26580,
"text": "\n22 Mar, 2022"
},
{
"code": null,
"e": 26714,
"s": 26608,
"text": "Given an array arr[] containing integers of size N, the task is to find the XOR of this array.Examples: "
},
{
"code": null,
"e": 26842,
"s": 26714,
"text": "Input: arr[] = {2, 4, 7} Output: 1 Explanation: XOR of the array = 2 ^ 4 ^ 7 = 1Input: arr[] = { 3, 9, 12, 13, 15 } Output: 4 "
},
{
"code": null,
"e": 27051,
"s": 26844,
"text": "Approach: In order to find the XOR of all elements in the array, we simply iterate through the array and find the XOR using ‘^’ operator. Therefore, the following steps are followed to compute the answer: "
},
{
"code": null,
"e": 27287,
"s": 27051,
"text": "Create a variable to store the XOR of the array as a result.For each element in the array, find the XOR of the element and the result variable using ‘^’ operator.Finally, the result variable stores the XOR of all elements in the array."
},
{
"code": null,
"e": 27348,
"s": 27287,
"text": "Create a variable to store the XOR of the array as a result."
},
{
"code": null,
"e": 27451,
"s": 27348,
"text": "For each element in the array, find the XOR of the element and the result variable using ‘^’ operator."
},
{
"code": null,
"e": 27525,
"s": 27451,
"text": "Finally, the result variable stores the XOR of all elements in the array."
},
{
"code": null,
"e": 27578,
"s": 27525,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 27582,
"s": 27578,
"text": "CPP"
},
{
"code": null,
"e": 27584,
"s": 27582,
"text": "C"
},
{
"code": null,
"e": 27589,
"s": 27584,
"text": "Java"
},
{
"code": null,
"e": 27597,
"s": 27589,
"text": "Python3"
},
{
"code": null,
"e": 27600,
"s": 27597,
"text": "C#"
},
{
"code": null,
"e": 27611,
"s": 27600,
"text": "Javascript"
},
{
"code": "// C++ program to find the XOR of// all elements in the array #include <bits/stdc++.h>using namespace std; // Function to find the XOR of// all elements in the arrayint xorOfArray(int arr[], int n){ // Resultant variable int xor_arr = 0; // Iterating through every element in // the array for (int i = 0; i < n; i++) { // Find XOR with the result xor_arr = xor_arr ^ arr[i]; } // Return the XOR return xor_arr;} // Driver Codeint main(){ int arr[] = { 3, 9, 12, 13, 15 }; int n = sizeof(arr) / sizeof(arr[0]); // Function call cout << xorOfArray(arr, n) << endl; return 0;}",
"e": 28244,
"s": 27611,
"text": null
},
{
"code": "// C program to find the XOR of// all elements in the array#include <stdio.h> // Function to find the XOR of// all elements in the arrayint xorOfArray(int arr[], int n){ // Resultant variable int xor_arr = 0; // Iterating through every element in // the array for (int i = 0; i < n; i++) { // Find XOR with the result xor_arr = xor_arr ^ arr[i]; } // Return the XOR return xor_arr;} // Driver Codeint main(){ int arr[] = { 3, 9, 12, 13, 15 }; int n = sizeof(arr) / sizeof(arr[0]); // Function Call printf(\"%d\\n\", xorOfArray(arr, n)); return 0;} // This code is contributed by phalashi.",
"e": 28888,
"s": 28244,
"text": null
},
{
"code": "// Java program to find the XOR of// all elements in the arrayclass GFG { // Function to find the XOR of // all elements in the array static int xorOfArray(int arr[], int n) { // Resultant variable int xor_arr = 0; // Iterating through every element in // the array for (int i = 0; i < n; i++) { // Find XOR with the result xor_arr = xor_arr ^ arr[i]; } // Return the XOR return xor_arr; } // Driver Code public static void main (String[] args) { int arr[] = { 3, 9, 12, 13, 15 }; int n = arr.length; // Function call System.out.println(xorOfArray(arr, n)); }} // This code is contributed by Yash_R",
"e": 29656,
"s": 28888,
"text": null
},
{
"code": "# Python3 program to find the XOR of# all elements in the array # Function to find the XOR of# all elements in the arraydef xorOfArray(arr, n): # Resultant variable xor_arr = 0 # Iterating through every element in # the array for i in range(n): # Find XOR with the result xor_arr = xor_arr ^ arr[i] # Return the XOR return xor_arr # Driver Codeif __name__ == '__main__': arr = [3, 9, 12, 13, 15] n = len(arr) # Function call print(xorOfArray(arr, n)) # This code is contributed by mohit kumar 29",
"e": 30204,
"s": 29656,
"text": null
},
{
"code": "// C# program to find the XOR of// all elements in the arrayusing System; class GFG { // Function to find the XOR of // all elements in the array static int xorOfArray(int []arr, int n) { // Resultant variable int xor_arr = 0; // Iterating through every element in // the array for (int i = 0; i < n; i++) { // Find XOR with the result xor_arr = xor_arr ^ arr[i]; } // Return the XOR return xor_arr; } // Driver Code public static void Main (string[] args) { int []arr = { 3, 9, 12, 13, 15 }; int n = arr.Length; // Function call Console.WriteLine(xorOfArray(arr, n)); }} // This code is contributed by AnkitRai01",
"e": 30986,
"s": 30204,
"text": null
},
{
"code": "<script> // JavaScript program to find the XOR of// all elements in the array // Function to find the XOR of// all elements in the arrayfunction xorOfArray(arr, n){ // Resultant variable let xor_arr = 0; // Iterating through every element in // the array for (let i = 0; i < n; i++) { // Find XOR with the result xor_arr = xor_arr ^ arr[i]; } // Return the XOR return xor_arr;} // Driver Code let arr = [ 3, 9, 12, 13, 15 ]; let n = arr.length; // Function call document.write(xorOfArray(arr, n) + \"<br>\"); // This code is contributed by Surbhi Tyagi. </script>",
"e": 31602,
"s": 30986,
"text": null
},
{
"code": null,
"e": 31604,
"s": 31602,
"text": "4"
},
{
"code": null,
"e": 31664,
"s": 31606,
"text": "Time Complexity: O(N), where N is the size of the array. "
},
{
"code": null,
"e": 31679,
"s": 31664,
"text": "mohit kumar 29"
},
{
"code": null,
"e": 31686,
"s": 31679,
"text": "Yash_R"
},
{
"code": null,
"e": 31694,
"s": 31686,
"text": "ankthon"
},
{
"code": null,
"e": 31708,
"s": 31694,
"text": "surbhityagi15"
},
{
"code": null,
"e": 31718,
"s": 31708,
"text": "phasing17"
},
{
"code": null,
"e": 31730,
"s": 31718,
"text": "Bitwise-XOR"
},
{
"code": null,
"e": 31744,
"s": 31730,
"text": "number-digits"
},
{
"code": null,
"e": 31751,
"s": 31744,
"text": "Arrays"
},
{
"code": null,
"e": 31761,
"s": 31751,
"text": "Bit Magic"
},
{
"code": null,
"e": 31768,
"s": 31761,
"text": "Arrays"
},
{
"code": null,
"e": 31778,
"s": 31768,
"text": "Bit Magic"
},
{
"code": null,
"e": 31876,
"s": 31778,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31944,
"s": 31876,
"text": "Maximum and minimum of an array using minimum number of comparisons"
},
{
"code": null,
"e": 31988,
"s": 31944,
"text": "Top 50 Array Coding Problems for Interviews"
},
{
"code": null,
"e": 32011,
"s": 31988,
"text": "Introduction to Arrays"
},
{
"code": null,
"e": 32043,
"s": 32011,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 32057,
"s": 32043,
"text": "Linear Search"
},
{
"code": null,
"e": 32084,
"s": 32057,
"text": "Bitwise Operators in C/C++"
},
{
"code": null,
"e": 32130,
"s": 32084,
"text": "Left Shift and Right Shift Operators in C/C++"
},
{
"code": null,
"e": 32198,
"s": 32130,
"text": "Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)"
},
{
"code": null,
"e": 32227,
"s": 32198,
"text": "Count set bits in an integer"
}
] |
Apache POI - Fonts
|
This chapter explains how to set different fonts, apply styles, and display text in different angles of direction in an Excel spreadsheet.
Every system comes bundled with a huge collection of fonts such as Arial, Impact, Times New Roman, etc. The collection can also be updated with new fonts, if required. Similarly there are various styles in which a font can be displayed, for example, bold, italic, underline, strike through, etc.
The following code is used to apply a particular font and style to the contents of a cell.
import java.io.File;
import java.io.FileOutputStream;
import org.apache.poi.hssf.util.IndexedColors;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFFont;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class FontStyle {
public static void main(String[] args)throws Exception {
XSSFWorkbook workbook = new XSSFWorkbook();
XSSFSheet spreadsheet = workbook.createSheet("Fontstyle");
XSSFRow row = spreadsheet.createRow(2);
//Create a new font and alter it.
XSSFFont font = workbook.createFont();
font.setFontHeightInPoints((short) 30);
font.setFontName("IMPACT");
font.setItalic(true);
font.setColor(IndexedColors.BRIGHT_GREEN.index);
//Set font into style
XSSFCellStyle style = workbook.createCellStyle();
style.setFont(font);
// Create a cell with a value and set style to it.
XSSFCell cell = row.createCell(1);
cell.setCellValue("Font Style");
cell.setCellStyle(style);
FileOutputStream out = new FileOutputStream(new File("fontstyle.xlsx"));
workbook.write(out);
out.close();
System.out.println("fontstyle.xlsx written successfully");
}
}
Let us save the above code in a file named FontStyle.java. Compile and execute it from the command prompt as follows −
$javac FontStyle.java
$java FontStyle
It generates an Excel file named fontstyle.xlsx in your current directory and display the following output on the command prompt.
fontstyle.xlsx written successfully
The fontstyle.xlsx file looks as follows −
Here you can learn how to set the text direction in different angles. Usually cell contents are displayed horizontally, from left to right, and at 00 angle; however you can use the following code to rotate the text direction, if required.
import java.io.File;
import java.io.FileOutputStream;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class TextDirection {
public static void main(String[] args)throws Exception {
XSSFWorkbook workbook = new XSSFWorkbook();
XSSFSheet spreadsheet = workbook.createSheet("Text direction");
XSSFRow row = spreadsheet.createRow(2);
XSSFCellStyle myStyle = workbook.createCellStyle();
myStyle.setRotation((short) 0);
XSSFCell cell = row.createCell(1);
cell.setCellValue("0D angle");
cell.setCellStyle(myStyle);
//30 degrees
myStyle = workbook.createCellStyle();
myStyle.setRotation((short) 30);
cell = row.createCell(3);
cell.setCellValue("30D angle");
cell.setCellStyle(myStyle);
//90 degrees
myStyle = workbook.createCellStyle();
myStyle.setRotation((short) 90);
cell = row.createCell(5);
cell.setCellValue("90D angle");
cell.setCellStyle(myStyle);
//120 degrees
myStyle = workbook.createCellStyle();
myStyle.setRotation((short) 120);
cell = row.createCell(7);
cell.setCellValue("120D angle");
cell.setCellStyle(myStyle);
//270 degrees
myStyle = workbook.createCellStyle();
myStyle.setRotation((short) 270);
cell = row.createCell(9);
cell.setCellValue("270D angle");
cell.setCellStyle(myStyle);
//360 degrees
myStyle = workbook.createCellStyle();
myStyle.setRotation((short) 360);
cell = row.createCell(12);
cell.setCellValue("360D angle");
cell.setCellStyle(myStyle);
FileOutputStream out = new FileOutputStream(new File("textdirection.xlsx"));
workbook.write(out);
out.close();
System.out.println("textdirection.xlsx written successfully");
}
}
Keep the above code in TextDirectin.java file, then compile and execute it from the command prompt as follows −
$javac TextDirection.java
$java TextDirection
It will compile and execute to generate an Excel file named textdirection.xlsx in your current directory and display the following output on the command prompt.
textdirection.xlsx written successfully
The textdirection.xlsx file looks as follows −
46 Lectures
3.5 hours
Arnab Chakraborty
23 Lectures
1.5 hours
Mukund Kumar Mishra
16 Lectures
1 hours
Nilay Mehta
52 Lectures
1.5 hours
Bigdata Engineer
14 Lectures
1 hours
Bigdata Engineer
23 Lectures
1 hours
Bigdata Engineer
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2043,
"s": 1904,
"text": "This chapter explains how to set different fonts, apply styles, and display text in different angles of direction in an Excel spreadsheet."
},
{
"code": null,
"e": 2339,
"s": 2043,
"text": "Every system comes bundled with a huge collection of fonts such as Arial, Impact, Times New Roman, etc. The collection can also be updated with new fonts, if required. Similarly there are various styles in which a font can be displayed, for example, bold, italic, underline, strike through, etc."
},
{
"code": null,
"e": 2430,
"s": 2339,
"text": "The following code is used to apply a particular font and style to the contents of a cell."
},
{
"code": null,
"e": 3805,
"s": 2430,
"text": "import java.io.File;\nimport java.io.FileOutputStream;\nimport org.apache.poi.hssf.util.IndexedColors;\nimport org.apache.poi.xssf.usermodel.XSSFCell;\nimport org.apache.poi.xssf.usermodel.XSSFCellStyle;\nimport org.apache.poi.xssf.usermodel.XSSFFont;\nimport org.apache.poi.xssf.usermodel.XSSFRow;\nimport org.apache.poi.xssf.usermodel.XSSFSheet;\nimport org.apache.poi.xssf.usermodel.XSSFWorkbook;\n\npublic class FontStyle {\n public static void main(String[] args)throws Exception {\n XSSFWorkbook workbook = new XSSFWorkbook(); \n XSSFSheet spreadsheet = workbook.createSheet(\"Fontstyle\");\n XSSFRow row = spreadsheet.createRow(2);\n\n //Create a new font and alter it.\n XSSFFont font = workbook.createFont();\n font.setFontHeightInPoints((short) 30);\n font.setFontName(\"IMPACT\");\n font.setItalic(true);\n font.setColor(IndexedColors.BRIGHT_GREEN.index);\n\n //Set font into style\n XSSFCellStyle style = workbook.createCellStyle();\n style.setFont(font);\n\n // Create a cell with a value and set style to it.\n XSSFCell cell = row.createCell(1);\n cell.setCellValue(\"Font Style\");\n cell.setCellStyle(style);\n \n FileOutputStream out = new FileOutputStream(new File(\"fontstyle.xlsx\"));\n workbook.write(out);\n out.close();\n System.out.println(\"fontstyle.xlsx written successfully\");\n }\n}"
},
{
"code": null,
"e": 3924,
"s": 3805,
"text": "Let us save the above code in a file named FontStyle.java. Compile and execute it from the command prompt as follows −"
},
{
"code": null,
"e": 3963,
"s": 3924,
"text": "$javac FontStyle.java\n$java FontStyle\n"
},
{
"code": null,
"e": 4093,
"s": 3963,
"text": "It generates an Excel file named fontstyle.xlsx in your current directory and display the following output on the command prompt."
},
{
"code": null,
"e": 4130,
"s": 4093,
"text": "fontstyle.xlsx written successfully\n"
},
{
"code": null,
"e": 4173,
"s": 4130,
"text": "The fontstyle.xlsx file looks as follows −"
},
{
"code": null,
"e": 4412,
"s": 4173,
"text": "Here you can learn how to set the text direction in different angles. Usually cell contents are displayed horizontally, from left to right, and at 00 angle; however you can use the following code to rotate the text direction, if required."
},
{
"code": null,
"e": 6433,
"s": 4412,
"text": "import java.io.File;\nimport java.io.FileOutputStream;\n\nimport org.apache.poi.xssf.usermodel.XSSFCell;\nimport org.apache.poi.xssf.usermodel.XSSFCellStyle;\nimport org.apache.poi.xssf.usermodel.XSSFRow;\nimport org.apache.poi.xssf.usermodel.XSSFSheet;\nimport org.apache.poi.xssf.usermodel.XSSFWorkbook;\n\npublic class TextDirection {\n public static void main(String[] args)throws Exception {\n XSSFWorkbook workbook = new XSSFWorkbook(); \n XSSFSheet spreadsheet = workbook.createSheet(\"Text direction\");\n XSSFRow row = spreadsheet.createRow(2);\n XSSFCellStyle myStyle = workbook.createCellStyle();\n myStyle.setRotation((short) 0);\n XSSFCell cell = row.createCell(1);\n cell.setCellValue(\"0D angle\");\n cell.setCellStyle(myStyle);\n\n //30 degrees\n myStyle = workbook.createCellStyle();\n myStyle.setRotation((short) 30);\n cell = row.createCell(3);\n cell.setCellValue(\"30D angle\");\n cell.setCellStyle(myStyle);\n\n //90 degrees\n myStyle = workbook.createCellStyle();\n myStyle.setRotation((short) 90);\n cell = row.createCell(5);\n cell.setCellValue(\"90D angle\");\n cell.setCellStyle(myStyle);\n\n //120 degrees\n myStyle = workbook.createCellStyle();\n myStyle.setRotation((short) 120);\n cell = row.createCell(7);\n cell.setCellValue(\"120D angle\");\n cell.setCellStyle(myStyle);\n\n //270 degrees\n myStyle = workbook.createCellStyle();\n myStyle.setRotation((short) 270);\n cell = row.createCell(9);\n cell.setCellValue(\"270D angle\");\n cell.setCellStyle(myStyle);\n\n //360 degrees\n myStyle = workbook.createCellStyle();\n myStyle.setRotation((short) 360);\n cell = row.createCell(12);\n cell.setCellValue(\"360D angle\");\n cell.setCellStyle(myStyle);\n \n FileOutputStream out = new FileOutputStream(new File(\"textdirection.xlsx\"));\n workbook.write(out);\n out.close();\n System.out.println(\"textdirection.xlsx written successfully\");\n }\n}"
},
{
"code": null,
"e": 6545,
"s": 6433,
"text": "Keep the above code in TextDirectin.java file, then compile and execute it from the command prompt as follows −"
},
{
"code": null,
"e": 6592,
"s": 6545,
"text": "$javac TextDirection.java\n$java TextDirection\n"
},
{
"code": null,
"e": 6753,
"s": 6592,
"text": "It will compile and execute to generate an Excel file named textdirection.xlsx in your current directory and display the following output on the command prompt."
},
{
"code": null,
"e": 6794,
"s": 6753,
"text": "textdirection.xlsx written successfully\n"
},
{
"code": null,
"e": 6841,
"s": 6794,
"text": "The textdirection.xlsx file looks as follows −"
},
{
"code": null,
"e": 6876,
"s": 6841,
"text": "\n 46 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 6895,
"s": 6876,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 6930,
"s": 6895,
"text": "\n 23 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 6951,
"s": 6930,
"text": " Mukund Kumar Mishra"
},
{
"code": null,
"e": 6984,
"s": 6951,
"text": "\n 16 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 6997,
"s": 6984,
"text": " Nilay Mehta"
},
{
"code": null,
"e": 7032,
"s": 6997,
"text": "\n 52 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 7050,
"s": 7032,
"text": " Bigdata Engineer"
},
{
"code": null,
"e": 7083,
"s": 7050,
"text": "\n 14 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 7101,
"s": 7083,
"text": " Bigdata Engineer"
},
{
"code": null,
"e": 7134,
"s": 7101,
"text": "\n 23 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 7152,
"s": 7134,
"text": " Bigdata Engineer"
},
{
"code": null,
"e": 7159,
"s": 7152,
"text": " Print"
},
{
"code": null,
"e": 7170,
"s": 7159,
"text": " Add Notes"
}
] |
PHP mysqli_connect_error() Function
|
During the attempt to connect to a MySQL server, if an occurs, the mysqli_connect_error() function returns the description of the error occurred (during the last connect call).
mysqli_connect_error()
This method doesn't accept any parameters.
PHP mysqli_connect_error() function returns an string value representing the description of the error from the last connection call, incase of a failure. If the connection was successful this function returns Null.
This function was first introduced in PHP Version 5 and works works in all the later versions.
Following example demonstrates the usage of the mysqli_connect_error() function (in procedural style) −
<?php
//Creating a connection
$con = @mysqli_connect("localhost", "root", "wrong_password", "mydb");
//Connection Error
$error = mysqli_connect_error($con);
print("Error: ".$error);
?>
This will produce following result −
Error: Access denied for user 'root'@'localhost' (using password: YES)
In object oriented style the syntax of this function is $con -> connect_error. Following is the example of this function in object oriented style −
<?php
//Creating a connection
$con = @new mysqli("localhost", "root", "wrong_password", "mydb");
//Connection Error
$error = $con->connect_error;
print("Error: ".$error);
?>
This will produce following result −
Error: Access denied for user 'root'@'localhost' (using password: YES)
Following example demonstrates the behaviour of the mysqli_connect_error() function incase of a successful connection −
<?php
//Creating a connection
$con = @mysqli_connect("localhost", "root", "password", "mydb");
//Connection Error
$error = mysqli_connect_error();
if(!$con){
print("Connection Failed: ".$error);
}else{
print("Connection Established Successfully");
}
?>
This will produce following result −
Connection Established Successfully
<?php
$connection = @mysqli_connect("localhost","root","wrong_pass","wrong_db");
if (!$connection){
die("Connection error: " . mysqli_connect_error());
}
?>
This will produce following result −
Connection error: Access denied for user 'root'@'localhost' (using password: YES)
|
[
{
"code": null,
"e": 3068,
"s": 2891,
"text": "During the attempt to connect to a MySQL server, if an occurs, the mysqli_connect_error() function returns the description of the error occurred (during the last connect call)."
},
{
"code": null,
"e": 3092,
"s": 3068,
"text": "mysqli_connect_error()\n"
},
{
"code": null,
"e": 3135,
"s": 3092,
"text": "This method doesn't accept any parameters."
},
{
"code": null,
"e": 3350,
"s": 3135,
"text": "PHP mysqli_connect_error() function returns an string value representing the description of the error from the last connection call, incase of a failure. If the connection was successful this function returns Null."
},
{
"code": null,
"e": 3445,
"s": 3350,
"text": "This function was first introduced in PHP Version 5 and works works in all the later versions."
},
{
"code": null,
"e": 3549,
"s": 3445,
"text": "Following example demonstrates the usage of the mysqli_connect_error() function (in procedural style) −"
},
{
"code": null,
"e": 3750,
"s": 3549,
"text": "<?php\n //Creating a connection\n $con = @mysqli_connect(\"localhost\", \"root\", \"wrong_password\", \"mydb\");\n\n //Connection Error\n $error = mysqli_connect_error($con);\n print(\"Error: \".$error);\n?>"
},
{
"code": null,
"e": 3787,
"s": 3750,
"text": "This will produce following result −"
},
{
"code": null,
"e": 3859,
"s": 3787,
"text": "Error: Access denied for user 'root'@'localhost' (using password: YES)\n"
},
{
"code": null,
"e": 4007,
"s": 3859,
"text": "In object oriented style the syntax of this function is $con -> connect_error. Following is the example of this function in object oriented style −"
},
{
"code": null,
"e": 4197,
"s": 4007,
"text": "<?php\n //Creating a connection\n $con = @new mysqli(\"localhost\", \"root\", \"wrong_password\", \"mydb\");\n\n //Connection Error\n $error = $con->connect_error;\n print(\"Error: \".$error);\n?>"
},
{
"code": null,
"e": 4234,
"s": 4197,
"text": "This will produce following result −"
},
{
"code": null,
"e": 4306,
"s": 4234,
"text": "Error: Access denied for user 'root'@'localhost' (using password: YES)\n"
},
{
"code": null,
"e": 4426,
"s": 4306,
"text": "Following example demonstrates the behaviour of the mysqli_connect_error() function incase of a successful connection −"
},
{
"code": null,
"e": 4716,
"s": 4426,
"text": "<?php\n //Creating a connection\n $con = @mysqli_connect(\"localhost\", \"root\", \"password\", \"mydb\");\n \n //Connection Error\n $error = mysqli_connect_error();\n if(!$con){\n print(\"Connection Failed: \".$error);\n }else{\n print(\"Connection Established Successfully\");\n }\n?>"
},
{
"code": null,
"e": 4753,
"s": 4716,
"text": "This will produce following result −"
},
{
"code": null,
"e": 4790,
"s": 4753,
"text": "Connection Established Successfully\n"
},
{
"code": null,
"e": 4966,
"s": 4790,
"text": "<?php\n $connection = @mysqli_connect(\"localhost\",\"root\",\"wrong_pass\",\"wrong_db\");\n \n if (!$connection){\n die(\"Connection error: \" . mysqli_connect_error());\n }\n?>"
},
{
"code": null,
"e": 5003,
"s": 4966,
"text": "This will produce following result −"
}
] |
CIL or MSIL | Microsoft Intermediate Language or Common Intermediate Language
|
30 Apr, 2019
The Microsoft Intermediate Language (MSIL), also known as the Common Intermediate Language (CIL) is a set of instructions that are platform independent and are generated by the language-specific compiler from the source code. The MSIL is platform independent and consequently, it can be executed on any of the Common Language Infrastructure supported environments such as the Windows .NET runtime.The MSIL is converted into a particular computer environment specific machine code by the JIT compiler. This is done before the MSIL can be executed. Also, the MSIL is converted into the machine code on a requirement basis i.e. the JIT compiler compiles the MSIL as required rather than the whole of it.
Execution process in Common Language Runtime (CLR): The execution process that includes the creation of the MSIL and the conversion of the MSIL into machine code by the JIT compiler is given as follows:
The source code is converted into the MSIL by a language-specific compiler in the compile time of the CLR. Also, along with the MSIL, metadata is also produced in the compilation. The metadata contains information such as the definition and signature of the types in the code, runtime information, etc.
A Common Language Infrastructure (CLI) assembly is created by assembling the MSIL. This assembly is basically a compiled code library that is used for security, deployment, versioning, etc. and it is of two types i.e. process assembly (EXE) and library assembly (DLL).
The JIT compiler then converts the Microsoft Intermediate Language(MSIL) into the machine code that is specific to the computer environment that the JIT compiler runs on. The MSIL is converted into the machine code on a requirement basis i.e. the JIT compiler compiles the MSIL as required rather than the whole of it.
The machine code obtained using the JIT compiler is then executed by the processor of the computer.
Example: The MSIL is generated by the language specific compiler from the source code given below. To understand the MSIL in detail, simple C# source code with the class Demo that prints “GeeksforGeeks is given as follows:
using System; public class Demo { public static void Main() { Console.WriteLine("GeeksforGeeks"); }}
The MSIL that is created by the C# compiler for the code provided above is given as follows:
// =============== CLASS MEMBERS DECLARATION ===================
.class public auto ansi beforefieldinit Demo
extends [mscorlib]System.Object
{
.method public hidebysig static void Main() cil managed
{
//
.maxstack 8
IL_0000: nop
IL_0001: ldstr "GeeksforGeeks"
IL_0006: call void [mscorlib]System.Console::WriteLine(string)
IL_000b: nop
IL_000c: ret
} // end of method Demo::Main
.method public hidebysig specialname rtspecialname
instance void .ctor() cil managed
{
//
.maxstack 8
IL_0000: ldarg.0
IL_0001: call instance void [mscorlib]System.Object::.ctor()
IL_0006: ret
} // end of method Demo::.ctor
} // end of class Demo
// =============================================================
In the above MSIL, there are opcodes that are one or two bytes long. The base class declarations from which all other classes are inherited are contained in the mscorlib.dll. In the method Main(), the instruction ldstr loads the string “GeeksforGeeks” on the stack. Then the static System.Console.Writeline function is called and the string is popped from the stack. Finally, the ret instruction signals the end of the function call.Then the .ctor() statement implies a default constructor without parameters for the class Demo. This constructor is automatically created by the compiler for the non-static class Demo. The call instruction passes the base object constructor and the ret instruction signals the end of the function call.
Dot-NET
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n30 Apr, 2019"
},
{
"code": null,
"e": 755,
"s": 54,
"text": "The Microsoft Intermediate Language (MSIL), also known as the Common Intermediate Language (CIL) is a set of instructions that are platform independent and are generated by the language-specific compiler from the source code. The MSIL is platform independent and consequently, it can be executed on any of the Common Language Infrastructure supported environments such as the Windows .NET runtime.The MSIL is converted into a particular computer environment specific machine code by the JIT compiler. This is done before the MSIL can be executed. Also, the MSIL is converted into the machine code on a requirement basis i.e. the JIT compiler compiles the MSIL as required rather than the whole of it."
},
{
"code": null,
"e": 958,
"s": 755,
"text": "Execution process in Common Language Runtime (CLR): The execution process that includes the creation of the MSIL and the conversion of the MSIL into machine code by the JIT compiler is given as follows:"
},
{
"code": null,
"e": 1261,
"s": 958,
"text": "The source code is converted into the MSIL by a language-specific compiler in the compile time of the CLR. Also, along with the MSIL, metadata is also produced in the compilation. The metadata contains information such as the definition and signature of the types in the code, runtime information, etc."
},
{
"code": null,
"e": 1530,
"s": 1261,
"text": "A Common Language Infrastructure (CLI) assembly is created by assembling the MSIL. This assembly is basically a compiled code library that is used for security, deployment, versioning, etc. and it is of two types i.e. process assembly (EXE) and library assembly (DLL)."
},
{
"code": null,
"e": 1849,
"s": 1530,
"text": "The JIT compiler then converts the Microsoft Intermediate Language(MSIL) into the machine code that is specific to the computer environment that the JIT compiler runs on. The MSIL is converted into the machine code on a requirement basis i.e. the JIT compiler compiles the MSIL as required rather than the whole of it."
},
{
"code": null,
"e": 1949,
"s": 1849,
"text": "The machine code obtained using the JIT compiler is then executed by the processor of the computer."
},
{
"code": null,
"e": 2172,
"s": 1949,
"text": "Example: The MSIL is generated by the language specific compiler from the source code given below. To understand the MSIL in detail, simple C# source code with the class Demo that prints “GeeksforGeeks is given as follows:"
},
{
"code": "using System; public class Demo { public static void Main() { Console.WriteLine(\"GeeksforGeeks\"); }}",
"e": 2290,
"s": 2172,
"text": null
},
{
"code": null,
"e": 2383,
"s": 2290,
"text": "The MSIL that is created by the C# compiler for the code provided above is given as follows:"
},
{
"code": null,
"e": 3190,
"s": 2383,
"text": "// =============== CLASS MEMBERS DECLARATION ===================\n\n.class public auto ansi beforefieldinit Demo\n extends [mscorlib]System.Object\n{\n .method public hidebysig static void Main() cil managed\n {\n // \n .maxstack 8\n IL_0000: nop\n IL_0001: ldstr \"GeeksforGeeks\"\n IL_0006: call void [mscorlib]System.Console::WriteLine(string)\n IL_000b: nop\n IL_000c: ret\n } // end of method Demo::Main\n\n .method public hidebysig specialname rtspecialname \n instance void .ctor() cil managed\n {\n // \n .maxstack 8\n IL_0000: ldarg.0\n IL_0001: call instance void [mscorlib]System.Object::.ctor()\n IL_0006: ret\n } // end of method Demo::.ctor\n\n} // end of class Demo\n\n\n// =============================================================\n"
},
{
"code": null,
"e": 3926,
"s": 3190,
"text": "In the above MSIL, there are opcodes that are one or two bytes long. The base class declarations from which all other classes are inherited are contained in the mscorlib.dll. In the method Main(), the instruction ldstr loads the string “GeeksforGeeks” on the stack. Then the static System.Console.Writeline function is called and the string is popped from the stack. Finally, the ret instruction signals the end of the function call.Then the .ctor() statement implies a default constructor without parameters for the class Demo. This constructor is automatically created by the compiler for the non-static class Demo. The call instruction passes the base object constructor and the ret instruction signals the end of the function call."
},
{
"code": null,
"e": 3934,
"s": 3926,
"text": "Dot-NET"
},
{
"code": null,
"e": 3937,
"s": 3934,
"text": "C#"
}
] |
Python – Find union of multiple sets
|
02 Feb, 2021
Given multiple sets list, the task is to write a Python program to find union of each set.
Examples:
Input : test_list = [{4, 3, 5, 2}, {8, 4, 7, 2}, {1, 2, 3, 4}, {9, 5, 3, 7}]
Output : {1, 2, 3, 4, 5, 7, 8, 9}
Explanation : All elements from all sets included. Duplicates removed.
Input : test_list = [{4, 3, 5, 2}, {8, 4, 7, 2}, {1, 2, 3, 4}]
Output : {1, 2, 3, 4, 5, 7, 8}
Explanation : All elements from all sets included. Duplicates removed.
Method #1 : Using union() + * operator
In this, we perform task of getting union using union(), and * operator is used to perform task of packing all the sets together.
Python3
# Python3 code to demonstrate working of# Union multiple sets# Using union() + * operator # initializing listtest_list = [{4, 3, 5, 2}, {8, 4, 7, 2}, {1, 2, 3, 4}, {9, 5, 3, 7}] # printing original listprint("The original list is : " + str(test_list)) # * operator packs sets for unionres = set().union(*test_list) # printing resultprint("Multiple set union : " + str(res))
Output:
The original list is : [{2, 3, 4, 5}, {8, 2, 4, 7}, {1, 2, 3, 4}, {9, 3, 5, 7}]
Multiple set union : {1, 2, 3, 4, 5, 7, 8, 9}
Method #2 : Using chain.from_iterable() + * operator
In this, we perform task of union, which in turn is flattening using from_iterable().
Python3
# Python3 code to demonstrate working of# Union multiple sets# Using chain.from_iterable() + * operatorfrom itertools import chain # initializing listtest_list = [{4, 3, 5, 2}, {8, 4, 7, 2}, {1, 2, 3, 4}, {9, 5, 3, 7}] # printing original listprint("The original list is : " + str(test_list)) # * operator packs sets for unionres = set(chain(*test_list)) # printing resultprint("Multiple set union : " + str(res))
Output:
The original list is : [{2, 3, 4, 5}, {8, 2, 4, 7}, {1, 2, 3, 4}, {9, 3, 5, 7}]
Multiple set union : {1, 2, 3, 4, 5, 7, 8, 9}
Python set-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n02 Feb, 2021"
},
{
"code": null,
"e": 119,
"s": 28,
"text": "Given multiple sets list, the task is to write a Python program to find union of each set."
},
{
"code": null,
"e": 129,
"s": 119,
"text": "Examples:"
},
{
"code": null,
"e": 206,
"s": 129,
"text": "Input : test_list = [{4, 3, 5, 2}, {8, 4, 7, 2}, {1, 2, 3, 4}, {9, 5, 3, 7}]"
},
{
"code": null,
"e": 240,
"s": 206,
"text": "Output : {1, 2, 3, 4, 5, 7, 8, 9}"
},
{
"code": null,
"e": 311,
"s": 240,
"text": "Explanation : All elements from all sets included. Duplicates removed."
},
{
"code": null,
"e": 374,
"s": 311,
"text": "Input : test_list = [{4, 3, 5, 2}, {8, 4, 7, 2}, {1, 2, 3, 4}]"
},
{
"code": null,
"e": 405,
"s": 374,
"text": "Output : {1, 2, 3, 4, 5, 7, 8}"
},
{
"code": null,
"e": 476,
"s": 405,
"text": "Explanation : All elements from all sets included. Duplicates removed."
},
{
"code": null,
"e": 515,
"s": 476,
"text": "Method #1 : Using union() + * operator"
},
{
"code": null,
"e": 645,
"s": 515,
"text": "In this, we perform task of getting union using union(), and * operator is used to perform task of packing all the sets together."
},
{
"code": null,
"e": 653,
"s": 645,
"text": "Python3"
},
{
"code": "# Python3 code to demonstrate working of# Union multiple sets# Using union() + * operator # initializing listtest_list = [{4, 3, 5, 2}, {8, 4, 7, 2}, {1, 2, 3, 4}, {9, 5, 3, 7}] # printing original listprint(\"The original list is : \" + str(test_list)) # * operator packs sets for unionres = set().union(*test_list) # printing resultprint(\"Multiple set union : \" + str(res))",
"e": 1031,
"s": 653,
"text": null
},
{
"code": null,
"e": 1039,
"s": 1031,
"text": "Output:"
},
{
"code": null,
"e": 1119,
"s": 1039,
"text": "The original list is : [{2, 3, 4, 5}, {8, 2, 4, 7}, {1, 2, 3, 4}, {9, 3, 5, 7}]"
},
{
"code": null,
"e": 1165,
"s": 1119,
"text": "Multiple set union : {1, 2, 3, 4, 5, 7, 8, 9}"
},
{
"code": null,
"e": 1218,
"s": 1165,
"text": "Method #2 : Using chain.from_iterable() + * operator"
},
{
"code": null,
"e": 1304,
"s": 1218,
"text": "In this, we perform task of union, which in turn is flattening using from_iterable()."
},
{
"code": null,
"e": 1312,
"s": 1304,
"text": "Python3"
},
{
"code": "# Python3 code to demonstrate working of# Union multiple sets# Using chain.from_iterable() + * operatorfrom itertools import chain # initializing listtest_list = [{4, 3, 5, 2}, {8, 4, 7, 2}, {1, 2, 3, 4}, {9, 5, 3, 7}] # printing original listprint(\"The original list is : \" + str(test_list)) # * operator packs sets for unionres = set(chain(*test_list)) # printing resultprint(\"Multiple set union : \" + str(res))",
"e": 1730,
"s": 1312,
"text": null
},
{
"code": null,
"e": 1738,
"s": 1730,
"text": "Output:"
},
{
"code": null,
"e": 1818,
"s": 1738,
"text": "The original list is : [{2, 3, 4, 5}, {8, 2, 4, 7}, {1, 2, 3, 4}, {9, 3, 5, 7}]"
},
{
"code": null,
"e": 1864,
"s": 1818,
"text": "Multiple set union : {1, 2, 3, 4, 5, 7, 8, 9}"
},
{
"code": null,
"e": 1884,
"s": 1864,
"text": "Python set-programs"
},
{
"code": null,
"e": 1891,
"s": 1884,
"text": "Python"
},
{
"code": null,
"e": 1907,
"s": 1891,
"text": "Python Programs"
}
] |
Storing money amounts in MySQL?
|
To store money amounts in MySQL, the best choice is to use DECIMAL data type or NUMERIC type. Float data type is not a good choice for money amounts. It gives some rounding errors. Therefore, avoid float for money amounts.
Let us first create a table with data type DECIMAL. The following is the query to create a table −
mysql> create table MoneyStorageDemo
-> (
-> Amount DECIMAL(4,2)
-> );
Query OK, 0 rows affected (0.44 sec)
Inserting some values into the table with the help of insert command. The query is as follows −
mysql> insert into MoneyStorageDemo values(50.2);
Query OK, 1 row affected (0.10 sec)
mysql> insert into MoneyStorageDemo values(5.50);
Query OK, 1 row affected (0.32 sec)
mysql> insert into MoneyStorageDemo values(10.4);
Query OK, 1 row affected (0.26 sec)
Now you can display all the values from the table with the help of select statement. The query is as follows −
mysql> select *from MoneyStorageDemo;
Here is the output −
+--------+
| Amount |
+--------+
| 50.20 |
| 5.50 |
| 10.40 |
+--------+
3 rows in set (0.00 sec)
|
[
{
"code": null,
"e": 1285,
"s": 1062,
"text": "To store money amounts in MySQL, the best choice is to use DECIMAL data type or NUMERIC type. Float data type is not a good choice for money amounts. It gives some rounding errors. Therefore, avoid float for money amounts."
},
{
"code": null,
"e": 1384,
"s": 1285,
"text": "Let us first create a table with data type DECIMAL. The following is the query to create a table −"
},
{
"code": null,
"e": 1501,
"s": 1384,
"text": "mysql> create table MoneyStorageDemo\n -> (\n -> Amount DECIMAL(4,2)\n -> );\nQuery OK, 0 rows affected (0.44 sec)"
},
{
"code": null,
"e": 1597,
"s": 1501,
"text": "Inserting some values into the table with the help of insert command. The query is as follows −"
},
{
"code": null,
"e": 1855,
"s": 1597,
"text": "mysql> insert into MoneyStorageDemo values(50.2);\nQuery OK, 1 row affected (0.10 sec)\nmysql> insert into MoneyStorageDemo values(5.50);\nQuery OK, 1 row affected (0.32 sec)\nmysql> insert into MoneyStorageDemo values(10.4);\nQuery OK, 1 row affected (0.26 sec)"
},
{
"code": null,
"e": 1966,
"s": 1855,
"text": "Now you can display all the values from the table with the help of select statement. The query is as follows −"
},
{
"code": null,
"e": 2004,
"s": 1966,
"text": "mysql> select *from MoneyStorageDemo;"
},
{
"code": null,
"e": 2025,
"s": 2004,
"text": "Here is the output −"
},
{
"code": null,
"e": 2127,
"s": 2025,
"text": "+--------+\n| Amount |\n+--------+\n| 50.20 |\n| 5.50 |\n| 10.40 |\n+--------+\n3 rows in set (0.00 sec)"
}
] |
An intuitive approach to DTW — Dynamic Time Warping | by Himanshu Chandra | Towards Data Science
|
Since you are here, I assume you already know the reason why we use Dynamic Time Warping, or DTW in time-series data. Simply put, it’s used to align or match two similar patterns.
One of the reasons DTW was initially developed was for speech recognition. Your mother may speak slowly one day, and hurriedly on another; even have a bit of cold and sore throat on some days, but you still can recognize her voice. Can machines do the same? Can they somehow match the highs and lows, the peaks and troughs, the frequencies of her voice, no manner how she speaks and tell us it is her voice indeed?
There are several awesome real life situations were DTW just rocks — if you do not know them already, I recommend getting to know them — they are really fun!
You can read more about DTW here and about it’s many applications here (refer the Introduction section)
I love this algorithm! In essence, it is one of those short and elegant algos which pack a punch. It is a classic example of finding the shortest path using the Dynamic Programming approach.
I have had colleagues running away from understanding the inner workings of the algo as it involves recursion. This eventually stops them from understanding the nuances of the approach and from learning how to tweak it as per their requirements.
Let’s visualize the logic behind the algorithm in a non-programmatic way so that we can write it from scratch.
To understand recursion, one must first understand recursion.
— Stephen Hawking
Imagine you are standing at the blue square and wish to go to the red square. All the numbers that you see in the cells along the path, correspond to the toll amount you have to pay at each step (arbitrarily decided, for now). If I were to ask you, “Tell me the least amount one needs to spend to reach from blue to red”, how would you do it?
In fact, I’ll make it simpler by saying that you are supposed to move only in the ‘forward’ direction. The black arrows show the only 3 ‘allowed’ directions (right, down, right-down diagonal) and red arrows show ‘restricted’ directions, which are everything apart from the 3 allowed ones (up, left, other diagonals, etc.). This is similar to what DTW assumes before solving the problem.
Another way to say the above fact is that, “You can arrive at any square only from one of the 3 adjacent squares”:
A ‘brute-force’ way would be to try all the paths possible from the blue to the red square and choose the cheapest one. However, dynamic programming and recursion give us a better, smarter way.
I like to solve all recursion problems by thinking as ‘the lazy boss’ who has uncountable minions at his disposal to do the job. If someone asked me to solve the above problem, I would simply say, “Minions A, B and C, tell me the least cost to reach the 3 squares surrounding the red square, and then I’ll calculate the answer in a minute. Till then, don’t bother me.”
This is the trick recursion uses — give the exact same kind of work you have been asked to do, to your underlings, after ‘scaling down’ the work a bit. And make sure to keep something simple for yourself, so that no one can say you did nothing!
Suppose by some magic (which you are not interested in knowing about), the minions bring you the answer, marked in green cells:
All I need to do now is find the minimum of (10, 7, 7), which is 7 and then add current square’s cost, which is 2. This gives me the answer as 9. Done!
9 is the minimum cost of travelling from blue to red. But wait, how did the minions come up with the green values? They of course, emulate you and act as lazy bosses too!
Each minion gets hold of 3 junior minions (the damned hierarchy in the office, I tell you!) and tells them to bring them least cost values for their 3 neighbourhood/adjacent squares. Here’s an animation to better explain this:
This keeps going on and on, with each junior minion ‘magically’ getting its answer. But for how long? Surely it ends sometime? Yes, it does. When there is no way to subdivide the work further. When a minion gets the task to calculate the cost at the blue square, he can’t delegate it to anyone else, as there is no neighbourhood to go to. He just needs to know that the cost there is zero.
That’s it. You can translate this into a recursive python function in just a few lines of code:
def cheapest(cost, i, j): if (i==0) & (j==0): return 0 ## can't subdivide the work anymore if (i<0) | (j<0): return np.inf ## current square's cost + minimum of the 3 neigbours return cost[i][j] + min(cheapest(cost, i-1, j-1), cheapest(cost, i-1, j), cheapest(cost, i, j-1))
Here, cost is a 2-D array, our initial matrix:
cost = [ [0,2,5,1,1], [5,3,4,2,2], [1,1,6,1,3], [1,3,2,1,2]]
Notice how I have returned np.inf (infinity) when either i or j is less than zero. This is just a way to ignore the neighbour which doesn’t exist. For example, when you are in a top-row square, the only neighbour you need to consider is the left one, as there’s no square above the current square. Similar logic goes for squares in the first column, where there’s no neighbour to the left.
And you can call the recursive function by simply calling:
output_cost = cheapest(cost, 3, 4)print(output_cost)
The output it will give is 9.
If you call it for all the squares, you can finally create a cheapest cost matrix as output:
output_cost_matrix = [] ## used to store all outputsfor i in range(4): for j in range(5): output_cost_matrix.append(cheapest(cost, i, j))## reshape the output for better displayoutput_cost_matrix= (np.array(output_cost_matrix)).reshape(-1,5)print(output_cost_matrix)
Output:
[[ 0, 2, 7, 8, 9], [ 5, 3, 6, 8, 10], [ 6, 4, 9, 7, 10], [ 7, 7, 6, 7, 9]]
So, what would be the cheapest path from the blue square to the red square?
We just need to track the minimum-neighbour around each square. Here’s the code if you want to print the path too. This is certainly not optimized, but is simple to understand:
def trace_path(output_cost_matrix, i, j): path = [(i, j)] while ((i>0) | (j>0)): neighbours = [output_cost_matrix[i-1, j-1], output_cost_matrix[i-1, j], output_cost_matrix[i, j-1]] ## see which neighbour is the smallest path_min = np.argmin(neighbours) ## store the position of the smallest neighbour if path_min==0: i=i-1 j=j-1 elif path_min==1: i=i-1 else: j=j-1 path.append((i, j)) return path[::-1] ## return after reversing the list
Let’s see the path returned from blue to red square by calling:
trace_path(output_cost_matrix, 3, 4)
Output:
[(0, 0), (0, 1), (1, 2), (2, 3), (3, 4)]
Representing this graphically:
Or tracing it over our original matrix:
Quite right! How does DTW picture into all of this?
Well, DTW is nothing but simply matching one point in time-series pattern1 with the closest point in pattern2.
Let’s look at the mapping of two signals again. The one in cyan is pattern1 and the one in orange is pattern2, with the red lines trying to find a corresponding point on pattern1 for every point on pattern2:
So essentially, we are finding the shortest or cheapest path between a pattern2-point and pattern1-point. But what is the cost between any two points. Do we put it randomly like we did in our example for each square?
You have various choices you can pick from here, as per your use-case, but the most common one is the euclidean distance between those points.
You arrange all pattern1-points as column axis of the matrix and all pattern2-points as row axis. Then fill each square with the euclidean distance:
And then it’s the recursive algorithm we just went through. An output path like [(0,0), (0,1), (1,1), (2,2), (3,3), (4,3)] would mean that point 0 in pattern1 should be matched up with points 0 and 1 in pattern2. Points 1, 2, 3 and 4 in pattern1 should be matched with points 1, 2, 3 and 3 in pattern2.
But what does that actually achieve? What does such shortest-distance matching mean?
I like to imagine it as a solution where you are trying to match pattern2 with pattern1 in a manner that ensures least stretching (or shrinking) of pattern2; greedily matching it to the closest neighbour.
And there you have it. A simple DTW algorithm implemented from scratch.
I have not mentioned several nuances and variations of the DTW process, for example a windowed DTW where we add a locality constraint. I hope this article has sparked your interest in knowing more about it. Do let me know if you discover something cool about it!
Interested in sharing ideas, asking questions or simply discussing thoughts? Connect with me on LinkedIn, YouTube, GitHub or through my website: I am Just a Student.
See you around & happy learning!
|
[
{
"code": null,
"e": 352,
"s": 172,
"text": "Since you are here, I assume you already know the reason why we use Dynamic Time Warping, or DTW in time-series data. Simply put, it’s used to align or match two similar patterns."
},
{
"code": null,
"e": 767,
"s": 352,
"text": "One of the reasons DTW was initially developed was for speech recognition. Your mother may speak slowly one day, and hurriedly on another; even have a bit of cold and sore throat on some days, but you still can recognize her voice. Can machines do the same? Can they somehow match the highs and lows, the peaks and troughs, the frequencies of her voice, no manner how she speaks and tell us it is her voice indeed?"
},
{
"code": null,
"e": 925,
"s": 767,
"text": "There are several awesome real life situations were DTW just rocks — if you do not know them already, I recommend getting to know them — they are really fun!"
},
{
"code": null,
"e": 1029,
"s": 925,
"text": "You can read more about DTW here and about it’s many applications here (refer the Introduction section)"
},
{
"code": null,
"e": 1220,
"s": 1029,
"text": "I love this algorithm! In essence, it is one of those short and elegant algos which pack a punch. It is a classic example of finding the shortest path using the Dynamic Programming approach."
},
{
"code": null,
"e": 1466,
"s": 1220,
"text": "I have had colleagues running away from understanding the inner workings of the algo as it involves recursion. This eventually stops them from understanding the nuances of the approach and from learning how to tweak it as per their requirements."
},
{
"code": null,
"e": 1577,
"s": 1466,
"text": "Let’s visualize the logic behind the algorithm in a non-programmatic way so that we can write it from scratch."
},
{
"code": null,
"e": 1639,
"s": 1577,
"text": "To understand recursion, one must first understand recursion."
},
{
"code": null,
"e": 1657,
"s": 1639,
"text": "— Stephen Hawking"
},
{
"code": null,
"e": 2000,
"s": 1657,
"text": "Imagine you are standing at the blue square and wish to go to the red square. All the numbers that you see in the cells along the path, correspond to the toll amount you have to pay at each step (arbitrarily decided, for now). If I were to ask you, “Tell me the least amount one needs to spend to reach from blue to red”, how would you do it?"
},
{
"code": null,
"e": 2387,
"s": 2000,
"text": "In fact, I’ll make it simpler by saying that you are supposed to move only in the ‘forward’ direction. The black arrows show the only 3 ‘allowed’ directions (right, down, right-down diagonal) and red arrows show ‘restricted’ directions, which are everything apart from the 3 allowed ones (up, left, other diagonals, etc.). This is similar to what DTW assumes before solving the problem."
},
{
"code": null,
"e": 2502,
"s": 2387,
"text": "Another way to say the above fact is that, “You can arrive at any square only from one of the 3 adjacent squares”:"
},
{
"code": null,
"e": 2696,
"s": 2502,
"text": "A ‘brute-force’ way would be to try all the paths possible from the blue to the red square and choose the cheapest one. However, dynamic programming and recursion give us a better, smarter way."
},
{
"code": null,
"e": 3065,
"s": 2696,
"text": "I like to solve all recursion problems by thinking as ‘the lazy boss’ who has uncountable minions at his disposal to do the job. If someone asked me to solve the above problem, I would simply say, “Minions A, B and C, tell me the least cost to reach the 3 squares surrounding the red square, and then I’ll calculate the answer in a minute. Till then, don’t bother me.”"
},
{
"code": null,
"e": 3310,
"s": 3065,
"text": "This is the trick recursion uses — give the exact same kind of work you have been asked to do, to your underlings, after ‘scaling down’ the work a bit. And make sure to keep something simple for yourself, so that no one can say you did nothing!"
},
{
"code": null,
"e": 3438,
"s": 3310,
"text": "Suppose by some magic (which you are not interested in knowing about), the minions bring you the answer, marked in green cells:"
},
{
"code": null,
"e": 3590,
"s": 3438,
"text": "All I need to do now is find the minimum of (10, 7, 7), which is 7 and then add current square’s cost, which is 2. This gives me the answer as 9. Done!"
},
{
"code": null,
"e": 3761,
"s": 3590,
"text": "9 is the minimum cost of travelling from blue to red. But wait, how did the minions come up with the green values? They of course, emulate you and act as lazy bosses too!"
},
{
"code": null,
"e": 3988,
"s": 3761,
"text": "Each minion gets hold of 3 junior minions (the damned hierarchy in the office, I tell you!) and tells them to bring them least cost values for their 3 neighbourhood/adjacent squares. Here’s an animation to better explain this:"
},
{
"code": null,
"e": 4378,
"s": 3988,
"text": "This keeps going on and on, with each junior minion ‘magically’ getting its answer. But for how long? Surely it ends sometime? Yes, it does. When there is no way to subdivide the work further. When a minion gets the task to calculate the cost at the blue square, he can’t delegate it to anyone else, as there is no neighbourhood to go to. He just needs to know that the cost there is zero."
},
{
"code": null,
"e": 4474,
"s": 4378,
"text": "That’s it. You can translate this into a recursive python function in just a few lines of code:"
},
{
"code": null,
"e": 4808,
"s": 4474,
"text": "def cheapest(cost, i, j): if (i==0) & (j==0): return 0 ## can't subdivide the work anymore if (i<0) | (j<0): return np.inf ## current square's cost + minimum of the 3 neigbours return cost[i][j] + min(cheapest(cost, i-1, j-1), cheapest(cost, i-1, j), cheapest(cost, i, j-1))"
},
{
"code": null,
"e": 4855,
"s": 4808,
"text": "Here, cost is a 2-D array, our initial matrix:"
},
{
"code": null,
"e": 4916,
"s": 4855,
"text": "cost = [ [0,2,5,1,1], [5,3,4,2,2], [1,1,6,1,3], [1,3,2,1,2]]"
},
{
"code": null,
"e": 5306,
"s": 4916,
"text": "Notice how I have returned np.inf (infinity) when either i or j is less than zero. This is just a way to ignore the neighbour which doesn’t exist. For example, when you are in a top-row square, the only neighbour you need to consider is the left one, as there’s no square above the current square. Similar logic goes for squares in the first column, where there’s no neighbour to the left."
},
{
"code": null,
"e": 5365,
"s": 5306,
"text": "And you can call the recursive function by simply calling:"
},
{
"code": null,
"e": 5418,
"s": 5365,
"text": "output_cost = cheapest(cost, 3, 4)print(output_cost)"
},
{
"code": null,
"e": 5448,
"s": 5418,
"text": "The output it will give is 9."
},
{
"code": null,
"e": 5541,
"s": 5448,
"text": "If you call it for all the squares, you can finally create a cheapest cost matrix as output:"
},
{
"code": null,
"e": 5817,
"s": 5541,
"text": "output_cost_matrix = [] ## used to store all outputsfor i in range(4): for j in range(5): output_cost_matrix.append(cheapest(cost, i, j))## reshape the output for better displayoutput_cost_matrix= (np.array(output_cost_matrix)).reshape(-1,5)print(output_cost_matrix)"
},
{
"code": null,
"e": 5825,
"s": 5817,
"text": "Output:"
},
{
"code": null,
"e": 5914,
"s": 5825,
"text": "[[ 0, 2, 7, 8, 9], [ 5, 3, 6, 8, 10], [ 6, 4, 9, 7, 10], [ 7, 7, 6, 7, 9]]"
},
{
"code": null,
"e": 5990,
"s": 5914,
"text": "So, what would be the cheapest path from the blue square to the red square?"
},
{
"code": null,
"e": 6167,
"s": 5990,
"text": "We just need to track the minimum-neighbour around each square. Here’s the code if you want to print the path too. This is certainly not optimized, but is simple to understand:"
},
{
"code": null,
"e": 6675,
"s": 6167,
"text": "def trace_path(output_cost_matrix, i, j): path = [(i, j)] while ((i>0) | (j>0)): neighbours = [output_cost_matrix[i-1, j-1], output_cost_matrix[i-1, j], output_cost_matrix[i, j-1]] ## see which neighbour is the smallest path_min = np.argmin(neighbours) ## store the position of the smallest neighbour if path_min==0: i=i-1 j=j-1 elif path_min==1: i=i-1 else: j=j-1 path.append((i, j)) return path[::-1] ## return after reversing the list"
},
{
"code": null,
"e": 6739,
"s": 6675,
"text": "Let’s see the path returned from blue to red square by calling:"
},
{
"code": null,
"e": 6776,
"s": 6739,
"text": "trace_path(output_cost_matrix, 3, 4)"
},
{
"code": null,
"e": 6784,
"s": 6776,
"text": "Output:"
},
{
"code": null,
"e": 6825,
"s": 6784,
"text": "[(0, 0), (0, 1), (1, 2), (2, 3), (3, 4)]"
},
{
"code": null,
"e": 6856,
"s": 6825,
"text": "Representing this graphically:"
},
{
"code": null,
"e": 6896,
"s": 6856,
"text": "Or tracing it over our original matrix:"
},
{
"code": null,
"e": 6948,
"s": 6896,
"text": "Quite right! How does DTW picture into all of this?"
},
{
"code": null,
"e": 7059,
"s": 6948,
"text": "Well, DTW is nothing but simply matching one point in time-series pattern1 with the closest point in pattern2."
},
{
"code": null,
"e": 7267,
"s": 7059,
"text": "Let’s look at the mapping of two signals again. The one in cyan is pattern1 and the one in orange is pattern2, with the red lines trying to find a corresponding point on pattern1 for every point on pattern2:"
},
{
"code": null,
"e": 7484,
"s": 7267,
"text": "So essentially, we are finding the shortest or cheapest path between a pattern2-point and pattern1-point. But what is the cost between any two points. Do we put it randomly like we did in our example for each square?"
},
{
"code": null,
"e": 7627,
"s": 7484,
"text": "You have various choices you can pick from here, as per your use-case, but the most common one is the euclidean distance between those points."
},
{
"code": null,
"e": 7776,
"s": 7627,
"text": "You arrange all pattern1-points as column axis of the matrix and all pattern2-points as row axis. Then fill each square with the euclidean distance:"
},
{
"code": null,
"e": 8079,
"s": 7776,
"text": "And then it’s the recursive algorithm we just went through. An output path like [(0,0), (0,1), (1,1), (2,2), (3,3), (4,3)] would mean that point 0 in pattern1 should be matched up with points 0 and 1 in pattern2. Points 1, 2, 3 and 4 in pattern1 should be matched with points 1, 2, 3 and 3 in pattern2."
},
{
"code": null,
"e": 8164,
"s": 8079,
"text": "But what does that actually achieve? What does such shortest-distance matching mean?"
},
{
"code": null,
"e": 8369,
"s": 8164,
"text": "I like to imagine it as a solution where you are trying to match pattern2 with pattern1 in a manner that ensures least stretching (or shrinking) of pattern2; greedily matching it to the closest neighbour."
},
{
"code": null,
"e": 8441,
"s": 8369,
"text": "And there you have it. A simple DTW algorithm implemented from scratch."
},
{
"code": null,
"e": 8704,
"s": 8441,
"text": "I have not mentioned several nuances and variations of the DTW process, for example a windowed DTW where we add a locality constraint. I hope this article has sparked your interest in knowing more about it. Do let me know if you discover something cool about it!"
},
{
"code": null,
"e": 8870,
"s": 8704,
"text": "Interested in sharing ideas, asking questions or simply discussing thoughts? Connect with me on LinkedIn, YouTube, GitHub or through my website: I am Just a Student."
}
] |
Is it mandatory to override the default methods of an interface in Java?
|
The default methods are introduced in an interface since Java8. Unlike other abstract methods these are the methods can have 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.
In short, you can access the default methods of an interface using the objects of the implementing classes.
interface MyInterface{
public static int num = 100;
public default void display() {
System.out.println("display method of MyInterface");
}
}
public class InterfaceExample implements MyInterface{
public static void main(String args[]) {
InterfaceExample obj = new InterfaceExample();
obj.display();
}
}
display method of MyInterface
But, when your class implements two interfaces, and if they both have methods with same name and prototype. You must override this method else a compile time error is generated.
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 static void main(String args[]) {
InterfaceExample obj = new InterfaceExample();
// obj.display();
}
}
InterfaceExample.java:14: error: class InterfaceExample inherits unrelated defaults for display() from types MyInterface1 and MyInterface2
public class InterfaceExample implements MyInterface1, MyInterface2{
^
1 error
To resolve this you need to override either (or, both) of the display() methods in the implementing class −
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
|
[
{
"code": null,
"e": 1368,
"s": 1062,
"text": "The default methods are introduced in an interface since Java8. Unlike other abstract methods these are the methods can have 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."
},
{
"code": null,
"e": 1476,
"s": 1368,
"text": "In short, you can access the default methods of an interface using the objects of the implementing classes."
},
{
"code": null,
"e": 1811,
"s": 1476,
"text": "interface MyInterface{\n public static int num = 100;\n public default void display() {\n System.out.println(\"display method of MyInterface\");\n }\n}\npublic class InterfaceExample implements MyInterface{\n public static void main(String args[]) {\n InterfaceExample obj = new InterfaceExample();\n obj.display();\n }\n}"
},
{
"code": null,
"e": 1841,
"s": 1811,
"text": "display method of MyInterface"
},
{
"code": null,
"e": 2019,
"s": 1841,
"text": "But, when your class implements two interfaces, and if they both have methods with same name and prototype. You must override this method else a compile time error is generated."
},
{
"code": null,
"e": 2533,
"s": 2019,
"text": "interface MyInterface1{\n public static int num = 100;\n public default void display() {\n System.out.println(\"display method of MyInterface1\");\n }\n}\ninterface MyInterface2{\n public static int num = 1000;\n public default void display() {\n System.out.println(\"display method of MyInterface2\");\n }\n}\npublic class InterfaceExample implements MyInterface1, MyInterface2{\n public static void main(String args[]) {\n InterfaceExample obj = new InterfaceExample();\n // obj.display();\n }\n}"
},
{
"code": null,
"e": 2751,
"s": 2533,
"text": "InterfaceExample.java:14: error: class InterfaceExample inherits unrelated defaults for display() from types MyInterface1 and MyInterface2\npublic class InterfaceExample implements MyInterface1, MyInterface2{\n^\n1 error"
},
{
"code": null,
"e": 2859,
"s": 2751,
"text": "To resolve this you need to override either (or, both) of the display() methods in the implementing class −"
},
{
"code": null,
"e": 3486,
"s": 2859,
"text": "interface MyInterface1{\n public static int num = 100;\n public default void display() {\n System.out.println(\"display method of MyInterface1\");\n }\n}\ninterface MyInterface2{\n public static int num = 1000;\n public default void display() {\n System.out.println(\"display method of MyInterface2\");\n }\n}\npublic class InterfaceExample implements MyInterface1, MyInterface2{\n public void display() {\n MyInterface1.super.display();\n //or,\n MyInterface2.super.display();\n }\n public static void main(String args[]) {\n InterfaceExample obj = new InterfaceExample();\n obj.display();\n }\n}"
},
{
"code": null,
"e": 3548,
"s": 3486,
"text": "display method of MyInterface1\ndisplay method of MyInterface2"
}
] |
React Native - State
|
The data inside React Components is managed by state and props. In this chapter, we will talk about state.
The state is mutable while props are immutable. This means that state can be updated in the future while props cannot be updated.
This is our root component. We are just importing Home which will be used in most of the chapters.
App.js
import React from 'react';
import { StyleSheet, Text, View } from 'react-native';
export default class App extends React.Component {
state = {
myState: 'Lorem ipsum dolor sit amet, consectetur adipisicing elit, used do eiusmod
tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis
nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu
fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in
culpa qui officia deserunt mollit anim id est laborum.'
}
render() {
return (
<View>
<Text> {this.state.myState} </Text>
</View>
);
}
}
We can see in emulator text from the state as in the following screenshot.
Since state is mutable, we can update it by creating the deleteState function and call it using the onPress = {this.deleteText} event.
Home.js
import React, { Component } from 'react'
import { Text, View } from 'react-native'
class Home extends Component {
state = {
myState: 'Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed
do eiusmod tempor incididunt ut labore et dolore magna aliqua.
Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi
ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit
in voluptate velit esse cillum dolore eu fugiat nulla pariatur.
Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia
deserunt mollit anim id est laborum.'
}
updateState = () ⇒ this.setState({ myState: 'The state is updated' })
render() {
return (
<View>
<Text onPress = {this.updateState}>
{this.state.myState}
</Text>
</View>
);
}
}
export default Home;
NOTES − In all chapters, we will use the class syntax for stateful (container) components and function syntax for stateless (presentational) components. We will learn more about components in the next chapter.
We will also learn how to use the arrow function syntax for updateState. You should keep in mind that this syntax uses the lexical scope, and this keyword will be bound to the environment object (Class). This will sometimes lead to unexpected behavior.
The other way to define methods is to use the EC5 functions but in that case we will need to bind this manually in the constructor. Consider the following example to understand this.
class Home extends Component {
constructor() {
super()
this.updateState = this.updateState.bind(this)
}
updateState() {
//
}
render() {
//
}
}
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
|
[
{
"code": null,
"e": 2451,
"s": 2344,
"text": "The data inside React Components is managed by state and props. In this chapter, we will talk about state."
},
{
"code": null,
"e": 2581,
"s": 2451,
"text": "The state is mutable while props are immutable. This means that state can be updated in the future while props cannot be updated."
},
{
"code": null,
"e": 2680,
"s": 2581,
"text": "This is our root component. We are just importing Home which will be used in most of the chapters."
},
{
"code": null,
"e": 2687,
"s": 2680,
"text": "App.js"
},
{
"code": null,
"e": 3451,
"s": 2687,
"text": "import React from 'react';\nimport { StyleSheet, Text, View } from 'react-native';\n\nexport default class App extends React.Component {\n state = {\n myState: 'Lorem ipsum dolor sit amet, consectetur adipisicing elit, used do eiusmod\n tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis\n nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.\n Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu\n fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in\n culpa qui officia deserunt mollit anim id est laborum.'\n }\n render() {\n return (\n <View>\n <Text> {this.state.myState} </Text>\n </View>\n );\n }\n}"
},
{
"code": null,
"e": 3526,
"s": 3451,
"text": "We can see in emulator text from the state as in the following screenshot."
},
{
"code": null,
"e": 3661,
"s": 3526,
"text": "Since state is mutable, we can update it by creating the deleteState function and call it using the onPress = {this.deleteText} event."
},
{
"code": null,
"e": 3669,
"s": 3661,
"text": "Home.js"
},
{
"code": null,
"e": 4598,
"s": 3669,
"text": "import React, { Component } from 'react'\nimport { Text, View } from 'react-native'\n\nclass Home extends Component {\n state = {\n myState: 'Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed \n do eiusmod tempor incididunt ut labore et dolore magna aliqua.\n Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi\n ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit \n in voluptate velit esse cillum dolore eu fugiat nulla pariatur.\n Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia\n deserunt mollit anim id est laborum.'\n }\n updateState = () ⇒ this.setState({ myState: 'The state is updated' })\n render() {\n return (\n <View>\n <Text onPress = {this.updateState}>\n {this.state.myState}\n </Text>\n </View>\n );\n }\n}\nexport default Home;"
},
{
"code": null,
"e": 4808,
"s": 4598,
"text": "NOTES − In all chapters, we will use the class syntax for stateful (container) components and function syntax for stateless (presentational) components. We will learn more about components in the next chapter."
},
{
"code": null,
"e": 5061,
"s": 4808,
"text": "We will also learn how to use the arrow function syntax for updateState. You should keep in mind that this syntax uses the lexical scope, and this keyword will be bound to the environment object (Class). This will sometimes lead to unexpected behavior."
},
{
"code": null,
"e": 5244,
"s": 5061,
"text": "The other way to define methods is to use the EC5 functions but in that case we will need to bind this manually in the constructor. Consider the following example to understand this."
},
{
"code": null,
"e": 5429,
"s": 5244,
"text": "class Home extends Component {\n constructor() {\n super()\n this.updateState = this.updateState.bind(this)\n }\n updateState() {\n //\n }\n render() {\n //\n }\n}"
},
{
"code": null,
"e": 5464,
"s": 5429,
"text": "\n 20 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 5478,
"s": 5464,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 5513,
"s": 5478,
"text": "\n 61 Lectures \n 6.5 hours \n"
},
{
"code": null,
"e": 5528,
"s": 5513,
"text": " A To Z Mentor"
},
{
"code": null,
"e": 5563,
"s": 5528,
"text": "\n 40 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 5591,
"s": 5563,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 5627,
"s": 5591,
"text": "\n 56 Lectures \n 12.5 hours \n"
},
{
"code": null,
"e": 5655,
"s": 5627,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 5690,
"s": 5655,
"text": "\n 62 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 5702,
"s": 5690,
"text": " Senol Atac"
},
{
"code": null,
"e": 5737,
"s": 5702,
"text": "\n 67 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 5749,
"s": 5737,
"text": " Senol Atac"
},
{
"code": null,
"e": 5756,
"s": 5749,
"text": " Print"
},
{
"code": null,
"e": 5767,
"s": 5756,
"text": " Add Notes"
}
] |
How can we delete multiple rows from a MySQL table?
|
We can use DELETE statement along with a WHERE clause, which identifies those multiple rows, to delete multiple rows from MySQL table.
mysql> Select * from names;
+------+-----------+
| id | name |
+------+-----------+
| 1 | Rahul |
| 2 | Gaurav |
| 3 | Raman |
| 5 | Ram |
+------+-----------+
4 rows in set (0.00 sec)
mysql> DELETE from names WHERE id > 2;
Query OK, 2 rows affected (0.04 sec)
The query above will delete multiple rows because WHERE clause identify two rows having id > 2 from table ‘names’.
mysql> Select * from names;
+------+-----------+
| id | name |
+------+-----------+
| 1 | Rahul |
| 2 | Gaurav |
+------+-----------+
2 rows in set (0.00 sec)
|
[
{
"code": null,
"e": 1197,
"s": 1062,
"text": "We can use DELETE statement along with a WHERE clause, which identifies those multiple rows, to delete multiple rows from MySQL table."
},
{
"code": null,
"e": 1495,
"s": 1197,
"text": "mysql> Select * from names;\n+------+-----------+\n| id | name |\n+------+-----------+\n| 1 | Rahul |\n| 2 | Gaurav |\n| 3 | Raman |\n| 5 | Ram |\n+------+-----------+\n4 rows in set (0.00 sec)\n\nmysql> DELETE from names WHERE id > 2;\nQuery OK, 2 rows affected (0.04 sec)"
},
{
"code": null,
"e": 1610,
"s": 1495,
"text": "The query above will delete multiple rows because WHERE clause identify two rows having id > 2 from table ‘names’."
},
{
"code": null,
"e": 1789,
"s": 1610,
"text": "mysql> Select * from names;\n+------+-----------+\n| id | name |\n+------+-----------+\n| 1 | Rahul |\n| 2 | Gaurav |\n+------+-----------+\n2 rows in set (0.00 sec)"
}
] |
How to create a subset of matrix in R using greater than or less than a certain value of a column?
|
Subsetting can be required in many different ways, we can say that there might be infinite number of ways for subsetting as it depends on the objective of the bigger or smaller analysis. One such way is subsetting a matrix based on a certain value of column of the matrix. In R, we can easily do the same with the help of subset function as shown in below example.
Live Demo
M<-matrix(1:100,ncol=10)
M
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
[1,] 1 11 21 31 41 51 61 71 81 91
[2,] 2 12 22 32 42 52 62 72 82 92
[3,] 3 13 23 33 43 53 63 73 83 93
[4,] 4 14 24 34 44 54 64 74 84 94
[5,] 5 15 25 35 45 55 65 75 85 95
[6,] 6 16 26 36 46 56 66 76 86 96
[7,] 7 17 27 37 47 57 67 77 87 97
[8,] 8 18 28 38 48 58 68 78 88 98
[9,] 9 19 29 39 49 59 69 79 89 99
[10,] 10 20 30 40 50 60 70 80 90 100
subset(M,M[,1]<6)
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
[1,] 1 11 21 31 41 51 61 71 81 91
[2,] 2 12 22 32 42 52 62 72 82 92
[3,] 3 13 24 34 44 54 64 74 84 94
[5,] 5 15 25 35 45 55 65 75 85 95
subset(M,M[,1]>6)
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
[1,] 7 17 27 37 47 57 67 77 87 97
[2,] 8 18 28 38 48 58 68 78 88 98
[3,] 9 19 29 39 49 59 69 79 89 99
[4,] 10 20 30 40 50 60 70 80 90 100
subset(M,M[,1]==6)
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
[1,] 6 16 26 36 46 56 66 76 86 96
subset(M,M[,1]>3)
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
[1,] 4 14 24 34 44 54 64 74 84 94
[2,] 5 15 25 35 45 55 65 75 85 95
[3,] 6 16 26 36 46 56 66 76 86 96
[4,] 7 17 27 37 47 57 67 77 87 97
[5,] 8 18 28 38 48 58 68 78 88 98
[6,] 9 19 29 39 49 59 69 79 89 99
[7,] 10 20 30 40 50 60 70 80 90 100
subset(M,M[,1]<8)
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
[1,] 1 11 21 31 41 51 61 71 81 91
[2,] 2 12 22 32 42 52 62 72 82 92
[3,] 3 13 23 33 43 53 63 73 83 93
[4,] 4 14 24 34 44 54 64 74 84 94
[5,] 5 15 25 35 45 55 65 75 85 95
[6,] 6 16 26 36 46 56 66 76 86 96
[7,] 7 17 27 37 47 57 67 77 87 97
subset(M,M[,2]<20)
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
[1,] 1 11 21 31 41 51 61 71 81 91
[2,] 2 12 22 32 42 52 62 72 82 92
[3,] 3 13 23 33 43 53 63 73 83 93
[4,] 4 14 24 34 44 54 64 74 84 94
[5,] 5 15 25 35 45 55 65 75 85 95
[6,] 6 16 26 36 46 56 66 76 86 96
[7,] 7 17 27 37 47 57 67 77 87 97
[8,] 8 18 28 38 48 58 68 78 88 98
[9,] 9 19 29 39 49 59 69 79 89 99
subset(M,M[,2]<25)
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
[1,] 1 11 21 31 41 51 61 71 81 91
[2,] 2 12 22 32 42 52 62 72 82 92
[3,] 3 13 23 33 43 53 63 73 83 93
[4,] 4 14 24 34 44 54 64 74 84 94
[5,] 5 15 25 35 45 55 65 75 85 95
[6,] 6 16 26 36 46 56 66 76 86 96
[7,] 7 17 27 37 47 57 67 77 87 97
[8,] 8 18 28 38 48 58 68 78 88 98
[9,] 9 19 29 39 49 59 69 79 89 99
[10,] 10 20 30 40 50 60 70 80 90 100
subset(M,M[,5]>45)
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
[1,] 6 16 26 36 46 56 66 76 86 96
[2,] 7 17 27 37 47 57 67 77 87 97
[3,] 8 18 28 38 48 58 68 78 88 98
[4,] 9 19 29 39 49 59 69 79 89 99
[5,] 10 20 30 40 50 60 70 80 90 100
subset(M,M[,5]>48)
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
[1,] 9 19 29 39 49 59 69 79 89 99
[2,] 10 20 30 40 50 60 70 80 90 100
subset(M,M[,8]>75)
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
[1,] 6 16 26 36 46 56 66 76 86 96
[2,] 7 17 27 37 47 57 67 77 87 97
[3,] 8 18 28 38 48 58 68 78 88 98
[4,] 9 19 29 39 49 59 69 79 89 99
[5,] 10 20 30 40 50 60 70 80 90 100
subset(M,M[,9]>81)
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
[1,] 2 12 22 32 42 52 62 72 82 92
[2,] 3 13 23 33 43 53 63 73 83 93
[3,] 4 14 24 34 44 54 64 74 84 94
[4,] 5 15 25 35 45 55 65 75 85 95
[5,] 6 16 26 36 46 56 66 76 86 96
[6,] 7 17 27 37 47 57 67 77 87 97
[7,] 8 18 28 38 48 58 68 78 88 98
[8,] 9 19 29 39 49 59 69 79 89 99
[9,] 10 20 30 40 50 60 70 80 90 100
subset(M,M[,9]<90)
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
[1,] 1 11 21 31 41 51 61 71 81 91
[2,] 2 12 22 32 42 52 62 72 82 92
[3,] 3 13 23 33 43 53 63 73 83 93
[4,] 4 14 24 34 44 54 64 74 84 94
[5,] 5 15 25 35 45 55 65 75 85 95
[6,] 6 16 26 36 46 56 66 76 86 96
[7,] 7 17 27 37 47 57 67 77 87 97
[8,] 8 18 28 38 48 58 68 78 88 98
[9,] 9 19 29 39 49 59 69 79 89 99
subset(M,M[,10]<100)
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
[1,] 1 11 21 31 41 51 61 71 81 91
[2,] 2 12 22 32 42 52 62 72 82 92
[3,] 3 13 23 33 43 53 63 73 83 93
[4,] 4 14 24 34 44 54 64 74 84 94
[5,] 5 15 25 35 45 55 65 75 85 95
[6,] 6 16 26 36 46 56 66 76 86 96
[7,] 7 17 27 37 47 57 67 77 87 97
[8,] 8 18 28 38 48 58 68 78 88 98
[9,] 9 19 29 39 49 59 69 79 89 99
subset(M,M[,10]<96)
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
[1,] 1 11 21 31 41 51 61 71 81 91
[2,] 2 12 22 32 42 52 62 72 82 92
[3,] 3 13 23 33 43 53 63 73 83 93
[4,] 4 14 24 34 44 54 64 74 84 94
[5,] 5 15 25 35 45 55 65 75 85 95
|
[
{
"code": null,
"e": 1427,
"s": 1062,
"text": "Subsetting can be required in many different ways, we can say that there might be infinite number of ways for subsetting as it depends on the objective of the bigger or smaller analysis. One such way is subsetting a matrix based on a certain value of column of the matrix. In R, we can easily do the same with the help of subset function as shown in below example."
},
{
"code": null,
"e": 1438,
"s": 1427,
"text": " Live Demo"
},
{
"code": null,
"e": 1465,
"s": 1438,
"text": "M<-matrix(1:100,ncol=10)\nM"
},
{
"code": null,
"e": 2039,
"s": 1465,
"text": " [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]\n[1,] 1 11 21 31 41 51 61 71 81 91\n[2,] 2 12 22 32 42 52 62 72 82 92\n[3,] 3 13 23 33 43 53 63 73 83 93\n[4,] 4 14 24 34 44 54 64 74 84 94\n[5,] 5 15 25 35 45 55 65 75 85 95\n[6,] 6 16 26 36 46 56 66 76 86 96\n[7,] 7 17 27 37 47 57 67 77 87 97\n[8,] 8 18 28 38 48 58 68 78 88 98\n[9,] 9 19 29 39 49 59 69 79 89 99\n[10,] 10 20 30 40 50 60 70 80 90 100"
},
{
"code": null,
"e": 2057,
"s": 2039,
"text": "subset(M,M[,1]<6)"
},
{
"code": null,
"e": 2244,
"s": 2057,
"text": "[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]\n[1,] 1 11 21 31 41 51 61 71 81 91\n[2,] 2 12 22 32 42 52 62 72 82 92\n[3,] 3 13 24 34 44 54 64 74 84 94\n[5,] 5 15 25 35 45 55 65 75 85 95"
},
{
"code": null,
"e": 2262,
"s": 2244,
"text": "subset(M,M[,1]>6)"
},
{
"code": null,
"e": 2453,
"s": 2262,
"text": " [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]\n[1,] 7 17 27 37 47 57 67 77 87 97\n[2,] 8 18 28 38 48 58 68 78 88 98\n[3,] 9 19 29 39 49 59 69 79 89 99\n[4,] 10 20 30 40 50 60 70 80 90 100"
},
{
"code": null,
"e": 2472,
"s": 2453,
"text": "subset(M,M[,1]==6)"
},
{
"code": null,
"e": 2581,
"s": 2472,
"text": " [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]\n[1,] 6 16 26 36 46 56 66 76 86 96"
},
{
"code": null,
"e": 2599,
"s": 2581,
"text": "subset(M,M[,1]>3)"
},
{
"code": null,
"e": 2892,
"s": 2599,
"text": " [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]\n[1,] 4 14 24 34 44 54 64 74 84 94\n[2,] 5 15 25 35 45 55 65 75 85 95\n[3,] 6 16 26 36 46 56 66 76 86 96\n[4,] 7 17 27 37 47 57 67 77 87 97\n[5,] 8 18 28 38 48 58 68 78 88 98\n[6,] 9 19 29 39 49 59 69 79 89 99\n[7,] 10 20 30 40 50 60 70 80 90 100"
},
{
"code": null,
"e": 2910,
"s": 2892,
"text": "subset(M,M[,1]<8)"
},
{
"code": null,
"e": 3324,
"s": 2910,
"text": " [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]\n[1,] 1 11 21 31 41 51 61 71 81 91\n[2,] 2 12 22 32 42 52 62 72 82 92\n[3,] 3 13 23 33 43 53 63 73 83 93\n[4,] 4 14 24 34 44 54 64 74 84 94\n[5,] 5 15 25 35 45 55 65 75 85 95\n[6,] 6 16 26 36 46 56 66 76 86 96\n[7,] 7 17 27 37 47 57 67 77 87 97"
},
{
"code": null,
"e": 3343,
"s": 3324,
"text": "subset(M,M[,2]<20)"
},
{
"code": null,
"e": 3711,
"s": 3343,
"text": " [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]\n[1,] 1 11 21 31 41 51 61 71 81 91\n[2,] 2 12 22 32 42 52 62 72 82 92\n[3,] 3 13 23 33 43 53 63 73 83 93\n[4,] 4 14 24 34 44 54 64 74 84 94\n[5,] 5 15 25 35 45 55 65 75 85 95\n[6,] 6 16 26 36 46 56 66 76 86 96\n[7,] 7 17 27 37 47 57 67 77 87 97\n[8,] 8 18 28 38 48 58 68 78 88 98\n[9,] 9 19 29 39 49 59 69 79 89 99"
},
{
"code": null,
"e": 3730,
"s": 3711,
"text": "subset(M,M[,2]<25)"
},
{
"code": null,
"e": 4308,
"s": 3730,
"text": " [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]\n[1,] 1 11 21 31 41 51 61 71 81 91\n[2,] 2 12 22 32 42 52 62 72 82 92\n[3,] 3 13 23 33 43 53 63 73 83 93\n[4,] 4 14 24 34 44 54 64 74 84 94\n[5,] 5 15 25 35 45 55 65 75 85 95\n[6,] 6 16 26 36 46 56 66 76 86 96\n[7,] 7 17 27 37 47 57 67 77 87 97\n[8,] 8 18 28 38 48 58 68 78 88 98\n[9,] 9 19 29 39 49 59 69 79 89 99\n[10,] 10 20 30 40 50 60 70 80 90 100"
},
{
"code": null,
"e": 4327,
"s": 4308,
"text": "subset(M,M[,5]>45)"
},
{
"code": null,
"e": 4584,
"s": 4327,
"text": " [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]\n[1,] 6 16 26 36 46 56 66 76 86 96\n[2,] 7 17 27 37 47 57 67 77 87 97\n[3,] 8 18 28 38 48 58 68 78 88 98\n[4,] 9 19 29 39 49 59 69 79 89 99\n[5,] 10 20 30 40 50 60 70 80 90 100"
},
{
"code": null,
"e": 4603,
"s": 4584,
"text": "subset(M,M[,5]>48)"
},
{
"code": null,
"e": 4724,
"s": 4603,
"text": "[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]\n[1,] 9 19 29 39 49 59 69 79 89 99\n[2,] 10 20 30 40 50 60 70 80 90 100"
},
{
"code": null,
"e": 4743,
"s": 4724,
"text": "subset(M,M[,8]>75)"
},
{
"code": null,
"e": 4966,
"s": 4743,
"text": "[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]\n[1,] 6 16 26 36 46 56 66 76 86 96\n[2,] 7 17 27 37 47 57 67 77 87 97\n[3,] 8 18 28 38 48 58 68 78 88 98\n[4,] 9 19 29 39 49 59 69 79 89 99\n[5,] 10 20 30 40 50 60 70 80 90 100"
},
{
"code": null,
"e": 4985,
"s": 4966,
"text": "subset(M,M[,9]>81)"
},
{
"code": null,
"e": 5344,
"s": 4985,
"text": "[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]\n[1,] 2 12 22 32 42 52 62 72 82 92\n[2,] 3 13 23 33 43 53 63 73 83 93\n[3,] 4 14 24 34 44 54 64 74 84 94\n[4,] 5 15 25 35 45 55 65 75 85 95\n[5,] 6 16 26 36 46 56 66 76 86 96\n[6,] 7 17 27 37 47 57 67 77 87 97\n[7,] 8 18 28 38 48 58 68 78 88 98\n[8,] 9 19 29 39 49 59 69 79 89 99\n[9,] 10 20 30 40 50 60 70 80 90 100"
},
{
"code": null,
"e": 5363,
"s": 5344,
"text": "subset(M,M[,9]<90)"
},
{
"code": null,
"e": 5720,
"s": 5363,
"text": "[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]\n[1,] 1 11 21 31 41 51 61 71 81 91\n[2,] 2 12 22 32 42 52 62 72 82 92\n[3,] 3 13 23 33 43 53 63 73 83 93\n[4,] 4 14 24 34 44 54 64 74 84 94\n[5,] 5 15 25 35 45 55 65 75 85 95\n[6,] 6 16 26 36 46 56 66 76 86 96\n[7,] 7 17 27 37 47 57 67 77 87 97\n[8,] 8 18 28 38 48 58 68 78 88 98\n[9,] 9 19 29 39 49 59 69 79 89 99"
},
{
"code": null,
"e": 5741,
"s": 5720,
"text": "subset(M,M[,10]<100)"
},
{
"code": null,
"e": 6098,
"s": 5741,
"text": "[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]\n[1,] 1 11 21 31 41 51 61 71 81 91\n[2,] 2 12 22 32 42 52 62 72 82 92\n[3,] 3 13 23 33 43 53 63 73 83 93\n[4,] 4 14 24 34 44 54 64 74 84 94\n[5,] 5 15 25 35 45 55 65 75 85 95\n[6,] 6 16 26 36 46 56 66 76 86 96\n[7,] 7 17 27 37 47 57 67 77 87 97\n[8,] 8 18 28 38 48 58 68 78 88 98\n[9,] 9 19 29 39 49 59 69 79 89 99"
},
{
"code": null,
"e": 6118,
"s": 6098,
"text": "subset(M,M[,10]<96)"
},
{
"code": null,
"e": 6339,
"s": 6118,
"text": "[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]\n[1,] 1 11 21 31 41 51 61 71 81 91\n[2,] 2 12 22 32 42 52 62 72 82 92\n[3,] 3 13 23 33 43 53 63 73 83 93\n[4,] 4 14 24 34 44 54 64 74 84 94\n[5,] 5 15 25 35 45 55 65 75 85 95"
}
] |
Difference between Early and Late Binding in Java - GeeksforGeeks
|
17 Jun, 2019
Early Binding: The binding which can be resolved at compile time by the compiler is known as static or early binding. Binding of all the static, private and final methods is done at compile-time.
Example:
public class NewClass { public static class superclass { static void print() { System.out.println("print in superclass."); } } public static class subclass extends superclass { static void print() { System.out.println("print in subclass."); } } public static void main(String[] args) { superclass A = new superclass(); superclass B = new subclass(); A.print(); B.print(); }}
print in superclass.
print in superclass.
Late binding: In the late binding or dynamic binding, the compiler doesn’t decide the method to be called. Overriding is a perfect example of dynamic binding. In overriding both parent and child classes have the same method.
Example:
public class NewClass { public static class superclass { void print() { System.out.println("print in superclass."); } } public static class subclass extends superclass { @Override void print() { System.out.println("print in subclass."); } } public static void main(String[] args) { superclass A = new superclass(); superclass B = new subclass(); A.print(); B.print(); }}
print in superclass.
print in subclass.
Difference table between early and late binding:
Picked
Difference Between
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Difference Between Spark DataFrame and Pandas DataFrame
Difference between var, let and const keywords in JavaScript
Difference Between Method Overloading and Method Overriding in Java
Difference between Internal and External fragmentation
Difference between Prim's and Kruskal's algorithm for MST
Arrays in Java
Split() String method in Java with examples
For-each loop in Java
Arrays.sort() in Java with examples
Initialize an ArrayList in Java
|
[
{
"code": null,
"e": 24804,
"s": 24776,
"text": "\n17 Jun, 2019"
},
{
"code": null,
"e": 25000,
"s": 24804,
"text": "Early Binding: The binding which can be resolved at compile time by the compiler is known as static or early binding. Binding of all the static, private and final methods is done at compile-time."
},
{
"code": null,
"e": 25009,
"s": 25000,
"text": "Example:"
},
{
"code": "public class NewClass { public static class superclass { static void print() { System.out.println(\"print in superclass.\"); } } public static class subclass extends superclass { static void print() { System.out.println(\"print in subclass.\"); } } public static void main(String[] args) { superclass A = new superclass(); superclass B = new subclass(); A.print(); B.print(); }}",
"e": 25499,
"s": 25009,
"text": null
},
{
"code": null,
"e": 25542,
"s": 25499,
"text": "print in superclass.\nprint in superclass.\n"
},
{
"code": null,
"e": 25767,
"s": 25542,
"text": "Late binding: In the late binding or dynamic binding, the compiler doesn’t decide the method to be called. Overriding is a perfect example of dynamic binding. In overriding both parent and child classes have the same method."
},
{
"code": null,
"e": 25776,
"s": 25767,
"text": "Example:"
},
{
"code": "public class NewClass { public static class superclass { void print() { System.out.println(\"print in superclass.\"); } } public static class subclass extends superclass { @Override void print() { System.out.println(\"print in subclass.\"); } } public static void main(String[] args) { superclass A = new superclass(); superclass B = new subclass(); A.print(); B.print(); }}",
"e": 26271,
"s": 25776,
"text": null
},
{
"code": null,
"e": 26312,
"s": 26271,
"text": "print in superclass.\nprint in subclass.\n"
},
{
"code": null,
"e": 26361,
"s": 26312,
"text": "Difference table between early and late binding:"
},
{
"code": null,
"e": 26368,
"s": 26361,
"text": "Picked"
},
{
"code": null,
"e": 26387,
"s": 26368,
"text": "Difference Between"
},
{
"code": null,
"e": 26392,
"s": 26387,
"text": "Java"
},
{
"code": null,
"e": 26397,
"s": 26392,
"text": "Java"
},
{
"code": null,
"e": 26495,
"s": 26397,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26504,
"s": 26495,
"text": "Comments"
},
{
"code": null,
"e": 26517,
"s": 26504,
"text": "Old Comments"
},
{
"code": null,
"e": 26573,
"s": 26517,
"text": "Difference Between Spark DataFrame and Pandas DataFrame"
},
{
"code": null,
"e": 26634,
"s": 26573,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 26702,
"s": 26634,
"text": "Difference Between Method Overloading and Method Overriding in Java"
},
{
"code": null,
"e": 26757,
"s": 26702,
"text": "Difference between Internal and External fragmentation"
},
{
"code": null,
"e": 26815,
"s": 26757,
"text": "Difference between Prim's and Kruskal's algorithm for MST"
},
{
"code": null,
"e": 26830,
"s": 26815,
"text": "Arrays in Java"
},
{
"code": null,
"e": 26874,
"s": 26830,
"text": "Split() String method in Java with examples"
},
{
"code": null,
"e": 26896,
"s": 26874,
"text": "For-each loop in Java"
},
{
"code": null,
"e": 26932,
"s": 26896,
"text": "Arrays.sort() in Java with examples"
}
] |
JavaScript modules
|
Modules were introduced in ES 2015. Modules were introduced to break over code into smaller pieces. The modules could contain classes or functions in them. Keywords export and import are used to export variables, functions, objects and import them in other files.
Note − To run this example you will need to run a localhost server.
Following is the code for modules in JavaScript
INDEX.html
Live Demo
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
body {
font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
}
.result {
font-size: 18px;
font-weight: 500;
color:blueviolet;
}
</style>
</head>
<body>
<h1>JavaScript Modules</h1>
<button class="Btn">IMPORT</button>
<div class="result"></div>
<h3>Click on the above button to import module</h3>
<script src="script.js" type="module"></script>
<script src="sample.js" type="module"></script>
</body>
</html>
script.js
import test from './sample.js';
document.querySelector('.Btn').addEventListener('click',()=>{
test();
})
sample.js
let resultEle = document.querySelector(".result");
export default function testImport(){
resultEle.innerHTML = 'Module testImport has been imported';
}
On clicking the ‘IMPORT’ button −
|
[
{
"code": null,
"e": 1326,
"s": 1062,
"text": "Modules were introduced in ES 2015. Modules were introduced to break over code into smaller pieces. The modules could contain classes or functions in them. Keywords export and import are used to export variables, functions, objects and import them in other files."
},
{
"code": null,
"e": 1394,
"s": 1326,
"text": "Note − To run this example you will need to run a localhost server."
},
{
"code": null,
"e": 1442,
"s": 1394,
"text": "Following is the code for modules in JavaScript"
},
{
"code": null,
"e": 1453,
"s": 1442,
"text": "INDEX.html"
},
{
"code": null,
"e": 1464,
"s": 1453,
"text": " Live Demo"
},
{
"code": null,
"e": 2085,
"s": 1464,
"text": "<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n<meta charset=\"UTF-8\" />\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" />\n<title>Document</title>\n<style>\n body {\n font-family: \"Segoe UI\", Tahoma, Geneva, Verdana, sans-serif;\n }\n .result {\n font-size: 18px;\n font-weight: 500;\n color:blueviolet;\n }\n</style>\n</head>\n<body>\n<h1>JavaScript Modules</h1>\n<button class=\"Btn\">IMPORT</button>\n<div class=\"result\"></div>\n<h3>Click on the above button to import module</h3>\n<script src=\"script.js\" type=\"module\"></script>\n<script src=\"sample.js\" type=\"module\"></script>\n</body>\n</html>"
},
{
"code": null,
"e": 2095,
"s": 2085,
"text": "script.js"
},
{
"code": null,
"e": 2203,
"s": 2095,
"text": "import test from './sample.js';\ndocument.querySelector('.Btn').addEventListener('click',()=>{\n test();\n})"
},
{
"code": null,
"e": 2213,
"s": 2203,
"text": "sample.js"
},
{
"code": null,
"e": 2368,
"s": 2213,
"text": "let resultEle = document.querySelector(\".result\");\nexport default function testImport(){\n resultEle.innerHTML = 'Module testImport has been imported';\n}"
},
{
"code": null,
"e": 2402,
"s": 2368,
"text": "On clicking the ‘IMPORT’ button −"
}
] |
DFS of Graph | Practice | GeeksforGeeks
|
Given a connected undirected graph. Perform a Depth First Traversal of the graph.
Note: Use recursive approach to find the DFS traversal of the graph starting from the 0th vertex from left to right according to the graph..
Example 1:
Input:
Output: 0 1 2 4 3
Explanation:
0 is connected to 1, 2, 4.
1 is connected to 0.
2 is connected to 0.
3 is connected to 4.
4 is connected to 0, 3.
so starting from 0, it will go to 1 then 2
then 4, and then from 4 to 3.
Thus dfs will be 0 1 2 4 3.
Example 2:
Input:
Output: 0 1 2 3
Explanation:
0 is connected to 1 , 3.
1 is connected to 2.
2 is connected to 1.
3 is connected to 0.
so starting from 0, it will go to 1 then 2
then back to 0 then 0 to 3
thus dfs will be 0 1 2 3.
Your task:
You dont need to read input or print anything. Your task is to complete the function dfsOfGraph() which takes the integer V denoting the number of vertices and adjacency list as input parameters and returns a list containing the DFS traversal of the graph starting from the 0th vertex from left to right according to the graph.
Expected Time Complexity: O(V + E)
Expected Auxiliary Space: O(V)
Constraints:
1 ≤ V, E ≤ 104
0
kundan_2508
This comment was deleted.
+1
kharsh82211 hours ago
Java Solution
// { Driver Code Starts
// Initial Template for Java
import java.util.*;
import java.lang.*;
import java.io.*;
class GFG {
public static void main(String[] args) throws IOException {
BufferedReader br =
new BufferedReader(new InputStreamReader(System.in));
int T = Integer.parseInt(br.readLine().trim());
while (T-- > 0) {
String[] s = br.readLine().trim().split(" ");
int V = Integer.parseInt(s[0]);
int E = Integer.parseInt(s[1]);
ArrayList<ArrayList<Integer>> adj =
new ArrayList<ArrayList<Integer>>();
for (int i = 0; i < V; i++) adj.add(new ArrayList<Integer>());
for (int i = 0; i < E; i++) {
String[] S = br.readLine().trim().split(" ");
int u = Integer.parseInt(S[0]);
int v = Integer.parseInt(S[1]);
adj.get(u).add(v);
adj.get(v).add(u);
}
Solution obj = new Solution();
ArrayList<Integer> ans = obj.dfsOfGraph(V, adj);
for (int i = 0; i < ans.size(); i++)
System.out.print(ans.get(i) + " ");
System.out.println();
}
}
}
// } Driver Code Ends
class Solution {
// Function to return a list containing the DFS traversal of the graph.
public ArrayList<Integer> dfsOfGraph(int V, ArrayList<ArrayList<Integer>> adj) {
boolean [] visited=new boolean[V];
ArrayList<Integer>[] list1 =new ArrayList[V];
for (int i = 0; i < V; i++) {
list1[i] = new ArrayList<Integer>();
}
for(int i=0;i<adj.size();i++){
for(int j =0;j<adj.get(i).size();j++){
list1[i].add(adj.get(i).get(j));
list1[adj.get(i).get(j)].add(i);
}
}
ArrayList<Integer> list =new ArrayList<>();
helper(list1,list,visited,0);
return list;
}
public void helper(ArrayList<Integer>[] list1,ArrayList<Integer> list ,boolean [] visited,int src){
visited[src]=true;
list.add(src);
for(int a :list1[src]){
if(visited[a]==false){
helper(list1,list,visited,a);
}
}
}
}
0
thakuraditya6211 day ago
// Function to return a list containing the DFS traversal of the graph.
public ArrayList<Integer> dfsOfGraph(int V, ArrayList<ArrayList<Integer>> adj) {
// Code here
ArrayList<Integer> arr = new ArrayList<>();
boolean[] visited = new boolean [V+1];
for(int i =0; i < V; i++){
if(visited[i] == false){
DFS(adj, arr, visited, i);
}
}
return arr;
}
void DFS(ArrayList<ArrayList<Integer>> list, ArrayList<Integer> ans, boolean visited[], int src){
visited[src] = true;
ans.add(src);
for(int nbr : list.get(src)){
if(visited[nbr] == false){
DFS(list, ans, visited, nbr);
}
}
}
0
indreshgoswami1492 days ago
void dfs(int node, vector<int> &vis, vector<int> adj[], vector<int> &storeDfs) {
storeDfs.push_back(node);
vis[node] = 1;
for(auto it : adj[node]) {
if(!vis[it]) {
dfs(it, vis, adj, storeDfs);
}
}
}
public:
// Function to return a list containing the DFS traversal of the graph.
vector<int> dfsOfGraph(int V, vector<int> adj[]) {
// Code here
vector<int> storeDfs;
vector<int> vis(V+1, 0);
for(int i = 1;i<=V;i++) {
if(!vis[i]) dfs(i, vis, adj, storeDfs);
}
return storeDfs;
}
};
0
deeptimayeemaharana064 days ago
WHAT'S THE ERROR IN THIS?
void dfs(int node,vector<int>&vis,vector<int>adj[],vector<int>&storedfs){ storedfs.push_back(node); vis[node]=1; for(auto it:adj[node]) { if(!vis[it]){ dfs(it,vis,adj,storedfs); } } } vector<int> dfsOfGraph(int V,vector<int> adj[]) { vector<int>dfs; vector<int> vis(V+1,0); dfs(0,vis,adj,dfs); return dfs; }
0
gp9199344 days ago
void Dfsrec(vector<int> adj[],int s,vector<int>&visited){ visited[s]=1; cout<<s<<" "; for(auto x:adj[s]){ if(visited[x]==false){ Dfsrec(adj,x,visited); } } } vector<int> dfsOfGraph(int v, vector<int> adj[]) { vector<int>visited(v+1,0); for(int i=0;i<v;i++){ if(visited[i]==false){ Dfsrec(adj,i,visited); } } return {};
}
0
singhdipranjan671 week ago
class Solution {
// Function to return a list containing the DFS traversal of the graph.
public ArrayList<Integer> dfsOfGraph(int V, ArrayList<ArrayList<Integer>> list) {
ArrayList<Integer> brr=new ArrayList<>();
boolean arr[]=new boolean[V+1];
for(int i=0; i<V; i++)
{
if(arr[i]==false)
DFSrec(list, brr, arr, i);
}
return brr;
}
void DFSrec(ArrayList<ArrayList<Integer>> list, ArrayList<Integer> brr, boolean arr[], int s)
{
arr[s]=true;
brr.add(s);
for(int u: list.get(s))
{
if(arr[u]==false)
DFSrec(list, brr, arr, u);
}
}
}
0
harshscode1 week ago
o(v+e) and o(v)
void dfs(int src,vector<int> &v1,vector<int> &vis,vector<int> adj[]) { vector<int> r; vis[src]=1; v1.push_back(src); for(auto x:adj[src]) if(!vis[x]) dfs(x,v1,vis,adj);
}
vector<int> dfsOfGraph(int v, vector<int> adj[]) { vector<int> vis(v); for(int i=0;i<v;i++) vis[i]=0; vector<int> v1; dfs(0,v1,vis,adj); return v1; }
0
ajaynikumbh4341 week ago
class Solution
{
public:
void dfs(vector<int> adj[], int i , vector<bool> &v)
{
cout<<i<<" ";
v[i] = true;
for(auto nbr: adj[i])
{
if(!v[nbr])
{
dfs(adj, nbr, v);
}
}
}
vector<int> dfsOfGraph(int v, vector<int> adj[])
{
vector<bool> visit(v,false);
for(int i=0;i<v;i++)
{
if(!visit[i])
{
dfs(adj, i, visit);
}
}
return {};
}
};
0
jainmuskan5651 week ago
vector<int> ans; void solve(int node, vector<int> adj[],bool visited[]){ visited[node]=true; ans.push_back(node); for(int neighbor: adj[node]){ if(!visited[neighbor]){ solve(neighbor,adj,visited); } } } vector<int> dfsOfGraph(int V, vector<int> adj[]) { // use recursion and visited array bool visited[V]={0}; ans.clear(); solve(0,adj,visited); return ans; }
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
want to view the editorial?
Login to access your submissions.
Problem
Contest
Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.
|
[
{
"code": null,
"e": 461,
"s": 238,
"text": "Given a connected undirected graph. Perform a Depth First Traversal of the graph.\nNote: Use recursive approach to find the DFS traversal of the graph starting from the 0th vertex from left to right according to the graph.."
},
{
"code": null,
"e": 473,
"s": 461,
"text": "\nExample 1:"
},
{
"code": null,
"e": 729,
"s": 473,
"text": "Input:\n\nOutput: 0 1 2 4 3\nExplanation: \n0 is connected to 1, 2, 4.\n1 is connected to 0.\n2 is connected to 0.\n3 is connected to 4.\n4 is connected to 0, 3.\nso starting from 0, it will go to 1 then 2\nthen 4, and then from 4 to 3.\nThus dfs will be 0 1 2 4 3.\n"
},
{
"code": null,
"e": 740,
"s": 729,
"text": "Example 2:"
},
{
"code": null,
"e": 965,
"s": 740,
"text": "Input:\n\nOutput: 0 1 2 3\nExplanation:\n0 is connected to 1 , 3.\n1 is connected to 2. \n2 is connected to 1.\n3 is connected to 0. \nso starting from 0, it will go to 1 then 2\nthen back to 0 then 0 to 3\nthus dfs will be 0 1 2 3. \n"
},
{
"code": null,
"e": 1306,
"s": 965,
"text": "\nYour task:\nYou dont need to read input or print anything. Your task is to complete the function dfsOfGraph() which takes the integer V denoting the number of vertices and adjacency list as input parameters and returns a list containing the DFS traversal of the graph starting from the 0th vertex from left to right according to the graph."
},
{
"code": null,
"e": 1373,
"s": 1306,
"text": "\nExpected Time Complexity: O(V + E)\nExpected Auxiliary Space: O(V)"
},
{
"code": null,
"e": 1402,
"s": 1373,
"text": "\nConstraints:\n1 ≤ V, E ≤ 104"
},
{
"code": null,
"e": 1404,
"s": 1402,
"text": "0"
},
{
"code": null,
"e": 1416,
"s": 1404,
"text": "kundan_2508"
},
{
"code": null,
"e": 1442,
"s": 1416,
"text": "This comment was deleted."
},
{
"code": null,
"e": 1445,
"s": 1442,
"text": "+1"
},
{
"code": null,
"e": 1467,
"s": 1445,
"text": "kharsh82211 hours ago"
},
{
"code": null,
"e": 1481,
"s": 1467,
"text": "Java Solution"
},
{
"code": null,
"e": 3830,
"s": 1481,
"text": "// { Driver Code Starts\n// Initial Template for Java\nimport java.util.*;\nimport java.lang.*;\nimport java.io.*;\nclass GFG {\n public static void main(String[] args) throws IOException {\n BufferedReader br =\n new BufferedReader(new InputStreamReader(System.in));\n int T = Integer.parseInt(br.readLine().trim());\n while (T-- > 0) {\n String[] s = br.readLine().trim().split(\" \");\n int V = Integer.parseInt(s[0]);\n int E = Integer.parseInt(s[1]);\n ArrayList<ArrayList<Integer>> adj =\n new ArrayList<ArrayList<Integer>>();\n for (int i = 0; i < V; i++) adj.add(new ArrayList<Integer>());\n for (int i = 0; i < E; i++) {\n String[] S = br.readLine().trim().split(\" \");\n int u = Integer.parseInt(S[0]);\n int v = Integer.parseInt(S[1]);\n adj.get(u).add(v);\n adj.get(v).add(u);\n }\n Solution obj = new Solution();\n ArrayList<Integer> ans = obj.dfsOfGraph(V, adj);\n for (int i = 0; i < ans.size(); i++)\n System.out.print(ans.get(i) + \" \");\n System.out.println();\n }\n }\n}\n// } Driver Code Ends\n\n\nclass Solution {\n // Function to return a list containing the DFS traversal of the graph.\n public ArrayList<Integer> dfsOfGraph(int V, ArrayList<ArrayList<Integer>> adj) {\n \n boolean [] visited=new boolean[V];\n \n ArrayList<Integer>[] list1 =new ArrayList[V];\n \n for (int i = 0; i < V; i++) {\n list1[i] = new ArrayList<Integer>();\n }\n \n for(int i=0;i<adj.size();i++){\n for(int j =0;j<adj.get(i).size();j++){\n list1[i].add(adj.get(i).get(j));\n list1[adj.get(i).get(j)].add(i);\n \n }\n \n }\n \n ArrayList<Integer> list =new ArrayList<>();\n \n helper(list1,list,visited,0);\n \n return list;\n }\n \n public void helper(ArrayList<Integer>[] list1,ArrayList<Integer> list ,boolean [] visited,int src){\n visited[src]=true;\n list.add(src);\n \n for(int a :list1[src]){\n if(visited[a]==false){\n helper(list1,list,visited,a);\n }\n }\n }\n}"
},
{
"code": null,
"e": 3832,
"s": 3830,
"text": "0"
},
{
"code": null,
"e": 3857,
"s": 3832,
"text": "thakuraditya6211 day ago"
},
{
"code": null,
"e": 4630,
"s": 3857,
"text": "// Function to return a list containing the DFS traversal of the graph.\n public ArrayList<Integer> dfsOfGraph(int V, ArrayList<ArrayList<Integer>> adj) {\n // Code here\n ArrayList<Integer> arr = new ArrayList<>();\n boolean[] visited = new boolean [V+1];\n \n for(int i =0; i < V; i++){\n if(visited[i] == false){\n DFS(adj, arr, visited, i);\n }\n }\n return arr;\n }\n \n void DFS(ArrayList<ArrayList<Integer>> list, ArrayList<Integer> ans, boolean visited[], int src){\n visited[src] = true;\n ans.add(src);\n \n for(int nbr : list.get(src)){\n if(visited[nbr] == false){\n DFS(list, ans, visited, nbr);\n }\n }\n }"
},
{
"code": null,
"e": 4632,
"s": 4630,
"text": "0"
},
{
"code": null,
"e": 4660,
"s": 4632,
"text": "indreshgoswami1492 days ago"
},
{
"code": null,
"e": 5286,
"s": 4660,
"text": "\n\nvoid dfs(int node, vector<int> &vis, vector<int> adj[], vector<int> &storeDfs) {\n storeDfs.push_back(node); \n vis[node] = 1; \n for(auto it : adj[node]) {\n if(!vis[it]) {\n dfs(it, vis, adj, storeDfs); \n }\n }\n }\n\npublic:\n // Function to return a list containing the DFS traversal of the graph.\n vector<int> dfsOfGraph(int V, vector<int> adj[]) {\n // Code here\n vector<int> storeDfs; \n\t vector<int> vis(V+1, 0); \n for(int i = 1;i<=V;i++) {\n if(!vis[i]) dfs(i, vis, adj, storeDfs); \n }\n\t return storeDfs; \n }\n};\n\n"
},
{
"code": null,
"e": 5288,
"s": 5286,
"text": "0"
},
{
"code": null,
"e": 5320,
"s": 5288,
"text": "deeptimayeemaharana064 days ago"
},
{
"code": null,
"e": 5348,
"s": 5322,
"text": "WHAT'S THE ERROR IN THIS?"
},
{
"code": null,
"e": 5754,
"s": 5350,
"text": "void dfs(int node,vector<int>&vis,vector<int>adj[],vector<int>&storedfs){ storedfs.push_back(node); vis[node]=1; for(auto it:adj[node]) { if(!vis[it]){ dfs(it,vis,adj,storedfs); } } } vector<int> dfsOfGraph(int V,vector<int> adj[]) { vector<int>dfs; vector<int> vis(V+1,0); dfs(0,vis,adj,dfs); return dfs; }"
},
{
"code": null,
"e": 5758,
"s": 5756,
"text": "0"
},
{
"code": null,
"e": 5777,
"s": 5758,
"text": "gp9199344 days ago"
},
{
"code": null,
"e": 6216,
"s": 5777,
"text": "void Dfsrec(vector<int> adj[],int s,vector<int>&visited){ visited[s]=1; cout<<s<<\" \"; for(auto x:adj[s]){ if(visited[x]==false){ Dfsrec(adj,x,visited); } } } vector<int> dfsOfGraph(int v, vector<int> adj[]) { vector<int>visited(v+1,0); for(int i=0;i<v;i++){ if(visited[i]==false){ Dfsrec(adj,i,visited); } } return {};"
},
{
"code": null,
"e": 6218,
"s": 6216,
"text": "}"
},
{
"code": null,
"e": 6220,
"s": 6218,
"text": "0"
},
{
"code": null,
"e": 6247,
"s": 6220,
"text": "singhdipranjan671 week ago"
},
{
"code": null,
"e": 6942,
"s": 6247,
"text": "class Solution {\n // Function to return a list containing the DFS traversal of the graph.\n public ArrayList<Integer> dfsOfGraph(int V, ArrayList<ArrayList<Integer>> list) {\n ArrayList<Integer> brr=new ArrayList<>();\n boolean arr[]=new boolean[V+1];\n for(int i=0; i<V; i++)\n {\n if(arr[i]==false)\n DFSrec(list, brr, arr, i);\n }\n \n return brr;\n }\n void DFSrec(ArrayList<ArrayList<Integer>> list, ArrayList<Integer> brr, boolean arr[], int s)\n {\n arr[s]=true;\n brr.add(s);\n for(int u: list.get(s))\n {\n if(arr[u]==false)\n DFSrec(list, brr, arr, u);\n }\n }\n}\n"
},
{
"code": null,
"e": 6944,
"s": 6942,
"text": "0"
},
{
"code": null,
"e": 6965,
"s": 6944,
"text": "harshscode1 week ago"
},
{
"code": null,
"e": 6981,
"s": 6965,
"text": "o(v+e) and o(v)"
},
{
"code": null,
"e": 7311,
"s": 6981,
"text": " void dfs(int src,vector<int> &v1,vector<int> &vis,vector<int> adj[]) { vector<int> r; vis[src]=1; v1.push_back(src); for(auto x:adj[src]) if(!vis[x]) dfs(x,v1,vis,adj); "
},
{
"code": null,
"e": 7319,
"s": 7311,
"text": " }"
},
{
"code": null,
"e": 7519,
"s": 7319,
"text": " vector<int> dfsOfGraph(int v, vector<int> adj[]) { vector<int> vis(v); for(int i=0;i<v;i++) vis[i]=0; vector<int> v1; dfs(0,v1,vis,adj); return v1; }"
},
{
"code": null,
"e": 7521,
"s": 7519,
"text": "0"
},
{
"code": null,
"e": 7546,
"s": 7521,
"text": "ajaynikumbh4341 week ago"
},
{
"code": null,
"e": 8095,
"s": 7546,
"text": "class Solution \n{\n public:\n void dfs(vector<int> adj[], int i , vector<bool> &v)\n {\n cout<<i<<\" \";\n v[i] = true;\n for(auto nbr: adj[i])\n {\n if(!v[nbr])\n {\n dfs(adj, nbr, v);\n }\n }\n }\n \n vector<int> dfsOfGraph(int v, vector<int> adj[])\n {\n vector<bool> visit(v,false);\n for(int i=0;i<v;i++)\n {\n if(!visit[i])\n {\n dfs(adj, i, visit);\n }\n }\n return {};\n } \n};\n"
},
{
"code": null,
"e": 8097,
"s": 8095,
"text": "0"
},
{
"code": null,
"e": 8121,
"s": 8097,
"text": "jainmuskan5651 week ago"
},
{
"code": null,
"e": 8584,
"s": 8121,
"text": " vector<int> ans; void solve(int node, vector<int> adj[],bool visited[]){ visited[node]=true; ans.push_back(node); for(int neighbor: adj[node]){ if(!visited[neighbor]){ solve(neighbor,adj,visited); } } } vector<int> dfsOfGraph(int V, vector<int> adj[]) { // use recursion and visited array bool visited[V]={0}; ans.clear(); solve(0,adj,visited); return ans; }"
},
{
"code": null,
"e": 8730,
"s": 8584,
"text": "We strongly recommend solving this problem on your own before viewing its editorial. Do you still\n want to view the editorial?"
},
{
"code": null,
"e": 8766,
"s": 8730,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 8776,
"s": 8766,
"text": "\nProblem\n"
},
{
"code": null,
"e": 8786,
"s": 8776,
"text": "\nContest\n"
},
{
"code": null,
"e": 8849,
"s": 8786,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 8997,
"s": 8849,
"text": "Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values."
},
{
"code": null,
"e": 9205,
"s": 8997,
"text": "Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints."
},
{
"code": null,
"e": 9311,
"s": 9205,
"text": "You can access the hints to get an idea about what is expected of you as well as the final solution code."
}
] |
Implement and set DOUBLE length in MySQL
|
To implement DOUBLE in MySQL, the syntax is as follows −
create table yourTableName
(
yourColumnName double(5,2) unsigned
);
Let us first create a table −
mysql> create table DemoTable1814
(
Amount double(5,2) unsigned
);
Query OK, 0 rows affected (0.00 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable1814 values(1.98);
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1814 values(100.24);
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1814 values(198.50);
Query OK, 1 row affected (0.00 sec)
Display all records from the table using select statement −
mysql> select * from DemoTable1814;
This will produce the following output −
+--------+
| Amount |
+--------+
| 1.98 |
| 100.24 |
| 198.50 |
+--------+
3 rows in set (0.00 sec)
|
[
{
"code": null,
"e": 1119,
"s": 1062,
"text": "To implement DOUBLE in MySQL, the syntax is as follows −"
},
{
"code": null,
"e": 1197,
"s": 1119,
"text": "create table yourTableName\n (\n yourColumnName double(5,2) unsigned\n);"
},
{
"code": null,
"e": 1227,
"s": 1197,
"text": "Let us first create a table −"
},
{
"code": null,
"e": 1346,
"s": 1227,
"text": "mysql> create table DemoTable1814\n (\n Amount double(5,2) unsigned\n );\nQuery OK, 0 rows affected (0.00 sec)"
},
{
"code": null,
"e": 1402,
"s": 1346,
"text": "Insert some records in the table using insert command −"
},
{
"code": null,
"e": 1655,
"s": 1402,
"text": "mysql> insert into DemoTable1814 values(1.98);\nQuery OK, 1 row affected (0.00 sec)\nmysql> insert into DemoTable1814 values(100.24);\nQuery OK, 1 row affected (0.00 sec)\nmysql> insert into DemoTable1814 values(198.50);\nQuery OK, 1 row affected (0.00 sec)"
},
{
"code": null,
"e": 1715,
"s": 1655,
"text": "Display all records from the table using select statement −"
},
{
"code": null,
"e": 1751,
"s": 1715,
"text": "mysql> select * from DemoTable1814;"
},
{
"code": null,
"e": 1792,
"s": 1751,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 1894,
"s": 1792,
"text": "+--------+\n| Amount |\n+--------+\n| 1.98 |\n| 100.24 |\n| 198.50 |\n+--------+\n3 rows in set (0.00 sec)"
}
] |
HTML5 - datetime
|
A date and time (year, month, day, hour, minute, second, fractions of a second) encoded according to ISO 8601 with the time zone set to UTC.
<!DOCTYPE HTML>
<html>
<body>
<form action = "/cgi-bin/html5.cgi" method = "get">
Date and Time : <input type = "datetime" name = "newinput" />
<input type = "submit" value = "submit" />
</form>
</body>
</html>
19 Lectures
2 hours
Anadi Sharma
16 Lectures
1.5 hours
Anadi Sharma
18 Lectures
1.5 hours
Frahaan Hussain
57 Lectures
5.5 hours
DigiFisk (Programming Is Fun)
54 Lectures
6 hours
DigiFisk (Programming Is Fun)
45 Lectures
5.5 hours
DigiFisk (Programming Is Fun)
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2749,
"s": 2608,
"text": "A date and time (year, month, day, hour, minute, second, fractions of a second) encoded according to ISO 8601 with the time zone set to UTC."
},
{
"code": null,
"e": 3011,
"s": 2749,
"text": "<!DOCTYPE HTML>\n<html>\n \n <body>\n \n <form action = \"/cgi-bin/html5.cgi\" method = \"get\">\n Date and Time : <input type = \"datetime\" name = \"newinput\" />\n <input type = \"submit\" value = \"submit\" />\n </form>\n \n </body>\n</html>"
},
{
"code": null,
"e": 3044,
"s": 3011,
"text": "\n 19 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 3058,
"s": 3044,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 3093,
"s": 3058,
"text": "\n 16 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 3107,
"s": 3093,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 3142,
"s": 3107,
"text": "\n 18 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 3159,
"s": 3142,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 3194,
"s": 3159,
"text": "\n 57 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 3225,
"s": 3194,
"text": " DigiFisk (Programming Is Fun)"
},
{
"code": null,
"e": 3258,
"s": 3225,
"text": "\n 54 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 3289,
"s": 3258,
"text": " DigiFisk (Programming Is Fun)"
},
{
"code": null,
"e": 3324,
"s": 3289,
"text": "\n 45 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 3355,
"s": 3324,
"text": " DigiFisk (Programming Is Fun)"
},
{
"code": null,
"e": 3362,
"s": 3355,
"text": " Print"
},
{
"code": null,
"e": 3373,
"s": 3362,
"text": " Add Notes"
}
] |
JavaFX | Group Class - GeeksforGeeks
|
10 Sep, 2018
Group class is a part of JavaFX. A Group contains the number of nodes. A Group will take on the collective bounds of its children and is not directly resizable. Group class inherits Parent class.
Constructor of the class:
Group(): Constructs a new group.Group(Collection children): Constructs a new group with specified nodes.Group(Node... c): Constructs a new group with specified nodes.
Group(): Constructs a new group.
Group(Collection children): Constructs a new group with specified nodes.
Group(Node... c): Constructs a new group with specified nodes.
Commonly Used Methods:
Below programs illustrate the use of Group class:
Java Program to create a Group and add it to the stage: In this program we are creating a Label named label, and a Circle named circle. Now create a Group name group and add the label and circle to it by using the getChildren().add() function. Create a scene and add the group to the scene. Add the scene to the stage and display the stage to view the final results.// Java Program to create a Group// and add it to the stageimport javafx.application.Application;import javafx.scene.Scene;import javafx.scene.control.*;import javafx.scene.layout.*;import javafx.stage.Stage;import javafx.event.ActionEvent;import javafx.event.EventHandler;import javafx.scene.canvas.*;import javafx.scene.web.*;import javafx.scene.Group;import javafx.scene.shape.*; public class Group_1 extends Application { // launch the application public void start(Stage stage) { try { // set title for the stage stage.setTitle("Group"); // create a Group Group group = new Group(); // create a label Label label = new Label("this is Group example"); // add label to group group.getChildren().add(label); // circle Circle c = new Circle(100, 100, 30); // add Circle to Group group.getChildren().add(c); // create a scene Scene scene = new Scene(group, 400, 300); // set the scene stage.setScene(scene); stage.show(); } catch (Exception e) { System.out.println(e.getMessage()); } } // Main Method public static void main(String args[]) { // launch the application launch(args); }}Output:Java Program to create a Group, set auto resize to true and add it to the stage: In this program we are creating a Label named label and a Circle named circle. Then we will create a Group name group and add the label and circle to it by using the getChildren().add() function. Set the auto size children to true using the setAutoSize() function. Create a scene and add the group to the scene. Add the scene to the stage and display the stage to view the final results.// Java Program to create a Group,// set auto resize to true// and add it to the stageimport javafx.application.Application;import javafx.scene.Scene;import javafx.scene.control.*;import javafx.scene.layout.*;import javafx.stage.Stage;import javafx.event.ActionEvent;import javafx.event.EventHandler;import javafx.scene.canvas.*;import javafx.scene.web.*;import javafx.scene.Group;import javafx.scene.shape.*; public class Group_2 extends Application { // launch the application public void start(Stage stage) { try { // set title for the stage stage.setTitle("Group"); // create a Group Group group = new Group(); // create a label Label label = new Label("this is Group example"); // add label to group group.getChildren().add(label); // circle Circle c = new Circle(50, 50, 30); // set auto resize group.setAutoSizeChildren(true); // add Circle to Group group.getChildren().add(c); // create a scene Scene scene = new Scene(group, 400, 300); // set the scene stage.setScene(scene); stage.show(); } catch (Exception e) { System.out.println(e.getMessage()); } } // Main Method public static void main(String args[]) { // launch the application launch(args); }}Output:
Java Program to create a Group and add it to the stage: In this program we are creating a Label named label, and a Circle named circle. Now create a Group name group and add the label and circle to it by using the getChildren().add() function. Create a scene and add the group to the scene. Add the scene to the stage and display the stage to view the final results.// Java Program to create a Group// and add it to the stageimport javafx.application.Application;import javafx.scene.Scene;import javafx.scene.control.*;import javafx.scene.layout.*;import javafx.stage.Stage;import javafx.event.ActionEvent;import javafx.event.EventHandler;import javafx.scene.canvas.*;import javafx.scene.web.*;import javafx.scene.Group;import javafx.scene.shape.*; public class Group_1 extends Application { // launch the application public void start(Stage stage) { try { // set title for the stage stage.setTitle("Group"); // create a Group Group group = new Group(); // create a label Label label = new Label("this is Group example"); // add label to group group.getChildren().add(label); // circle Circle c = new Circle(100, 100, 30); // add Circle to Group group.getChildren().add(c); // create a scene Scene scene = new Scene(group, 400, 300); // set the scene stage.setScene(scene); stage.show(); } catch (Exception e) { System.out.println(e.getMessage()); } } // Main Method public static void main(String args[]) { // launch the application launch(args); }}Output:
// Java Program to create a Group// and add it to the stageimport javafx.application.Application;import javafx.scene.Scene;import javafx.scene.control.*;import javafx.scene.layout.*;import javafx.stage.Stage;import javafx.event.ActionEvent;import javafx.event.EventHandler;import javafx.scene.canvas.*;import javafx.scene.web.*;import javafx.scene.Group;import javafx.scene.shape.*; public class Group_1 extends Application { // launch the application public void start(Stage stage) { try { // set title for the stage stage.setTitle("Group"); // create a Group Group group = new Group(); // create a label Label label = new Label("this is Group example"); // add label to group group.getChildren().add(label); // circle Circle c = new Circle(100, 100, 30); // add Circle to Group group.getChildren().add(c); // create a scene Scene scene = new Scene(group, 400, 300); // set the scene stage.setScene(scene); stage.show(); } catch (Exception e) { System.out.println(e.getMessage()); } } // Main Method public static void main(String args[]) { // launch the application launch(args); }}
Output:
Java Program to create a Group, set auto resize to true and add it to the stage: In this program we are creating a Label named label and a Circle named circle. Then we will create a Group name group and add the label and circle to it by using the getChildren().add() function. Set the auto size children to true using the setAutoSize() function. Create a scene and add the group to the scene. Add the scene to the stage and display the stage to view the final results.// Java Program to create a Group,// set auto resize to true// and add it to the stageimport javafx.application.Application;import javafx.scene.Scene;import javafx.scene.control.*;import javafx.scene.layout.*;import javafx.stage.Stage;import javafx.event.ActionEvent;import javafx.event.EventHandler;import javafx.scene.canvas.*;import javafx.scene.web.*;import javafx.scene.Group;import javafx.scene.shape.*; public class Group_2 extends Application { // launch the application public void start(Stage stage) { try { // set title for the stage stage.setTitle("Group"); // create a Group Group group = new Group(); // create a label Label label = new Label("this is Group example"); // add label to group group.getChildren().add(label); // circle Circle c = new Circle(50, 50, 30); // set auto resize group.setAutoSizeChildren(true); // add Circle to Group group.getChildren().add(c); // create a scene Scene scene = new Scene(group, 400, 300); // set the scene stage.setScene(scene); stage.show(); } catch (Exception e) { System.out.println(e.getMessage()); } } // Main Method public static void main(String args[]) { // launch the application launch(args); }}Output:
// Java Program to create a Group,// set auto resize to true// and add it to the stageimport javafx.application.Application;import javafx.scene.Scene;import javafx.scene.control.*;import javafx.scene.layout.*;import javafx.stage.Stage;import javafx.event.ActionEvent;import javafx.event.EventHandler;import javafx.scene.canvas.*;import javafx.scene.web.*;import javafx.scene.Group;import javafx.scene.shape.*; public class Group_2 extends Application { // launch the application public void start(Stage stage) { try { // set title for the stage stage.setTitle("Group"); // create a Group Group group = new Group(); // create a label Label label = new Label("this is Group example"); // add label to group group.getChildren().add(label); // circle Circle c = new Circle(50, 50, 30); // set auto resize group.setAutoSizeChildren(true); // add Circle to Group group.getChildren().add(c); // create a scene Scene scene = new Scene(group, 400, 300); // set the scene stage.setScene(scene); stage.show(); } catch (Exception e) { System.out.println(e.getMessage()); } } // Main Method public static void main(String args[]) { // launch the application launch(args); }}
Output:
Note: The above programs might not run in an online IDE. Please use an offline compiler.
Reference: https://docs.oracle.com/javase/8/javafx/api/javafx/scene/Group.html
JavaFX
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Initialize an ArrayList in Java
HashMap in Java with Examples
Interfaces in Java
Object Oriented Programming (OOPs) Concept in Java
How to iterate any Map in Java
Multidimensional Arrays in Java
Stack Class in Java
Set in Java
Singleton Class in Java
Overriding in Java
|
[
{
"code": null,
"e": 24048,
"s": 24020,
"text": "\n10 Sep, 2018"
},
{
"code": null,
"e": 24244,
"s": 24048,
"text": "Group class is a part of JavaFX. A Group contains the number of nodes. A Group will take on the collective bounds of its children and is not directly resizable. Group class inherits Parent class."
},
{
"code": null,
"e": 24270,
"s": 24244,
"text": "Constructor of the class:"
},
{
"code": null,
"e": 24437,
"s": 24270,
"text": "Group(): Constructs a new group.Group(Collection children): Constructs a new group with specified nodes.Group(Node... c): Constructs a new group with specified nodes."
},
{
"code": null,
"e": 24470,
"s": 24437,
"text": "Group(): Constructs a new group."
},
{
"code": null,
"e": 24543,
"s": 24470,
"text": "Group(Collection children): Constructs a new group with specified nodes."
},
{
"code": null,
"e": 24606,
"s": 24543,
"text": "Group(Node... c): Constructs a new group with specified nodes."
},
{
"code": null,
"e": 24629,
"s": 24606,
"text": "Commonly Used Methods:"
},
{
"code": null,
"e": 24679,
"s": 24629,
"text": "Below programs illustrate the use of Group class:"
},
{
"code": null,
"e": 28387,
"s": 24679,
"text": "Java Program to create a Group and add it to the stage: In this program we are creating a Label named label, and a Circle named circle. Now create a Group name group and add the label and circle to it by using the getChildren().add() function. Create a scene and add the group to the scene. Add the scene to the stage and display the stage to view the final results.// Java Program to create a Group// and add it to the stageimport javafx.application.Application;import javafx.scene.Scene;import javafx.scene.control.*;import javafx.scene.layout.*;import javafx.stage.Stage;import javafx.event.ActionEvent;import javafx.event.EventHandler;import javafx.scene.canvas.*;import javafx.scene.web.*;import javafx.scene.Group;import javafx.scene.shape.*; public class Group_1 extends Application { // launch the application public void start(Stage stage) { try { // set title for the stage stage.setTitle(\"Group\"); // create a Group Group group = new Group(); // create a label Label label = new Label(\"this is Group example\"); // add label to group group.getChildren().add(label); // circle Circle c = new Circle(100, 100, 30); // add Circle to Group group.getChildren().add(c); // create a scene Scene scene = new Scene(group, 400, 300); // set the scene stage.setScene(scene); stage.show(); } catch (Exception e) { System.out.println(e.getMessage()); } } // Main Method public static void main(String args[]) { // launch the application launch(args); }}Output:Java Program to create a Group, set auto resize to true and add it to the stage: In this program we are creating a Label named label and a Circle named circle. Then we will create a Group name group and add the label and circle to it by using the getChildren().add() function. Set the auto size children to true using the setAutoSize() function. Create a scene and add the group to the scene. Add the scene to the stage and display the stage to view the final results.// Java Program to create a Group,// set auto resize to true// and add it to the stageimport javafx.application.Application;import javafx.scene.Scene;import javafx.scene.control.*;import javafx.scene.layout.*;import javafx.stage.Stage;import javafx.event.ActionEvent;import javafx.event.EventHandler;import javafx.scene.canvas.*;import javafx.scene.web.*;import javafx.scene.Group;import javafx.scene.shape.*; public class Group_2 extends Application { // launch the application public void start(Stage stage) { try { // set title for the stage stage.setTitle(\"Group\"); // create a Group Group group = new Group(); // create a label Label label = new Label(\"this is Group example\"); // add label to group group.getChildren().add(label); // circle Circle c = new Circle(50, 50, 30); // set auto resize group.setAutoSizeChildren(true); // add Circle to Group group.getChildren().add(c); // create a scene Scene scene = new Scene(group, 400, 300); // set the scene stage.setScene(scene); stage.show(); } catch (Exception e) { System.out.println(e.getMessage()); } } // Main Method public static void main(String args[]) { // launch the application launch(args); }}Output:"
},
{
"code": null,
"e": 30140,
"s": 28387,
"text": "Java Program to create a Group and add it to the stage: In this program we are creating a Label named label, and a Circle named circle. Now create a Group name group and add the label and circle to it by using the getChildren().add() function. Create a scene and add the group to the scene. Add the scene to the stage and display the stage to view the final results.// Java Program to create a Group// and add it to the stageimport javafx.application.Application;import javafx.scene.Scene;import javafx.scene.control.*;import javafx.scene.layout.*;import javafx.stage.Stage;import javafx.event.ActionEvent;import javafx.event.EventHandler;import javafx.scene.canvas.*;import javafx.scene.web.*;import javafx.scene.Group;import javafx.scene.shape.*; public class Group_1 extends Application { // launch the application public void start(Stage stage) { try { // set title for the stage stage.setTitle(\"Group\"); // create a Group Group group = new Group(); // create a label Label label = new Label(\"this is Group example\"); // add label to group group.getChildren().add(label); // circle Circle c = new Circle(100, 100, 30); // add Circle to Group group.getChildren().add(c); // create a scene Scene scene = new Scene(group, 400, 300); // set the scene stage.setScene(scene); stage.show(); } catch (Exception e) { System.out.println(e.getMessage()); } } // Main Method public static void main(String args[]) { // launch the application launch(args); }}Output:"
},
{
"code": "// Java Program to create a Group// and add it to the stageimport javafx.application.Application;import javafx.scene.Scene;import javafx.scene.control.*;import javafx.scene.layout.*;import javafx.stage.Stage;import javafx.event.ActionEvent;import javafx.event.EventHandler;import javafx.scene.canvas.*;import javafx.scene.web.*;import javafx.scene.Group;import javafx.scene.shape.*; public class Group_1 extends Application { // launch the application public void start(Stage stage) { try { // set title for the stage stage.setTitle(\"Group\"); // create a Group Group group = new Group(); // create a label Label label = new Label(\"this is Group example\"); // add label to group group.getChildren().add(label); // circle Circle c = new Circle(100, 100, 30); // add Circle to Group group.getChildren().add(c); // create a scene Scene scene = new Scene(group, 400, 300); // set the scene stage.setScene(scene); stage.show(); } catch (Exception e) { System.out.println(e.getMessage()); } } // Main Method public static void main(String args[]) { // launch the application launch(args); }}",
"e": 31520,
"s": 30140,
"text": null
},
{
"code": null,
"e": 31528,
"s": 31520,
"text": "Output:"
},
{
"code": null,
"e": 33484,
"s": 31528,
"text": "Java Program to create a Group, set auto resize to true and add it to the stage: In this program we are creating a Label named label and a Circle named circle. Then we will create a Group name group and add the label and circle to it by using the getChildren().add() function. Set the auto size children to true using the setAutoSize() function. Create a scene and add the group to the scene. Add the scene to the stage and display the stage to view the final results.// Java Program to create a Group,// set auto resize to true// and add it to the stageimport javafx.application.Application;import javafx.scene.Scene;import javafx.scene.control.*;import javafx.scene.layout.*;import javafx.stage.Stage;import javafx.event.ActionEvent;import javafx.event.EventHandler;import javafx.scene.canvas.*;import javafx.scene.web.*;import javafx.scene.Group;import javafx.scene.shape.*; public class Group_2 extends Application { // launch the application public void start(Stage stage) { try { // set title for the stage stage.setTitle(\"Group\"); // create a Group Group group = new Group(); // create a label Label label = new Label(\"this is Group example\"); // add label to group group.getChildren().add(label); // circle Circle c = new Circle(50, 50, 30); // set auto resize group.setAutoSizeChildren(true); // add Circle to Group group.getChildren().add(c); // create a scene Scene scene = new Scene(group, 400, 300); // set the scene stage.setScene(scene); stage.show(); } catch (Exception e) { System.out.println(e.getMessage()); } } // Main Method public static void main(String args[]) { // launch the application launch(args); }}Output:"
},
{
"code": "// Java Program to create a Group,// set auto resize to true// and add it to the stageimport javafx.application.Application;import javafx.scene.Scene;import javafx.scene.control.*;import javafx.scene.layout.*;import javafx.stage.Stage;import javafx.event.ActionEvent;import javafx.event.EventHandler;import javafx.scene.canvas.*;import javafx.scene.web.*;import javafx.scene.Group;import javafx.scene.shape.*; public class Group_2 extends Application { // launch the application public void start(Stage stage) { try { // set title for the stage stage.setTitle(\"Group\"); // create a Group Group group = new Group(); // create a label Label label = new Label(\"this is Group example\"); // add label to group group.getChildren().add(label); // circle Circle c = new Circle(50, 50, 30); // set auto resize group.setAutoSizeChildren(true); // add Circle to Group group.getChildren().add(c); // create a scene Scene scene = new Scene(group, 400, 300); // set the scene stage.setScene(scene); stage.show(); } catch (Exception e) { System.out.println(e.getMessage()); } } // Main Method public static void main(String args[]) { // launch the application launch(args); }}",
"e": 34965,
"s": 33484,
"text": null
},
{
"code": null,
"e": 34973,
"s": 34965,
"text": "Output:"
},
{
"code": null,
"e": 35062,
"s": 34973,
"text": "Note: The above programs might not run in an online IDE. Please use an offline compiler."
},
{
"code": null,
"e": 35141,
"s": 35062,
"text": "Reference: https://docs.oracle.com/javase/8/javafx/api/javafx/scene/Group.html"
},
{
"code": null,
"e": 35148,
"s": 35141,
"text": "JavaFX"
},
{
"code": null,
"e": 35153,
"s": 35148,
"text": "Java"
},
{
"code": null,
"e": 35158,
"s": 35153,
"text": "Java"
},
{
"code": null,
"e": 35256,
"s": 35158,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 35265,
"s": 35256,
"text": "Comments"
},
{
"code": null,
"e": 35278,
"s": 35265,
"text": "Old Comments"
},
{
"code": null,
"e": 35310,
"s": 35278,
"text": "Initialize an ArrayList in Java"
},
{
"code": null,
"e": 35340,
"s": 35310,
"text": "HashMap in Java with Examples"
},
{
"code": null,
"e": 35359,
"s": 35340,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 35410,
"s": 35359,
"text": "Object Oriented Programming (OOPs) Concept in Java"
},
{
"code": null,
"e": 35441,
"s": 35410,
"text": "How to iterate any Map in Java"
},
{
"code": null,
"e": 35473,
"s": 35441,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 35493,
"s": 35473,
"text": "Stack Class in Java"
},
{
"code": null,
"e": 35505,
"s": 35493,
"text": "Set in Java"
},
{
"code": null,
"e": 35529,
"s": 35505,
"text": "Singleton Class in Java"
}
] |
A Simple Approach To Templated SQL Queries In Python | by Sergei Izrailev | Towards Data Science
|
There are numerous situations in which one would want to insert parameters in a SQL query, and there are many ways to implement templated SQL queries in python. Without going into comparing different approaches, this post explains a simple and effective method for parameterizing SQL using JinjaSql. Besides many powerful features of Jinja2, such as conditional statements and loops, JinjaSql offers a clean and straightforward way to parameterize not only the values substituted into the where and in clauses, but also SQL statements themselves, including parameterizing table and column names and composing queries by combining whole code blocks.
Let’s assume we have a table transactions holding records about financial transactions. The columns in this table could be transaction_id, user_id, transaction_date, and amount. To compute the number of transactions and the total amount for a given user on a given day, a query directly to the database may look something like
select user_id , count(*) as num_transactions , sum(amount) as total_amountfrom transactionswhere user_id = 1234 and transaction_date = '2019-03-02'group by user_id
Here, we assume that the database will automatically convert the YYYY-MM-DD format of the string representation of the date into a proper date type.
If we want to run the query above for an arbitrary user and date, we need to parameterize the user_id and the transaction_date values. In JinjaSql, the corresponding template would simply become
select user_id , count(*) as num_transactions , sum(amount) as total_amountfrom transactionswhere user_id = {{ uid }} and transaction_date = {{ tdate }}group by user_id
Here, the values were replaced by placeholders with python variable names enclosed in double curly braces {{ }}. Note that the variable names uid and tdate were picked only to demonstrate that they are variable names and don't have anything to do with the column names themselves. A more readable version of the same template stored in a python variable is
user_transaction_template = '''select user_id , count(*) as num_transactions , sum(amount) as total_amountfrom transactionswhere user_id = {{ user_id }} and transaction_date = {{ transaction_date }}group by user_id'''
Next, we need to set the parameters for the query.
params = { 'user_id': 1234, 'transaction_date': '2019-03-02',}
Now, generating a SQL query from this template is straightforward.
from jinjasql import JinjaSqlj = JinjaSql(param_style='pyformat')query, bind_params = j.prepare_query(user_transaction_template, params)
If we print query and bind_params, we find that the former is a parameterized string, and the latter is an OrderedDict of parameters:
>>> print(query)select user_id , count(*) as num_transactions , sum(amount) as total_amountfrom transactionswhere user_id = %(user_id)s and transaction_date = %(transaction_date)sgroup by user_id>>> print(bind_params)OrderedDict([('user_id', 1234), ('transaction_date', '2018-03-01')])
Many database connections have an option to pass bind_params as an argument to the method executing the SQL query on a connection. For a data scientist, it may be natural to get results of the query in a Pandas data frame. Once we have a connection conn, it is as easy as running read_sql:
import pandas as pdfrm = pd.read_sql(query, conn, params=bind_params)
See the JinjaSql docs for other examples.
It is often desired to fully expand the query with all parameters before running it. For example, logging the full query is invaluable for debugging batch processes because one can copy-paste the query from the logs directly into an interactive SQL interface. It is tempting to substitute bind_params into the query using python built-in string substitution. However, we quickly find that string parameters need to be quoted to result in proper SQL. For example, in the template above, the date value must be enclosed in single quotes.
>>> print(query % bind_params)select user_id , count(*) as num_transactions , sum(amount) as total_amountfrom transactionswhere user_id = 1234 and transaction_date = 2018-03-01group by user_id
To deal with this, we need a helper function to correctly quote parameters that are strings. We detect whether a parameter is a string, by calling
from six import string_typesisinstance(value, string_types)
This works for both python 3 and 2.7. The string parameters are converted to the str type, single quotes in the names are escaped by another single quote, and finally, the whole value is enclosed in single quotes.
from six import string_typesdef quote_sql_string(value): ''' If `value` is a string type, escapes single quotes in the string and returns the string enclosed in single quotes. ''' if isinstance(value, string_types): new_value = str(value) new_value = new_value.replace("'", "''") return "'{}'".format(new_value) return value
Finally, to convert the template to proper SQL, we loop over bind_params, quote the strings, and then perform string substitution.
from copy import deepcopydef get_sql_from_template(query, bind_params): if not bind_params: return query params = deepcopy(bind_params) for key, val in params.items(): params[key] = quote_sql_string(val) return query % params
Now we can easily get the final query that we can log or run interactively:
>>> print(get_sql_from_template(query, bind_params))select user_id , count(*) as num_transactions , sum(amount) as total_amountfrom transactionswhere user_id = 1234 and transaction_date = '2018-03-01'group by user_id
Putting it all together, another helper function wraps the JinjaSql calls and simply takes the template and a dict of parameters, and returns the full SQL.
from jinjasql import JinjaSqldef apply_sql_template(template, parameters): ''' Apply a JinjaSql template (string) substituting parameters (dict) and return the final SQL. ''' j = JinjaSql(param_style='pyformat') query, bind_params = j.prepare_query(template, parameters) return get_sql_from_template(query, bind_params)
Computing statistics on the values stored in a particular database column is handy both when first exploring the data and for data validation in production. Since we only want to demonstrate some features of the templates, for simplicity, let’s just work with integer columns, such as the column user_id in the table transactions above. For integer columns, we are interested in the number of unique values, min and max values, and the number of nulls. Some columns may have a default of say, -1, the drawbacks of which are beyond the scope of this post, however, we do want to capture that by reporting the number of default values.
Consider the following template and function. The function takes the table name, the column name and the default value as arguments, and returns the SQL for computing the statistics.
COLUMN_STATS_TEMPLATE = '''select {{ column_name | sqlsafe }} as column_name , count(*) as num_rows , count(distinct {{ column_name | sqlsafe }}) as num_unique , sum(case when {{ column_name | sqlsafe }} is null then 1 else 0 end) as num_nulls {% if default_value %} , sum(case when {{ column_name | sqlsafe }} = {{ default_value }} then 1 else 0 end) as num_default {% else %} , 0 as num_default {% endif %} , min({{ column_name | sqlsafe }}) as min_value , max({{ column_name | sqlsafe }}) as max_valuefrom {{ table_name | sqlsafe }}'''def get_column_stats_sql(table_name, column_name, default_value): ''' Returns the SQL for computing column statistics. Passing None for the default_value results in zero output for the number of default values. ''' params = { 'table_name': table_name, 'column_name': column_name, 'default_value': default_value, } return apply_sql_template(COLUMN_STATS_TEMPLATE, params)
This function is straightforward and very powerful because it applies to any column in any table. Note the {% if default_value %} syntax in the template. If the default value that is passed to the function is None, the SQL returns zero in the num_default field.
The function and template above will also work with strings, dates, and other data types if the default_value is set to None. However, to handle different data types more intelligently, it is necessary to extend the function to also take the data type as an argument and build the logic specific to different data types. For example, one might want to know the min and max of the string length instead of the min and max of the value itself.
Let’s look at the output for the transactions.user_id column.
>>> print(get_column_stats_sql('transactions', 'user_id', None))select user_id as column_name , count(*) as num_rows , count(distinct user_id) as num_unique , sum(case when user_id is null then 1 else 0 end) as num_nulls , 0 as num_default , min(user_id) as min_value , max(user_id) as max_valuefrom transactions
Note that blank lines appear in place of the {% %} clauses and could be removed.
With the helper functions above, creating and running templated SQL queries in python is very easy. Because the details of parameter substitution are hidden, one can focus on building the template and the set of parameters and then call a single function to get the final SQL.
One important caveat is the risk of code injection. For batch processes, it should not be an issue, but using the sqlsafe construct in web applications could be dangerous. The sqlsafe keyword indicates that the user (you) is confident that no code injection is possible and takes responsibility for simply putting whatever string is passed in the parameters directly into the query.
On the other hand, the ability to put an arbitrary string in the query allows one to pass whole code blocks into a template. For example, instead of passing table_name='transactions' above, one could pass '(select * from transactions where transaction_date = 2018-03-01) t', and the query would still work.
To explore even more powerful features of SQL templates, also see a tutorial on Advanced SQL Templates In Python with JinjaSql.
The code in this post is licensed under the MIT License. This post first appeared on the Life Around Data blog.
Photo and image by Sergei Izrailev
|
[
{
"code": null,
"e": 820,
"s": 171,
"text": "There are numerous situations in which one would want to insert parameters in a SQL query, and there are many ways to implement templated SQL queries in python. Without going into comparing different approaches, this post explains a simple and effective method for parameterizing SQL using JinjaSql. Besides many powerful features of Jinja2, such as conditional statements and loops, JinjaSql offers a clean and straightforward way to parameterize not only the values substituted into the where and in clauses, but also SQL statements themselves, including parameterizing table and column names and composing queries by combining whole code blocks."
},
{
"code": null,
"e": 1147,
"s": 820,
"text": "Let’s assume we have a table transactions holding records about financial transactions. The columns in this table could be transaction_id, user_id, transaction_date, and amount. To compute the number of transactions and the total amount for a given user on a given day, a query directly to the database may look something like"
},
{
"code": null,
"e": 1333,
"s": 1147,
"text": "select user_id , count(*) as num_transactions , sum(amount) as total_amountfrom transactionswhere user_id = 1234 and transaction_date = '2019-03-02'group by user_id"
},
{
"code": null,
"e": 1482,
"s": 1333,
"text": "Here, we assume that the database will automatically convert the YYYY-MM-DD format of the string representation of the date into a proper date type."
},
{
"code": null,
"e": 1677,
"s": 1482,
"text": "If we want to run the query above for an arbitrary user and date, we need to parameterize the user_id and the transaction_date values. In JinjaSql, the corresponding template would simply become"
},
{
"code": null,
"e": 1867,
"s": 1677,
"text": "select user_id , count(*) as num_transactions , sum(amount) as total_amountfrom transactionswhere user_id = {{ uid }} and transaction_date = {{ tdate }}group by user_id"
},
{
"code": null,
"e": 2224,
"s": 1867,
"text": "Here, the values were replaced by placeholders with python variable names enclosed in double curly braces {{ }}. Note that the variable names uid and tdate were picked only to demonstrate that they are variable names and don't have anything to do with the column names themselves. A more readable version of the same template stored in a python variable is"
},
{
"code": null,
"e": 2463,
"s": 2224,
"text": "user_transaction_template = '''select user_id , count(*) as num_transactions , sum(amount) as total_amountfrom transactionswhere user_id = {{ user_id }} and transaction_date = {{ transaction_date }}group by user_id'''"
},
{
"code": null,
"e": 2514,
"s": 2463,
"text": "Next, we need to set the parameters for the query."
},
{
"code": null,
"e": 2583,
"s": 2514,
"text": "params = { 'user_id': 1234, 'transaction_date': '2019-03-02',}"
},
{
"code": null,
"e": 2650,
"s": 2583,
"text": "Now, generating a SQL query from this template is straightforward."
},
{
"code": null,
"e": 2787,
"s": 2650,
"text": "from jinjasql import JinjaSqlj = JinjaSql(param_style='pyformat')query, bind_params = j.prepare_query(user_transaction_template, params)"
},
{
"code": null,
"e": 2921,
"s": 2787,
"text": "If we print query and bind_params, we find that the former is a parameterized string, and the latter is an OrderedDict of parameters:"
},
{
"code": null,
"e": 3228,
"s": 2921,
"text": ">>> print(query)select user_id , count(*) as num_transactions , sum(amount) as total_amountfrom transactionswhere user_id = %(user_id)s and transaction_date = %(transaction_date)sgroup by user_id>>> print(bind_params)OrderedDict([('user_id', 1234), ('transaction_date', '2018-03-01')])"
},
{
"code": null,
"e": 3518,
"s": 3228,
"text": "Many database connections have an option to pass bind_params as an argument to the method executing the SQL query on a connection. For a data scientist, it may be natural to get results of the query in a Pandas data frame. Once we have a connection conn, it is as easy as running read_sql:"
},
{
"code": null,
"e": 3588,
"s": 3518,
"text": "import pandas as pdfrm = pd.read_sql(query, conn, params=bind_params)"
},
{
"code": null,
"e": 3630,
"s": 3588,
"text": "See the JinjaSql docs for other examples."
},
{
"code": null,
"e": 4166,
"s": 3630,
"text": "It is often desired to fully expand the query with all parameters before running it. For example, logging the full query is invaluable for debugging batch processes because one can copy-paste the query from the logs directly into an interactive SQL interface. It is tempting to substitute bind_params into the query using python built-in string substitution. However, we quickly find that string parameters need to be quoted to result in proper SQL. For example, in the template above, the date value must be enclosed in single quotes."
},
{
"code": null,
"e": 4381,
"s": 4166,
"text": ">>> print(query % bind_params)select user_id , count(*) as num_transactions , sum(amount) as total_amountfrom transactionswhere user_id = 1234 and transaction_date = 2018-03-01group by user_id"
},
{
"code": null,
"e": 4528,
"s": 4381,
"text": "To deal with this, we need a helper function to correctly quote parameters that are strings. We detect whether a parameter is a string, by calling"
},
{
"code": null,
"e": 4588,
"s": 4528,
"text": "from six import string_typesisinstance(value, string_types)"
},
{
"code": null,
"e": 4802,
"s": 4588,
"text": "This works for both python 3 and 2.7. The string parameters are converted to the str type, single quotes in the names are escaped by another single quote, and finally, the whole value is enclosed in single quotes."
},
{
"code": null,
"e": 5166,
"s": 4802,
"text": "from six import string_typesdef quote_sql_string(value): ''' If `value` is a string type, escapes single quotes in the string and returns the string enclosed in single quotes. ''' if isinstance(value, string_types): new_value = str(value) new_value = new_value.replace(\"'\", \"''\") return \"'{}'\".format(new_value) return value"
},
{
"code": null,
"e": 5297,
"s": 5166,
"text": "Finally, to convert the template to proper SQL, we loop over bind_params, quote the strings, and then perform string substitution."
},
{
"code": null,
"e": 5549,
"s": 5297,
"text": "from copy import deepcopydef get_sql_from_template(query, bind_params): if not bind_params: return query params = deepcopy(bind_params) for key, val in params.items(): params[key] = quote_sql_string(val) return query % params"
},
{
"code": null,
"e": 5625,
"s": 5549,
"text": "Now we can easily get the final query that we can log or run interactively:"
},
{
"code": null,
"e": 5863,
"s": 5625,
"text": ">>> print(get_sql_from_template(query, bind_params))select user_id , count(*) as num_transactions , sum(amount) as total_amountfrom transactionswhere user_id = 1234 and transaction_date = '2018-03-01'group by user_id"
},
{
"code": null,
"e": 6019,
"s": 5863,
"text": "Putting it all together, another helper function wraps the JinjaSql calls and simply takes the template and a dict of parameters, and returns the full SQL."
},
{
"code": null,
"e": 6361,
"s": 6019,
"text": "from jinjasql import JinjaSqldef apply_sql_template(template, parameters): ''' Apply a JinjaSql template (string) substituting parameters (dict) and return the final SQL. ''' j = JinjaSql(param_style='pyformat') query, bind_params = j.prepare_query(template, parameters) return get_sql_from_template(query, bind_params)"
},
{
"code": null,
"e": 6995,
"s": 6361,
"text": "Computing statistics on the values stored in a particular database column is handy both when first exploring the data and for data validation in production. Since we only want to demonstrate some features of the templates, for simplicity, let’s just work with integer columns, such as the column user_id in the table transactions above. For integer columns, we are interested in the number of unique values, min and max values, and the number of nulls. Some columns may have a default of say, -1, the drawbacks of which are beyond the scope of this post, however, we do want to capture that by reporting the number of default values."
},
{
"code": null,
"e": 7178,
"s": 6995,
"text": "Consider the following template and function. The function takes the table name, the column name and the default value as arguments, and returns the SQL for computing the statistics."
},
{
"code": null,
"e": 8170,
"s": 7178,
"text": "COLUMN_STATS_TEMPLATE = '''select {{ column_name | sqlsafe }} as column_name , count(*) as num_rows , count(distinct {{ column_name | sqlsafe }}) as num_unique , sum(case when {{ column_name | sqlsafe }} is null then 1 else 0 end) as num_nulls {% if default_value %} , sum(case when {{ column_name | sqlsafe }} = {{ default_value }} then 1 else 0 end) as num_default {% else %} , 0 as num_default {% endif %} , min({{ column_name | sqlsafe }}) as min_value , max({{ column_name | sqlsafe }}) as max_valuefrom {{ table_name | sqlsafe }}'''def get_column_stats_sql(table_name, column_name, default_value): ''' Returns the SQL for computing column statistics. Passing None for the default_value results in zero output for the number of default values. ''' params = { 'table_name': table_name, 'column_name': column_name, 'default_value': default_value, } return apply_sql_template(COLUMN_STATS_TEMPLATE, params)"
},
{
"code": null,
"e": 8432,
"s": 8170,
"text": "This function is straightforward and very powerful because it applies to any column in any table. Note the {% if default_value %} syntax in the template. If the default value that is passed to the function is None, the SQL returns zero in the num_default field."
},
{
"code": null,
"e": 8874,
"s": 8432,
"text": "The function and template above will also work with strings, dates, and other data types if the default_value is set to None. However, to handle different data types more intelligently, it is necessary to extend the function to also take the data type as an argument and build the logic specific to different data types. For example, one might want to know the min and max of the string length instead of the min and max of the value itself."
},
{
"code": null,
"e": 8936,
"s": 8874,
"text": "Let’s look at the output for the transactions.user_id column."
},
{
"code": null,
"e": 9273,
"s": 8936,
"text": ">>> print(get_column_stats_sql('transactions', 'user_id', None))select user_id as column_name , count(*) as num_rows , count(distinct user_id) as num_unique , sum(case when user_id is null then 1 else 0 end) as num_nulls , 0 as num_default , min(user_id) as min_value , max(user_id) as max_valuefrom transactions"
},
{
"code": null,
"e": 9354,
"s": 9273,
"text": "Note that blank lines appear in place of the {% %} clauses and could be removed."
},
{
"code": null,
"e": 9631,
"s": 9354,
"text": "With the helper functions above, creating and running templated SQL queries in python is very easy. Because the details of parameter substitution are hidden, one can focus on building the template and the set of parameters and then call a single function to get the final SQL."
},
{
"code": null,
"e": 10014,
"s": 9631,
"text": "One important caveat is the risk of code injection. For batch processes, it should not be an issue, but using the sqlsafe construct in web applications could be dangerous. The sqlsafe keyword indicates that the user (you) is confident that no code injection is possible and takes responsibility for simply putting whatever string is passed in the parameters directly into the query."
},
{
"code": null,
"e": 10321,
"s": 10014,
"text": "On the other hand, the ability to put an arbitrary string in the query allows one to pass whole code blocks into a template. For example, instead of passing table_name='transactions' above, one could pass '(select * from transactions where transaction_date = 2018-03-01) t', and the query would still work."
},
{
"code": null,
"e": 10449,
"s": 10321,
"text": "To explore even more powerful features of SQL templates, also see a tutorial on Advanced SQL Templates In Python with JinjaSql."
},
{
"code": null,
"e": 10561,
"s": 10449,
"text": "The code in this post is licensed under the MIT License. This post first appeared on the Life Around Data blog."
}
] |
How to copy a String into another String in C#
|
To copy a String into another String, the code is as follows −
Live Demo
using System;
public class Demo {
static public void Main(){
string str1 = "Kevin";
string str2 = String.Copy(str1);
Console.WriteLine("String1 = "+str1);
Console.WriteLine("String2 = "+str2);
}
}
This will produce the following output −
String1 = Kevin
String2 = Kevin
Let us now see another example −
Live Demo
using System;
public class Demo {
static public void Main(){
string str1 = "Maisie";
string str2 = "Ryan";
Console.WriteLine("String1 (Before copying) = "+str1);
Console.WriteLine("String2 (Before copying) = "+str2);
str2 = String.Copy(str1);
Console.WriteLine("String1 = "+str1);
Console.WriteLine("String2 (Updated) = "+str2);
}
}
This will produce the following output −
String1 (Before copying) = Maisie String2 (Before copying) = Ryan
String1 = Maisie
String2 (Updated) = Maisie
|
[
{
"code": null,
"e": 1125,
"s": 1062,
"text": "To copy a String into another String, the code is as follows −"
},
{
"code": null,
"e": 1136,
"s": 1125,
"text": " Live Demo"
},
{
"code": null,
"e": 1363,
"s": 1136,
"text": "using System;\npublic class Demo {\n static public void Main(){\n string str1 = \"Kevin\";\n string str2 = String.Copy(str1);\n Console.WriteLine(\"String1 = \"+str1);\n Console.WriteLine(\"String2 = \"+str2);\n }\n}"
},
{
"code": null,
"e": 1404,
"s": 1363,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 1436,
"s": 1404,
"text": "String1 = Kevin\nString2 = Kevin"
},
{
"code": null,
"e": 1469,
"s": 1436,
"text": "Let us now see another example −"
},
{
"code": null,
"e": 1480,
"s": 1469,
"text": " Live Demo"
},
{
"code": null,
"e": 1861,
"s": 1480,
"text": "using System;\npublic class Demo {\n static public void Main(){\n string str1 = \"Maisie\";\n string str2 = \"Ryan\";\n Console.WriteLine(\"String1 (Before copying) = \"+str1);\n Console.WriteLine(\"String2 (Before copying) = \"+str2);\n str2 = String.Copy(str1);\n Console.WriteLine(\"String1 = \"+str1);\n Console.WriteLine(\"String2 (Updated) = \"+str2);\n }\n}"
},
{
"code": null,
"e": 1902,
"s": 1861,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2012,
"s": 1902,
"text": "String1 (Before copying) = Maisie String2 (Before copying) = Ryan\nString1 = Maisie\nString2 (Updated) = Maisie"
}
] |
GATE | GATE-CS-2006 | Question 59 - GeeksforGeeks
|
15 Sep, 2021
Consider the following translation scheme.S → ERR → *E{print(“*”);}R | εE → F + E {print(“+”);} | FF → (S) | id {print(id.value);}Here id is a token that represents an integer and id.value represents the corresponding integer value. For an input ‘2 * 3 + 4’, this translation scheme prints(A) 2 * 3 + 4(B) 2 * +3 4(C) 2 3 * 4 +(D) 2 3 4+*Answer: (D)Explanation: Background Required to solve the question – Syntax Directed Translation andParse Tree Construction.
Explanation : We are given L-Attributed Syntax Directed Translation as
semantic actions like printf statements are inserted anywhere on the
RHS of production (R → *E{print(“*”);}R). After constructing the parse tree
as shown below from the given grammar, we will follow depth first order left
to right evaluation in order to generate the final output.
Parse Tree:
Just follow the arrows in the picture (This is actually Depth first
left to right evaluation ) and the moment we take exit from any child
which is printf statement in this question, we print that symbol which
can be a integer value or ‘*’ or ‘+’.
Evaluation :
This explanation has been contributed by Pranjul Ahuja.
YouTubeGeeksforGeeks GATE Computer Science16.1K subscribersPYQ - Parsing and SDT (Continued) Part 4 with Joyojyoti Acharya | GeeksforGeeks GATEWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:0050:18 / 58:40•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=LdMTs93sekg" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>Quiz of this Question
GATE-CS-2006
GATE-GATE-CS-2006
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-2015 (Set 3) | Question 65
GATE | GATE-CS-2016 (Set 2) | Question 48
GATE | GATE-CS-2014-(Set-3) | Question 38
GATE | GATE CS 2018 | Question 37
GATE | GATE-CS-2016 (Set 1) | Question 65
GATE | GATE-IT-2004 | Question 83
GATE | GATE-CS-2016 (Set 1) | Question 63
GATE | GATE-CS-2014-(Set-2) | Question 65
|
[
{
"code": null,
"e": 24456,
"s": 24428,
"text": "\n15 Sep, 2021"
},
{
"code": null,
"e": 24918,
"s": 24456,
"text": "Consider the following translation scheme.S → ERR → *E{print(“*”);}R | εE → F + E {print(“+”);} | FF → (S) | id {print(id.value);}Here id is a token that represents an integer and id.value represents the corresponding integer value. For an input ‘2 * 3 + 4’, this translation scheme prints(A) 2 * 3 + 4(B) 2 * +3 4(C) 2 3 * 4 +(D) 2 3 4+*Answer: (D)Explanation: Background Required to solve the question – Syntax Directed Translation andParse Tree Construction."
},
{
"code": null,
"e": 25274,
"s": 24918,
"text": "Explanation : We are given L-Attributed Syntax Directed Translation as\nsemantic actions like printf statements are inserted anywhere on the \nRHS of production (R → *E{print(“*”);}R). After constructing the parse tree \nas shown below from the given grammar, we will follow depth first order left \nto right evaluation in order to generate the final output.\n"
},
{
"code": null,
"e": 25286,
"s": 25274,
"text": "Parse Tree:"
},
{
"code": null,
"e": 25537,
"s": 25286,
"text": "Just follow the arrows in the picture (This is actually Depth first \nleft to right evaluation ) and the moment we take exit from any child \nwhich is printf statement in this question, we print that symbol which \ncan be a integer value or ‘*’ or ‘+’.\n"
},
{
"code": null,
"e": 25550,
"s": 25537,
"text": "Evaluation :"
},
{
"code": null,
"e": 25606,
"s": 25550,
"text": "This explanation has been contributed by Pranjul Ahuja."
},
{
"code": null,
"e": 26519,
"s": 25606,
"text": "YouTubeGeeksforGeeks GATE Computer Science16.1K subscribersPYQ - Parsing and SDT (Continued) Part 4 with Joyojyoti Acharya | GeeksforGeeks GATEWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:0050:18 / 58:40•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=LdMTs93sekg\" target=\"_blank\">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>Quiz of this Question"
},
{
"code": null,
"e": 26532,
"s": 26519,
"text": "GATE-CS-2006"
},
{
"code": null,
"e": 26550,
"s": 26532,
"text": "GATE-GATE-CS-2006"
},
{
"code": null,
"e": 26555,
"s": 26550,
"text": "GATE"
},
{
"code": null,
"e": 26653,
"s": 26555,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26662,
"s": 26653,
"text": "Comments"
},
{
"code": null,
"e": 26675,
"s": 26662,
"text": "Old Comments"
},
{
"code": null,
"e": 26709,
"s": 26675,
"text": "GATE | GATE-IT-2004 | Question 71"
},
{
"code": null,
"e": 26742,
"s": 26709,
"text": "GATE | GATE CS 2011 | Question 7"
},
{
"code": null,
"e": 26784,
"s": 26742,
"text": "GATE | GATE-CS-2015 (Set 3) | Question 65"
},
{
"code": null,
"e": 26826,
"s": 26784,
"text": "GATE | GATE-CS-2016 (Set 2) | Question 48"
},
{
"code": null,
"e": 26868,
"s": 26826,
"text": "GATE | GATE-CS-2014-(Set-3) | Question 38"
},
{
"code": null,
"e": 26902,
"s": 26868,
"text": "GATE | GATE CS 2018 | Question 37"
},
{
"code": null,
"e": 26944,
"s": 26902,
"text": "GATE | GATE-CS-2016 (Set 1) | Question 65"
},
{
"code": null,
"e": 26978,
"s": 26944,
"text": "GATE | GATE-IT-2004 | Question 83"
},
{
"code": null,
"e": 27020,
"s": 26978,
"text": "GATE | GATE-CS-2016 (Set 1) | Question 63"
}
] |
nested if statement in java
|
It is always legal to nest if-else statements which means you can use one if or else if statement inside another if or else if statement.
The syntax for a nested if...else is as follows −
if(Boolean_expression 1) {
// Executes when the Boolean expression 1 is true
if(Boolean_expression 2) {
// Executes when the Boolean expression 2 is true
}
}
You can nest else if...else in the similar way as we have nested if statement.
public class Test {
public static void main(String args[]) {
int x = 30;
int y = 10;
if( x == 30 ) {
if( y == 10 ) {
System.out.print("X = 30 and Y = 10");
}
}
}
}
This will produce the following result −
X = 30 and Y = 10
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
|
[
{
"code": null,
"e": 2515,
"s": 2377,
"text": "It is always legal to nest if-else statements which means you can use one if or else if statement inside another if or else if statement."
},
{
"code": null,
"e": 2565,
"s": 2515,
"text": "The syntax for a nested if...else is as follows −"
},
{
"code": null,
"e": 2739,
"s": 2565,
"text": "if(Boolean_expression 1) {\n // Executes when the Boolean expression 1 is true\n if(Boolean_expression 2) {\n // Executes when the Boolean expression 2 is true\n }\n}\n"
},
{
"code": null,
"e": 2818,
"s": 2739,
"text": "You can nest else if...else in the similar way as we have nested if statement."
},
{
"code": null,
"e": 3044,
"s": 2818,
"text": "public class Test {\n\n public static void main(String args[]) {\n int x = 30;\n int y = 10;\n\n if( x == 30 ) {\n if( y == 10 ) {\n System.out.print(\"X = 30 and Y = 10\");\n }\n }\n }\n}"
},
{
"code": null,
"e": 3085,
"s": 3044,
"text": "This will produce the following result −"
},
{
"code": null,
"e": 3104,
"s": 3085,
"text": "X = 30 and Y = 10\n"
},
{
"code": null,
"e": 3137,
"s": 3104,
"text": "\n 16 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 3153,
"s": 3137,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 3186,
"s": 3153,
"text": "\n 19 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 3202,
"s": 3186,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 3237,
"s": 3202,
"text": "\n 25 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 3251,
"s": 3237,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 3285,
"s": 3251,
"text": "\n 126 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 3299,
"s": 3285,
"text": " Tushar Kale"
},
{
"code": null,
"e": 3336,
"s": 3299,
"text": "\n 119 Lectures \n 17.5 hours \n"
},
{
"code": null,
"e": 3351,
"s": 3336,
"text": " Monica Mittal"
},
{
"code": null,
"e": 3384,
"s": 3351,
"text": "\n 76 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 3403,
"s": 3384,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 3410,
"s": 3403,
"text": " Print"
},
{
"code": null,
"e": 3421,
"s": 3410,
"text": " Add Notes"
}
] |
D3.js selection.text() Function - GeeksforGeeks
|
23 Aug, 2020
The selection.text() function in d3.js is used to set the text content to the specified value of the selected elements thus, it replaces any existing child elements. If the value that is given is constant than all elements will be given that constant value.
Syntax:
selection.text([value]);
Parameters: This function takes only one parameter which is given above and described below:
value: Text content value to set.
Return Values: This function does not return any value.
Example 1:
HTML
<!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" path1tent= "width=device-width,initial-scale=1.0"> <script src="https://d3js.org/d3.v4.min.js"> </script></head> <body> <h1 style="color: green">GeeksforGeeks</h1> <div> <button>Click me</button> </div> <script> function func() { // Sets the text-content of the button var chk = d3.select("button") .text("This is the changed text"); var text = document.querySelector("button"); } let btn = document.querySelector("button"); btn.addEventListener("click", func); </script></body> </html>
Output:
Before clicking the button:
Before clicking the button:
After clicking the button:
After clicking the button:
Example 2:
HTML
<!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" path1tent= "width=device-width, initial-scale=1.0"> <script src="https://d3js.org/d3.v4.min.js"> </script></head> <body> <h1 style="color: green;">GeeksforGeeks</h1> <div style="background-color: green; width: fit-content; padding: 10px; margin-top: 5px;" class="btn"> This text will be changed </div> <div style="background-color: green; width: fit-content; padding: 10px; margin-top: 5px;" class="btn"> This text will be changed </div><br> <br> <button class="Clickme">Change text</button> <script> function func() { // Selecting all buttons and // Setting the text content of the button var chk = d3.selectAll(".btn") .text("This text is changed"); var text = document.querySelector("button"); } let btn = document.querySelector(".Clickme"); btn.addEventListener("click", func); </script></body> </html>
Output:
Before clicking the button:
Before clicking the button:
After clicking the button:
After clicking the button:
D3.js
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Convert a string to an integer in JavaScript
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
How to append HTML code to a div using JavaScript ?
How to Open URL in New Tab using JavaScript ?
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
|
[
{
"code": null,
"e": 24306,
"s": 24278,
"text": "\n23 Aug, 2020"
},
{
"code": null,
"e": 24564,
"s": 24306,
"text": "The selection.text() function in d3.js is used to set the text content to the specified value of the selected elements thus, it replaces any existing child elements. If the value that is given is constant than all elements will be given that constant value."
},
{
"code": null,
"e": 24572,
"s": 24564,
"text": "Syntax:"
},
{
"code": null,
"e": 24598,
"s": 24572,
"text": "selection.text([value]);\n"
},
{
"code": null,
"e": 24691,
"s": 24598,
"text": "Parameters: This function takes only one parameter which is given above and described below:"
},
{
"code": null,
"e": 24725,
"s": 24691,
"text": "value: Text content value to set."
},
{
"code": null,
"e": 24781,
"s": 24725,
"text": "Return Values: This function does not return any value."
},
{
"code": null,
"e": 24792,
"s": 24781,
"text": "Example 1:"
},
{
"code": null,
"e": 24797,
"s": 24792,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\"> <meta name=\"viewport\" path1tent= \"width=device-width,initial-scale=1.0\"> <script src=\"https://d3js.org/d3.v4.min.js\"> </script></head> <body> <h1 style=\"color: green\">GeeksforGeeks</h1> <div> <button>Click me</button> </div> <script> function func() { // Sets the text-content of the button var chk = d3.select(\"button\") .text(\"This is the changed text\"); var text = document.querySelector(\"button\"); } let btn = document.querySelector(\"button\"); btn.addEventListener(\"click\", func); </script></body> </html>",
"e": 25514,
"s": 24797,
"text": null
},
{
"code": null,
"e": 25522,
"s": 25514,
"text": "Output:"
},
{
"code": null,
"e": 25550,
"s": 25522,
"text": "Before clicking the button:"
},
{
"code": null,
"e": 25578,
"s": 25550,
"text": "Before clicking the button:"
},
{
"code": null,
"e": 25605,
"s": 25578,
"text": "After clicking the button:"
},
{
"code": null,
"e": 25632,
"s": 25605,
"text": "After clicking the button:"
},
{
"code": null,
"e": 25643,
"s": 25632,
"text": "Example 2:"
},
{
"code": null,
"e": 25648,
"s": 25643,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\"> <meta name=\"viewport\" path1tent= \"width=device-width, initial-scale=1.0\"> <script src=\"https://d3js.org/d3.v4.min.js\"> </script></head> <body> <h1 style=\"color: green;\">GeeksforGeeks</h1> <div style=\"background-color: green; width: fit-content; padding: 10px; margin-top: 5px;\" class=\"btn\"> This text will be changed </div> <div style=\"background-color: green; width: fit-content; padding: 10px; margin-top: 5px;\" class=\"btn\"> This text will be changed </div><br> <br> <button class=\"Clickme\">Change text</button> <script> function func() { // Selecting all buttons and // Setting the text content of the button var chk = d3.selectAll(\".btn\") .text(\"This text is changed\"); var text = document.querySelector(\"button\"); } let btn = document.querySelector(\".Clickme\"); btn.addEventListener(\"click\", func); </script></body> </html>",
"e": 26807,
"s": 25648,
"text": null
},
{
"code": null,
"e": 26816,
"s": 26807,
"text": "Output: "
},
{
"code": null,
"e": 26844,
"s": 26816,
"text": "Before clicking the button:"
},
{
"code": null,
"e": 26872,
"s": 26844,
"text": "Before clicking the button:"
},
{
"code": null,
"e": 26899,
"s": 26872,
"text": "After clicking the button:"
},
{
"code": null,
"e": 26926,
"s": 26899,
"text": "After clicking the button:"
},
{
"code": null,
"e": 26932,
"s": 26926,
"text": "D3.js"
},
{
"code": null,
"e": 26943,
"s": 26932,
"text": "JavaScript"
},
{
"code": null,
"e": 26960,
"s": 26943,
"text": "Web Technologies"
},
{
"code": null,
"e": 27058,
"s": 26960,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27067,
"s": 27058,
"text": "Comments"
},
{
"code": null,
"e": 27080,
"s": 27067,
"text": "Old Comments"
},
{
"code": null,
"e": 27125,
"s": 27080,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 27186,
"s": 27125,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 27258,
"s": 27186,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 27310,
"s": 27258,
"text": "How to append HTML code to a div using JavaScript ?"
},
{
"code": null,
"e": 27356,
"s": 27310,
"text": "How to Open URL in New Tab using JavaScript ?"
},
{
"code": null,
"e": 27398,
"s": 27356,
"text": "Roadmap to Become a Web Developer in 2022"
},
{
"code": null,
"e": 27431,
"s": 27398,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 27474,
"s": 27431,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 27536,
"s": 27474,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
}
] |
SWING - JWindow Class
|
The class JWindow is a container that can be displayed but does not have the title bar or window-management buttons.
Following is the declaration for javax.swing.JWindow class −
public class JWindow
extends Window
implements Accessible, RootPaneContainer
Following are the fields for java.awt.Component class −
protected AccessibleContext accessibleContext − The accessible context property.
protected AccessibleContext accessibleContext − The accessible context property.
protected JRootPane rootPane − The JRootPane instance that manages the contentPane and optional menuBar for this frame, as well as the glassPane.
protected JRootPane rootPane − The JRootPane instance that manages the contentPane and optional menuBar for this frame, as well as the glassPane.
protected boolean rootPaneCheckingEnabled − If true then calls to add and setLayout will be forwarded to the contentPane.
protected boolean rootPaneCheckingEnabled − If true then calls to add and setLayout will be forwarded to the contentPane.
JWindow()
Creates a window with no specified owner.
JWindow(Frame owner)
Creates a window with the specified owner frame.
JWindow(GraphicsConfiguration gc)
Creates a window with the specified GraphicsConfiguration of a screen device.
JWindow(Window owner)
Creates a window with the specified owner window.
JWindow(Window owner, GraphicsConfiguration gc)
Creates a window with the specified owner window and GraphicsConfiguration of a screen device.
protected void addImpl(Component comp, Object constraints, int index)
Adds the specified child Component.
protected JRootPane createRootPane()
Called by the constructor methods to create the default rootPane.
AccessibleContext getAccessibleContext()
Gets the AccessibleContext associated with this JWindow.
Container getContentPane()
Returns the Container which is the contentPane for this window.
Component getGlassPane()
Returns the glassPane Component for this window.
Graphics getGraphics()
Creates a graphics context for this component.
JLayeredPane getLayeredPane()
Returns the layeredPane object for this window.
JRootPane getRootPane()
Returns the rootPane object for this window.
TransferHandler getTransferHandler()
Gets the transferHandler property.
protected boolean isRootPaneCheckingEnabled()
Returns whether calls to add and setLayout are forwarded to the contentPane.
protected String paramString()
Returns a string representation of this JWindow.
void remove(Component comp)
Removes the specified component from the container.
void repaint(long time, int x, int y, int width, int height)
Repaints the specified rectangle of this component within time milliseconds.
void setContentPane(Container contentPane)
Sets the contentPane property for this window.
void setGlassPane(Component glassPane)
Sets the glassPane property.
void setLayeredPane(JLayeredPane layeredPane)
Sets the layeredPane property.
void setLayout(LayoutManager manager)
Sets the LayoutManager.
protected void setRootPane(JRootPane root)
Sets the new rootPane object for this window.
protected void setRootPaneCheckingEnabled(boolean enabled)
Sets whether calls to add and setLayout are forwarded to the contentPane.
void setTransferHandler(TransferHandler newHandler)
Sets the transferHandler property, which is a mechanism to support the transfer of data into this component.
void update(Graphics g)
Calls paint(g).
protected void windowInit()
Called by the constructors to init the JWindow properly.
This class inherits methods from the following classes −
java.awt.Window
java.awt.Container
java.awt.Component
java.lang.Object
Create the following Java program using any editor of your choice in say D:/ > SWING > com > tutorialspoint > gui >
SwingContainerDemo.java
package com.tutorialspoint.gui;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class SwingContainerDemo {
private JFrame mainFrame;
private JLabel headerLabel;
private JLabel statusLabel;
private JPanel controlPanel;
private JLabel msglabel;
public SwingContainerDemo(){
prepareGUI();
}
public static void main(String[] args){
SwingContainerDemo swingContainerDemo = new SwingContainerDemo();
swingContainerDemo.showJWindowDemo();
}
private void prepareGUI(){
mainFrame = new JFrame("Java Swing Examples");
mainFrame.setSize(400,400);
mainFrame.setLayout(new GridLayout(3, 1));
mainFrame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent windowEvent){
System.exit(0);
}
});
headerLabel = new JLabel("", JLabel.CENTER);
statusLabel = new JLabel("",JLabel.CENTER);
statusLabel.setSize(350,100);
msglabel = new JLabel("Welcome to TutorialsPoint SWING Tutorial.", JLabel.CENTER);
controlPanel = new JPanel();
controlPanel.setLayout(new FlowLayout());
mainFrame.add(headerLabel);
mainFrame.add(controlPanel);
mainFrame.add(statusLabel);
mainFrame.setVisible(true);
}
private void showJWindowDemo(){
headerLabel.setText("Container in action: JWindow");
final MessageWindow window = new MessageWindow(
mainFrame, "Welcome to TutorialsPoint SWING Tutorial.");
JButton okButton = new JButton("Open a Window");
okButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
window.setVisible(true);
statusLabel.setText("A Window shown to the user.");
}
});
controlPanel.add(okButton);
mainFrame.setVisible(true);
}
class MessageWindow extends JWindow{
private String message;
public MessageWindow(JFrame parent, String message) {
super(parent);
this.message = message;
setSize(300, 300);
setLocationRelativeTo(parent);
}
public void paint(Graphics g) {
super.paint(g);
g.drawRect(0,0,getSize().width - 1,getSize().height - 1);
g.drawString(message,50,150);
}
}
}
Compile the program using the command prompt. Go to D:/ > SWING and type the following command.
D:\SWING>javac com\tutorialspoint\gui\SwingContainerDemo.java
If no error occurs, it means the compilation is successful. Run the program using the following command.
D:\SWING>java com.tutorialspoint.gui.SwingContainerDemo
Verify the following output.
30 Lectures
3.5 hours
Pranjal Srivastava
13 Lectures
1 hours
Pranjal Srivastava
25 Lectures
4.5 hours
Emenwa Global, Ejike IfeanyiChukwu
14 Lectures
1.5 hours
Travis Rose
14 Lectures
1 hours
Travis Rose
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 1880,
"s": 1763,
"text": "The class JWindow is a container that can be displayed but does not have the title bar or window-management buttons."
},
{
"code": null,
"e": 1941,
"s": 1880,
"text": "Following is the declaration for javax.swing.JWindow class −"
},
{
"code": null,
"e": 2028,
"s": 1941,
"text": "public class JWindow\n extends Window\n implements Accessible, RootPaneContainer\n"
},
{
"code": null,
"e": 2084,
"s": 2028,
"text": "Following are the fields for java.awt.Component class −"
},
{
"code": null,
"e": 2165,
"s": 2084,
"text": "protected AccessibleContext accessibleContext − The accessible context property."
},
{
"code": null,
"e": 2246,
"s": 2165,
"text": "protected AccessibleContext accessibleContext − The accessible context property."
},
{
"code": null,
"e": 2392,
"s": 2246,
"text": "protected JRootPane rootPane − The JRootPane instance that manages the contentPane and optional menuBar for this frame, as well as the glassPane."
},
{
"code": null,
"e": 2538,
"s": 2392,
"text": "protected JRootPane rootPane − The JRootPane instance that manages the contentPane and optional menuBar for this frame, as well as the glassPane."
},
{
"code": null,
"e": 2660,
"s": 2538,
"text": "protected boolean rootPaneCheckingEnabled − If true then calls to add and setLayout will be forwarded to the contentPane."
},
{
"code": null,
"e": 2782,
"s": 2660,
"text": "protected boolean rootPaneCheckingEnabled − If true then calls to add and setLayout will be forwarded to the contentPane."
},
{
"code": null,
"e": 2792,
"s": 2782,
"text": "JWindow()"
},
{
"code": null,
"e": 2834,
"s": 2792,
"text": "Creates a window with no specified owner."
},
{
"code": null,
"e": 2855,
"s": 2834,
"text": "JWindow(Frame owner)"
},
{
"code": null,
"e": 2904,
"s": 2855,
"text": "Creates a window with the specified owner frame."
},
{
"code": null,
"e": 2938,
"s": 2904,
"text": "JWindow(GraphicsConfiguration gc)"
},
{
"code": null,
"e": 3016,
"s": 2938,
"text": "Creates a window with the specified GraphicsConfiguration of a screen device."
},
{
"code": null,
"e": 3038,
"s": 3016,
"text": "JWindow(Window owner)"
},
{
"code": null,
"e": 3088,
"s": 3038,
"text": "Creates a window with the specified owner window."
},
{
"code": null,
"e": 3136,
"s": 3088,
"text": "JWindow(Window owner, GraphicsConfiguration gc)"
},
{
"code": null,
"e": 3231,
"s": 3136,
"text": "Creates a window with the specified owner window and GraphicsConfiguration of a screen device."
},
{
"code": null,
"e": 3301,
"s": 3231,
"text": "protected void\taddImpl(Component comp, Object constraints, int index)"
},
{
"code": null,
"e": 3337,
"s": 3301,
"text": "Adds the specified child Component."
},
{
"code": null,
"e": 3374,
"s": 3337,
"text": "protected JRootPane createRootPane()"
},
{
"code": null,
"e": 3440,
"s": 3374,
"text": "Called by the constructor methods to create the default rootPane."
},
{
"code": null,
"e": 3481,
"s": 3440,
"text": "AccessibleContext getAccessibleContext()"
},
{
"code": null,
"e": 3538,
"s": 3481,
"text": "Gets the AccessibleContext associated with this JWindow."
},
{
"code": null,
"e": 3565,
"s": 3538,
"text": "Container getContentPane()"
},
{
"code": null,
"e": 3629,
"s": 3565,
"text": "Returns the Container which is the contentPane for this window."
},
{
"code": null,
"e": 3654,
"s": 3629,
"text": "Component getGlassPane()"
},
{
"code": null,
"e": 3703,
"s": 3654,
"text": "Returns the glassPane Component for this window."
},
{
"code": null,
"e": 3726,
"s": 3703,
"text": "Graphics getGraphics()"
},
{
"code": null,
"e": 3773,
"s": 3726,
"text": "Creates a graphics context for this component."
},
{
"code": null,
"e": 3803,
"s": 3773,
"text": "JLayeredPane getLayeredPane()"
},
{
"code": null,
"e": 3851,
"s": 3803,
"text": "Returns the layeredPane object for this window."
},
{
"code": null,
"e": 3875,
"s": 3851,
"text": "JRootPane getRootPane()"
},
{
"code": null,
"e": 3920,
"s": 3875,
"text": "Returns the rootPane object for this window."
},
{
"code": null,
"e": 3957,
"s": 3920,
"text": "TransferHandler getTransferHandler()"
},
{
"code": null,
"e": 3992,
"s": 3957,
"text": "Gets the transferHandler property."
},
{
"code": null,
"e": 4038,
"s": 3992,
"text": "protected boolean isRootPaneCheckingEnabled()"
},
{
"code": null,
"e": 4115,
"s": 4038,
"text": "Returns whether calls to add and setLayout are forwarded to the contentPane."
},
{
"code": null,
"e": 4146,
"s": 4115,
"text": "protected String\tparamString()"
},
{
"code": null,
"e": 4195,
"s": 4146,
"text": "Returns a string representation of this JWindow."
},
{
"code": null,
"e": 4223,
"s": 4195,
"text": "void remove(Component comp)"
},
{
"code": null,
"e": 4275,
"s": 4223,
"text": "Removes the specified component from the container."
},
{
"code": null,
"e": 4336,
"s": 4275,
"text": "void repaint(long time, int x, int y, int width, int height)"
},
{
"code": null,
"e": 4413,
"s": 4336,
"text": "Repaints the specified rectangle of this component within time milliseconds."
},
{
"code": null,
"e": 4456,
"s": 4413,
"text": "void setContentPane(Container contentPane)"
},
{
"code": null,
"e": 4503,
"s": 4456,
"text": "Sets the contentPane property for this window."
},
{
"code": null,
"e": 4542,
"s": 4503,
"text": "void setGlassPane(Component glassPane)"
},
{
"code": null,
"e": 4571,
"s": 4542,
"text": "Sets the glassPane property."
},
{
"code": null,
"e": 4617,
"s": 4571,
"text": "void setLayeredPane(JLayeredPane layeredPane)"
},
{
"code": null,
"e": 4648,
"s": 4617,
"text": "Sets the layeredPane property."
},
{
"code": null,
"e": 4686,
"s": 4648,
"text": "void setLayout(LayoutManager manager)"
},
{
"code": null,
"e": 4710,
"s": 4686,
"text": "Sets the LayoutManager."
},
{
"code": null,
"e": 4753,
"s": 4710,
"text": "protected void setRootPane(JRootPane root)"
},
{
"code": null,
"e": 4799,
"s": 4753,
"text": "Sets the new rootPane object for this window."
},
{
"code": null,
"e": 4858,
"s": 4799,
"text": "protected void setRootPaneCheckingEnabled(boolean enabled)"
},
{
"code": null,
"e": 4932,
"s": 4858,
"text": "Sets whether calls to add and setLayout are forwarded to the contentPane."
},
{
"code": null,
"e": 4984,
"s": 4932,
"text": "void setTransferHandler(TransferHandler newHandler)"
},
{
"code": null,
"e": 5093,
"s": 4984,
"text": "Sets the transferHandler property, which is a mechanism to support the transfer of data into this component."
},
{
"code": null,
"e": 5117,
"s": 5093,
"text": "void update(Graphics g)"
},
{
"code": null,
"e": 5133,
"s": 5117,
"text": "Calls paint(g)."
},
{
"code": null,
"e": 5161,
"s": 5133,
"text": "protected void windowInit()"
},
{
"code": null,
"e": 5218,
"s": 5161,
"text": "Called by the constructors to init the JWindow properly."
},
{
"code": null,
"e": 5275,
"s": 5218,
"text": "This class inherits methods from the following classes −"
},
{
"code": null,
"e": 5291,
"s": 5275,
"text": "java.awt.Window"
},
{
"code": null,
"e": 5310,
"s": 5291,
"text": "java.awt.Container"
},
{
"code": null,
"e": 5329,
"s": 5310,
"text": "java.awt.Component"
},
{
"code": null,
"e": 5346,
"s": 5329,
"text": "java.lang.Object"
},
{
"code": null,
"e": 5462,
"s": 5346,
"text": "Create the following Java program using any editor of your choice in say D:/ > SWING > com > tutorialspoint > gui >"
},
{
"code": null,
"e": 5486,
"s": 5462,
"text": "SwingContainerDemo.java"
},
{
"code": null,
"e": 7881,
"s": 5486,
"text": "package com.tutorialspoint.gui;\n\nimport java.awt.*;\nimport java.awt.event.*;\nimport javax.swing.*;\n\npublic class SwingContainerDemo {\n private JFrame mainFrame;\n private JLabel headerLabel;\n private JLabel statusLabel;\n private JPanel controlPanel;\n private JLabel msglabel;\n\n public SwingContainerDemo(){\n prepareGUI();\n }\n public static void main(String[] args){\n SwingContainerDemo swingContainerDemo = new SwingContainerDemo(); \n swingContainerDemo.showJWindowDemo();\n }\n private void prepareGUI(){\n mainFrame = new JFrame(\"Java Swing Examples\");\n mainFrame.setSize(400,400);\n mainFrame.setLayout(new GridLayout(3, 1));\n \n mainFrame.addWindowListener(new WindowAdapter() {\n public void windowClosing(WindowEvent windowEvent){\n System.exit(0);\n } \n }); \n headerLabel = new JLabel(\"\", JLabel.CENTER); \n statusLabel = new JLabel(\"\",JLabel.CENTER); \n statusLabel.setSize(350,100);\n\n msglabel = new JLabel(\"Welcome to TutorialsPoint SWING Tutorial.\", JLabel.CENTER);\n\n controlPanel = new JPanel();\n controlPanel.setLayout(new FlowLayout());\n\n mainFrame.add(headerLabel);\n mainFrame.add(controlPanel);\n mainFrame.add(statusLabel);\n mainFrame.setVisible(true); \n }\n private void showJWindowDemo(){\n headerLabel.setText(\"Container in action: JWindow\"); \n final MessageWindow window = new MessageWindow(\n mainFrame, \"Welcome to TutorialsPoint SWING Tutorial.\");\n\n JButton okButton = new JButton(\"Open a Window\");\n okButton.addActionListener(new ActionListener() {\n public void actionPerformed(ActionEvent e) {\n window.setVisible(true);\n statusLabel.setText(\"A Window shown to the user.\"); \n }\n });\n controlPanel.add(okButton);\n mainFrame.setVisible(true); \n }\n class MessageWindow extends JWindow{\n private String message; \n public MessageWindow(JFrame parent, String message) { \n super(parent); \n this.message = message; \n setSize(300, 300); \n setLocationRelativeTo(parent); \n }\n public void paint(Graphics g) { \n super.paint(g);\n g.drawRect(0,0,getSize().width - 1,getSize().height - 1); \n g.drawString(message,50,150); \n } \n }\n}"
},
{
"code": null,
"e": 7977,
"s": 7881,
"text": "Compile the program using the command prompt. Go to D:/ > SWING and type the following command."
},
{
"code": null,
"e": 8040,
"s": 7977,
"text": "D:\\SWING>javac com\\tutorialspoint\\gui\\SwingContainerDemo.java\n"
},
{
"code": null,
"e": 8145,
"s": 8040,
"text": "If no error occurs, it means the compilation is successful. Run the program using the following command."
},
{
"code": null,
"e": 8202,
"s": 8145,
"text": "D:\\SWING>java com.tutorialspoint.gui.SwingContainerDemo\n"
},
{
"code": null,
"e": 8231,
"s": 8202,
"text": "Verify the following output."
},
{
"code": null,
"e": 8266,
"s": 8231,
"text": "\n 30 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 8286,
"s": 8266,
"text": " Pranjal Srivastava"
},
{
"code": null,
"e": 8319,
"s": 8286,
"text": "\n 13 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 8339,
"s": 8319,
"text": " Pranjal Srivastava"
},
{
"code": null,
"e": 8374,
"s": 8339,
"text": "\n 25 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 8410,
"s": 8374,
"text": " Emenwa Global, Ejike IfeanyiChukwu"
},
{
"code": null,
"e": 8445,
"s": 8410,
"text": "\n 14 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 8458,
"s": 8445,
"text": " Travis Rose"
},
{
"code": null,
"e": 8491,
"s": 8458,
"text": "\n 14 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 8504,
"s": 8491,
"text": " Travis Rose"
},
{
"code": null,
"e": 8511,
"s": 8504,
"text": " Print"
},
{
"code": null,
"e": 8522,
"s": 8511,
"text": " Add Notes"
}
] |
Merge 3 Sorted Arrays - GeeksforGeeks
|
26 Apr, 2022
Given 3 arrays (A, B, C) which are sorted in ascending order, we are required to merge them together in ascending order and output the array D.
Examples:
Input : A = [1, 2, 3, 4, 5] B = [2, 3, 4] C = [4, 5, 6, 7]Output : D = [1, 2, 2, 3, 3, 4, 4, 4, 5, 5, 6, 7]
Input : A = [1, 2, 3, 5] B = [6, 7, 8, 9 ] C = [10, 11, 12]Output: D = [1, 2, 3, 5, 6, 7, 8, 9. 10, 11, 12]
Method 1 (Two Arrays at a time) We have discussed at Merging 2 Sorted arrays . So we can first merge two arrays and then merge the resultant with the third array.
Algorithm
function merge(A, B)
Let m and n be the sizes of A and B
Let D be the array to store result
// Merge by taking smaller element from A and B
while i < m and j < n
if A[i] <= B[j]
Add A[i] to D and increment i by 1
else Add B[j] to D and increment j by 1
// If array A has exhausted, put elements from B
while j < n
Add B[j] to D and increment j by 1
// If array B has exhausted, put elements from A
while i < n
Add A[j] to D and increment i by 1
Return D
function merge_three(A, B, C)
T = merge(A, B)
return merge(T, C)
Below is the implementation of the above approach:
C++
Java
Python
Javascript
// C++ program to merge three sorted arrays// by merging two at a time.#include <iostream>#include <vector>using namespace std; using Vector = vector<int>; void printVector(const Vector& a){ cout << "["; for (auto e : a) cout << e << " "; cout << "]" << endl;} Vector mergeTwo(Vector& A, Vector& B){ // Get sizes of vectors int m = A.size(); int n = B.size(); // Vector for storing Result Vector D; D.reserve(m + n); int i = 0, j = 0; while (i < m && j < n) { if (A[i] <= B[j]) D.push_back(A[i++]); else D.push_back(B[j++]); } // B has exhausted while (i < m) D.push_back(A[i++]); // A has exhausted while (j < n) D.push_back(B[j++]); return D;} // Driver Codeint main(){ Vector A = { 1, 2, 3, 5 }; Vector B = { 6, 7, 8, 9 }; Vector C = { 10, 11, 12 }; // First Merge A and B Vector T = mergeTwo(A, B); // Print Result after merging T with C printVector(mergeTwo(T, C)); return 0;}
import java.util.*;// Java program to merge three sorted arrays// by merging two at a time.class GFG { static ArrayList<Integer> mergeTwo(List<Integer> A, List<Integer> B) { // Get sizes of vectors int m = A.size(); int n = B.size(); // ArrayList for storing Result ArrayList<Integer> D = new ArrayList<Integer>(m + n); int i = 0, j = 0; while (i < m && j < n) { if (A.get(i) <= B.get(j)) D.add(A.get(i++)); else D.add(B.get(j++)); } // B has exhausted while (i < m) D.add(A.get(i++)); // A has exhausted while (j < n) D.add(B.get(j++)); return D; } // Driver code public static void main(String[] args) { Integer[] a = { 1, 2, 3, 5 }; Integer[] b = { 6, 7, 8, 9 }; Integer[] c = { 10, 11, 12 }; List<Integer> A = Arrays.asList(a); List<Integer> B = Arrays.asList(b); List<Integer> C = Arrays.asList(c); // First Merge A and B ArrayList<Integer> T = mergeTwo(A, B); // Print Result after merging T with C System.out.println(mergeTwo(T, C)); }} /* This code contributed by PrinciRaj1992 */
# Python program to merge three sorted arrays# by merging two at a time. def merge_two(a, b): (m, n) = (len(a), len(b)) i = j = 0 # Destination Array d = [] # Merge from a and b together while i < m and j < n: if a[i] <= b[j]: d.append(a[i]) i += 1 else: d.append(b[j]) j += 1 # Merge from a if b has run out while i < m: d.append(a[i]) i += 1 # Merge from b if a has run out while j < n: d.append(b[j]) j += 1 return d def merge(a, b, c): t = merge_two(a, b) return merge_two(t, c) if __name__ == "__main__": A = [1, 2, 3, 5] B = [6, 7, 8, 9] C = [10, 11, 12] print(merge(A, B, C))
<script>// Javascript program to merge three sorted arrays// by merging two at a time. function mergeTwo(A, B){ // Get sizes of vectors let m = A.length; let n = B.length; // Vector for storing Result let D = []; let i = 0, j = 0; while (i < m && j < n) { if (A[i] <= B[j]) D.push(A[i++]); else D.push(B[j++]); } // B has exhausted while (i < m) D.push(A[i++]); // A has exhausted while (j < n) D.push(B[j++]); return D;} // Driver Code let A = [ 1, 2, 3, 5 ]; let B = [ 6, 7, 8, 9 ]; let C = [ 10, 11, 12 ]; // First Merge A and B let T = mergeTwo(A, B); // Print Result after merging T with C document.write(mergeTwo(T, C));</script>
[1 2 3 5 6 7 8 9 10 11 12 ]
Time Complexity: O(m+n+o) where m, n, o are the lengths of the 1st, 2nd, 3rd Array.Auxiliary Space: O(m + n + o).
Method 2 (Three arrays at a time) The Space complexity of method 1 can be improved if we merge the three arrays together.
function merge-three(A, B, C)
Let m, n, o be size of A, B, and C
Let D be the array to store the result
// Merge three arrays at the same time
while i < m and j < n and k < o
Get minimum of A[i], B[j], C[i]
if the minimum is from A, add it to
D and advance i
else if the minimum is from B add it
to D and advance j
else if the minimum is from C add it
to D and advance k
// After above step at least 1 array has
// exhausted. Only C has exhausted
while i < m and j < n
put minimum of A[i] and B[j] into D
Advance i if minimum is from A else advance j
// Only B has exhausted
while i < m and k < o
Put minimum of A[i] and C[k] into D
Advance i if minimum is from A else advance k
// Only A has exhausted
while j < n and k < o
Put minimum of B[j] and C[k] into D
Advance j if minimum is from B else advance k
// After above steps at least 2 arrays have
// exhausted
if A and B have exhausted take elements from C
if B and C have exhausted take elements from A
if A and C have exhausted take elements from B
return D
Time Complexity: O(m+n+o) where m, n, o are the lengths of the 1st, 2nd, and 3rd array.Auxiliary Space: O(1).
Below is the implementation of the above approach:
C++
Java
Python
Javascript
// C++ program to merger three sorted arrays// by merging three simultaneously.#include <iostream>#include <vector>using namespace std; using Vector = vector<int>; void printVector(const Vector& a){ cout << "["; for (auto e : a) { cout << e << " "; } cout << "]" << endl;} Vector mergeThree(Vector& A, Vector& B, Vector& C){ int m, n, o, i, j, k; // Get Sizes of three vectors m = A.size(); n = B.size(); o = C.size(); // Vector for storing output Vector D; D.reserve(m + n + o); i = j = k = 0; while (i < m && j < n && k < o) { // Get minimum of a, b, c int m = min(min(A[i], B[j]), C[k]); // Put m in D D.push_back(m); // Increment i, j, k if (m == A[i]) i++; else if (m == B[j]) j++; else k++; } // C has exhausted while (i < m && j < n) { if (A[i] <= B[j]) { D.push_back(A[i]); i++; } else { D.push_back(B[j]); j++; } } // B has exhausted while (i < m && k < o) { if (A[i] <= C[k]) { D.push_back(A[i]); i++; } else { D.push_back(C[k]); k++; } } // A has exhausted while (j < n && k < o) { if (B[j] <= C[k]) { D.push_back(B[j]); j++; } else { D.push_back(C[k]); k++; } } // A and B have exhausted while (k < o) D.push_back(C[k++]); // B and C have exhausted while (i < m) D.push_back(A[i++]); // A and C have exhausted while (j < n) D.push_back(B[j++]); return D;} // Driver Codeint main(){ Vector A = { 1, 2, 41, 52, 84 }; Vector B = { 1, 2, 41, 52, 67 }; Vector C = { 1, 2, 41, 52, 67, 85 }; // Print Result printVector(mergeThree(A, B, C)); return 0;}
import java.util.*;import java.io.*;import java.lang.*;class Sorting { public static void main(String[] args) { int A[] = { 1, 2, 41, 52, 84 }; int B[] = { 1, 2, 41, 52, 67 }; int C[] = { 1, 2, 41, 52, 67, 85 }; // call the function to sort and print the sorted numbers merge3sorted(A, B, C); } // Function to merge three sorted arrays // A[], B[], C[]: input arrays static void merge3sorted(int A[], int B[], int C[]) { // creating an empty list to store sorted numbers ArrayList<Integer> list = new ArrayList<Integer>(); int i = 0, j = 0, k = 0; // using merge concept and trying to find // smallest of three while all three arrays // contains at least one element while (i < A.length && j < B.length && k < C.length) { int a = A[i]; int b = B[j]; int c = C[k]; if (a <= b && a <= c) { list.add(a); i++; } else if (b <= a && b <= c) { list.add(b); j++; } else { list.add(c); k++; } } // next three while loop is to sort two // of arrays if one of the three gets exhausted while (i < A.length && j < B.length) { if (A[i] < B[j]) { list.add(A[i]); i++; } else { list.add(B[j]); j++; } } while (j < B.length && k < C.length) { if (B[j] < C[k]) { list.add(B[j]); j++; } else { list.add(C[k]); k++; } } while (i < A.length && k < C.length) { if (A[i] < C[k]) { list.add(A[i]); i++; } else { list.add(C[k]); k++; } } // if one of the array are left then // simply appending them as there will // be only largest element left while (i < A.length) { list.add(A[i]); i++; } while (j < B.length) { list.add(B[j]); j++; } while (k < C.length) { list.add(C[k]); k++; } // finally print the list for (Integer x : list) System.out.print(x + " "); } // merge3sorted closing braces}
# Python program to merge three sorted arrays# simultaneously. def merge_three(a, b, c): (m, n, o) = (len(a), len(b), len(c)) i = j = k = 0 # Destination array d = [] while i < m and j < n and k < o: # Get Minimum element m = min(a[i], b[j], c[k]) # Add m to D d.append(m) # Increment the source pointer which # gives m if a[i] == m: i += 1 elif b[j] == m: j += 1 elif c[k] == m: k += 1 # Merge a and b in c has exhausted while i < m and j < n: if a[i] <= b[k]: d.append(a[i]) i += 1 else: d.append(b[j]) j += 1 # Merge b and c if a has exhausted while j < n and k < o: if b[j] <= c[k]: d.append(b[j]) j += 1 else: d.append(c[k]) k += 1 # Merge a and c if b has exhausted while i < m and k < o: if a[i] <= c[k]: d.append(a[i]) i += 1 else: d.append(c[k]) k += 1 # Take elements from a if b and c # have exhausted while i < m: d.append(a[i]) i += 1 # Take elements from b if a and c # have exhausted while j < n: d.append(b[j]) j += 1 # Take elements from c if a and # b have exhausted while k < o: d.append(c[k]) k += 1 return d if __name__ == "__main__": a = [1, 2, 41, 52, 84] b = [1, 2, 41, 52, 67] c = [1, 2, 41, 52, 67, 85] print(merge_three(a, b, c))
<script>// Javascript program to merger three sorted arrays// by merging three simultaneously.function printVector(a) { document.write("["); for (let e of a) { document.write(e + " "); } document.write("]" + "<br>");} function mergeThree(A, B, C){ let m, n, o, i, j, k; // Get Sizes of three vectors m = A.length; n = B.length; o = C.length; // Vector for storing output let D = []; i = j = k = 0; while (i < m && j < n && k < o) { // Get minimum of a, b, c let m = Math.min(Math.min(A[i], B[j]), C[k]); // Put m in D D.push(m); // Increment i, j, k if (m == A[i]) i++; else if (m == B[j]) j++; else k++; } // C has exhausted while (i < m && j < n) { if (A[i] <= B[j]) { D.push(A[i]); i++; } else { D.push(B[j]); j++; } } // B has exhausted while (i < m && k < o) { if (A[i] <= C[k]) { D.push(A[i]); i++; } else { D.push(C[k]); k++; } } // A has exhausted while (j < n && k < o) { if (B[j] <= C[k]) { D.push(B[j]); j++; } else { D.push(C[k]); k++; } } // A and B have exhausted while (k < o) D.push(C[k++]); // B and C have exhausted while (i < m) D.push(A[i++]); // A and C have exhausted while (j < n) D.push(B[j++]); return D;} // Driver Code let A = [1, 2, 41, 52, 84];let B = [1, 2, 41, 52, 67];let C = [1, 2, 41, 52, 67, 85]; // Print ResultprintVector(mergeThree(A, B, C)); // This code is contributed by gfgking.</script>
[1 1 1 2 2 2 41 41 41 52 52 52 67 67 84 85 ]
Note: While it is relatively easy to implement direct procedures to merge two or three arrays, the process becomes cumbersome if we want to merge 4 or more arrays. In such cases, we should follow the procedure shown in Merge K Sorted Arrays .
Another Approach (Without caring about the exhausting array):The code written above can be shortened by the below code. Here we do not need to write code if any array gets exhausted.
Below is the implementation of the above approach:
Java
/*package whatever //do not write package name here */ import java.io.*;import java.lang.*;import java.util.*; // Java program to merge three sorted arrays// by merging two at a time. // This code is contributed by Animesh Nag class Solution { // A[], B[], C[]: input arrays // Function to merge three sorted lists into a single // list. static ArrayList<Integer> merge3sorted(int A[], int B[], int C[]) { ArrayList<Integer> ans = new ArrayList<Integer>(); int l1 = A.length; int l2 = B.length; int l3 = C.length; int i = 0, j = 0, k = 0; while (i < l1 || j < l2 || k < l3) { // Assigning a, b, c with max values so that if // any value is not present then also we can sort // the array. int a = Integer.MAX_VALUE, b = Integer.MAX_VALUE, c = Integer.MAX_VALUE; // a, b, c variables are assigned only if the // value exist in the array. if (i < l1) a = A[i]; if (j < l2) b = B[j]; if (k < l3) c = C[k]; // Cheking if 'a' is the minimum if (a <= b && a <= c) { ans.add(a); i++; } // Cheking if 'b' is the minimum else if (b <= a && b <= c) { ans.add(b); j++; } // Cheking if 'c' is the minimum else { if (c <= a && c <= b) { ans.add(c); k++; } } } return ans; }} class GFG { // Driver program to test above functions public static void main(String[] args) { int[] A = { 1, 2, 41, 52, 84 }; int[] B = { 1, 2, 41, 52, 67 }; int[] C = { 1, 2, 41, 52, 67, 85 }; Solution sol = new Solution(); ArrayList<Integer> final_ans = sol.merge3sorted(A, B, C); printeSorted(final_ans); } // A utility function to print array list static void printeSorted(ArrayList<Integer> list) { for (Integer x : list) System.out.print(x + " "); }}
1 1 1 2 2 2 41 41 41 52 52 52 67 67 84 85
Time Complexity: O(m+n+o) where m, n, o are the lengths of the 1st, 2nd, and 3rd array.Space Complexity: O(1)
princiraj1992
Devarshi_Singh
suprinilomous
sharmaadityansh
_saurabh_jaiswal
gfgking
AnimeshNag
array-merge
Arrays
Sorting
Arrays
Sorting
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Maximum and minimum of an array using minimum number of comparisons
Multidimensional Arrays in Java
Introduction to Arrays
Python | Using 2D arrays/lists the right way
Linked List vs Array
|
[
{
"code": null,
"e": 24766,
"s": 24738,
"text": "\n26 Apr, 2022"
},
{
"code": null,
"e": 24911,
"s": 24766,
"text": "Given 3 arrays (A, B, C) which are sorted in ascending order, we are required to merge them together in ascending order and output the array D. "
},
{
"code": null,
"e": 24922,
"s": 24911,
"text": "Examples: "
},
{
"code": null,
"e": 25045,
"s": 24922,
"text": "Input : A = [1, 2, 3, 4, 5] B = [2, 3, 4] C = [4, 5, 6, 7]Output : D = [1, 2, 2, 3, 3, 4, 4, 4, 5, 5, 6, 7]"
},
{
"code": null,
"e": 25167,
"s": 25045,
"text": "Input : A = [1, 2, 3, 5] B = [6, 7, 8, 9 ] C = [10, 11, 12]Output: D = [1, 2, 3, 5, 6, 7, 8, 9. 10, 11, 12]"
},
{
"code": null,
"e": 25330,
"s": 25167,
"text": "Method 1 (Two Arrays at a time) We have discussed at Merging 2 Sorted arrays . So we can first merge two arrays and then merge the resultant with the third array."
},
{
"code": null,
"e": 25341,
"s": 25330,
"text": "Algorithm "
},
{
"code": null,
"e": 25962,
"s": 25341,
"text": "function merge(A, B)\n Let m and n be the sizes of A and B\n Let D be the array to store result\n \n // Merge by taking smaller element from A and B\n while i < m and j < n\n if A[i] <= B[j]\n Add A[i] to D and increment i by 1\n else Add B[j] to D and increment j by 1\n\n // If array A has exhausted, put elements from B\n while j < n\n Add B[j] to D and increment j by 1\n \n // If array B has exhausted, put elements from A\n while i < n\n Add A[j] to D and increment i by 1\n \n Return D\n\nfunction merge_three(A, B, C)\n T = merge(A, B)\n return merge(T, C)"
},
{
"code": null,
"e": 26013,
"s": 25962,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 26017,
"s": 26013,
"text": "C++"
},
{
"code": null,
"e": 26022,
"s": 26017,
"text": "Java"
},
{
"code": null,
"e": 26029,
"s": 26022,
"text": "Python"
},
{
"code": null,
"e": 26040,
"s": 26029,
"text": "Javascript"
},
{
"code": "// C++ program to merge three sorted arrays// by merging two at a time.#include <iostream>#include <vector>using namespace std; using Vector = vector<int>; void printVector(const Vector& a){ cout << \"[\"; for (auto e : a) cout << e << \" \"; cout << \"]\" << endl;} Vector mergeTwo(Vector& A, Vector& B){ // Get sizes of vectors int m = A.size(); int n = B.size(); // Vector for storing Result Vector D; D.reserve(m + n); int i = 0, j = 0; while (i < m && j < n) { if (A[i] <= B[j]) D.push_back(A[i++]); else D.push_back(B[j++]); } // B has exhausted while (i < m) D.push_back(A[i++]); // A has exhausted while (j < n) D.push_back(B[j++]); return D;} // Driver Codeint main(){ Vector A = { 1, 2, 3, 5 }; Vector B = { 6, 7, 8, 9 }; Vector C = { 10, 11, 12 }; // First Merge A and B Vector T = mergeTwo(A, B); // Print Result after merging T with C printVector(mergeTwo(T, C)); return 0;}",
"e": 27062,
"s": 26040,
"text": null
},
{
"code": "import java.util.*;// Java program to merge three sorted arrays// by merging two at a time.class GFG { static ArrayList<Integer> mergeTwo(List<Integer> A, List<Integer> B) { // Get sizes of vectors int m = A.size(); int n = B.size(); // ArrayList for storing Result ArrayList<Integer> D = new ArrayList<Integer>(m + n); int i = 0, j = 0; while (i < m && j < n) { if (A.get(i) <= B.get(j)) D.add(A.get(i++)); else D.add(B.get(j++)); } // B has exhausted while (i < m) D.add(A.get(i++)); // A has exhausted while (j < n) D.add(B.get(j++)); return D; } // Driver code public static void main(String[] args) { Integer[] a = { 1, 2, 3, 5 }; Integer[] b = { 6, 7, 8, 9 }; Integer[] c = { 10, 11, 12 }; List<Integer> A = Arrays.asList(a); List<Integer> B = Arrays.asList(b); List<Integer> C = Arrays.asList(c); // First Merge A and B ArrayList<Integer> T = mergeTwo(A, B); // Print Result after merging T with C System.out.println(mergeTwo(T, C)); }} /* This code contributed by PrinciRaj1992 */",
"e": 28355,
"s": 27062,
"text": null
},
{
"code": "# Python program to merge three sorted arrays# by merging two at a time. def merge_two(a, b): (m, n) = (len(a), len(b)) i = j = 0 # Destination Array d = [] # Merge from a and b together while i < m and j < n: if a[i] <= b[j]: d.append(a[i]) i += 1 else: d.append(b[j]) j += 1 # Merge from a if b has run out while i < m: d.append(a[i]) i += 1 # Merge from b if a has run out while j < n: d.append(b[j]) j += 1 return d def merge(a, b, c): t = merge_two(a, b) return merge_two(t, c) if __name__ == \"__main__\": A = [1, 2, 3, 5] B = [6, 7, 8, 9] C = [10, 11, 12] print(merge(A, B, C))",
"e": 29080,
"s": 28355,
"text": null
},
{
"code": "<script>// Javascript program to merge three sorted arrays// by merging two at a time. function mergeTwo(A, B){ // Get sizes of vectors let m = A.length; let n = B.length; // Vector for storing Result let D = []; let i = 0, j = 0; while (i < m && j < n) { if (A[i] <= B[j]) D.push(A[i++]); else D.push(B[j++]); } // B has exhausted while (i < m) D.push(A[i++]); // A has exhausted while (j < n) D.push(B[j++]); return D;} // Driver Code let A = [ 1, 2, 3, 5 ]; let B = [ 6, 7, 8, 9 ]; let C = [ 10, 11, 12 ]; // First Merge A and B let T = mergeTwo(A, B); // Print Result after merging T with C document.write(mergeTwo(T, C));</script>",
"e": 29838,
"s": 29080,
"text": null
},
{
"code": null,
"e": 29867,
"s": 29838,
"text": "[1 2 3 5 6 7 8 9 10 11 12 ]\n"
},
{
"code": null,
"e": 29981,
"s": 29867,
"text": "Time Complexity: O(m+n+o) where m, n, o are the lengths of the 1st, 2nd, 3rd Array.Auxiliary Space: O(m + n + o)."
},
{
"code": null,
"e": 30104,
"s": 29981,
"text": "Method 2 (Three arrays at a time) The Space complexity of method 1 can be improved if we merge the three arrays together. "
},
{
"code": null,
"e": 31317,
"s": 30104,
"text": "function merge-three(A, B, C)\n Let m, n, o be size of A, B, and C\n Let D be the array to store the result\n \n // Merge three arrays at the same time\n while i < m and j < n and k < o\n Get minimum of A[i], B[j], C[i]\n if the minimum is from A, add it to \n D and advance i\n else if the minimum is from B add it \n to D and advance j\n else if the minimum is from C add it \n to D and advance k\n \n // After above step at least 1 array has \n // exhausted. Only C has exhausted\n while i < m and j < n\n put minimum of A[i] and B[j] into D\n Advance i if minimum is from A else advance j \n \n // Only B has exhausted\n while i < m and k < o\n Put minimum of A[i] and C[k] into D\n Advance i if minimum is from A else advance k\n \n // Only A has exhausted\n while j < n and k < o\n Put minimum of B[j] and C[k] into D\n Advance j if minimum is from B else advance k\n\n // After above steps at least 2 arrays have \n // exhausted\n if A and B have exhausted take elements from C\n if B and C have exhausted take elements from A\n if A and C have exhausted take elements from B\n \n return D"
},
{
"code": null,
"e": 31427,
"s": 31317,
"text": "Time Complexity: O(m+n+o) where m, n, o are the lengths of the 1st, 2nd, and 3rd array.Auxiliary Space: O(1)."
},
{
"code": null,
"e": 31478,
"s": 31427,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 31482,
"s": 31478,
"text": "C++"
},
{
"code": null,
"e": 31487,
"s": 31482,
"text": "Java"
},
{
"code": null,
"e": 31494,
"s": 31487,
"text": "Python"
},
{
"code": null,
"e": 31505,
"s": 31494,
"text": "Javascript"
},
{
"code": "// C++ program to merger three sorted arrays// by merging three simultaneously.#include <iostream>#include <vector>using namespace std; using Vector = vector<int>; void printVector(const Vector& a){ cout << \"[\"; for (auto e : a) { cout << e << \" \"; } cout << \"]\" << endl;} Vector mergeThree(Vector& A, Vector& B, Vector& C){ int m, n, o, i, j, k; // Get Sizes of three vectors m = A.size(); n = B.size(); o = C.size(); // Vector for storing output Vector D; D.reserve(m + n + o); i = j = k = 0; while (i < m && j < n && k < o) { // Get minimum of a, b, c int m = min(min(A[i], B[j]), C[k]); // Put m in D D.push_back(m); // Increment i, j, k if (m == A[i]) i++; else if (m == B[j]) j++; else k++; } // C has exhausted while (i < m && j < n) { if (A[i] <= B[j]) { D.push_back(A[i]); i++; } else { D.push_back(B[j]); j++; } } // B has exhausted while (i < m && k < o) { if (A[i] <= C[k]) { D.push_back(A[i]); i++; } else { D.push_back(C[k]); k++; } } // A has exhausted while (j < n && k < o) { if (B[j] <= C[k]) { D.push_back(B[j]); j++; } else { D.push_back(C[k]); k++; } } // A and B have exhausted while (k < o) D.push_back(C[k++]); // B and C have exhausted while (i < m) D.push_back(A[i++]); // A and C have exhausted while (j < n) D.push_back(B[j++]); return D;} // Driver Codeint main(){ Vector A = { 1, 2, 41, 52, 84 }; Vector B = { 1, 2, 41, 52, 67 }; Vector C = { 1, 2, 41, 52, 67, 85 }; // Print Result printVector(mergeThree(A, B, C)); return 0;}",
"e": 33438,
"s": 31505,
"text": null
},
{
"code": "import java.util.*;import java.io.*;import java.lang.*;class Sorting { public static void main(String[] args) { int A[] = { 1, 2, 41, 52, 84 }; int B[] = { 1, 2, 41, 52, 67 }; int C[] = { 1, 2, 41, 52, 67, 85 }; // call the function to sort and print the sorted numbers merge3sorted(A, B, C); } // Function to merge three sorted arrays // A[], B[], C[]: input arrays static void merge3sorted(int A[], int B[], int C[]) { // creating an empty list to store sorted numbers ArrayList<Integer> list = new ArrayList<Integer>(); int i = 0, j = 0, k = 0; // using merge concept and trying to find // smallest of three while all three arrays // contains at least one element while (i < A.length && j < B.length && k < C.length) { int a = A[i]; int b = B[j]; int c = C[k]; if (a <= b && a <= c) { list.add(a); i++; } else if (b <= a && b <= c) { list.add(b); j++; } else { list.add(c); k++; } } // next three while loop is to sort two // of arrays if one of the three gets exhausted while (i < A.length && j < B.length) { if (A[i] < B[j]) { list.add(A[i]); i++; } else { list.add(B[j]); j++; } } while (j < B.length && k < C.length) { if (B[j] < C[k]) { list.add(B[j]); j++; } else { list.add(C[k]); k++; } } while (i < A.length && k < C.length) { if (A[i] < C[k]) { list.add(A[i]); i++; } else { list.add(C[k]); k++; } } // if one of the array are left then // simply appending them as there will // be only largest element left while (i < A.length) { list.add(A[i]); i++; } while (j < B.length) { list.add(B[j]); j++; } while (k < C.length) { list.add(C[k]); k++; } // finally print the list for (Integer x : list) System.out.print(x + \" \"); } // merge3sorted closing braces}",
"e": 35944,
"s": 33438,
"text": null
},
{
"code": "# Python program to merge three sorted arrays# simultaneously. def merge_three(a, b, c): (m, n, o) = (len(a), len(b), len(c)) i = j = k = 0 # Destination array d = [] while i < m and j < n and k < o: # Get Minimum element m = min(a[i], b[j], c[k]) # Add m to D d.append(m) # Increment the source pointer which # gives m if a[i] == m: i += 1 elif b[j] == m: j += 1 elif c[k] == m: k += 1 # Merge a and b in c has exhausted while i < m and j < n: if a[i] <= b[k]: d.append(a[i]) i += 1 else: d.append(b[j]) j += 1 # Merge b and c if a has exhausted while j < n and k < o: if b[j] <= c[k]: d.append(b[j]) j += 1 else: d.append(c[k]) k += 1 # Merge a and c if b has exhausted while i < m and k < o: if a[i] <= c[k]: d.append(a[i]) i += 1 else: d.append(c[k]) k += 1 # Take elements from a if b and c # have exhausted while i < m: d.append(a[i]) i += 1 # Take elements from b if a and c # have exhausted while j < n: d.append(b[j]) j += 1 # Take elements from c if a and # b have exhausted while k < o: d.append(c[k]) k += 1 return d if __name__ == \"__main__\": a = [1, 2, 41, 52, 84] b = [1, 2, 41, 52, 67] c = [1, 2, 41, 52, 67, 85] print(merge_three(a, b, c))",
"e": 37501,
"s": 35944,
"text": null
},
{
"code": "<script>// Javascript program to merger three sorted arrays// by merging three simultaneously.function printVector(a) { document.write(\"[\"); for (let e of a) { document.write(e + \" \"); } document.write(\"]\" + \"<br>\");} function mergeThree(A, B, C){ let m, n, o, i, j, k; // Get Sizes of three vectors m = A.length; n = B.length; o = C.length; // Vector for storing output let D = []; i = j = k = 0; while (i < m && j < n && k < o) { // Get minimum of a, b, c let m = Math.min(Math.min(A[i], B[j]), C[k]); // Put m in D D.push(m); // Increment i, j, k if (m == A[i]) i++; else if (m == B[j]) j++; else k++; } // C has exhausted while (i < m && j < n) { if (A[i] <= B[j]) { D.push(A[i]); i++; } else { D.push(B[j]); j++; } } // B has exhausted while (i < m && k < o) { if (A[i] <= C[k]) { D.push(A[i]); i++; } else { D.push(C[k]); k++; } } // A has exhausted while (j < n && k < o) { if (B[j] <= C[k]) { D.push(B[j]); j++; } else { D.push(C[k]); k++; } } // A and B have exhausted while (k < o) D.push(C[k++]); // B and C have exhausted while (i < m) D.push(A[i++]); // A and C have exhausted while (j < n) D.push(B[j++]); return D;} // Driver Code let A = [1, 2, 41, 52, 84];let B = [1, 2, 41, 52, 67];let C = [1, 2, 41, 52, 67, 85]; // Print ResultprintVector(mergeThree(A, B, C)); // This code is contributed by gfgking.</script>",
"e": 39273,
"s": 37501,
"text": null
},
{
"code": null,
"e": 39319,
"s": 39273,
"text": "[1 1 1 2 2 2 41 41 41 52 52 52 67 67 84 85 ]\n"
},
{
"code": null,
"e": 39562,
"s": 39319,
"text": "Note: While it is relatively easy to implement direct procedures to merge two or three arrays, the process becomes cumbersome if we want to merge 4 or more arrays. In such cases, we should follow the procedure shown in Merge K Sorted Arrays ."
},
{
"code": null,
"e": 39745,
"s": 39562,
"text": "Another Approach (Without caring about the exhausting array):The code written above can be shortened by the below code. Here we do not need to write code if any array gets exhausted."
},
{
"code": null,
"e": 39796,
"s": 39745,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 39801,
"s": 39796,
"text": "Java"
},
{
"code": "/*package whatever //do not write package name here */ import java.io.*;import java.lang.*;import java.util.*; // Java program to merge three sorted arrays// by merging two at a time. // This code is contributed by Animesh Nag class Solution { // A[], B[], C[]: input arrays // Function to merge three sorted lists into a single // list. static ArrayList<Integer> merge3sorted(int A[], int B[], int C[]) { ArrayList<Integer> ans = new ArrayList<Integer>(); int l1 = A.length; int l2 = B.length; int l3 = C.length; int i = 0, j = 0, k = 0; while (i < l1 || j < l2 || k < l3) { // Assigning a, b, c with max values so that if // any value is not present then also we can sort // the array. int a = Integer.MAX_VALUE, b = Integer.MAX_VALUE, c = Integer.MAX_VALUE; // a, b, c variables are assigned only if the // value exist in the array. if (i < l1) a = A[i]; if (j < l2) b = B[j]; if (k < l3) c = C[k]; // Cheking if 'a' is the minimum if (a <= b && a <= c) { ans.add(a); i++; } // Cheking if 'b' is the minimum else if (b <= a && b <= c) { ans.add(b); j++; } // Cheking if 'c' is the minimum else { if (c <= a && c <= b) { ans.add(c); k++; } } } return ans; }} class GFG { // Driver program to test above functions public static void main(String[] args) { int[] A = { 1, 2, 41, 52, 84 }; int[] B = { 1, 2, 41, 52, 67 }; int[] C = { 1, 2, 41, 52, 67, 85 }; Solution sol = new Solution(); ArrayList<Integer> final_ans = sol.merge3sorted(A, B, C); printeSorted(final_ans); } // A utility function to print array list static void printeSorted(ArrayList<Integer> list) { for (Integer x : list) System.out.print(x + \" \"); }}",
"e": 42035,
"s": 39801,
"text": null
},
{
"code": null,
"e": 42078,
"s": 42035,
"text": "1 1 1 2 2 2 41 41 41 52 52 52 67 67 84 85 "
},
{
"code": null,
"e": 42188,
"s": 42078,
"text": "Time Complexity: O(m+n+o) where m, n, o are the lengths of the 1st, 2nd, and 3rd array.Space Complexity: O(1)"
},
{
"code": null,
"e": 42202,
"s": 42188,
"text": "princiraj1992"
},
{
"code": null,
"e": 42217,
"s": 42202,
"text": "Devarshi_Singh"
},
{
"code": null,
"e": 42231,
"s": 42217,
"text": "suprinilomous"
},
{
"code": null,
"e": 42247,
"s": 42231,
"text": "sharmaadityansh"
},
{
"code": null,
"e": 42264,
"s": 42247,
"text": "_saurabh_jaiswal"
},
{
"code": null,
"e": 42272,
"s": 42264,
"text": "gfgking"
},
{
"code": null,
"e": 42283,
"s": 42272,
"text": "AnimeshNag"
},
{
"code": null,
"e": 42295,
"s": 42283,
"text": "array-merge"
},
{
"code": null,
"e": 42302,
"s": 42295,
"text": "Arrays"
},
{
"code": null,
"e": 42310,
"s": 42302,
"text": "Sorting"
},
{
"code": null,
"e": 42317,
"s": 42310,
"text": "Arrays"
},
{
"code": null,
"e": 42325,
"s": 42317,
"text": "Sorting"
},
{
"code": null,
"e": 42423,
"s": 42325,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 42491,
"s": 42423,
"text": "Maximum and minimum of an array using minimum number of comparisons"
},
{
"code": null,
"e": 42523,
"s": 42491,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 42546,
"s": 42523,
"text": "Introduction to Arrays"
},
{
"code": null,
"e": 42591,
"s": 42546,
"text": "Python | Using 2D arrays/lists the right way"
}
] |
How to make Analysis Tool with Python | Towards Data Science
|
Since the new policy in October last year, Medium calculates the earnings differently and updates them daily. Before the change, it was based on the number of claps from members and the amount that they themselves clap in general, but now it is based on reading time. Similar to youtube’s algorithm, which is watch time.
The important thing is that it updates daily and you want to know how much have your stories made and how many views you have in the last 30 days.
As an example website for making this simple Analysis Tool, we will take Medium. But you can do it basically with any site out there that has stats you need.
It is a very simple use of Python and you do not need any specific or rather spectacular skills to do this with me. We will go step by step and build everything from the ground up.
Let’s just jump right into it!
There are a few steps when building such a tool and first, we have to see how to get to what we want.This is where we land when we go to Medium’s welcome page.
It is rather simple and we have sign-in/up buttons. We are going to use those in order to login to our profile. We are going to automate this tool in order for it to click, fill out emails, passwords and log us in. After that, we will get to the data we need.
You are going to have to install a ChromeDriver, which is going to enable us to manipulate the browser and send commands to it for testing and after for use.
Open the link and download the file for your operating system. I recommend the latest stable release unless you know what you are doing already.
Next up, you need to unzip that file. I would recommend going into Files and doing it manually by right-clicking and then “Extract here”.
Inside the folder, there is a file called “chromedriver”, which we have to move to a specific folder on your computer.
Open the terminal and type these commands:
sudo su #enter the root modecd #go back to base from the current locationmv /home/*your_pc_name*/Downloads/chromedriver /usr/local/bin #move the file to the right location
Just instead of *your_pc_name* insert your actual name of the computer.
Once we are done with that, we open the editor. My personal choice is Visual Studio Code. It is straightforward to use, customizable, and light for your computer.
Open a new Project where ever you like and create two new files. This is an example of how mine looks like to help you:
In the VS Code, there is a “Terminal” tab with which you can open an internal terminal inside the VS Code, which is very useful to have everything in one place.
When you have that open, there is few more thing we need to install and that is the virtual environment and selenium for web driver. Type these commands into your terminal.
pip3 install virtualenvsource venv/bin/activatepip3 install selenium
After activating the virtual environment, we are completely ready to go.
We will create it as a class and make functions for it. So let’s start!
Create your tool with any name and start the driver for Chrome.
class MediumBot(): def __init__(self): self.driver = webdriver.Chrome()
That is all we need to start developing. Now go to your terminal and type:
python -i scrape.py
This command lets us our file as an interactive playground. The new tab of the browser will be opened and we can start issuing commands to it.If you want to experiment you can use the command line instead of just typing it directly to your source file. Just instead of self use bot.
For Terminal:
bot = MediumBot()bot.driver.get('https://medium.com/')
And now for the source code:
self.driver.get('https://medium.com/')
Now we went over to mediums welcome page and what we want next is to log in. We inspect the element (F12 on keyboard) and copy elements XPath.
Right-click in that marked blue section of code and copy by XPath. Next up, we have to make a command to click that button for us.
sign_in = self.driver.find_element_by_xpath('//*[@id="root"]/div/div[4]/div/div/div[3]/div/div[2]/h4/a')sign_in.click()
In single quotes (‘ ’) is my XPath and you have to adjust yours if you are doing other websites.
I saved the XPath to a variable and perform a click() function on it.
I have done 2 types of login for Medium and those are Google and Facebook, you can also choose which method better suits you, but turn off 2-factor-authentication just so this process gets easier.
For the Facebook method, you will select the Login with Facebook button, get its XPath and click it again.
Now we have to input our username and password and we do it by the send_keys() function.
Again, select the text box and now just send a text to that field like this:
email_in = self.driver.find_element_by_xpath('//*[@id="email"]')email_in.send_keys(username)
Do the same for the password and then Log In with click() function.After logging in, we have access to data we want to get to and I wrote two separate functions to get both earnings and views of your stories.
First views:
def stats(self): self.driver.get('https://medium.com/me/stats') sleep(3) total_views = self.driver.find_element_by_xpath('/html/body/div[1]/div[2]/div/div[3]/div/ul/li[1]/div/div[1]') print(total_views.text)
And now earnings:
def earnings(self): self.driver.get('https://medium.com/me/partner/dashboard') sleep(3) total_earnings = self.driver.find_element_by_xpath('/html/body/div[1]/div[2]/div/div[3]/section/div/div[2]/div/div/div/div[3]') print(total_earnings.text)
In both of these, I use sleep() function, which lets me pause the further execution for a certain amount of time, so sleep(1) will pause for 1 second.You have to import this at the beginning of your code.
Once you are done with extracting data. All you have to do now is create an instance of this tool outside the class and perform a function on it.
bot = MediumBot()bot.login_facebook()
Save that and run the script. Watch the magic happen before your own eyes!
Here is a complete code on my GitHub page:
github.com
Also, you can change the creditentials.py and fill it with your own data in order to log in.
We are done!
If you want to take this further you can also implement some functions like emails sending at a certain goal you reach or extract data for specific stories you want to track your data.
I hope you liked this little tutorial and follow me for more!
Thanks for reading!
|
[
{
"code": null,
"e": 492,
"s": 171,
"text": "Since the new policy in October last year, Medium calculates the earnings differently and updates them daily. Before the change, it was based on the number of claps from members and the amount that they themselves clap in general, but now it is based on reading time. Similar to youtube’s algorithm, which is watch time."
},
{
"code": null,
"e": 639,
"s": 492,
"text": "The important thing is that it updates daily and you want to know how much have your stories made and how many views you have in the last 30 days."
},
{
"code": null,
"e": 797,
"s": 639,
"text": "As an example website for making this simple Analysis Tool, we will take Medium. But you can do it basically with any site out there that has stats you need."
},
{
"code": null,
"e": 978,
"s": 797,
"text": "It is a very simple use of Python and you do not need any specific or rather spectacular skills to do this with me. We will go step by step and build everything from the ground up."
},
{
"code": null,
"e": 1009,
"s": 978,
"text": "Let’s just jump right into it!"
},
{
"code": null,
"e": 1169,
"s": 1009,
"text": "There are a few steps when building such a tool and first, we have to see how to get to what we want.This is where we land when we go to Medium’s welcome page."
},
{
"code": null,
"e": 1429,
"s": 1169,
"text": "It is rather simple and we have sign-in/up buttons. We are going to use those in order to login to our profile. We are going to automate this tool in order for it to click, fill out emails, passwords and log us in. After that, we will get to the data we need."
},
{
"code": null,
"e": 1587,
"s": 1429,
"text": "You are going to have to install a ChromeDriver, which is going to enable us to manipulate the browser and send commands to it for testing and after for use."
},
{
"code": null,
"e": 1732,
"s": 1587,
"text": "Open the link and download the file for your operating system. I recommend the latest stable release unless you know what you are doing already."
},
{
"code": null,
"e": 1870,
"s": 1732,
"text": "Next up, you need to unzip that file. I would recommend going into Files and doing it manually by right-clicking and then “Extract here”."
},
{
"code": null,
"e": 1989,
"s": 1870,
"text": "Inside the folder, there is a file called “chromedriver”, which we have to move to a specific folder on your computer."
},
{
"code": null,
"e": 2032,
"s": 1989,
"text": "Open the terminal and type these commands:"
},
{
"code": null,
"e": 2209,
"s": 2032,
"text": "sudo su #enter the root modecd #go back to base from the current locationmv /home/*your_pc_name*/Downloads/chromedriver /usr/local/bin #move the file to the right location"
},
{
"code": null,
"e": 2281,
"s": 2209,
"text": "Just instead of *your_pc_name* insert your actual name of the computer."
},
{
"code": null,
"e": 2444,
"s": 2281,
"text": "Once we are done with that, we open the editor. My personal choice is Visual Studio Code. It is straightforward to use, customizable, and light for your computer."
},
{
"code": null,
"e": 2564,
"s": 2444,
"text": "Open a new Project where ever you like and create two new files. This is an example of how mine looks like to help you:"
},
{
"code": null,
"e": 2725,
"s": 2564,
"text": "In the VS Code, there is a “Terminal” tab with which you can open an internal terminal inside the VS Code, which is very useful to have everything in one place."
},
{
"code": null,
"e": 2898,
"s": 2725,
"text": "When you have that open, there is few more thing we need to install and that is the virtual environment and selenium for web driver. Type these commands into your terminal."
},
{
"code": null,
"e": 2967,
"s": 2898,
"text": "pip3 install virtualenvsource venv/bin/activatepip3 install selenium"
},
{
"code": null,
"e": 3040,
"s": 2967,
"text": "After activating the virtual environment, we are completely ready to go."
},
{
"code": null,
"e": 3112,
"s": 3040,
"text": "We will create it as a class and make functions for it. So let’s start!"
},
{
"code": null,
"e": 3176,
"s": 3112,
"text": "Create your tool with any name and start the driver for Chrome."
},
{
"code": null,
"e": 3252,
"s": 3176,
"text": "class MediumBot(): def __init__(self): self.driver = webdriver.Chrome()"
},
{
"code": null,
"e": 3327,
"s": 3252,
"text": "That is all we need to start developing. Now go to your terminal and type:"
},
{
"code": null,
"e": 3347,
"s": 3327,
"text": "python -i scrape.py"
},
{
"code": null,
"e": 3630,
"s": 3347,
"text": "This command lets us our file as an interactive playground. The new tab of the browser will be opened and we can start issuing commands to it.If you want to experiment you can use the command line instead of just typing it directly to your source file. Just instead of self use bot."
},
{
"code": null,
"e": 3644,
"s": 3630,
"text": "For Terminal:"
},
{
"code": null,
"e": 3699,
"s": 3644,
"text": "bot = MediumBot()bot.driver.get('https://medium.com/')"
},
{
"code": null,
"e": 3728,
"s": 3699,
"text": "And now for the source code:"
},
{
"code": null,
"e": 3767,
"s": 3728,
"text": "self.driver.get('https://medium.com/')"
},
{
"code": null,
"e": 3910,
"s": 3767,
"text": "Now we went over to mediums welcome page and what we want next is to log in. We inspect the element (F12 on keyboard) and copy elements XPath."
},
{
"code": null,
"e": 4041,
"s": 3910,
"text": "Right-click in that marked blue section of code and copy by XPath. Next up, we have to make a command to click that button for us."
},
{
"code": null,
"e": 4161,
"s": 4041,
"text": "sign_in = self.driver.find_element_by_xpath('//*[@id=\"root\"]/div/div[4]/div/div/div[3]/div/div[2]/h4/a')sign_in.click()"
},
{
"code": null,
"e": 4258,
"s": 4161,
"text": "In single quotes (‘ ’) is my XPath and you have to adjust yours if you are doing other websites."
},
{
"code": null,
"e": 4328,
"s": 4258,
"text": "I saved the XPath to a variable and perform a click() function on it."
},
{
"code": null,
"e": 4525,
"s": 4328,
"text": "I have done 2 types of login for Medium and those are Google and Facebook, you can also choose which method better suits you, but turn off 2-factor-authentication just so this process gets easier."
},
{
"code": null,
"e": 4632,
"s": 4525,
"text": "For the Facebook method, you will select the Login with Facebook button, get its XPath and click it again."
},
{
"code": null,
"e": 4721,
"s": 4632,
"text": "Now we have to input our username and password and we do it by the send_keys() function."
},
{
"code": null,
"e": 4798,
"s": 4721,
"text": "Again, select the text box and now just send a text to that field like this:"
},
{
"code": null,
"e": 4891,
"s": 4798,
"text": "email_in = self.driver.find_element_by_xpath('//*[@id=\"email\"]')email_in.send_keys(username)"
},
{
"code": null,
"e": 5100,
"s": 4891,
"text": "Do the same for the password and then Log In with click() function.After logging in, we have access to data we want to get to and I wrote two separate functions to get both earnings and views of your stories."
},
{
"code": null,
"e": 5113,
"s": 5100,
"text": "First views:"
},
{
"code": null,
"e": 5325,
"s": 5113,
"text": "def stats(self): self.driver.get('https://medium.com/me/stats') sleep(3) total_views = self.driver.find_element_by_xpath('/html/body/div[1]/div[2]/div/div[3]/div/ul/li[1]/div/div[1]') print(total_views.text)"
},
{
"code": null,
"e": 5343,
"s": 5325,
"text": "And now earnings:"
},
{
"code": null,
"e": 5590,
"s": 5343,
"text": "def earnings(self): self.driver.get('https://medium.com/me/partner/dashboard') sleep(3) total_earnings = self.driver.find_element_by_xpath('/html/body/div[1]/div[2]/div/div[3]/section/div/div[2]/div/div/div/div[3]') print(total_earnings.text)"
},
{
"code": null,
"e": 5795,
"s": 5590,
"text": "In both of these, I use sleep() function, which lets me pause the further execution for a certain amount of time, so sleep(1) will pause for 1 second.You have to import this at the beginning of your code."
},
{
"code": null,
"e": 5941,
"s": 5795,
"text": "Once you are done with extracting data. All you have to do now is create an instance of this tool outside the class and perform a function on it."
},
{
"code": null,
"e": 5979,
"s": 5941,
"text": "bot = MediumBot()bot.login_facebook()"
},
{
"code": null,
"e": 6054,
"s": 5979,
"text": "Save that and run the script. Watch the magic happen before your own eyes!"
},
{
"code": null,
"e": 6097,
"s": 6054,
"text": "Here is a complete code on my GitHub page:"
},
{
"code": null,
"e": 6108,
"s": 6097,
"text": "github.com"
},
{
"code": null,
"e": 6201,
"s": 6108,
"text": "Also, you can change the creditentials.py and fill it with your own data in order to log in."
},
{
"code": null,
"e": 6214,
"s": 6201,
"text": "We are done!"
},
{
"code": null,
"e": 6399,
"s": 6214,
"text": "If you want to take this further you can also implement some functions like emails sending at a certain goal you reach or extract data for specific stories you want to track your data."
},
{
"code": null,
"e": 6461,
"s": 6399,
"text": "I hope you liked this little tutorial and follow me for more!"
}
] |
XPath - Predicate
|
Predicate refers to the XPath expression written in square brackets. It refers to restrict the selected nodes in a node set for some condition. For example,
/class/student[1]
Select first student element which is child of the class element.
/class/student[last()]
Select last student element which is child of the class element.
/class/student[@rolllno = 493]
Select student element with rollno 493.
/class/student[marks>85]
Select student element with marks > 85.
This example creates a table of <student> element with their details, by iterating over each student. It calculates the position of the student node and then prints the student(s) details along with serial no.
<?xml version = "1.0"?>
<?xml-stylesheet type = "text/xsl" href = "students.xsl"?>
<class>
<student rollno = "393">
<firstname>Dinkar</firstname>
<lastname>Kad</lastname>
<nickname>Dinkar</nickname>
<marks>85</marks>
</student>
<student rollno = "493">
<firstname>Vaneet</firstname>
<lastname>Gupta</lastname>
<nickname>Vinni</nickname>
<marks>95</marks>
</student>
<student rollno = "593">
<firstname>Jasvir</firstname>
<lastname>Singh</lastname>
<nickname>Jazz</nickname>
<marks>90</marks>
</student>
</class>
<?xml version = "1.0" encoding = "UTF-8"?>
<xsl:stylesheet version = "1.0"
xmlns:xsl = "http://www.w3.org/1999/XSL/Transform">
<xsl:template match = "/">
<html>
<body>
<h2>Students</h2>
<table border = "1">
<tr bgcolor = "#9acd32">
<th>Roll No</th>
<th>First Name</th>
<th>Last Name</th>
<th>Nick Name</th>
<th>Marks</th>
</tr>
<xsl:for-each select = "/class/student[1]">
<tr>
<td><xsl:value-of select = "@rollno"/></td>
<td><xsl:value-of select = "firstname"/></td>
<td><xsl:value-of select = "lastname"/></td>
<td><xsl:value-of select = "nickname"/></td>
<td><xsl:value-of select = "marks"/></td>
</tr>
</xsl:for-each>
<xsl:for-each select = "/class/student[last()]">
<tr>
<td><xsl:value-of select = "@rollno"/></td>
<td><xsl:value-of select = "firstname"/></td>
<td><xsl:value-of select = "lastname"/></td>
<td><xsl:value-of select = "nickname"/></td>
<td><xsl:value-of select = "marks"/></td>
</tr>
</xsl:for-each>
<xsl:for-each select = "/class/student[@rollno = 493]">
<tr>
<td><xsl:value-of select = "@rollno"/></td>
<td><xsl:value-of select = "firstname"/></td>
<td><xsl:value-of select = "lastname"/></td>
<td><xsl:value-of select = "nickname"/></td>
<td><xsl:value-of select = "marks"/></td>
</tr>
</xsl:for-each>
<xsl:for-each select = "/class/student[marks > 85]">
<tr>
<td><xsl:value-of select = "@rollno"/></td>
<td><xsl:value-of select = "firstname"/></td>
<td><xsl:value-of select = "lastname"/></td>
<td><xsl:value-of select = "nickname"/></td>
<td><xsl:value-of select = "marks"/></td>
</tr>
</xsl:for-each>
</table>
</body>
</html>
</xsl:template>
</xsl:stylesheet>
90 Lectures
20 hours
Arun Motoori
23 Lectures
8 hours
Sanjay Kumar
13 Lectures
1.5 hours
Sanjay Kumar
24 Lectures
1.5 hours
Sanjay Kumar
47 Lectures
3 hours
Krishna Sakinala
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 1886,
"s": 1729,
"text": "Predicate refers to the XPath expression written in square brackets. It refers to restrict the selected nodes in a node set for some condition. For example,"
},
{
"code": null,
"e": 1904,
"s": 1886,
"text": "/class/student[1]"
},
{
"code": null,
"e": 1970,
"s": 1904,
"text": "Select first student element which is child of the class element."
},
{
"code": null,
"e": 1993,
"s": 1970,
"text": "/class/student[last()]"
},
{
"code": null,
"e": 2058,
"s": 1993,
"text": "Select last student element which is child of the class element."
},
{
"code": null,
"e": 2089,
"s": 2058,
"text": "/class/student[@rolllno = 493]"
},
{
"code": null,
"e": 2129,
"s": 2089,
"text": "Select student element with rollno 493."
},
{
"code": null,
"e": 2154,
"s": 2129,
"text": "/class/student[marks>85]"
},
{
"code": null,
"e": 2194,
"s": 2154,
"text": "Select student element with marks > 85."
},
{
"code": null,
"e": 2404,
"s": 2194,
"text": "This example creates a table of <student> element with their details, by iterating over each student. It calculates the position of the student node and then prints the student(s) details along with serial no."
},
{
"code": null,
"e": 3006,
"s": 2404,
"text": "<?xml version = \"1.0\"?>\n<?xml-stylesheet type = \"text/xsl\" href = \"students.xsl\"?>\n<class>\n <student rollno = \"393\">\n <firstname>Dinkar</firstname>\n <lastname>Kad</lastname>\n <nickname>Dinkar</nickname>\n <marks>85</marks>\n </student>\n <student rollno = \"493\">\n <firstname>Vaneet</firstname>\n <lastname>Gupta</lastname>\n <nickname>Vinni</nickname>\n <marks>95</marks>\n </student>\n <student rollno = \"593\">\n <firstname>Jasvir</firstname>\n <lastname>Singh</lastname>\n <nickname>Jazz</nickname>\n <marks>90</marks>\n </student>\n</class>"
},
{
"code": null,
"e": 5520,
"s": 3006,
"text": "<?xml version = \"1.0\" encoding = \"UTF-8\"?>\n<xsl:stylesheet version = \"1.0\"\n xmlns:xsl = \"http://www.w3.org/1999/XSL/Transform\"> \n\n <xsl:template match = \"/\">\n <html>\n <body>\n <h2>Students</h2>\n <table border = \"1\">\n <tr bgcolor = \"#9acd32\">\t \n <th>Roll No</th>\n <th>First Name</th>\n <th>Last Name</th>\n <th>Nick Name</th>\n <th>Marks</th>\t \n </tr>\n\t\t\t\t\t\n <xsl:for-each select = \"/class/student[1]\">\n <tr>\t \n <td><xsl:value-of select = \"@rollno\"/></td>\n <td><xsl:value-of select = \"firstname\"/></td>\n <td><xsl:value-of select = \"lastname\"/></td>\n <td><xsl:value-of select = \"nickname\"/></td>\n <td><xsl:value-of select = \"marks\"/></td>\t \n </tr>\t\n </xsl:for-each>\n\t\t\t\t\t\n <xsl:for-each select = \"/class/student[last()]\">\n <tr>\t \n <td><xsl:value-of select = \"@rollno\"/></td>\n <td><xsl:value-of select = \"firstname\"/></td>\n <td><xsl:value-of select = \"lastname\"/></td>\n <td><xsl:value-of select = \"nickname\"/></td>\n <td><xsl:value-of select = \"marks\"/></td>\t \n </tr>\t\n </xsl:for-each>\n\t\n <xsl:for-each select = \"/class/student[@rollno = 493]\">\n <tr>\t \n <td><xsl:value-of select = \"@rollno\"/></td>\n <td><xsl:value-of select = \"firstname\"/></td>\n <td><xsl:value-of select = \"lastname\"/></td>\n <td><xsl:value-of select = \"nickname\"/></td>\n <td><xsl:value-of select = \"marks\"/></td>\t \n </tr>\t\n </xsl:for-each>\n\n <xsl:for-each select = \"/class/student[marks > 85]\">\n <tr>\t \n <td><xsl:value-of select = \"@rollno\"/></td>\n <td><xsl:value-of select = \"firstname\"/></td>\n <td><xsl:value-of select = \"lastname\"/></td>\n <td><xsl:value-of select = \"nickname\"/></td>\n <td><xsl:value-of select = \"marks\"/></td>\t \n </tr>\t\n </xsl:for-each>\n\t\n\t\n </table>\n \n </body>\n </html>\n </xsl:template>\n</xsl:stylesheet>"
},
{
"code": null,
"e": 5554,
"s": 5520,
"text": "\n 90 Lectures \n 20 hours \n"
},
{
"code": null,
"e": 5568,
"s": 5554,
"text": " Arun Motoori"
},
{
"code": null,
"e": 5601,
"s": 5568,
"text": "\n 23 Lectures \n 8 hours \n"
},
{
"code": null,
"e": 5615,
"s": 5601,
"text": " Sanjay Kumar"
},
{
"code": null,
"e": 5650,
"s": 5615,
"text": "\n 13 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 5664,
"s": 5650,
"text": " Sanjay Kumar"
},
{
"code": null,
"e": 5699,
"s": 5664,
"text": "\n 24 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 5713,
"s": 5699,
"text": " Sanjay Kumar"
},
{
"code": null,
"e": 5746,
"s": 5713,
"text": "\n 47 Lectures \n 3 hours \n"
},
{
"code": null,
"e": 5764,
"s": 5746,
"text": " Krishna Sakinala"
},
{
"code": null,
"e": 5771,
"s": 5764,
"text": " Print"
},
{
"code": null,
"e": 5782,
"s": 5771,
"text": " Add Notes"
}
] |
3 tips to handle timestamps in C. A concise guide to deal with time zones | by Mario Emmanuel | Towards Data Science
|
Whoever has handled timestamps with timezones in time series analysis has always faced some headache. No matter how many times I deal with time series, which in my case invariantly involves dealing with time zones, I always have to revisit how it works because it is often counter-intuitive.
Working with time series often involves dealing with different timezones. Even working with just one time zone, you might still want to visualise data in your local time zone, which might change depending on the country of the user.
This situation makes it convenient to use UTC as a reference. Why? Because it does not experience daylight saving changes and it is easy to convert to any timezone.
In terms of how can you represent a timestamp it can either be:
language specific date-time objects,
human-readable format based on integers (i.e. 20210126 for dates, 1530 for time),
human-readable text format (i.e. 1999–01–01T00:00:29.75),
UNIX Epoch time.
I prefer the latest because it simplifies the arithmetic of time. To iterate one minute you just have to increase 60 to whatever time cursor you are handling. It also defines a moment in time with precision. If you have hundreds of Gb or Tb of data, a purely numeric representation is the way to go.
I will present examples for this case, all the examples can be found in the documentation and Q&A forums — there is nothing new or exotic presented here — , but this information is often buried in other explanations, and often something as simple as converting a specific localised timestamp to UNIX Epoch and the opposite is not as simple to find as it shall be.
If you say, it is March 28th 2021 09:30 and you think you are done, you are wrong. The subsequent answer is, ok, it is March 28th 2021 09:30, but where? Every timestamp must have a location or time zone, implicit (can be by convention — all timestamps in this database use Frankfurt time — ) or explicit. So if you deliver data, do yourself and others a favour, do the exercise of explicitly stating the time zone of the timestamps included. This might be obvious but I assure you that more than half of the data sets I have seen involving timestamps lack this information.
The first mistake I find when approaching the problem is that it is easy to mix concepts. You will often hear things like “Frankfurt is ahead 5 hours of New York”, or “New York time zone is EST” which are wrong.
Frankfurt is sometimes 5 hours ahead of New York but in others it is 6, and when that happens depends on the specific year you are dealing with.
New York is not EST, New York is EST half of the year, being the other half EDT. When the transition happens vary year to year and the transitions could even disappear in the near future.
EST is not Eastern Time but Eastern Standard Time (and definitely is not “Easter Time” as I heard once). If you want to say Eastern Time that is ET.
It is ok to make such mistakes as we all began there but those need to be fixed soon otherwise you will be doing the wrong calculations.
The simplest way I have found to deal with time series associated with a particular location (in my industry, financial data traded in a given exchange) is to deal with the actual region/city. So saying “time in New York” implies that it would be EST or EDT depending on the specific year and day of the year, but the timestamp is properly defined. It is also often the right way to store data as many events take place at a given time no matter what. Stock exchanges normally open at 9:30 every day and you do the school run for your kid at the same time in the afternoon every day, they do not modify it depending on if daylight saving is observed or not.
Specifying a time zone might not uniquely define a moment in time as during the daylight adjustments it might be not clear what is the exact moment in time you are specifying, but it happens that all daylight adjustments take place during a weekend. If your data lacks weekends (such as it happens in data coming from many business-related fields) then you do not care about this detail.
If the daylight change is important because your data can take place during the weekend, then you are forced to use UTC always, as it does not experience any changes. That is why the military uses Zulu time because it is a shared global way to specify a moment in time.
Tip 1: when you specify a timestamps always specify which specific location (city) that time belongs to. If your time series involve weekends, use UTC.
The UNIX epoch time is defined as the number of seconds passed since January 1st, 1970 at 00:00 UTC. Notice that UNIX Epoch is UTC so it identifies without errors a specific moment in time. Never ask about the timezone of a UNIX epoch timestamp, it is UTC by definition.
A specific caveat about UNIX epoch are leap seconds, but unless you have to deal with leap seconds, UNIX epoch is fine. Bear in mind also that UNIX epoch can represent times up to 2038 timestamps when using 32 bits signed integers. See [1] for details, but normally these limitations will have no impact on your application.
Tip 2: UNIX epoch timestamps are a convenient way to store a given moment in time, they are normally accurate enough and they allow to do simple things such as adding 60 to get the next minute. They are efficient too as only 4 bytes can be used to store a timestamp. Being UTC by definition, there is no need to communicate the time zone and you always know how to convert that timestamp into any time zone.
The precision given by UNIX epoch is one second, although alternate version handling milliseconds are often used.
We will begin reviewing how C can handle timezones and timestamps. In C the standard never covered different timezones but it has somehow been covered in all UNIX systems since the 80s.
A UNIX Epoch time can be stored using a 32 bits integer, in the standard the type is time_t which has traditionally being an integer. The standard does not define a specific type (in my 64 bits FreeBSD box using clang is a long).
So if you want to specify a UNIX Epoch this is what you do:
/* 1616927900 Epoch is Sunday, 28 March 2021 10:38:20 GMT 1616927900 Epoch is Sunday March 28, 2021 06:38:20 (am) in time zone America/New York (EDT)*/time_t epoch_time = 1616927900;
In POSIX systems (all UNIX/Linux/BSD systems), you can convert this into any timestamp with timezone using TZ variable. Imagine that you want to know what time is that specific UNIX Epoch in New York. Then you do:
/* 1616927900 Epoch is Sunday, 28 March 2021 10:38:20 GMT 1616927900 Epoch is Sunday March 28, 2021 06:38:20 (am) in time zone America/New York (EDT)*/time_t epoch_time = 1616927900;/* CONVERT TO struct tm */struct tm *converted_time;converted_time = localtime(&epoch_time);/* GET SYSTEM TIME ZONE */tzset();/* DISPLAY TIME */char buffer[26];strftime(buffer, 26, "%Y-%m-%d %H:%M:%S", converted_time);printf("Timestamp for %ld is %s according to system timezone.\n", epoch_time, buffer);/* DISPLAY TIME ZONE */printf("Timezone for %ld is %s.\n", epoch_time, tzname[converted_time->tm_isdst]);---$ TZ='America/New_York' ./testTimestamp for 1616927900 is 2021-03-28 06:38:20 according to system timezone.Timezone for 1616927900 is EDT.
The struct tm has a field named tm_isdst which can be -1, 0 or 1.
-1 is used when you specify a given timestamp (I will cover that case later), 0 will mean that daylight saving is not being observed and 1 means that daylight saving is being observed.
tzset will retrieve the specific zone of the computer, localtime will use it to fill tm_isdst when using localtime , so that field of the struct gives you the right struct. tzset also sets the extern array tzname which can be used to get the time zone name.
If you want to use a different timezone than the one you system uses you have two options:
you can precede your program with the right TZ variable: $TZ='America/New_York' ./my_program . This is not part of C but just how a UNIX shell works to customize the environment when invoking a command.you can explicitly set the TZ variable with putenv("TZ=America/New_York"); before invoking tzset .
you can precede your program with the right TZ variable: $TZ='America/New_York' ./my_program . This is not part of C but just how a UNIX shell works to customize the environment when invoking a command.
you can explicitly set the TZ variable with putenv("TZ=America/New_York"); before invoking tzset .
If you want to do the opposite, i.e. getting the UNIX Epoch of a given localised timestamp (the question would be: which is the UNIX Epoch that corresponds to Sunday March 28, 2021 06:38:20 in New York?) this is the code you would use:
/* 1616927900 Epoch is Sunday, 28 March 2021 10:38:20 GMT 1616927900 Epoch is Sunday March 28, 2021 06:38:20 (am) in time zone America/New York (EDT)*//* GET SYSTEM TIME ZONE, MUST BE NEW YORK */tzset();/* DEFINE THE TIMESTAMP struct tm */struct tm localised_time;localised_time.tm_year = 2021 - 1900;localised_time.tm_mon = 3 - 1;localised_time.tm_mday = 28;localised_time.tm_hour = 6;localised_time.tm_min = 38;localised_time.tm_sec = 20;localised_time.tm_isdst = -1;time_t epoch_time = mktime(&localised_time);/* NOTICE HOW mktime FIXES tm_isdst */printf("Fixed tm_isdst is %d.\n", localised_time.tm_isdst);/* DISPLAY TIME ZONE */printf("Timezone is %s.\n", tzname[localised_time.tm_isdst]);/* DISPLAY EPOCH */printf("Epoch timestamp is %ld.\n", epoch_time);---$ TZ='America/New_York' ./test2Fixed tm_isdst is 1.Timezone is EDT.Epoch timestamp is 1616927900.
Notice that in the struct tm year is specified as the number of years since 1900 and that month is 0 for January. We use -1 for tm_isdst and mktime uses the time zone retrieved by tzset to fix this value and determine if it was EDT or EST at that day and time in New York.
This obviously only works if your computer is in America New York timezone or if you explicitly set or pass TZ to the program. Also notice that this will not work for Microsoft Windows.
Tip 3: In C UNIX/POSIX timezone resources and basic struct tm, mktime and localtime functions can be used to handle timezones. It works very well for most cases and it works with every C/C++ standard out of the box.
I use these simple recipes in C to handle timezones with success. There might be other cases where this simplicity might not be enough.
C++ has other alternatives to cope with timezones, the most relevant ones being the chrono [2] library part of the C++20 standard (the library can be also compiled for older standards). Boost [3] also includes a library to handle timezones, but apparently, it lacks some time zones or has limitations — I have not tried it — . There is also the ICU library [4] to handle localisation which seems to be exhaustive and complete and many other open source solutions. The problem with all those is that you add another dependency to your system and I did not find them straightforward to use.
I found the above method simple enough for my needs but it only works well for UNIX systems. It works for any C/C++ standard.
|
[
{
"code": null,
"e": 464,
"s": 172,
"text": "Whoever has handled timestamps with timezones in time series analysis has always faced some headache. No matter how many times I deal with time series, which in my case invariantly involves dealing with time zones, I always have to revisit how it works because it is often counter-intuitive."
},
{
"code": null,
"e": 697,
"s": 464,
"text": "Working with time series often involves dealing with different timezones. Even working with just one time zone, you might still want to visualise data in your local time zone, which might change depending on the country of the user."
},
{
"code": null,
"e": 862,
"s": 697,
"text": "This situation makes it convenient to use UTC as a reference. Why? Because it does not experience daylight saving changes and it is easy to convert to any timezone."
},
{
"code": null,
"e": 926,
"s": 862,
"text": "In terms of how can you represent a timestamp it can either be:"
},
{
"code": null,
"e": 963,
"s": 926,
"text": "language specific date-time objects,"
},
{
"code": null,
"e": 1045,
"s": 963,
"text": "human-readable format based on integers (i.e. 20210126 for dates, 1530 for time),"
},
{
"code": null,
"e": 1103,
"s": 1045,
"text": "human-readable text format (i.e. 1999–01–01T00:00:29.75),"
},
{
"code": null,
"e": 1120,
"s": 1103,
"text": "UNIX Epoch time."
},
{
"code": null,
"e": 1420,
"s": 1120,
"text": "I prefer the latest because it simplifies the arithmetic of time. To iterate one minute you just have to increase 60 to whatever time cursor you are handling. It also defines a moment in time with precision. If you have hundreds of Gb or Tb of data, a purely numeric representation is the way to go."
},
{
"code": null,
"e": 1784,
"s": 1420,
"text": "I will present examples for this case, all the examples can be found in the documentation and Q&A forums — there is nothing new or exotic presented here — , but this information is often buried in other explanations, and often something as simple as converting a specific localised timestamp to UNIX Epoch and the opposite is not as simple to find as it shall be."
},
{
"code": null,
"e": 2358,
"s": 1784,
"text": "If you say, it is March 28th 2021 09:30 and you think you are done, you are wrong. The subsequent answer is, ok, it is March 28th 2021 09:30, but where? Every timestamp must have a location or time zone, implicit (can be by convention — all timestamps in this database use Frankfurt time — ) or explicit. So if you deliver data, do yourself and others a favour, do the exercise of explicitly stating the time zone of the timestamps included. This might be obvious but I assure you that more than half of the data sets I have seen involving timestamps lack this information."
},
{
"code": null,
"e": 2570,
"s": 2358,
"text": "The first mistake I find when approaching the problem is that it is easy to mix concepts. You will often hear things like “Frankfurt is ahead 5 hours of New York”, or “New York time zone is EST” which are wrong."
},
{
"code": null,
"e": 2715,
"s": 2570,
"text": "Frankfurt is sometimes 5 hours ahead of New York but in others it is 6, and when that happens depends on the specific year you are dealing with."
},
{
"code": null,
"e": 2903,
"s": 2715,
"text": "New York is not EST, New York is EST half of the year, being the other half EDT. When the transition happens vary year to year and the transitions could even disappear in the near future."
},
{
"code": null,
"e": 3052,
"s": 2903,
"text": "EST is not Eastern Time but Eastern Standard Time (and definitely is not “Easter Time” as I heard once). If you want to say Eastern Time that is ET."
},
{
"code": null,
"e": 3189,
"s": 3052,
"text": "It is ok to make such mistakes as we all began there but those need to be fixed soon otherwise you will be doing the wrong calculations."
},
{
"code": null,
"e": 3847,
"s": 3189,
"text": "The simplest way I have found to deal with time series associated with a particular location (in my industry, financial data traded in a given exchange) is to deal with the actual region/city. So saying “time in New York” implies that it would be EST or EDT depending on the specific year and day of the year, but the timestamp is properly defined. It is also often the right way to store data as many events take place at a given time no matter what. Stock exchanges normally open at 9:30 every day and you do the school run for your kid at the same time in the afternoon every day, they do not modify it depending on if daylight saving is observed or not."
},
{
"code": null,
"e": 4235,
"s": 3847,
"text": "Specifying a time zone might not uniquely define a moment in time as during the daylight adjustments it might be not clear what is the exact moment in time you are specifying, but it happens that all daylight adjustments take place during a weekend. If your data lacks weekends (such as it happens in data coming from many business-related fields) then you do not care about this detail."
},
{
"code": null,
"e": 4505,
"s": 4235,
"text": "If the daylight change is important because your data can take place during the weekend, then you are forced to use UTC always, as it does not experience any changes. That is why the military uses Zulu time because it is a shared global way to specify a moment in time."
},
{
"code": null,
"e": 4657,
"s": 4505,
"text": "Tip 1: when you specify a timestamps always specify which specific location (city) that time belongs to. If your time series involve weekends, use UTC."
},
{
"code": null,
"e": 4928,
"s": 4657,
"text": "The UNIX epoch time is defined as the number of seconds passed since January 1st, 1970 at 00:00 UTC. Notice that UNIX Epoch is UTC so it identifies without errors a specific moment in time. Never ask about the timezone of a UNIX epoch timestamp, it is UTC by definition."
},
{
"code": null,
"e": 5253,
"s": 4928,
"text": "A specific caveat about UNIX epoch are leap seconds, but unless you have to deal with leap seconds, UNIX epoch is fine. Bear in mind also that UNIX epoch can represent times up to 2038 timestamps when using 32 bits signed integers. See [1] for details, but normally these limitations will have no impact on your application."
},
{
"code": null,
"e": 5661,
"s": 5253,
"text": "Tip 2: UNIX epoch timestamps are a convenient way to store a given moment in time, they are normally accurate enough and they allow to do simple things such as adding 60 to get the next minute. They are efficient too as only 4 bytes can be used to store a timestamp. Being UTC by definition, there is no need to communicate the time zone and you always know how to convert that timestamp into any time zone."
},
{
"code": null,
"e": 5775,
"s": 5661,
"text": "The precision given by UNIX epoch is one second, although alternate version handling milliseconds are often used."
},
{
"code": null,
"e": 5961,
"s": 5775,
"text": "We will begin reviewing how C can handle timezones and timestamps. In C the standard never covered different timezones but it has somehow been covered in all UNIX systems since the 80s."
},
{
"code": null,
"e": 6191,
"s": 5961,
"text": "A UNIX Epoch time can be stored using a 32 bits integer, in the standard the type is time_t which has traditionally being an integer. The standard does not define a specific type (in my 64 bits FreeBSD box using clang is a long)."
},
{
"code": null,
"e": 6251,
"s": 6191,
"text": "So if you want to specify a UNIX Epoch this is what you do:"
},
{
"code": null,
"e": 6437,
"s": 6251,
"text": "/* 1616927900 Epoch is Sunday, 28 March 2021 10:38:20 GMT 1616927900 Epoch is Sunday March 28, 2021 06:38:20 (am) in time zone America/New York (EDT)*/time_t epoch_time = 1616927900;"
},
{
"code": null,
"e": 6651,
"s": 6437,
"text": "In POSIX systems (all UNIX/Linux/BSD systems), you can convert this into any timestamp with timezone using TZ variable. Imagine that you want to know what time is that specific UNIX Epoch in New York. Then you do:"
},
{
"code": null,
"e": 7387,
"s": 6651,
"text": "/* 1616927900 Epoch is Sunday, 28 March 2021 10:38:20 GMT 1616927900 Epoch is Sunday March 28, 2021 06:38:20 (am) in time zone America/New York (EDT)*/time_t epoch_time = 1616927900;/* CONVERT TO struct tm */struct tm *converted_time;converted_time = localtime(&epoch_time);/* GET SYSTEM TIME ZONE */tzset();/* DISPLAY TIME */char buffer[26];strftime(buffer, 26, \"%Y-%m-%d %H:%M:%S\", converted_time);printf(\"Timestamp for %ld is %s according to system timezone.\\n\", epoch_time, buffer);/* DISPLAY TIME ZONE */printf(\"Timezone for %ld is %s.\\n\", epoch_time, tzname[converted_time->tm_isdst]);---$ TZ='America/New_York' ./testTimestamp for 1616927900 is 2021-03-28 06:38:20 according to system timezone.Timezone for 1616927900 is EDT."
},
{
"code": null,
"e": 7453,
"s": 7387,
"text": "The struct tm has a field named tm_isdst which can be -1, 0 or 1."
},
{
"code": null,
"e": 7638,
"s": 7453,
"text": "-1 is used when you specify a given timestamp (I will cover that case later), 0 will mean that daylight saving is not being observed and 1 means that daylight saving is being observed."
},
{
"code": null,
"e": 7896,
"s": 7638,
"text": "tzset will retrieve the specific zone of the computer, localtime will use it to fill tm_isdst when using localtime , so that field of the struct gives you the right struct. tzset also sets the extern array tzname which can be used to get the time zone name."
},
{
"code": null,
"e": 7987,
"s": 7896,
"text": "If you want to use a different timezone than the one you system uses you have two options:"
},
{
"code": null,
"e": 8288,
"s": 7987,
"text": "you can precede your program with the right TZ variable: $TZ='America/New_York' ./my_program . This is not part of C but just how a UNIX shell works to customize the environment when invoking a command.you can explicitly set the TZ variable with putenv(\"TZ=America/New_York\"); before invoking tzset ."
},
{
"code": null,
"e": 8491,
"s": 8288,
"text": "you can precede your program with the right TZ variable: $TZ='America/New_York' ./my_program . This is not part of C but just how a UNIX shell works to customize the environment when invoking a command."
},
{
"code": null,
"e": 8590,
"s": 8491,
"text": "you can explicitly set the TZ variable with putenv(\"TZ=America/New_York\"); before invoking tzset ."
},
{
"code": null,
"e": 8826,
"s": 8590,
"text": "If you want to do the opposite, i.e. getting the UNIX Epoch of a given localised timestamp (the question would be: which is the UNIX Epoch that corresponds to Sunday March 28, 2021 06:38:20 in New York?) this is the code you would use:"
},
{
"code": null,
"e": 9691,
"s": 8826,
"text": "/* 1616927900 Epoch is Sunday, 28 March 2021 10:38:20 GMT 1616927900 Epoch is Sunday March 28, 2021 06:38:20 (am) in time zone America/New York (EDT)*//* GET SYSTEM TIME ZONE, MUST BE NEW YORK */tzset();/* DEFINE THE TIMESTAMP struct tm */struct tm localised_time;localised_time.tm_year = 2021 - 1900;localised_time.tm_mon = 3 - 1;localised_time.tm_mday = 28;localised_time.tm_hour = 6;localised_time.tm_min = 38;localised_time.tm_sec = 20;localised_time.tm_isdst = -1;time_t epoch_time = mktime(&localised_time);/* NOTICE HOW mktime FIXES tm_isdst */printf(\"Fixed tm_isdst is %d.\\n\", localised_time.tm_isdst);/* DISPLAY TIME ZONE */printf(\"Timezone is %s.\\n\", tzname[localised_time.tm_isdst]);/* DISPLAY EPOCH */printf(\"Epoch timestamp is %ld.\\n\", epoch_time);---$ TZ='America/New_York' ./test2Fixed tm_isdst is 1.Timezone is EDT.Epoch timestamp is 1616927900."
},
{
"code": null,
"e": 9964,
"s": 9691,
"text": "Notice that in the struct tm year is specified as the number of years since 1900 and that month is 0 for January. We use -1 for tm_isdst and mktime uses the time zone retrieved by tzset to fix this value and determine if it was EDT or EST at that day and time in New York."
},
{
"code": null,
"e": 10150,
"s": 9964,
"text": "This obviously only works if your computer is in America New York timezone or if you explicitly set or pass TZ to the program. Also notice that this will not work for Microsoft Windows."
},
{
"code": null,
"e": 10366,
"s": 10150,
"text": "Tip 3: In C UNIX/POSIX timezone resources and basic struct tm, mktime and localtime functions can be used to handle timezones. It works very well for most cases and it works with every C/C++ standard out of the box."
},
{
"code": null,
"e": 10502,
"s": 10366,
"text": "I use these simple recipes in C to handle timezones with success. There might be other cases where this simplicity might not be enough."
},
{
"code": null,
"e": 11091,
"s": 10502,
"text": "C++ has other alternatives to cope with timezones, the most relevant ones being the chrono [2] library part of the C++20 standard (the library can be also compiled for older standards). Boost [3] also includes a library to handle timezones, but apparently, it lacks some time zones or has limitations — I have not tried it — . There is also the ICU library [4] to handle localisation which seems to be exhaustive and complete and many other open source solutions. The problem with all those is that you add another dependency to your system and I did not find them straightforward to use."
}
] |
MySQL - Clone Tables
|
There may be a situation when you need an exact copy of a table and CREATE TABLE ... SELECT doesn't suit your purposes because the copy must include the same indexes, default values and so forth.
You can handle this situation by following the steps given below −
Use SHOW CREATE TABLE to get a CREATE TABLE statement that specifies the source table's structure, indexes and all.
Use SHOW CREATE TABLE to get a CREATE TABLE statement that specifies the source table's structure, indexes and all.
Modify the statement to change the table name to that of the clone table and execute the statement. This way, you will have the exact clone table.
Modify the statement to change the table name to that of the clone table and execute the statement. This way, you will have the exact clone table.
Optionally, if you need the table contents copied as well, issue an INSERT INTO ... SELECT statement, too.
Optionally, if you need the table contents copied as well, issue an INSERT INTO ... SELECT statement, too.
Try out the following example to create a clone table for tutorials_tbl.
Step 1 − Get the complete structure about the table.
mysql> SHOW CREATE TABLE tutorials_tbl \G;
*************************** 1. row ***************************
Table: tutorials_tbl
Create Table: CREATE TABLE `tutorials_tbl` (
`tutorial_id` int(11) NOT NULL auto_increment,
`tutorial_title` varchar(100) NOT NULL default '',
`tutorial_author` varchar(40) NOT NULL default '',
`submission_date` date default NULL,
PRIMARY KEY (`tutorial_id`),
UNIQUE KEY `AUTHOR_INDEX` (`tutorial_author`)
) TYPE = MyISAM
1 row in set (0.00 sec)
ERROR:
No query specified
Step 2 − Rename this table and create another table.
mysql> CREATE TABLE clone_tbl (
-> tutorial_id int(11) NOT NULL auto_increment,
-> tutorial_title varchar(100) NOT NULL default '',
-> tutorial_author varchar(40) NOT NULL default '',
-> submission_date date default NULL,
-> PRIMARY KEY (tutorial_id),
-> UNIQUE KEY AUTHOR_INDEX (tutorial_author)
-> ) TYPE = MyISAM;
Query OK, 0 rows affected (1.80 sec)
Step 3 − After executing step 2, you will create a clone table in your database. If you want to copy data from old table then you can do it by using INSERT INTO... SELECT statement.
mysql> INSERT INTO clone_tbl (tutorial_id,
-> tutorial_title,
-> tutorial_author,
-> submission_date)
-> SELECT tutorial_id,tutorial_title,
-> tutorial_author,submission_date
-> FROM tutorials_tbl;
Query OK, 3 rows affected (0.07 sec)
Records: 3 Duplicates: 0 Warnings: 0
Finally, you will have an exact clone table as you wanted to have.
31 Lectures
6 hours
Eduonix Learning Solutions
84 Lectures
5.5 hours
Frahaan Hussain
6 Lectures
3.5 hours
DATAhill Solutions Srinivas Reddy
60 Lectures
10 hours
Vijay Kumar Parvatha Reddy
10 Lectures
1 hours
Harshit Srivastava
25 Lectures
4 hours
Trevoir Williams
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2529,
"s": 2333,
"text": "There may be a situation when you need an exact copy of a table and CREATE TABLE ... SELECT doesn't suit your purposes because the copy must include the same indexes, default values and so forth."
},
{
"code": null,
"e": 2596,
"s": 2529,
"text": "You can handle this situation by following the steps given below −"
},
{
"code": null,
"e": 2712,
"s": 2596,
"text": "Use SHOW CREATE TABLE to get a CREATE TABLE statement that specifies the source table's structure, indexes and all."
},
{
"code": null,
"e": 2828,
"s": 2712,
"text": "Use SHOW CREATE TABLE to get a CREATE TABLE statement that specifies the source table's structure, indexes and all."
},
{
"code": null,
"e": 2975,
"s": 2828,
"text": "Modify the statement to change the table name to that of the clone table and execute the statement. This way, you will have the exact clone table."
},
{
"code": null,
"e": 3122,
"s": 2975,
"text": "Modify the statement to change the table name to that of the clone table and execute the statement. This way, you will have the exact clone table."
},
{
"code": null,
"e": 3229,
"s": 3122,
"text": "Optionally, if you need the table contents copied as well, issue an INSERT INTO ... SELECT statement, too."
},
{
"code": null,
"e": 3336,
"s": 3229,
"text": "Optionally, if you need the table contents copied as well, issue an INSERT INTO ... SELECT statement, too."
},
{
"code": null,
"e": 3409,
"s": 3336,
"text": "Try out the following example to create a clone table for tutorials_tbl."
},
{
"code": null,
"e": 3462,
"s": 3409,
"text": "Step 1 − Get the complete structure about the table."
},
{
"code": null,
"e": 3987,
"s": 3462,
"text": "mysql> SHOW CREATE TABLE tutorials_tbl \\G;\n*************************** 1. row ***************************\n Table: tutorials_tbl\nCreate Table: CREATE TABLE `tutorials_tbl` (\n `tutorial_id` int(11) NOT NULL auto_increment,\n `tutorial_title` varchar(100) NOT NULL default '',\n `tutorial_author` varchar(40) NOT NULL default '',\n `submission_date` date default NULL,\n PRIMARY KEY (`tutorial_id`),\n UNIQUE KEY `AUTHOR_INDEX` (`tutorial_author`)\n) TYPE = MyISAM\n1 row in set (0.00 sec)\n\nERROR:\nNo query specified"
},
{
"code": null,
"e": 4040,
"s": 3987,
"text": "Step 2 − Rename this table and create another table."
},
{
"code": null,
"e": 4413,
"s": 4040,
"text": "mysql> CREATE TABLE clone_tbl (\n -> tutorial_id int(11) NOT NULL auto_increment,\n -> tutorial_title varchar(100) NOT NULL default '',\n -> tutorial_author varchar(40) NOT NULL default '',\n -> submission_date date default NULL,\n -> PRIMARY KEY (tutorial_id),\n -> UNIQUE KEY AUTHOR_INDEX (tutorial_author)\n-> ) TYPE = MyISAM;\nQuery OK, 0 rows affected (1.80 sec)"
},
{
"code": null,
"e": 4595,
"s": 4413,
"text": "Step 3 − After executing step 2, you will create a clone table in your database. If you want to copy data from old table then you can do it by using INSERT INTO... SELECT statement."
},
{
"code": null,
"e": 4891,
"s": 4595,
"text": "mysql> INSERT INTO clone_tbl (tutorial_id,\n -> tutorial_title,\n -> tutorial_author,\n -> submission_date)\n \n -> SELECT tutorial_id,tutorial_title,\n -> tutorial_author,submission_date\n -> FROM tutorials_tbl;\nQuery OK, 3 rows affected (0.07 sec)\nRecords: 3 Duplicates: 0 Warnings: 0"
},
{
"code": null,
"e": 4958,
"s": 4891,
"text": "Finally, you will have an exact clone table as you wanted to have."
},
{
"code": null,
"e": 4991,
"s": 4958,
"text": "\n 31 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 5019,
"s": 4991,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 5054,
"s": 5019,
"text": "\n 84 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 5071,
"s": 5054,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 5105,
"s": 5071,
"text": "\n 6 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 5140,
"s": 5105,
"text": " DATAhill Solutions Srinivas Reddy"
},
{
"code": null,
"e": 5174,
"s": 5140,
"text": "\n 60 Lectures \n 10 hours \n"
},
{
"code": null,
"e": 5202,
"s": 5174,
"text": " Vijay Kumar Parvatha Reddy"
},
{
"code": null,
"e": 5235,
"s": 5202,
"text": "\n 10 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 5255,
"s": 5235,
"text": " Harshit Srivastava"
},
{
"code": null,
"e": 5288,
"s": 5255,
"text": "\n 25 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 5306,
"s": 5288,
"text": " Trevoir Williams"
},
{
"code": null,
"e": 5313,
"s": 5306,
"text": " Print"
},
{
"code": null,
"e": 5324,
"s": 5313,
"text": " Add Notes"
}
] |
Android Custom Component with Custom Attributes
|
Following example shows you how to define a simple Android custom component with custom attributes.
Following is the content of the modified main activity file src/com.example.dateviewdemo/MainActivity.java. This file can include each of the fundamental lifecycle methods.
package com.example.dateviewdemo;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the
// action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
Following will be the content of res/values/attrs.xml file −
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="DateView">
<attr name="delimiter" format="string"/>
<attr name="fancyText" format="boolean"/>
</declare-styleable>
</resources>
Following will be the content of new file src/com.example.dateviewdemo/DateView.java, which will have additional functionality to show current date −
package com.example.dateviewdemo;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Color;
import android.util.AttributeSet;
import android.util.Log;
import android.widget.TextView;
public class DateView extends TextView {
public String delimiter;
public boolean fancyText;
public DateView(Context context) {
super(context);
setDate();
}
public DateView(Context context, AttributeSet attrs) {
super(context, attrs);
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.DateView );
final int N = a.getIndexCount();
for (int i = 0; i < N; ++i) {
int attr = a.getIndex(i);
switch (attr) {
case R.styleable.DateView_delimiter:
delimiter = a.getString(attr);
setDate();
break;
case R.styleable.DateView_fancyText:
fancyText = a.getBoolean(attr, false);
fancyText();
break;
}
}
a.recycle();
}
public DateView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
setDate();
}
private void setDate() {
SimpleDateFormat dateFormat =
new SimpleDateFormat("yyyy" + delimiter + "MM" + delimiter + "dd");
String today = dateFormat.format(Calendar.getInstance().getTime());
setText(today); // self = DateView = subclass of TextView
}
private void fancyText() {
if( this.fancyText){
setShadowLayer(9, 1, 1, Color.rgb(44, 44, 40));
}
}
}
Following will be the content of res/layout/activity_main.xml file −
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:custom="http://schemas.android.com/apk/res/com.example.dateviewdemo"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<com.example.dateviewdemo.DateView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColor="#fff"
android:textSize="40sp"
custom:delimiter="-"
custom:fancyText="true"
>
</RelativeLayout>
Following will be the content of res/values/strings.xml to define two new constants −
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">DateViewDemo</string>
<string name="action_settings">Settings</string>
<string name="hello_world">Hello world!</string>
</resources>
Following is the default content of AndroidManifest.xml −
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.guidemo"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="22" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.example.guidemo.MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Let's try to run your DateViewDemo application. I assume you had created your AVD while doing environment setup. To run the app from Android Studio, open one of your project's activity files and click Run icon from the toolbar. Android studio installs the app on your AVD and starts it and if everything is fine with your setup and application, it will display following Emulator window −
46 Lectures
7.5 hours
Aditya Dua
32 Lectures
3.5 hours
Sharad Kumar
9 Lectures
1 hours
Abhilash Nelson
14 Lectures
1.5 hours
Abhilash Nelson
15 Lectures
1.5 hours
Abhilash Nelson
10 Lectures
1 hours
Abhilash Nelson
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 3707,
"s": 3607,
"text": "Following example shows you how to define a simple Android custom component with custom attributes."
},
{
"code": null,
"e": 3880,
"s": 3707,
"text": "Following is the content of the modified main activity file src/com.example.dateviewdemo/MainActivity.java. This file can include each of the fundamental lifecycle methods."
},
{
"code": null,
"e": 4439,
"s": 3880,
"text": "package com.example.dateviewdemo;\n\nimport android.os.Bundle;\nimport android.app.Activity;\nimport android.view.Menu;\n\npublic class MainActivity extends Activity {\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n }\n \n @Override\n public boolean onCreateOptionsMenu(Menu menu) {\n // Inflate the menu; this adds items to the \n // action bar if it is present.\n getMenuInflater().inflate(R.menu.main, menu);\n return true;\n }\n}"
},
{
"code": null,
"e": 4500,
"s": 4439,
"text": "Following will be the content of res/values/attrs.xml file −"
},
{
"code": null,
"e": 4716,
"s": 4500,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<resources>\n <declare-styleable name=\"DateView\">\n <attr name=\"delimiter\" format=\"string\"/>\n <attr name=\"fancyText\" format=\"boolean\"/>\n </declare-styleable>\n</resources>"
},
{
"code": null,
"e": 4866,
"s": 4716,
"text": "Following will be the content of new file src/com.example.dateviewdemo/DateView.java, which will have additional functionality to show current date −"
},
{
"code": null,
"e": 6533,
"s": 4866,
"text": "package com.example.dateviewdemo;\n\nimport java.text.SimpleDateFormat;\nimport java.util.Calendar;\n\nimport android.content.Context;\nimport android.content.res.TypedArray;\nimport android.graphics.Color;\nimport android.util.AttributeSet;\nimport android.util.Log;\nimport android.widget.TextView;\n\npublic class DateView extends TextView {\n public String delimiter;\n public boolean fancyText;\n \n public DateView(Context context) {\n super(context);\n setDate();\n }\n \n public DateView(Context context, AttributeSet attrs) {\n super(context, attrs);\n TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.DateView );\n final int N = a.getIndexCount();\n for (int i = 0; i < N; ++i) {\n int attr = a.getIndex(i);\n switch (attr) {\n case R.styleable.DateView_delimiter:\n delimiter = a.getString(attr);\n setDate();\n break;\n \n case R.styleable.DateView_fancyText:\n fancyText = a.getBoolean(attr, false);\n fancyText();\n break;\n }\n }\n a.recycle();\n }\n\n public DateView(Context context, AttributeSet attrs, int defStyle) {\n super(context, attrs, defStyle);\n setDate();\n }\n\n private void setDate() {\n SimpleDateFormat dateFormat = \n new SimpleDateFormat(\"yyyy\" + delimiter + \"MM\" + delimiter + \"dd\");\n String today = dateFormat.format(Calendar.getInstance().getTime());\n setText(today); // self = DateView = subclass of TextView\n }\n\n private void fancyText() {\n if( this.fancyText){\n setShadowLayer(9, 1, 1, Color.rgb(44, 44, 40));\n }\n }\n}"
},
{
"code": null,
"e": 6602,
"s": 6533,
"text": "Following will be the content of res/layout/activity_main.xml file −"
},
{
"code": null,
"e": 7432,
"s": 6602,
"text": "<RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n xmlns:tools=\"http://schemas.android.com/tools\"\n xmlns:custom=\"http://schemas.android.com/apk/res/com.example.dateviewdemo\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n android:paddingBottom=\"@dimen/activity_vertical_margin\"\n android:paddingLeft=\"@dimen/activity_horizontal_margin\"\n android:paddingRight=\"@dimen/activity_horizontal_margin\"\n android:paddingTop=\"@dimen/activity_vertical_margin\"\n tools:context=\".MainActivity\" >\n \n <com.example.dateviewdemo.DateView\n android:layout_width=\"match_parent\"\n android:layout_height=\"wrap_content\" \n android:textColor=\"#fff\"\n android:textSize=\"40sp\"\n custom:delimiter=\"-\"\n custom:fancyText=\"true\"\n >\n \n</RelativeLayout>"
},
{
"code": null,
"e": 7518,
"s": 7432,
"text": "Following will be the content of res/values/strings.xml to define two new constants −"
},
{
"code": null,
"e": 7735,
"s": 7518,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<resources>\n <string name=\"app_name\">DateViewDemo</string>\n <string name=\"action_settings\">Settings</string>\n <string name=\"hello_world\">Hello world!</string>\n</resources>"
},
{
"code": null,
"e": 7793,
"s": 7735,
"text": "Following is the default content of AndroidManifest.xml −"
},
{
"code": null,
"e": 8643,
"s": 7793,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\"\n package=\"com.example.guidemo\"\n android:versionCode=\"1\"\n android:versionName=\"1.0\" >\n \n <uses-sdk\n android:minSdkVersion=\"8\"\n android:targetSdkVersion=\"22\" />\n \n <application\n android:allowBackup=\"true\"\n android:icon=\"@drawable/ic_launcher\"\n android:label=\"@string/app_name\"\n android:theme=\"@style/AppTheme\" >\n \n <activity\n android:name=\"com.example.guidemo.MainActivity\"\n android:label=\"@string/app_name\" >\n \n <intent-filter>\n <action android:name=\"android.intent.action.MAIN\" />\n <category android:name=\"android.intent.category.LAUNCHER\" />\n </intent-filter>\n \n </activity>\n \n </application>\n</manifest>"
},
{
"code": null,
"e": 9033,
"s": 8643,
"text": "Let's try to run your DateViewDemo application. I assume you had created your AVD while doing environment setup. To run the app from Android Studio, open one of your project's activity files and click Run icon from the toolbar. Android studio installs the app on your AVD and starts it and if everything is fine with your setup and application, it will display following Emulator window −"
},
{
"code": null,
"e": 9068,
"s": 9033,
"text": "\n 46 Lectures \n 7.5 hours \n"
},
{
"code": null,
"e": 9080,
"s": 9068,
"text": " Aditya Dua"
},
{
"code": null,
"e": 9115,
"s": 9080,
"text": "\n 32 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 9129,
"s": 9115,
"text": " Sharad Kumar"
},
{
"code": null,
"e": 9161,
"s": 9129,
"text": "\n 9 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 9178,
"s": 9161,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 9213,
"s": 9178,
"text": "\n 14 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 9230,
"s": 9213,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 9265,
"s": 9230,
"text": "\n 15 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 9282,
"s": 9265,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 9315,
"s": 9282,
"text": "\n 10 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 9332,
"s": 9315,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 9339,
"s": 9332,
"text": " Print"
},
{
"code": null,
"e": 9350,
"s": 9339,
"text": " Add Notes"
}
] |
C++ Program for Recursive Bubble Sort - GeeksforGeeks
|
28 Jun, 2021
Background :Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in wrong order.Following is iterative Bubble sort algorithm :
// Iterative Bubble Sort
bubbleSort(arr[], n)
{
for (i = 0; i < n-1; i++)
// Last i elements are already in place
for (j = 0; j arr[j+1])
swap(arr[j], arr[j+1]);
}
Recursion Idea.
Base Case: If array size is 1, return.Do One Pass of normal Bubble Sort. This pass fixes last element of current subarray.Recur for all elements except last of current subarray.
Base Case: If array size is 1, return.
Do One Pass of normal Bubble Sort. This pass fixes last element of current subarray.
Recur for all elements except last of current subarray.
// C/C++ program for recursive implementation// of Bubble sort#include <bits/stdc++.h>using namespace std; // A function to implement bubble sortvoid bubbleSort(int arr[], int n){ // Base case if (n == 1) return; // One pass of bubble sort. After // this pass, the largest element // is moved (or bubbled) to end. for (int i=0; i<n-1; i++) if (arr[i] > arr[i+1]) swap(arr[i], arr[i+1]); // Largest element is fixed, // recur for remaining array bubbleSort(arr, n-1);} /* Function to print an array */void printArray(int arr[], int n){ for (int i=0; i < n; i++) printf("%d ", arr[i]); printf("\n");} // Driver program to test above functionsint main(){ int arr[] = {64, 34, 25, 12, 22, 11, 90}; int n = sizeof(arr)/sizeof(arr[0]); bubbleSort(arr, n); printf("Sorted array : \n"); printArray(arr, n); return 0;}
Please refer complete article on Recursive Bubble Sort for more details!
BubbleSort
C++ Programs
Sorting
Sorting
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Passing a function as a parameter in C++
Const keyword in C++
Program to implement Singly Linked List in C++ using class
cout in C++
Dynamic _Cast in C++
|
[
{
"code": null,
"e": 24631,
"s": 24603,
"text": "\n28 Jun, 2021"
},
{
"code": null,
"e": 24819,
"s": 24631,
"text": "Background :Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in wrong order.Following is iterative Bubble sort algorithm :"
},
{
"code": null,
"e": 25016,
"s": 24819,
"text": "// Iterative Bubble Sort\nbubbleSort(arr[], n)\n{\n for (i = 0; i < n-1; i++) \n\n // Last i elements are already in place \n for (j = 0; j arr[j+1])\n swap(arr[j], arr[j+1]);\n} "
},
{
"code": null,
"e": 25032,
"s": 25016,
"text": "Recursion Idea."
},
{
"code": null,
"e": 25210,
"s": 25032,
"text": "Base Case: If array size is 1, return.Do One Pass of normal Bubble Sort. This pass fixes last element of current subarray.Recur for all elements except last of current subarray."
},
{
"code": null,
"e": 25249,
"s": 25210,
"text": "Base Case: If array size is 1, return."
},
{
"code": null,
"e": 25334,
"s": 25249,
"text": "Do One Pass of normal Bubble Sort. This pass fixes last element of current subarray."
},
{
"code": null,
"e": 25390,
"s": 25334,
"text": "Recur for all elements except last of current subarray."
},
{
"code": "// C/C++ program for recursive implementation// of Bubble sort#include <bits/stdc++.h>using namespace std; // A function to implement bubble sortvoid bubbleSort(int arr[], int n){ // Base case if (n == 1) return; // One pass of bubble sort. After // this pass, the largest element // is moved (or bubbled) to end. for (int i=0; i<n-1; i++) if (arr[i] > arr[i+1]) swap(arr[i], arr[i+1]); // Largest element is fixed, // recur for remaining array bubbleSort(arr, n-1);} /* Function to print an array */void printArray(int arr[], int n){ for (int i=0; i < n; i++) printf(\"%d \", arr[i]); printf(\"\\n\");} // Driver program to test above functionsint main(){ int arr[] = {64, 34, 25, 12, 22, 11, 90}; int n = sizeof(arr)/sizeof(arr[0]); bubbleSort(arr, n); printf(\"Sorted array : \\n\"); printArray(arr, n); return 0;}",
"e": 26290,
"s": 25390,
"text": null
},
{
"code": null,
"e": 26363,
"s": 26290,
"text": "Please refer complete article on Recursive Bubble Sort for more details!"
},
{
"code": null,
"e": 26374,
"s": 26363,
"text": "BubbleSort"
},
{
"code": null,
"e": 26387,
"s": 26374,
"text": "C++ Programs"
},
{
"code": null,
"e": 26395,
"s": 26387,
"text": "Sorting"
},
{
"code": null,
"e": 26403,
"s": 26395,
"text": "Sorting"
},
{
"code": null,
"e": 26501,
"s": 26403,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26510,
"s": 26501,
"text": "Comments"
},
{
"code": null,
"e": 26523,
"s": 26510,
"text": "Old Comments"
},
{
"code": null,
"e": 26564,
"s": 26523,
"text": "Passing a function as a parameter in C++"
},
{
"code": null,
"e": 26585,
"s": 26564,
"text": "Const keyword in C++"
},
{
"code": null,
"e": 26644,
"s": 26585,
"text": "Program to implement Singly Linked List in C++ using class"
},
{
"code": null,
"e": 26656,
"s": 26644,
"text": "cout in C++"
}
] |
How to plot multiple data columns in a DataFrame? - GeeksforGeeks
|
30 Dec, 2021
Prerequisites: Pandas
Python comes with a lot of useful packages such as pandas, matplotlib, numpy etc. To use dataframe, we need pandas library and to plot columns of a dataframe, we require matplotlib. Pandas has a tight integration with Matplotlib. You can plot data directly from your DataFrame using the plot() method.
To plot multiple data columns in single frame we simply have to pass the list of columns to the y argument of the plot function. Given below is aproper approach to do so along with example implementation.
Import module
Create or load data
Convert to dataframe
Using plot() method, specify a single column along X-axis and multiple columns as an array along Y-axis.
Display graph.
Below are few examples which illustrates the above approach to plot multiples data columns in a Dataframe.
Example 1:
Database: Bestsellers
Python3
import pandas as pdimport matplotlib.pyplot as mp # take datadata = pd.read_csv("Bestsellers.csv") # form dataframedata = data.head() df = pd.DataFrame(data, columns=["Name", "Price", "User Rating"]) # plot the dataframedf.plot(x="Name", y=["Price", "User Rating"], kind="bar", figsize=(9, 8)) # print bar graphmp.show()
Output:
Example 2:
Python3
import pandas as pdimport matplotlib.pyplot as mp # data to be plotteddata = [["New York", 8.6, 20], ["Chicago", 2.7, 20], ["Los Angeles", 3.9, 20], ["Philadelphia", 1.5, 20], ["Houston", 2.1, 20]] # form dataframe from datadf = pd.DataFrame(data, columns=["City", "Population(million)", "Year(2020)"]) # plot multiple columns such as population and year from dataframedf.plot(x="City", y=["Population(million)", "Year(2020)"], kind="line", figsize=(10, 10)) # display plotmp.show()
Output:
gulshankumarar231
Picked
Python Pandas-exercise
Python pandas-plotting
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Check if element exists in list in Python
Selecting rows in pandas DataFrame based on conditions
Python | os.path.join() method
Defaultdict in Python
Create a directory in Python
Python | Get unique values from a list
Python | Pandas dataframe.groupby()
|
[
{
"code": null,
"e": 24292,
"s": 24264,
"text": "\n30 Dec, 2021"
},
{
"code": null,
"e": 24314,
"s": 24292,
"text": "Prerequisites: Pandas"
},
{
"code": null,
"e": 24617,
"s": 24314,
"text": "Python comes with a lot of useful packages such as pandas, matplotlib, numpy etc. To use dataframe, we need pandas library and to plot columns of a dataframe, we require matplotlib. Pandas has a tight integration with Matplotlib. You can plot data directly from your DataFrame using the plot() method. "
},
{
"code": null,
"e": 24822,
"s": 24617,
"text": "To plot multiple data columns in single frame we simply have to pass the list of columns to the y argument of the plot function. Given below is aproper approach to do so along with example implementation."
},
{
"code": null,
"e": 24836,
"s": 24822,
"text": "Import module"
},
{
"code": null,
"e": 24856,
"s": 24836,
"text": "Create or load data"
},
{
"code": null,
"e": 24877,
"s": 24856,
"text": "Convert to dataframe"
},
{
"code": null,
"e": 24982,
"s": 24877,
"text": "Using plot() method, specify a single column along X-axis and multiple columns as an array along Y-axis."
},
{
"code": null,
"e": 24997,
"s": 24982,
"text": "Display graph."
},
{
"code": null,
"e": 25104,
"s": 24997,
"text": "Below are few examples which illustrates the above approach to plot multiples data columns in a Dataframe."
},
{
"code": null,
"e": 25115,
"s": 25104,
"text": "Example 1:"
},
{
"code": null,
"e": 25137,
"s": 25115,
"text": "Database: Bestsellers"
},
{
"code": null,
"e": 25145,
"s": 25137,
"text": "Python3"
},
{
"code": "import pandas as pdimport matplotlib.pyplot as mp # take datadata = pd.read_csv(\"Bestsellers.csv\") # form dataframedata = data.head() df = pd.DataFrame(data, columns=[\"Name\", \"Price\", \"User Rating\"]) # plot the dataframedf.plot(x=\"Name\", y=[\"Price\", \"User Rating\"], kind=\"bar\", figsize=(9, 8)) # print bar graphmp.show()",
"e": 25466,
"s": 25145,
"text": null
},
{
"code": null,
"e": 25474,
"s": 25466,
"text": "Output:"
},
{
"code": null,
"e": 25485,
"s": 25474,
"text": "Example 2:"
},
{
"code": null,
"e": 25493,
"s": 25485,
"text": "Python3"
},
{
"code": "import pandas as pdimport matplotlib.pyplot as mp # data to be plotteddata = [[\"New York\", 8.6, 20], [\"Chicago\", 2.7, 20], [\"Los Angeles\", 3.9, 20], [\"Philadelphia\", 1.5, 20], [\"Houston\", 2.1, 20]] # form dataframe from datadf = pd.DataFrame(data, columns=[\"City\", \"Population(million)\", \"Year(2020)\"]) # plot multiple columns such as population and year from dataframedf.plot(x=\"City\", y=[\"Population(million)\", \"Year(2020)\"], kind=\"line\", figsize=(10, 10)) # display plotmp.show()",
"e": 26011,
"s": 25493,
"text": null
},
{
"code": null,
"e": 26019,
"s": 26011,
"text": "Output:"
},
{
"code": null,
"e": 26037,
"s": 26019,
"text": "gulshankumarar231"
},
{
"code": null,
"e": 26044,
"s": 26037,
"text": "Picked"
},
{
"code": null,
"e": 26067,
"s": 26044,
"text": "Python Pandas-exercise"
},
{
"code": null,
"e": 26090,
"s": 26067,
"text": "Python pandas-plotting"
},
{
"code": null,
"e": 26104,
"s": 26090,
"text": "Python-pandas"
},
{
"code": null,
"e": 26111,
"s": 26104,
"text": "Python"
},
{
"code": null,
"e": 26209,
"s": 26111,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26241,
"s": 26209,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 26283,
"s": 26241,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 26339,
"s": 26283,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 26381,
"s": 26339,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 26436,
"s": 26381,
"text": "Selecting rows in pandas DataFrame based on conditions"
},
{
"code": null,
"e": 26467,
"s": 26436,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 26489,
"s": 26467,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 26518,
"s": 26489,
"text": "Create a directory in Python"
},
{
"code": null,
"e": 26557,
"s": 26518,
"text": "Python | Get unique values from a list"
}
] |
Count of interesting primes upto N - GeeksforGeeks
|
24 Nov, 2021
Given a number N, the task is to find the number of interesting primes less than equal to N.An interesting prime is any prime number which can be written as a2 + b4, where a and b are positive integers. For e.g. The smallest interesting prime number is 2 = 12 + 14.
Examples:
Input: N = 10 Output: 2 2 = 12 + 14 5 = 22 + 14 Both are interesting primes less than equal to 10
Input: N = 1000 Output: 28
Naive Approach:
Iterate through all numbers from 1 to N.For each number, check whether its prime or not.If it is prime, then check whether it can be represented as a2 + b4 by: Iterate through all possible values of b from 1 to N1/4.For each value of b, check whether N – b4 is a perfect square or not (i.e it can be a2 or not).
Iterate through all numbers from 1 to N.
For each number, check whether its prime or not.
If it is prime, then check whether it can be represented as a2 + b4 by: Iterate through all possible values of b from 1 to N1/4.For each value of b, check whether N – b4 is a perfect square or not (i.e it can be a2 or not).
Iterate through all possible values of b from 1 to N1/4.
For each value of b, check whether N – b4 is a perfect square or not (i.e it can be a2 or not).
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program to find the number// of interesting primes up to N #include <bits/stdc++.h>using namespace std; // Function to check if a number// is prime or notbool isPrime(int n){ int flag = 1; // If n is divisible by any // number between 2 and sqrt(n), // it is not prime for (int i = 2; i * i <= n; i++) { if (n % i == 0) { flag = 0; break; } } return (flag == 1 ? true : false);} // Function to check if a number// is perfect square or notbool isPerfectSquare(int x){ // Find floating point value of // square root of x. long double sr = sqrt(x); // If square root is an integer return ((sr - floor(sr)) == 0);} // Function to find the number of interesting// primes less than equal to N.int countInterestingPrimes(int n){ int answer = 0; for (int i = 2; i <= n; i++) { // Check whether the number // is prime or not if (isPrime(i)) { // Iterate for values of b for (int j = 1; j * j * j * j <= i; j++) { // Check condition for a if ( isPerfectSquare( i - j * j * j * j)) { answer++; break; } } } } // Return the required answer return answer;} // Driver codeint main(){ int N = 10; cout << countInterestingPrimes(N); return 0;}
// Java program to find the number// of interesting primes up to Nclass GFG{ // Function to check if a number// is prime or notstatic boolean isPrime(int n){ int flag = 1; // If n is divisible by any // number between 2 and Math.sqrt(n), // it is not prime for (int i = 2; i * i <= n; i++) { if (n % i == 0) { flag = 0; break; } } return (flag == 1 ? true : false);} // Function to check if a number// is perfect square or notstatic boolean isPerfectSquare(int x){ // Find floating point value of // square root of x. double sr = Math.sqrt(x); // If square root is an integer return ((sr - Math.floor(sr)) == 0);} // Function to find the number of interesting// primes less than equal to N.static int countInterestingPrimes(int n){ int answer = 0; for (int i = 2; i <= n; i++) { // Check whether the number // is prime or not if (isPrime(i)) { // Iterate for values of b for (int j = 1; j * j * j * j <= i; j++) { // Check condition for a if ( isPerfectSquare( i - j * j * j * j)) { answer++; break; } } } } // Return the required answer return answer;} // Driver codepublic static void main(String[] args){ int N = 10; System.out.print(countInterestingPrimes(N));}} // This code is contributed by Princi Singh
# Python3 program to find the number# of interesting primes up to Nimport math # Function to check if a number# is prime or notdef isPrime(n): flag = 1 # If n is divisible by any # number between 2 and sqrt(n), # it is not prime i = 2 while(i * i <= n): if (n % i == 0): flag = 0 break i += 1 return (True if flag == 1 else False) # Function to check if a number# is perfect square or notdef isPerfectSquare(x): # Find floating povalue of # square root of x. sr = math.sqrt(x) # If square root is an integer return ((sr - math.floor(sr)) == 0) # Function to find the number of interesting# primes less than equal to N.def countInterestingPrimes(n): answer = 0 for i in range(2, n): # Check whether the number # is prime or not if (isPrime(i)): # Iterate for values of b j = 1 while(j * j * j * j <= i): # Check condition for a if (isPerfectSquare(i - j * j * j * j)): answer += 1 break j += 1 # Return the required answer return answer # Driver codeif __name__=='__main__': N = 10 print(countInterestingPrimes(N)) # This code is contributed by AbhiThakur
// C# program to find the number// of interesting primes up to Nusing System;using System.Collections.Generic; class GFG{ // Function to check if a number// is prime or notstatic bool isPrime(int n){ int flag = 1; // If n is divisible by any // number between 2 and Math.Sqrt(n), // it is not prime for (int i = 2; i * i <= n; i++) { if (n % i == 0) { flag = 0; break; } } return (flag == 1 ? true : false);} // Function to check if a number// is perfect square or notstatic bool isPerfectSquare(int x){ // Find floating point value of // square root of x. double sr = Math.Sqrt(x); // If square root is an integer return ((sr - Math.Floor(sr)) == 0);} // Function to find the number of interesting// primes less than equal to N.static int countInterestingPrimes(int n){ int answer = 0; for (int i = 2; i <= n; i++) { // Check whether the number // is prime or not if (isPrime(i)) { // Iterate for values of b for (int j = 1; j * j * j * j <= i; j++) { // Check condition for a if ( isPerfectSquare( i - j * j * j * j)) { answer++; break; } } } } // Return the required answer return answer;} // Driver codepublic static void Main(String[] args){ int N = 10; Console.Write(countInterestingPrimes(N));}} // This code is contributed by Rajput-Ji
<script>// Java script program to find the number// of interesting primes up to N // Function to check if a number// is prime or notfunction isPrime( n){ let flag = 1; // If n is divisible by any // number between 2 and Math.sqrt(n), // it is not prime for (let i = 2; i * i <= n; i++) { if (n % i == 0) { flag = 0; break; } } return (flag == 1 ? true : false);} // Function to check if a number// is perfect square or notfunction isPerfectSquare( x){ // Find floating point value of // square root of x. let sr = Math.sqrt(x); // If square root is an integer return ((sr - Math.floor(sr)) == 0);} // Function to find the number of interesting// primes less than equal to N.function countInterestingPrimes( n){ let answer = 0; for (let i = 2; i <= n; i++) { // Check whether the number // is prime or not if (isPrime(i)) { // Iterate for values of b for (let j = 1; j * j * j * j <= i; j++) { // Check condition for a if ( isPerfectSquare( i - j * j * j * j)) { answer++; break; } } } } // Return the required answer return answer;} // Driver code let N = 10; document.write(countInterestingPrimes(N)); // This code is contributed by Bobby</script>
2
Time Complexity: O(N)
Auxiliary Space: O(1)
Efficient Approach:
If we store all perfect squares and perfect quadruples up to N, then we can iterate through all the pairs and check whether the result is prime or not.To further optimise we can store all primes till N using sieve of eratosthenes and do the primality check in O(1).
If we store all perfect squares and perfect quadruples up to N, then we can iterate through all the pairs and check whether the result is prime or not.
To further optimise we can store all primes till N using sieve of eratosthenes and do the primality check in O(1).
Below is the implementation of the above approach:
C++
Java
Python3
C#
// C++ program to find the number// of interesting primes up to N. #include <bits/stdc++.h>using namespace std; // Function to find all prime numbersvoid SieveOfEratosthenes( int n, unordered_set<int>& allPrimes){ // Create a boolean array "prime[0..n]" // and initialize all entries as true. // A value in prime[i] will finally // be false if i is Not a prime. bool prime[n + 1]; memset(prime, true, sizeof(prime)); for (int p = 2; p * p <= n; p++) { // If prime[p] is not changed, // then it is a prime if (prime[p] == true) { // Update all multiples of p // greater than or equal to // the square of it for (int i = p * p; i <= n; i += p) prime[i] = false; } } // Store all prime numbers for (int p = 2; p <= n; p++) if (prime[p]) allPrimes.insert(p);} // Function to check if a number// is perfect square or notint countInterestingPrimes(int n){ // To store all primes unordered_set<int> allPrimes; SieveOfEratosthenes(n, allPrimes); // To store all interseting primes unordered_set<int> intersetingPrimes; vector<int> squares, quadruples; // Store all perfect squares for (int i = 1; i * i <= n; i++) { squares.push_back(i * i); } // Store all perfect quadruples for (int i = 1; i * i * i * i <= n; i++) { quadruples.push_back(i * i * i * i); } // Store all interseting primes for (auto a : squares) { for (auto b : quadruples) { if (allPrimes.count(a + b)) intersetingPrimes.insert(a + b); } } // Return count of interseting primes return intersetingPrimes.size();} // Driver codeint main(){ int N = 10; cout << countInterestingPrimes(N); return 0;}
// Java program to find the number// of interesting primes up to N.import java.util.*; class GFG{ // Function to find all prime numbersstatic void SieveOfEratosthenes( int n, HashSet<Integer> allPrimes){ // Create a boolean array "prime[0..n]" // and initialize all entries as true. // A value in prime[i] will finally // be false if i is Not a prime. boolean []prime = new boolean[n + 1]; Arrays.fill(prime, true); for (int p = 2; p * p <= n; p++) { // If prime[p] is not changed, // then it is a prime if (prime[p] == true) { // Update all multiples of p // greater than or equal to // the square of it for (int i = p * p; i <= n; i += p) prime[i] = false; } } // Store all prime numbers for (int p = 2; p <= n; p++) if (prime[p]) allPrimes.add(p);} // Function to check if a number// is perfect square or notstatic int countInterestingPrimes(int n){ // To store all primes HashSet<Integer> allPrimes = new HashSet<Integer>(); SieveOfEratosthenes(n, allPrimes); // To store all interseting primes HashSet<Integer> intersetingPrimes = new HashSet<Integer>(); Vector<Integer> squares = new Vector<Integer>() , quadruples = new Vector<Integer>(); // Store all perfect squares for (int i = 1; i * i <= n; i++) { squares.add(i * i); } // Store all perfect quadruples for (int i = 1; i * i * i * i <= n; i++) { quadruples.add(i * i * i * i); } // Store all interseting primes for (int a : squares) { for (int b : quadruples) { if (allPrimes.contains(a + b)) intersetingPrimes.add(a + b); } } // Return count of interseting primes return intersetingPrimes.size();} // Driver codepublic static void main(String[] args){ int N = 10; System.out.print(countInterestingPrimes(N));}} // This code is contributed by 29AjayKumar
# Python3 program to find the number# of interesting primes up to N. # Function to find all prime numbersdef SieveOfEratosthenes(n, allPrimes): # Create a boolean array "prime[0..n]" # and initialize all entries as true. # A value in prime[i] will finally # be false if i is Not a prime. prime = [True] * (n + 1) p = 2 while p * p <= n: # If prime[p] is not changed, # then it is a prime if prime[p] == True: # Update all multiples of p # greater than or equal to # the square of it for i in range(p * p, n + 1, p): prime[i] = False p += 1 # Store all prime numbers for p in range(2, n + 1): if prime[p]: allPrimes.add(p) # Function to check if a number# is perfect square or notdef countInterestingPrimes(n): # To store all primes allPrimes = set() # To store all interseting primes SieveOfEratosthenes(n, allPrimes) # To store all interseting primes interestingPrimes = set() squares, quadruples = [], [] # Store all perfect squares i = 1 while i * i <= n: squares.append(i * i) i += 1 # Store all perfect quadruples i = 1 while i * i * i * i <= n: quadruples.append(i * i * i * i) i += 1 # Store all interseting primes for a in squares: for b in quadruples: if a + b in allPrimes: interestingPrimes.add(a + b) # Return count of interseting primes return len(interestingPrimes) # Driver codeN = 10print(countInterestingPrimes(N)) # This code is contributed by Shivam Singh
// C# program to find the number// of interesting primes up to N.using System;using System.Collections.Generic; class GFG{ // Function to find all prime numbersstatic void SieveOfEratosthenes( int n, HashSet<int> allPrimes){ // Create a bool array "prime[0..n]" // and initialize all entries as true. // A value in prime[i] will finally // be false if i is Not a prime. bool []prime = new bool[n + 1]; for(int i = 0; i < n + 1; i++) prime[i] = true; for (int p = 2; p * p <= n; p++) { // If prime[p] is not changed, // then it is a prime if (prime[p] == true) { // Update all multiples of p // greater than or equal to // the square of it for (int i = p * p; i <= n; i += p) prime[i] = false; } } // Store all prime numbers for (int p = 2; p <= n; p++) if (prime[p]) allPrimes.Add(p);} // Function to check if a number// is perfect square or notstatic int countInterestingPrimes(int n){ // To store all primes HashSet<int> allPrimes = new HashSet<int>(); SieveOfEratosthenes(n, allPrimes); // To store all interseting primes HashSet<int> intersetingPrimes = new HashSet<int>(); List<int> squares = new List<int>() , quadruples = new List<int>(); // Store all perfect squares for (int i = 1; i * i <= n; i++) { squares.Add(i * i); } // Store all perfect quadruples for (int i = 1; i * i * i * i <= n; i++) { quadruples.Add(i * i * i * i); } // Store all interseting primes foreach (int a in squares) { foreach (int b in quadruples) { if (allPrimes.Contains(a + b)) intersetingPrimes.Add(a + b); } } // Return count of interseting primes return intersetingPrimes.Count;} // Driver codepublic static void Main(String[] args){ int N = 10; Console.Write(countInterestingPrimes(N));}} // This code is contributed by Rajput-Ji
2
Time Complexity: O(N)
Auxiliary Space: O(N)
princi singh
Rajput-Ji
abhaysingh290895
29AjayKumar
SHIVAMSINGH67
gottumukkalabobby
sagar0719kumar
subham348
math
maths-perfect-square
Algorithms
Greedy
Mathematical
Greedy
Mathematical
Algorithms
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
DSA Sheet by Love Babbar
Quadratic Probing in Hashing
SCAN (Elevator) Disk Scheduling Algorithms
K means Clustering - Introduction
Program for SSTF disk scheduling algorithm
Dijkstra's shortest path algorithm | Greedy Algo-7
Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2
Prim’s Minimum Spanning Tree (MST) | Greedy Algo-5
Program for array rotation
Huffman Coding | Greedy Algo-3
|
[
{
"code": null,
"e": 24692,
"s": 24664,
"text": "\n24 Nov, 2021"
},
{
"code": null,
"e": 24959,
"s": 24692,
"text": "Given a number N, the task is to find the number of interesting primes less than equal to N.An interesting prime is any prime number which can be written as a2 + b4, where a and b are positive integers. For e.g. The smallest interesting prime number is 2 = 12 + 14. "
},
{
"code": null,
"e": 24970,
"s": 24959,
"text": "Examples: "
},
{
"code": null,
"e": 25068,
"s": 24970,
"text": "Input: N = 10 Output: 2 2 = 12 + 14 5 = 22 + 14 Both are interesting primes less than equal to 10"
},
{
"code": null,
"e": 25096,
"s": 25068,
"text": "Input: N = 1000 Output: 28 "
},
{
"code": null,
"e": 25114,
"s": 25096,
"text": "Naive Approach: "
},
{
"code": null,
"e": 25426,
"s": 25114,
"text": "Iterate through all numbers from 1 to N.For each number, check whether its prime or not.If it is prime, then check whether it can be represented as a2 + b4 by: Iterate through all possible values of b from 1 to N1/4.For each value of b, check whether N – b4 is a perfect square or not (i.e it can be a2 or not)."
},
{
"code": null,
"e": 25467,
"s": 25426,
"text": "Iterate through all numbers from 1 to N."
},
{
"code": null,
"e": 25516,
"s": 25467,
"text": "For each number, check whether its prime or not."
},
{
"code": null,
"e": 25740,
"s": 25516,
"text": "If it is prime, then check whether it can be represented as a2 + b4 by: Iterate through all possible values of b from 1 to N1/4.For each value of b, check whether N – b4 is a perfect square or not (i.e it can be a2 or not)."
},
{
"code": null,
"e": 25797,
"s": 25740,
"text": "Iterate through all possible values of b from 1 to N1/4."
},
{
"code": null,
"e": 25893,
"s": 25797,
"text": "For each value of b, check whether N – b4 is a perfect square or not (i.e it can be a2 or not)."
},
{
"code": null,
"e": 25945,
"s": 25893,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 25949,
"s": 25945,
"text": "C++"
},
{
"code": null,
"e": 25954,
"s": 25949,
"text": "Java"
},
{
"code": null,
"e": 25962,
"s": 25954,
"text": "Python3"
},
{
"code": null,
"e": 25965,
"s": 25962,
"text": "C#"
},
{
"code": null,
"e": 25976,
"s": 25965,
"text": "Javascript"
},
{
"code": "// C++ program to find the number// of interesting primes up to N #include <bits/stdc++.h>using namespace std; // Function to check if a number// is prime or notbool isPrime(int n){ int flag = 1; // If n is divisible by any // number between 2 and sqrt(n), // it is not prime for (int i = 2; i * i <= n; i++) { if (n % i == 0) { flag = 0; break; } } return (flag == 1 ? true : false);} // Function to check if a number// is perfect square or notbool isPerfectSquare(int x){ // Find floating point value of // square root of x. long double sr = sqrt(x); // If square root is an integer return ((sr - floor(sr)) == 0);} // Function to find the number of interesting// primes less than equal to N.int countInterestingPrimes(int n){ int answer = 0; for (int i = 2; i <= n; i++) { // Check whether the number // is prime or not if (isPrime(i)) { // Iterate for values of b for (int j = 1; j * j * j * j <= i; j++) { // Check condition for a if ( isPerfectSquare( i - j * j * j * j)) { answer++; break; } } } } // Return the required answer return answer;} // Driver codeint main(){ int N = 10; cout << countInterestingPrimes(N); return 0;}",
"e": 27436,
"s": 25976,
"text": null
},
{
"code": "// Java program to find the number// of interesting primes up to Nclass GFG{ // Function to check if a number// is prime or notstatic boolean isPrime(int n){ int flag = 1; // If n is divisible by any // number between 2 and Math.sqrt(n), // it is not prime for (int i = 2; i * i <= n; i++) { if (n % i == 0) { flag = 0; break; } } return (flag == 1 ? true : false);} // Function to check if a number// is perfect square or notstatic boolean isPerfectSquare(int x){ // Find floating point value of // square root of x. double sr = Math.sqrt(x); // If square root is an integer return ((sr - Math.floor(sr)) == 0);} // Function to find the number of interesting// primes less than equal to N.static int countInterestingPrimes(int n){ int answer = 0; for (int i = 2; i <= n; i++) { // Check whether the number // is prime or not if (isPrime(i)) { // Iterate for values of b for (int j = 1; j * j * j * j <= i; j++) { // Check condition for a if ( isPerfectSquare( i - j * j * j * j)) { answer++; break; } } } } // Return the required answer return answer;} // Driver codepublic static void main(String[] args){ int N = 10; System.out.print(countInterestingPrimes(N));}} // This code is contributed by Princi Singh",
"e": 28982,
"s": 27436,
"text": null
},
{
"code": "# Python3 program to find the number# of interesting primes up to Nimport math # Function to check if a number# is prime or notdef isPrime(n): flag = 1 # If n is divisible by any # number between 2 and sqrt(n), # it is not prime i = 2 while(i * i <= n): if (n % i == 0): flag = 0 break i += 1 return (True if flag == 1 else False) # Function to check if a number# is perfect square or notdef isPerfectSquare(x): # Find floating povalue of # square root of x. sr = math.sqrt(x) # If square root is an integer return ((sr - math.floor(sr)) == 0) # Function to find the number of interesting# primes less than equal to N.def countInterestingPrimes(n): answer = 0 for i in range(2, n): # Check whether the number # is prime or not if (isPrime(i)): # Iterate for values of b j = 1 while(j * j * j * j <= i): # Check condition for a if (isPerfectSquare(i - j * j * j * j)): answer += 1 break j += 1 # Return the required answer return answer # Driver codeif __name__=='__main__': N = 10 print(countInterestingPrimes(N)) # This code is contributed by AbhiThakur",
"e": 30319,
"s": 28982,
"text": null
},
{
"code": "// C# program to find the number// of interesting primes up to Nusing System;using System.Collections.Generic; class GFG{ // Function to check if a number// is prime or notstatic bool isPrime(int n){ int flag = 1; // If n is divisible by any // number between 2 and Math.Sqrt(n), // it is not prime for (int i = 2; i * i <= n; i++) { if (n % i == 0) { flag = 0; break; } } return (flag == 1 ? true : false);} // Function to check if a number// is perfect square or notstatic bool isPerfectSquare(int x){ // Find floating point value of // square root of x. double sr = Math.Sqrt(x); // If square root is an integer return ((sr - Math.Floor(sr)) == 0);} // Function to find the number of interesting// primes less than equal to N.static int countInterestingPrimes(int n){ int answer = 0; for (int i = 2; i <= n; i++) { // Check whether the number // is prime or not if (isPrime(i)) { // Iterate for values of b for (int j = 1; j * j * j * j <= i; j++) { // Check condition for a if ( isPerfectSquare( i - j * j * j * j)) { answer++; break; } } } } // Return the required answer return answer;} // Driver codepublic static void Main(String[] args){ int N = 10; Console.Write(countInterestingPrimes(N));}} // This code is contributed by Rajput-Ji",
"e": 31912,
"s": 30319,
"text": null
},
{
"code": "<script>// Java script program to find the number// of interesting primes up to N // Function to check if a number// is prime or notfunction isPrime( n){ let flag = 1; // If n is divisible by any // number between 2 and Math.sqrt(n), // it is not prime for (let i = 2; i * i <= n; i++) { if (n % i == 0) { flag = 0; break; } } return (flag == 1 ? true : false);} // Function to check if a number// is perfect square or notfunction isPerfectSquare( x){ // Find floating point value of // square root of x. let sr = Math.sqrt(x); // If square root is an integer return ((sr - Math.floor(sr)) == 0);} // Function to find the number of interesting// primes less than equal to N.function countInterestingPrimes( n){ let answer = 0; for (let i = 2; i <= n; i++) { // Check whether the number // is prime or not if (isPrime(i)) { // Iterate for values of b for (let j = 1; j * j * j * j <= i; j++) { // Check condition for a if ( isPerfectSquare( i - j * j * j * j)) { answer++; break; } } } } // Return the required answer return answer;} // Driver code let N = 10; document.write(countInterestingPrimes(N)); // This code is contributed by Bobby</script>",
"e": 33384,
"s": 31912,
"text": null
},
{
"code": null,
"e": 33386,
"s": 33384,
"text": "2"
},
{
"code": null,
"e": 33410,
"s": 33388,
"text": "Time Complexity: O(N)"
},
{
"code": null,
"e": 33432,
"s": 33410,
"text": "Auxiliary Space: O(1)"
},
{
"code": null,
"e": 33453,
"s": 33432,
"text": "Efficient Approach: "
},
{
"code": null,
"e": 33719,
"s": 33453,
"text": "If we store all perfect squares and perfect quadruples up to N, then we can iterate through all the pairs and check whether the result is prime or not.To further optimise we can store all primes till N using sieve of eratosthenes and do the primality check in O(1)."
},
{
"code": null,
"e": 33871,
"s": 33719,
"text": "If we store all perfect squares and perfect quadruples up to N, then we can iterate through all the pairs and check whether the result is prime or not."
},
{
"code": null,
"e": 33986,
"s": 33871,
"text": "To further optimise we can store all primes till N using sieve of eratosthenes and do the primality check in O(1)."
},
{
"code": null,
"e": 34039,
"s": 33986,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 34043,
"s": 34039,
"text": "C++"
},
{
"code": null,
"e": 34048,
"s": 34043,
"text": "Java"
},
{
"code": null,
"e": 34056,
"s": 34048,
"text": "Python3"
},
{
"code": null,
"e": 34059,
"s": 34056,
"text": "C#"
},
{
"code": "// C++ program to find the number// of interesting primes up to N. #include <bits/stdc++.h>using namespace std; // Function to find all prime numbersvoid SieveOfEratosthenes( int n, unordered_set<int>& allPrimes){ // Create a boolean array \"prime[0..n]\" // and initialize all entries as true. // A value in prime[i] will finally // be false if i is Not a prime. bool prime[n + 1]; memset(prime, true, sizeof(prime)); for (int p = 2; p * p <= n; p++) { // If prime[p] is not changed, // then it is a prime if (prime[p] == true) { // Update all multiples of p // greater than or equal to // the square of it for (int i = p * p; i <= n; i += p) prime[i] = false; } } // Store all prime numbers for (int p = 2; p <= n; p++) if (prime[p]) allPrimes.insert(p);} // Function to check if a number// is perfect square or notint countInterestingPrimes(int n){ // To store all primes unordered_set<int> allPrimes; SieveOfEratosthenes(n, allPrimes); // To store all interseting primes unordered_set<int> intersetingPrimes; vector<int> squares, quadruples; // Store all perfect squares for (int i = 1; i * i <= n; i++) { squares.push_back(i * i); } // Store all perfect quadruples for (int i = 1; i * i * i * i <= n; i++) { quadruples.push_back(i * i * i * i); } // Store all interseting primes for (auto a : squares) { for (auto b : quadruples) { if (allPrimes.count(a + b)) intersetingPrimes.insert(a + b); } } // Return count of interseting primes return intersetingPrimes.size();} // Driver codeint main(){ int N = 10; cout << countInterestingPrimes(N); return 0;}",
"e": 35883,
"s": 34059,
"text": null
},
{
"code": "// Java program to find the number// of interesting primes up to N.import java.util.*; class GFG{ // Function to find all prime numbersstatic void SieveOfEratosthenes( int n, HashSet<Integer> allPrimes){ // Create a boolean array \"prime[0..n]\" // and initialize all entries as true. // A value in prime[i] will finally // be false if i is Not a prime. boolean []prime = new boolean[n + 1]; Arrays.fill(prime, true); for (int p = 2; p * p <= n; p++) { // If prime[p] is not changed, // then it is a prime if (prime[p] == true) { // Update all multiples of p // greater than or equal to // the square of it for (int i = p * p; i <= n; i += p) prime[i] = false; } } // Store all prime numbers for (int p = 2; p <= n; p++) if (prime[p]) allPrimes.add(p);} // Function to check if a number// is perfect square or notstatic int countInterestingPrimes(int n){ // To store all primes HashSet<Integer> allPrimes = new HashSet<Integer>(); SieveOfEratosthenes(n, allPrimes); // To store all interseting primes HashSet<Integer> intersetingPrimes = new HashSet<Integer>(); Vector<Integer> squares = new Vector<Integer>() , quadruples = new Vector<Integer>(); // Store all perfect squares for (int i = 1; i * i <= n; i++) { squares.add(i * i); } // Store all perfect quadruples for (int i = 1; i * i * i * i <= n; i++) { quadruples.add(i * i * i * i); } // Store all interseting primes for (int a : squares) { for (int b : quadruples) { if (allPrimes.contains(a + b)) intersetingPrimes.add(a + b); } } // Return count of interseting primes return intersetingPrimes.size();} // Driver codepublic static void main(String[] args){ int N = 10; System.out.print(countInterestingPrimes(N));}} // This code is contributed by 29AjayKumar",
"e": 37886,
"s": 35883,
"text": null
},
{
"code": "# Python3 program to find the number# of interesting primes up to N. # Function to find all prime numbersdef SieveOfEratosthenes(n, allPrimes): # Create a boolean array \"prime[0..n]\" # and initialize all entries as true. # A value in prime[i] will finally # be false if i is Not a prime. prime = [True] * (n + 1) p = 2 while p * p <= n: # If prime[p] is not changed, # then it is a prime if prime[p] == True: # Update all multiples of p # greater than or equal to # the square of it for i in range(p * p, n + 1, p): prime[i] = False p += 1 # Store all prime numbers for p in range(2, n + 1): if prime[p]: allPrimes.add(p) # Function to check if a number# is perfect square or notdef countInterestingPrimes(n): # To store all primes allPrimes = set() # To store all interseting primes SieveOfEratosthenes(n, allPrimes) # To store all interseting primes interestingPrimes = set() squares, quadruples = [], [] # Store all perfect squares i = 1 while i * i <= n: squares.append(i * i) i += 1 # Store all perfect quadruples i = 1 while i * i * i * i <= n: quadruples.append(i * i * i * i) i += 1 # Store all interseting primes for a in squares: for b in quadruples: if a + b in allPrimes: interestingPrimes.add(a + b) # Return count of interseting primes return len(interestingPrimes) # Driver codeN = 10print(countInterestingPrimes(N)) # This code is contributed by Shivam Singh",
"e": 39594,
"s": 37886,
"text": null
},
{
"code": "// C# program to find the number// of interesting primes up to N.using System;using System.Collections.Generic; class GFG{ // Function to find all prime numbersstatic void SieveOfEratosthenes( int n, HashSet<int> allPrimes){ // Create a bool array \"prime[0..n]\" // and initialize all entries as true. // A value in prime[i] will finally // be false if i is Not a prime. bool []prime = new bool[n + 1]; for(int i = 0; i < n + 1; i++) prime[i] = true; for (int p = 2; p * p <= n; p++) { // If prime[p] is not changed, // then it is a prime if (prime[p] == true) { // Update all multiples of p // greater than or equal to // the square of it for (int i = p * p; i <= n; i += p) prime[i] = false; } } // Store all prime numbers for (int p = 2; p <= n; p++) if (prime[p]) allPrimes.Add(p);} // Function to check if a number// is perfect square or notstatic int countInterestingPrimes(int n){ // To store all primes HashSet<int> allPrimes = new HashSet<int>(); SieveOfEratosthenes(n, allPrimes); // To store all interseting primes HashSet<int> intersetingPrimes = new HashSet<int>(); List<int> squares = new List<int>() , quadruples = new List<int>(); // Store all perfect squares for (int i = 1; i * i <= n; i++) { squares.Add(i * i); } // Store all perfect quadruples for (int i = 1; i * i * i * i <= n; i++) { quadruples.Add(i * i * i * i); } // Store all interseting primes foreach (int a in squares) { foreach (int b in quadruples) { if (allPrimes.Contains(a + b)) intersetingPrimes.Add(a + b); } } // Return count of interseting primes return intersetingPrimes.Count;} // Driver codepublic static void Main(String[] args){ int N = 10; Console.Write(countInterestingPrimes(N));}} // This code is contributed by Rajput-Ji",
"e": 41625,
"s": 39594,
"text": null
},
{
"code": null,
"e": 41627,
"s": 41625,
"text": "2"
},
{
"code": null,
"e": 41651,
"s": 41629,
"text": "Time Complexity: O(N)"
},
{
"code": null,
"e": 41673,
"s": 41651,
"text": "Auxiliary Space: O(N)"
},
{
"code": null,
"e": 41686,
"s": 41673,
"text": "princi singh"
},
{
"code": null,
"e": 41696,
"s": 41686,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 41713,
"s": 41696,
"text": "abhaysingh290895"
},
{
"code": null,
"e": 41725,
"s": 41713,
"text": "29AjayKumar"
},
{
"code": null,
"e": 41739,
"s": 41725,
"text": "SHIVAMSINGH67"
},
{
"code": null,
"e": 41757,
"s": 41739,
"text": "gottumukkalabobby"
},
{
"code": null,
"e": 41772,
"s": 41757,
"text": "sagar0719kumar"
},
{
"code": null,
"e": 41782,
"s": 41772,
"text": "subham348"
},
{
"code": null,
"e": 41787,
"s": 41782,
"text": "math"
},
{
"code": null,
"e": 41808,
"s": 41787,
"text": "maths-perfect-square"
},
{
"code": null,
"e": 41819,
"s": 41808,
"text": "Algorithms"
},
{
"code": null,
"e": 41826,
"s": 41819,
"text": "Greedy"
},
{
"code": null,
"e": 41839,
"s": 41826,
"text": "Mathematical"
},
{
"code": null,
"e": 41846,
"s": 41839,
"text": "Greedy"
},
{
"code": null,
"e": 41859,
"s": 41846,
"text": "Mathematical"
},
{
"code": null,
"e": 41870,
"s": 41859,
"text": "Algorithms"
},
{
"code": null,
"e": 41968,
"s": 41870,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 41977,
"s": 41968,
"text": "Comments"
},
{
"code": null,
"e": 41990,
"s": 41977,
"text": "Old Comments"
},
{
"code": null,
"e": 42015,
"s": 41990,
"text": "DSA Sheet by Love Babbar"
},
{
"code": null,
"e": 42044,
"s": 42015,
"text": "Quadratic Probing in Hashing"
},
{
"code": null,
"e": 42087,
"s": 42044,
"text": "SCAN (Elevator) Disk Scheduling Algorithms"
},
{
"code": null,
"e": 42121,
"s": 42087,
"text": "K means Clustering - Introduction"
},
{
"code": null,
"e": 42164,
"s": 42121,
"text": "Program for SSTF disk scheduling algorithm"
},
{
"code": null,
"e": 42215,
"s": 42164,
"text": "Dijkstra's shortest path algorithm | Greedy Algo-7"
},
{
"code": null,
"e": 42273,
"s": 42215,
"text": "Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2"
},
{
"code": null,
"e": 42324,
"s": 42273,
"text": "Prim’s Minimum Spanning Tree (MST) | Greedy Algo-5"
},
{
"code": null,
"e": 42351,
"s": 42324,
"text": "Program for array rotation"
}
] |
How to read data from a file stored in XAMPP webserver using PHP ? - GeeksforGeeks
|
01 Dec, 2020
We have given a file stored on XAMPP server and the task is to read the file from server and display the file content on the screen using PHP. We use some PHP functions to solve this problem.
File: A file is set of data stored in a disk in different formats. For example – .txt, .exe, .pdf etc
fopen() function: The fopen() function in PHP is an inbuilt function which is used to open a file or a URL. It is used to bind a resource to a steam using a specific filename. The filename and mode to be checked are sent as parameters to the fopen() function and it returns a file pointer resource if a match is found and a False on failure. The error output can be hidden by adding an ‘@’ in front of the function name.
Syntax:
fopen('filename', filemode)
Here, file name is name of the file and file mode includes read(r) mode,write(w) and binary(b) mode etc.
fopen($geek, r) — Here we are opening geek file in read mode.
fopen($geek, r+) — Here we are opening geek file in read and write mode.
fopen($geek, w) — Here we are opening geek file in write mode.
fopen($geek, w+) — Here we are opening geek file in read and write mode.
fopen($geek, b) — Here we are opening geek file in read and write mode.
Requirements:
XAMPP web server — If you have not installed XAMPP/WAMP web server then please install it by using the following steps:
Link to install: https://www.apachefriends.org/download.html
Start the XAMPP Server
Open the notepad and type the below code:
PHP
<?php // File to be read$file = "./welcome.txt"; // Opening file$f = fopen($file, "r") or exit("Unable to open file!"); // Read file line by line until// the end of file (feof)while(!feof($f)) { echo fgets($f)."<br />";} // Closing filefclose($f);?>
Data in welcome.txt file are:
GEEKS FOR GEEKS IS BEST FOR COMPUTER SCIENCE
Place these two files in folder (Path is show here)
Path
Running the Script Type the following URL in the browser: localhost/gfg/1.php
Output:
PHP-Misc
PHP
PHP Programs
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to fetch data from localserver database and display on HTML table using PHP ?
Different ways for passing data to view in Laravel
Create a drop-down list that options fetched from a MySQL database in PHP
How to generate PDF file using PHP ?
How to create admin login page using PHP?
How to call PHP function on the click of a Button ?
How to fetch data from localserver database and display on HTML table using PHP ?
How to create admin login page using PHP?
PHP | Ternary Operator
How to Install php-curl in Ubuntu ?
|
[
{
"code": null,
"e": 24972,
"s": 24944,
"text": "\n01 Dec, 2020"
},
{
"code": null,
"e": 25164,
"s": 24972,
"text": "We have given a file stored on XAMPP server and the task is to read the file from server and display the file content on the screen using PHP. We use some PHP functions to solve this problem."
},
{
"code": null,
"e": 25267,
"s": 25164,
"text": "File: A file is set of data stored in a disk in different formats. For example – .txt, .exe, .pdf etc "
},
{
"code": null,
"e": 25689,
"s": 25267,
"text": "fopen() function: The fopen() function in PHP is an inbuilt function which is used to open a file or a URL. It is used to bind a resource to a steam using a specific filename. The filename and mode to be checked are sent as parameters to the fopen() function and it returns a file pointer resource if a match is found and a False on failure. The error output can be hidden by adding an ‘@’ in front of the function name."
},
{
"code": null,
"e": 25697,
"s": 25689,
"text": "Syntax:"
},
{
"code": null,
"e": 25726,
"s": 25697,
"text": "fopen('filename', filemode)\n"
},
{
"code": null,
"e": 25831,
"s": 25726,
"text": "Here, file name is name of the file and file mode includes read(r) mode,write(w) and binary(b) mode etc."
},
{
"code": null,
"e": 25893,
"s": 25831,
"text": "fopen($geek, r) — Here we are opening geek file in read mode."
},
{
"code": null,
"e": 25966,
"s": 25893,
"text": "fopen($geek, r+) — Here we are opening geek file in read and write mode."
},
{
"code": null,
"e": 26029,
"s": 25966,
"text": "fopen($geek, w) — Here we are opening geek file in write mode."
},
{
"code": null,
"e": 26102,
"s": 26029,
"text": "fopen($geek, w+) — Here we are opening geek file in read and write mode."
},
{
"code": null,
"e": 26174,
"s": 26102,
"text": "fopen($geek, b) — Here we are opening geek file in read and write mode."
},
{
"code": null,
"e": 26188,
"s": 26174,
"text": "Requirements:"
},
{
"code": null,
"e": 26308,
"s": 26188,
"text": "XAMPP web server — If you have not installed XAMPP/WAMP web server then please install it by using the following steps:"
},
{
"code": null,
"e": 26369,
"s": 26308,
"text": "Link to install: https://www.apachefriends.org/download.html"
},
{
"code": null,
"e": 26392,
"s": 26369,
"text": "Start the XAMPP Server"
},
{
"code": null,
"e": 26434,
"s": 26392,
"text": "Open the notepad and type the below code:"
},
{
"code": null,
"e": 26438,
"s": 26434,
"text": "PHP"
},
{
"code": "<?php // File to be read$file = \"./welcome.txt\"; // Opening file$f = fopen($file, \"r\") or exit(\"Unable to open file!\"); // Read file line by line until// the end of file (feof)while(!feof($f)) { echo fgets($f).\"<br />\";} // Closing filefclose($f);?>",
"e": 26701,
"s": 26438,
"text": null
},
{
"code": null,
"e": 26731,
"s": 26701,
"text": "Data in welcome.txt file are:"
},
{
"code": null,
"e": 26776,
"s": 26731,
"text": "GEEKS FOR GEEKS IS BEST FOR COMPUTER SCIENCE"
},
{
"code": null,
"e": 26828,
"s": 26776,
"text": "Place these two files in folder (Path is show here)"
},
{
"code": null,
"e": 26833,
"s": 26828,
"text": "Path"
},
{
"code": null,
"e": 26913,
"s": 26835,
"text": "Running the Script Type the following URL in the browser: localhost/gfg/1.php"
},
{
"code": null,
"e": 26921,
"s": 26913,
"text": "Output:"
},
{
"code": null,
"e": 26930,
"s": 26921,
"text": "PHP-Misc"
},
{
"code": null,
"e": 26934,
"s": 26930,
"text": "PHP"
},
{
"code": null,
"e": 26947,
"s": 26934,
"text": "PHP Programs"
},
{
"code": null,
"e": 26964,
"s": 26947,
"text": "Web Technologies"
},
{
"code": null,
"e": 26968,
"s": 26964,
"text": "PHP"
},
{
"code": null,
"e": 27066,
"s": 26968,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27148,
"s": 27066,
"text": "How to fetch data from localserver database and display on HTML table using PHP ?"
},
{
"code": null,
"e": 27199,
"s": 27148,
"text": "Different ways for passing data to view in Laravel"
},
{
"code": null,
"e": 27273,
"s": 27199,
"text": "Create a drop-down list that options fetched from a MySQL database in PHP"
},
{
"code": null,
"e": 27310,
"s": 27273,
"text": "How to generate PDF file using PHP ?"
},
{
"code": null,
"e": 27352,
"s": 27310,
"text": "How to create admin login page using PHP?"
},
{
"code": null,
"e": 27404,
"s": 27352,
"text": "How to call PHP function on the click of a Button ?"
},
{
"code": null,
"e": 27486,
"s": 27404,
"text": "How to fetch data from localserver database and display on HTML table using PHP ?"
},
{
"code": null,
"e": 27528,
"s": 27486,
"text": "How to create admin login page using PHP?"
},
{
"code": null,
"e": 27551,
"s": 27528,
"text": "PHP | Ternary Operator"
}
] |
Display default initial values of DataTypes in Java
|
To display default initial values of a datatype, you need to just declare a variable of the same datatype and display it.
The following is a Java program to display initial values of DataTypes.
Live Demo
public class Demo {
boolean t;
byte b;
short s;
int i;
long l;
float f;
double d;
void Display() {
System.out.println("boolean (Initial Value) = " + t);
System.out.println("byte (Initial Value) = " + b);
System.out.println("short (Initial Value) = " + s);
System.out.println("int (Initial Value) = " + i);
System.out.println("long (Initial Value) = " + l);
System.out.println("float (Initial Value) = " + f);
System.out.println("double (Initial Value) = " + d);
}
public static void main(String[] args) {
Demo d = new Demo();
System.out.println("Displaying initial values...");
d.Display();
}
}
Displaying initial values...
boolean (Initial Value) = false
byte (Initial Value) = 0
short (Initial Value) = 0
int (Initial Value) = 0
long (Initial Value) = 0
float (Initial Value) = 0.0
double (Initial Value) = 0.0
In the above program, we have declared a variable with different datatypes.
boolean t;
byte b;
short s;
int i;
long l;
float f;
double d;
Now to get the default initial values, just print the variable declared above.
System.out.println("boolean (Initial Value) = " + t);
System.out.println("byte (Initial Value) = " + b);
System.out.println("short (Initial Value) = " + s);
System.out.println("int (Initial Value) = " + i);
System.out.println("long (Initial Value) = " + l);
System.out.println("float (Initial Value) = " + f);
System.out.println("double (Initial Value) = " + d);
The above displays the default values.
|
[
{
"code": null,
"e": 1184,
"s": 1062,
"text": "To display default initial values of a datatype, you need to just declare a variable of the same datatype and display it."
},
{
"code": null,
"e": 1256,
"s": 1184,
"text": "The following is a Java program to display initial values of DataTypes."
},
{
"code": null,
"e": 1267,
"s": 1256,
"text": " Live Demo"
},
{
"code": null,
"e": 1955,
"s": 1267,
"text": "public class Demo {\n boolean t;\n byte b;\n short s;\n int i;\n long l;\n float f;\n double d;\n void Display() {\n System.out.println(\"boolean (Initial Value) = \" + t);\n System.out.println(\"byte (Initial Value) = \" + b);\n System.out.println(\"short (Initial Value) = \" + s);\n System.out.println(\"int (Initial Value) = \" + i);\n System.out.println(\"long (Initial Value) = \" + l);\n System.out.println(\"float (Initial Value) = \" + f);\n System.out.println(\"double (Initial Value) = \" + d);\n }\n public static void main(String[] args) {\n Demo d = new Demo();\n System.out.println(\"Displaying initial values...\");\n d.Display();\n }\n}"
},
{
"code": null,
"e": 2173,
"s": 1955,
"text": "Displaying initial values...\nboolean (Initial Value) = false\nbyte (Initial Value) = 0\nshort (Initial Value) = 0\nint (Initial Value) = 0\nlong (Initial Value) = 0\nfloat (Initial Value) = 0.0\ndouble (Initial Value) = 0.0"
},
{
"code": null,
"e": 2249,
"s": 2173,
"text": "In the above program, we have declared a variable with different datatypes."
},
{
"code": null,
"e": 2311,
"s": 2249,
"text": "boolean t;\nbyte b;\nshort s;\nint i;\nlong l;\nfloat f;\ndouble d;"
},
{
"code": null,
"e": 2390,
"s": 2311,
"text": "Now to get the default initial values, just print the variable declared above."
},
{
"code": null,
"e": 2753,
"s": 2390,
"text": "System.out.println(\"boolean (Initial Value) = \" + t);\nSystem.out.println(\"byte (Initial Value) = \" + b);\nSystem.out.println(\"short (Initial Value) = \" + s);\nSystem.out.println(\"int (Initial Value) = \" + i);\nSystem.out.println(\"long (Initial Value) = \" + l);\nSystem.out.println(\"float (Initial Value) = \" + f);\nSystem.out.println(\"double (Initial Value) = \" + d);"
},
{
"code": null,
"e": 2792,
"s": 2753,
"text": "The above displays the default values."
}
] |
Check if the number is divisible 43 or not - GeeksforGeeks
|
24 Nov, 2021
Given a number N, the task is to check whether the number is divisible by 43 or not. Examples:
Input: N = 2795 Output: yes Explanation: 43 * 65 = 2795Input: N = 11094 Output: yes Explanation: 43 * 258 = 11094
Approach: The divisibility test of 43 is:
Extract the last digit.Add 13 * last digit from the remaining number obtained after removing the last digit.Repeat the above steps until a two-digit number, or zero, is obtained.If the two-digit number is divisible by 43, or it is 0, then the original number is also divisible by 43.
Extract the last digit.
Add 13 * last digit from the remaining number obtained after removing the last digit.
Repeat the above steps until a two-digit number, or zero, is obtained.
If the two-digit number is divisible by 43, or it is 0, then the original number is also divisible by 43.
For example:
If N = 11739
Step 1:
N = 11739
Last digit = 9
Remaining number = 1173
Adding 13 times last digit
Resultant number = 1173 + 13*9 = 1290
Step 2:
N = 1290
Since 129 is divisible by 43 as 43 * 3 = 129
Therefore N = 11739 is also divisible by 43
Below is the implementation of the above approach:
C++
Java
Python 3
C#
Javascript
// C++ program to check whether a number// is divisible by 43 or not #include<bits/stdc++.h>#include<stdlib.h> using namespace std;// Function to check if the number is divisible by 43 or notbool isDivisible(int n) { int d; // While there are at least two digits while (n / 100) { // Extracting the last d = n % 10; // Truncating the number n /= 10; // adding thirteen times the last // digit to the remaining number n = abs(n+(d * 13)); } // Finally return if the two-digit // number is divisible by 43 or not return (n % 43 == 0) ;} // Driver Codeint main() { int N = 2795; if (isDivisible(N)) cout<<"Yes"<<endl ; else cout<<"No"<<endl ; return 0; } // This code is contributed by ANKITKUMAR34
// Java program to check whether a number// is divisible by 43 or notclass GFG{ // Function to check if the number is divisible by 43 or notstatic boolean isDivisible(int n) { int d; // While there are at least two digits while ((n / 100) > 0) { // Extracting the last d = n % 10; // Truncating the number n /= 10; // adding thirteen times the last // digit to the remaining number n = Math.abs(n+(d * 13)); } // Finally return if the two-digit // number is divisible by 43 or not return (n % 43 == 0) ;} // Driver Codepublic static void main(String[] args) { int N = 2795; if (isDivisible(N)) System.out.print("Yes"); else System.out.print("No"); } } // This code is contributed by PrinciRaj1992
# Python program to check whether a number# is divisible by 43 or not # Function to check if the number is# divisible by 43 or notdef isDivisible(n) : # While there are at least two digits while n // 100 : # Extracting the last d = n % 10 # Truncating the number n //= 10 # Adding thirteen times the last # digit to the remaining number n = abs(n+(d * 13)) # Finally return if the two-digit # number is divisible by 43 or not return (n % 43 == 0) # Driver Codeif __name__ == "__main__" : N = 2795 if (isDivisible(N)): print("Yes") else : print("No")
// C# program to check whether a number// is divisible by 43 or notusing System; class GFG{ // Function to check if the number is divisible by 43 or notstatic bool isDivisible(int n){ int d; // While there are at least two digits while (n / 100 > 0) { // Extracting the last d = n % 10; // Truncating the number n /= 10; // adding thirteen times the last // digit to the remaining number n = Math.Abs(n + (d * 13)); } // Finally return if the two-digit // number is divisible by 43 or not return (n % 43 == 0) ;} // Driver Codepublic static void Main(){ int N = 2795; if (isDivisible(N)) Console.WriteLine("Yes"); else Console.WriteLine("No"); }} // This code is contributed by AbhiThakur
<script>//javascript program to check whether a number// is divisible by 43 or not // Function to check if the number is divisible by 43 or notfunction isDivisible(n){ let d; // While there are at least two digits while(parseInt(n/100) > 0) { // Extracting the last d = n % 10; // Truncating the number n = parseInt(n / 10) // adding thirteen times the last // digit to the remaining number n = Math.abs(n+(d * 13)); } // Finally return if the two-digit // number is divisible by 43 or not return (n % 43 == 0) ;} // Driver Code let N = 2795; if (isDivisible(N)) document.write("Yes"); else document.write("No"); // This code is contributed by vaibhavrabadiya117.</script>
Yes
Time Complexity: O(log10N)
Auxiliary Space: O(1)
ANKITKUMAR34
princiraj1992
abhaysingh290895
vaibhavrabadiya117
rishavmahato348
divisibility
Number Divisibility
Aptitude
Mathematical
School Programming
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Puzzle | How much money did the man have before entering the bank?
7 Best Tips to Prepare for Aptitude Test For Campus Placements
Puzzle | Splitting a Cake with a Missing Piece in two equal portion
Geometry and Co-ordinates
Program to find the last two digits of x^y
Program for Fibonacci numbers
C++ Data Types
Write a program to print all permutations of a given string
Set in C++ Standard Template Library (STL)
Program to find GCD or HCF of two numbers
|
[
{
"code": null,
"e": 25526,
"s": 25498,
"text": "\n24 Nov, 2021"
},
{
"code": null,
"e": 25623,
"s": 25526,
"text": "Given a number N, the task is to check whether the number is divisible by 43 or not. Examples: "
},
{
"code": null,
"e": 25739,
"s": 25623,
"text": "Input: N = 2795 Output: yes Explanation: 43 * 65 = 2795Input: N = 11094 Output: yes Explanation: 43 * 258 = 11094 "
},
{
"code": null,
"e": 25785,
"s": 25741,
"text": "Approach: The divisibility test of 43 is: "
},
{
"code": null,
"e": 26069,
"s": 25785,
"text": "Extract the last digit.Add 13 * last digit from the remaining number obtained after removing the last digit.Repeat the above steps until a two-digit number, or zero, is obtained.If the two-digit number is divisible by 43, or it is 0, then the original number is also divisible by 43."
},
{
"code": null,
"e": 26093,
"s": 26069,
"text": "Extract the last digit."
},
{
"code": null,
"e": 26179,
"s": 26093,
"text": "Add 13 * last digit from the remaining number obtained after removing the last digit."
},
{
"code": null,
"e": 26250,
"s": 26179,
"text": "Repeat the above steps until a two-digit number, or zero, is obtained."
},
{
"code": null,
"e": 26356,
"s": 26250,
"text": "If the two-digit number is divisible by 43, or it is 0, then the original number is also divisible by 43."
},
{
"code": null,
"e": 26371,
"s": 26356,
"text": "For example: "
},
{
"code": null,
"e": 26629,
"s": 26371,
"text": "If N = 11739\n\nStep 1:\n N = 11739\n Last digit = 9\n Remaining number = 1173\n Adding 13 times last digit\n Resultant number = 1173 + 13*9 = 1290\n\nStep 2:\n N = 1290\n Since 129 is divisible by 43 as 43 * 3 = 129\n\nTherefore N = 11739 is also divisible by 43"
},
{
"code": null,
"e": 26682,
"s": 26629,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 26686,
"s": 26682,
"text": "C++"
},
{
"code": null,
"e": 26691,
"s": 26686,
"text": "Java"
},
{
"code": null,
"e": 26700,
"s": 26691,
"text": "Python 3"
},
{
"code": null,
"e": 26703,
"s": 26700,
"text": "C#"
},
{
"code": null,
"e": 26714,
"s": 26703,
"text": "Javascript"
},
{
"code": "// C++ program to check whether a number// is divisible by 43 or not #include<bits/stdc++.h>#include<stdlib.h> using namespace std;// Function to check if the number is divisible by 43 or notbool isDivisible(int n) { int d; // While there are at least two digits while (n / 100) { // Extracting the last d = n % 10; // Truncating the number n /= 10; // adding thirteen times the last // digit to the remaining number n = abs(n+(d * 13)); } // Finally return if the two-digit // number is divisible by 43 or not return (n % 43 == 0) ;} // Driver Codeint main() { int N = 2795; if (isDivisible(N)) cout<<\"Yes\"<<endl ; else cout<<\"No\"<<endl ; return 0; } // This code is contributed by ANKITKUMAR34",
"e": 27529,
"s": 26714,
"text": null
},
{
"code": "// Java program to check whether a number// is divisible by 43 or notclass GFG{ // Function to check if the number is divisible by 43 or notstatic boolean isDivisible(int n) { int d; // While there are at least two digits while ((n / 100) > 0) { // Extracting the last d = n % 10; // Truncating the number n /= 10; // adding thirteen times the last // digit to the remaining number n = Math.abs(n+(d * 13)); } // Finally return if the two-digit // number is divisible by 43 or not return (n % 43 == 0) ;} // Driver Codepublic static void main(String[] args) { int N = 2795; if (isDivisible(N)) System.out.print(\"Yes\"); else System.out.print(\"No\"); } } // This code is contributed by PrinciRaj1992",
"e": 28348,
"s": 27529,
"text": null
},
{
"code": "# Python program to check whether a number# is divisible by 43 or not # Function to check if the number is# divisible by 43 or notdef isDivisible(n) : # While there are at least two digits while n // 100 : # Extracting the last d = n % 10 # Truncating the number n //= 10 # Adding thirteen times the last # digit to the remaining number n = abs(n+(d * 13)) # Finally return if the two-digit # number is divisible by 43 or not return (n % 43 == 0) # Driver Codeif __name__ == \"__main__\" : N = 2795 if (isDivisible(N)): print(\"Yes\") else : print(\"No\")",
"e": 28997,
"s": 28348,
"text": null
},
{
"code": "// C# program to check whether a number// is divisible by 43 or notusing System; class GFG{ // Function to check if the number is divisible by 43 or notstatic bool isDivisible(int n){ int d; // While there are at least two digits while (n / 100 > 0) { // Extracting the last d = n % 10; // Truncating the number n /= 10; // adding thirteen times the last // digit to the remaining number n = Math.Abs(n + (d * 13)); } // Finally return if the two-digit // number is divisible by 43 or not return (n % 43 == 0) ;} // Driver Codepublic static void Main(){ int N = 2795; if (isDivisible(N)) Console.WriteLine(\"Yes\"); else Console.WriteLine(\"No\"); }} // This code is contributed by AbhiThakur",
"e": 29811,
"s": 28997,
"text": null
},
{
"code": "<script>//javascript program to check whether a number// is divisible by 43 or not // Function to check if the number is divisible by 43 or notfunction isDivisible(n){ let d; // While there are at least two digits while(parseInt(n/100) > 0) { // Extracting the last d = n % 10; // Truncating the number n = parseInt(n / 10) // adding thirteen times the last // digit to the remaining number n = Math.abs(n+(d * 13)); } // Finally return if the two-digit // number is divisible by 43 or not return (n % 43 == 0) ;} // Driver Code let N = 2795; if (isDivisible(N)) document.write(\"Yes\"); else document.write(\"No\"); // This code is contributed by vaibhavrabadiya117.</script>",
"e": 30580,
"s": 29811,
"text": null
},
{
"code": null,
"e": 30584,
"s": 30580,
"text": "Yes"
},
{
"code": null,
"e": 30613,
"s": 30586,
"text": "Time Complexity: O(log10N)"
},
{
"code": null,
"e": 30635,
"s": 30613,
"text": "Auxiliary Space: O(1)"
},
{
"code": null,
"e": 30648,
"s": 30635,
"text": "ANKITKUMAR34"
},
{
"code": null,
"e": 30662,
"s": 30648,
"text": "princiraj1992"
},
{
"code": null,
"e": 30679,
"s": 30662,
"text": "abhaysingh290895"
},
{
"code": null,
"e": 30698,
"s": 30679,
"text": "vaibhavrabadiya117"
},
{
"code": null,
"e": 30714,
"s": 30698,
"text": "rishavmahato348"
},
{
"code": null,
"e": 30727,
"s": 30714,
"text": "divisibility"
},
{
"code": null,
"e": 30747,
"s": 30727,
"text": "Number Divisibility"
},
{
"code": null,
"e": 30756,
"s": 30747,
"text": "Aptitude"
},
{
"code": null,
"e": 30769,
"s": 30756,
"text": "Mathematical"
},
{
"code": null,
"e": 30788,
"s": 30769,
"text": "School Programming"
},
{
"code": null,
"e": 30801,
"s": 30788,
"text": "Mathematical"
},
{
"code": null,
"e": 30899,
"s": 30801,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30908,
"s": 30899,
"text": "Comments"
},
{
"code": null,
"e": 30921,
"s": 30908,
"text": "Old Comments"
},
{
"code": null,
"e": 30988,
"s": 30921,
"text": "Puzzle | How much money did the man have before entering the bank?"
},
{
"code": null,
"e": 31051,
"s": 30988,
"text": "7 Best Tips to Prepare for Aptitude Test For Campus Placements"
},
{
"code": null,
"e": 31119,
"s": 31051,
"text": "Puzzle | Splitting a Cake with a Missing Piece in two equal portion"
},
{
"code": null,
"e": 31145,
"s": 31119,
"text": "Geometry and Co-ordinates"
},
{
"code": null,
"e": 31188,
"s": 31145,
"text": "Program to find the last two digits of x^y"
},
{
"code": null,
"e": 31218,
"s": 31188,
"text": "Program for Fibonacci numbers"
},
{
"code": null,
"e": 31233,
"s": 31218,
"text": "C++ Data Types"
},
{
"code": null,
"e": 31293,
"s": 31233,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 31336,
"s": 31293,
"text": "Set in C++ Standard Template Library (STL)"
}
] |
C program to print the ASCII values in a string.
|
An array of characters is called a string.
Given below is the declaration of a string −
char stringname [size];
For example, char string[50]; string of length 50 characters.
Using single character constant.
char string[10] = { ‘H’, ‘e’, ‘l’, ‘l’, ‘o’ ,‘\0’}
Using string constants.
char string[10] = “Hello”:;
There is a control string “%s” used for accessing the string till it encounters ‘\0’.
The logic we used to print the ASCII values of a given string at runtime is as follows −
while(str[i]!='\0'){
printf("\nASCII Value of %c = %d", str[i], str[i]);
i++;
}
Following is the C program to print the ASCII values of a given string −
#include<stdio.h>
int main() {
char string[50];
int i=0;
printf("Enter the Sentenc: ");
gets(string);
while(string[i]!='\0') {
printf("\nASCII Value of %c=%d", string[i], string[i]);
i++;
}
getch();
return 0;
}
When the above program is executed, it produces the following output −
Enter the Sentence: Tutorials Point
ASCII Value of T = 84
ASCII Value of u = 117
ASCII Value of t = 116
ASCII Value of o = 111
ASCII Value of r = 114
ASCII Value of i = 105
ASCII Value of a = 97
ASCII Value of l = 108
ASCII Value of s = 115
ASCII Value of = 32
ASCII Value of P = 80
ASCII Value of o = 111
ASCII Value of i = 105
ASCII Value of n = 110
ASCII Value of t = 116
|
[
{
"code": null,
"e": 1105,
"s": 1062,
"text": "An array of characters is called a string."
},
{
"code": null,
"e": 1150,
"s": 1105,
"text": "Given below is the declaration of a string −"
},
{
"code": null,
"e": 1174,
"s": 1150,
"text": "char stringname [size];"
},
{
"code": null,
"e": 1236,
"s": 1174,
"text": "For example, char string[50]; string of length 50 characters."
},
{
"code": null,
"e": 1269,
"s": 1236,
"text": "Using single character constant."
},
{
"code": null,
"e": 1320,
"s": 1269,
"text": "char string[10] = { ‘H’, ‘e’, ‘l’, ‘l’, ‘o’ ,‘\\0’}"
},
{
"code": null,
"e": 1344,
"s": 1320,
"text": "Using string constants."
},
{
"code": null,
"e": 1372,
"s": 1344,
"text": "char string[10] = “Hello”:;"
},
{
"code": null,
"e": 1458,
"s": 1372,
"text": "There is a control string “%s” used for accessing the string till it encounters ‘\\0’."
},
{
"code": null,
"e": 1547,
"s": 1458,
"text": "The logic we used to print the ASCII values of a given string at runtime is as follows −"
},
{
"code": null,
"e": 1633,
"s": 1547,
"text": "while(str[i]!='\\0'){\n printf(\"\\nASCII Value of %c = %d\", str[i], str[i]);\n i++;\n}"
},
{
"code": null,
"e": 1706,
"s": 1633,
"text": "Following is the C program to print the ASCII values of a given string −"
},
{
"code": null,
"e": 1953,
"s": 1706,
"text": "#include<stdio.h>\nint main() {\n char string[50];\n int i=0;\n printf(\"Enter the Sentenc: \");\n gets(string);\n while(string[i]!='\\0') {\n printf(\"\\nASCII Value of %c=%d\", string[i], string[i]);\n i++;\n }\n getch();\n return 0;\n}"
},
{
"code": null,
"e": 2024,
"s": 1953,
"text": "When the above program is executed, it produces the following output −"
},
{
"code": null,
"e": 2402,
"s": 2024,
"text": "Enter the Sentence: Tutorials Point\n\nASCII Value of T = 84\nASCII Value of u = 117\nASCII Value of t = 116\nASCII Value of o = 111\nASCII Value of r = 114\nASCII Value of i = 105\nASCII Value of a = 97\nASCII Value of l = 108\nASCII Value of s = 115\nASCII Value of = 32\nASCII Value of P = 80\nASCII Value of o = 111\nASCII Value of i = 105\nASCII Value of n = 110\nASCII Value of t = 116"
}
] |
C library function - strftime()
|
The C library function size_t strftime(char *str, size_t maxsize, const char *format, const struct tm *timeptr) formats the time represented in the structure timeptr according to the formatting rules defined in format and stored into str.
Following is the declaration for strftime() function.
size_t strftime(char *str, size_t maxsize, const char *format, const struct tm *timeptr)
str − This is the pointer to the destination array where the resulting C string is copied.
str − This is the pointer to the destination array where the resulting C string is copied.
maxsize − This is the maximum number of characters to be copied to str.
maxsize − This is the maximum number of characters to be copied to str.
format − This is the C string containing any combination of regular characters and special format specifiers. These format specifiers are replaced by the function to the corresponding values to represent the time specified in tm. The format specifiers are −
format − This is the C string containing any combination of regular characters and special format specifiers. These format specifiers are replaced by the function to the corresponding values to represent the time specified in tm. The format specifiers are −
timeptr − This is the pointer to a tm structure that contains a calendar time broken down into its components as shown below −
timeptr − This is the pointer to a tm structure that contains a calendar time broken down into its components as shown below −
struct tm {
int tm_sec; /* seconds, range 0 to 59 */
int tm_min; /* minutes, range 0 to 59 */
int tm_hour; /* hours, range 0 to 23 */
int tm_mday; /* day of the month, range 1 to 31 */
int tm_mon; /* month, range 0 to 11 */
int tm_year; /* The number of years since 1900 */
int tm_wday; /* day of the week, range 0 to 6 */
int tm_yday; /* day in the year, range 0 to 365 */
int tm_isdst; /* daylight saving time */
};
If the resulting C string fits in less than size characters (which includes the terminating null-character), the total number of characters copied to str (not including the terminating null-character) is returned otherwise, it returns zero.
The following example shows the usage of strftime() function.
#include <stdio.h>
#include <time.h>
int main () {
time_t rawtime;
struct tm *info;
char buffer[80];
time( &rawtime );
info = localtime( &rawtime );
strftime(buffer,80,"%x - %I:%M%p", info);
printf("Formatted date & time : |%s|\n", buffer );
return(0);
}
Let us compile and run the above program that will produce the following result −
Formatted date & time : |08/23/12 - 12:40AM|
12 Lectures
2 hours
Nishant Malik
12 Lectures
2.5 hours
Nishant Malik
48 Lectures
6.5 hours
Asif Hussain
12 Lectures
2 hours
Richa Maheshwari
20 Lectures
3.5 hours
Vandana Annavaram
44 Lectures
1 hours
Amit Diwan
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2246,
"s": 2007,
"text": "The C library function size_t strftime(char *str, size_t maxsize, const char *format, const struct tm *timeptr) formats the time represented in the structure timeptr according to the formatting rules defined in format and stored into str."
},
{
"code": null,
"e": 2300,
"s": 2246,
"text": "Following is the declaration for strftime() function."
},
{
"code": null,
"e": 2389,
"s": 2300,
"text": "size_t strftime(char *str, size_t maxsize, const char *format, const struct tm *timeptr)"
},
{
"code": null,
"e": 2480,
"s": 2389,
"text": "str − This is the pointer to the destination array where the resulting C string is copied."
},
{
"code": null,
"e": 2571,
"s": 2480,
"text": "str − This is the pointer to the destination array where the resulting C string is copied."
},
{
"code": null,
"e": 2643,
"s": 2571,
"text": "maxsize − This is the maximum number of characters to be copied to str."
},
{
"code": null,
"e": 2715,
"s": 2643,
"text": "maxsize − This is the maximum number of characters to be copied to str."
},
{
"code": null,
"e": 2973,
"s": 2715,
"text": "format − This is the C string containing any combination of regular characters and special format specifiers. These format specifiers are replaced by the function to the corresponding values to represent the time specified in tm. The format specifiers are −"
},
{
"code": null,
"e": 3231,
"s": 2973,
"text": "format − This is the C string containing any combination of regular characters and special format specifiers. These format specifiers are replaced by the function to the corresponding values to represent the time specified in tm. The format specifiers are −"
},
{
"code": null,
"e": 3359,
"s": 3231,
"text": "timeptr − This is the pointer to a tm structure that contains a calendar time broken down into its components as shown below −\n"
},
{
"code": null,
"e": 3486,
"s": 3359,
"text": "timeptr − This is the pointer to a tm structure that contains a calendar time broken down into its components as shown below −"
},
{
"code": null,
"e": 4060,
"s": 3486,
"text": "struct tm {\n int tm_sec; /* seconds, range 0 to 59 */\n int tm_min; /* minutes, range 0 to 59 */\n int tm_hour; /* hours, range 0 to 23 */\n int tm_mday; /* day of the month, range 1 to 31 */\n int tm_mon; /* month, range 0 to 11 */\n int tm_year; /* The number of years since 1900 */\n int tm_wday; /* day of the week, range 0 to 6 */\n int tm_yday; /* day in the year, range 0 to 365 */\n int tm_isdst; /* daylight saving time */\t\n};"
},
{
"code": null,
"e": 4301,
"s": 4060,
"text": "If the resulting C string fits in less than size characters (which includes the terminating null-character), the total number of characters copied to str (not including the terminating null-character) is returned otherwise, it returns zero."
},
{
"code": null,
"e": 4363,
"s": 4301,
"text": "The following example shows the usage of strftime() function."
},
{
"code": null,
"e": 4649,
"s": 4363,
"text": "#include <stdio.h>\n#include <time.h>\n\nint main () {\n time_t rawtime;\n struct tm *info;\n char buffer[80];\n\n time( &rawtime );\n\n info = localtime( &rawtime );\n\n strftime(buffer,80,\"%x - %I:%M%p\", info);\n printf(\"Formatted date & time : |%s|\\n\", buffer );\n \n return(0);\n}"
},
{
"code": null,
"e": 4731,
"s": 4649,
"text": "Let us compile and run the above program that will produce the following result −"
},
{
"code": null,
"e": 4777,
"s": 4731,
"text": "Formatted date & time : |08/23/12 - 12:40AM|\n"
},
{
"code": null,
"e": 4810,
"s": 4777,
"text": "\n 12 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 4825,
"s": 4810,
"text": " Nishant Malik"
},
{
"code": null,
"e": 4860,
"s": 4825,
"text": "\n 12 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 4875,
"s": 4860,
"text": " Nishant Malik"
},
{
"code": null,
"e": 4910,
"s": 4875,
"text": "\n 48 Lectures \n 6.5 hours \n"
},
{
"code": null,
"e": 4924,
"s": 4910,
"text": " Asif Hussain"
},
{
"code": null,
"e": 4957,
"s": 4924,
"text": "\n 12 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 4975,
"s": 4957,
"text": " Richa Maheshwari"
},
{
"code": null,
"e": 5010,
"s": 4975,
"text": "\n 20 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 5029,
"s": 5010,
"text": " Vandana Annavaram"
},
{
"code": null,
"e": 5062,
"s": 5029,
"text": "\n 44 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 5074,
"s": 5062,
"text": " Amit Diwan"
},
{
"code": null,
"e": 5081,
"s": 5074,
"text": " Print"
},
{
"code": null,
"e": 5092,
"s": 5081,
"text": " Add Notes"
}
] |
Boosting your data science workflow with vim+tmux | by Grégoire Hornung | Towards Data Science
|
Like most of my peers, I started my career in data science working with the Jupyter ecosystem. Jupyter is a great environment, easy to set up, which offers useful built-in features.
At some points, I nevertheless felt that I needed to move beyond. Some limitations, inherent to notebooks, started to kill my productivity. Just to name a few:
Version control with notebooks is problematic. I was constantly fearing to send notebooks outputs containing client data online. In addition, it is pretty inconvenient to have git keeping track of the outputs modifications while the code is actually unchanged.
Even though progress has been made recently, editing capabilities, like advanced search-and-replace, are still very limited in the Jupyter environment.
When the project gets larger, it is common to have several notebooks open simultaneously. Navigating from notebook to notebook is a pain, especially if they lurk in an ocean of internet tabs. The browser is for googling, not for development for code’s sake!
I was therefore actively looking for alternatives and luckily, I met a bunch of cool dudes that taught me the old-school way of code development. It relies on the vim + tmux combo, which combines a powerful terminal-embedded editor with a multiplexer. Together they provide advanced editing capabilities but also interactivity, as required for data exploration. In addition, this workflow can be fully operated with the keyboard, resulting in a substantial amount of time saved since you no longer need to constantly switch between the keyboard and the mouse.
You may wonder why I didn’t consider using an IDE like Pycharm. Well, there are two main reasons for that. Firstly, IDEs are not really portable and, as a consultant, I tend to work on many different environments. Secondly, and more importantly, it looks so much cooler to work on a dark screen where you can execute code and move from pane to pane at (almost) the speed of thoughts.
This post first aims at guiding you through the setup of a basic, but functional, data science environment based on vim + tmux. I will also showcase how such a setup can boost your productivity in your projects.
Disclaimer: You will need basic familiarities with vim to follow this post. If you are a complete novice, maybe first take a look at this article and then come back.
Tmux is a command-line tool that enables multiple windows and panes within a single terminal window. Technically, it is called a multiplexer. Installation is as simple as sudo apt-get install tmux. You can then create your first session with:
tmux new -s mycoolproject
Within a session, you can control windows and panes using the prefix command ctrl+b and some specific keys. For instance, ctrl+b “ produces a horizontal split of the windows. You can then navigate between panes using ctrl+b arrows.
A big advantage of tmux is that it allows us to run multiple sessions in parallel. This is very convenient for quickly switching between different projects without risking to mixed-up your scripts. You can detach from your current session using ctrl+b d, list the existing sessions with tmux ls and attach to a different session with tmux a -t <session name>.
It is fairly easy to customize tmux, you simply need to edit the config file .tmux.conf located in your home directory. For instance, many people like to rebind the prefix command to ctrl+a.
I only aimed at providing a brief overview of tmux here, but if you want to learn more, there are plenty of great tutorials out there. It is also worth to take a look at this cheat sheet.
I like Vim. Really. Vim is one of those things like black coffee, Sunday morning jogging, or Godard movies that can feel a bit harsh at first, but that becomes more and more enjoyable through time and practice.
Some say that the learning curve is steep. It’s true. But it is also extremely rewarding when you start to master new shortcuts or macros that considerably improve your productivity.
Vim is a highly customizable text editor directly embedded in the terminal. Vim is present by default on all Unix-like systems. No installation needed. The basic configuration has limited capabilities but you can quickly add features (like syntax highlighting, auto-completion, etc..) by tuning or adding plugins to the .vimrc, the configuration file located in your home directory that is loaded when starting the editor.
I’ve made a simple .vimrc available in this repo. It will help you to replicate the steps described below. However, I strongly recommend to set-up your own config file in order to better feel the spirit of vim.
We will use three plugins in the course of this tutorial:
vimux, which enables vim to interact with tmux
vim-pyShell, a wrapper around vimux specifically designed to ease the use of ipython
vim-cellmode, a matlab-like code block execution for ipython
The easiest way to install plugins is through a plugin manager. I personally use vim-plug, but there are plenty of other good options.
Vim-plug is easy to install. It only requires a single bash command:
curl -fLo ~/.vim/autoload/plug.vim https://raw.github.com/junegunn/vim-plug/master/plug.vim
You then just need to specify the desired plugins in your .vimrc between call plug#begin() and call plug#end() as illustrated in the snapshot below.
To install the plugins, execute the command :PlugInstall with your .vimrc open. Then restart vim to source the config file.
Once our plugins are up and running, we can start to send instructions from vim to the terminal.
Within a tmux session, open a python script with vim. In normal mode, you can fire an ipython terminal by calling the dedicated function from the newly installed plugins with the command :call StartPyShell(). By default, this will create a pane at the bottom of the screen and starts an ipython session.
Code can be executed either by:
sending instructions line by line. To do this, move your cursor to the desired line and run the command :call RunPyShellSendLine().
sending code blocks delimited with ##{/##}. In this case, go to the block and call RunTmuxPythonCell(0).
This is already pretty cool, but it actually requires quite some typing. Can we do better?
Automating repetitive tasks. This is the secret for shortening development time and hence boost your productivity. And the good news is that vim is really good at that.
The main idea consists in creating mappings for the most common tasks. Let’s take a closer look at how to actually implement mappings. Again, this is done in the .vimrc. In the snippet below, lines 2 and 3 map the shortcuts ,ss and ,sk to ipython start and stop commands, respectively, while the second block defines the mappings for code execution.
It is well known that most of the time in data science is devoted to data preparation. This step heavily relies on dataframe manipulations. Hence, defining mappings associated with basic operations like:
printing the dataframe first elements: ,sdh
printing the dataframe info: ,sdi
plotting the content of the dataframe: ,spp
displaying the histograms: ,sph
showing the content of a variable: ,so
getting the length of an iterable: ,sl
will save you a lot of time. In addition, you are not polluting your script with numerous prints and outputs since the inspection is performed through passing the variable/object under the cursor to a backend function. No additional typing needed.
Let’s see those mappings in action!
Combining the advanced editing capabilities of vim with few well-designed mappings has really enhanced my productivity. This workflow helps me to meet the tight deadlines inherent to my job. It is true that it requires a substantial initial investment, but I am convinced that the pay-back is much higher, in terms of time saved but also in terms of working comfort.
What keeps amazing me with vim is the endless customization possibilities. So be creative, start to hack the .vimrc and implement your own mappings!
Thanks for reading! If you enjoyed this type of content, you may also be interested in this post. And feel free to follow me on Medium to not miss my next article on how to use vim in data science. You can also support my writing by joining Medium using my affiliated link.
|
[
{
"code": null,
"e": 353,
"s": 171,
"text": "Like most of my peers, I started my career in data science working with the Jupyter ecosystem. Jupyter is a great environment, easy to set up, which offers useful built-in features."
},
{
"code": null,
"e": 513,
"s": 353,
"text": "At some points, I nevertheless felt that I needed to move beyond. Some limitations, inherent to notebooks, started to kill my productivity. Just to name a few:"
},
{
"code": null,
"e": 774,
"s": 513,
"text": "Version control with notebooks is problematic. I was constantly fearing to send notebooks outputs containing client data online. In addition, it is pretty inconvenient to have git keeping track of the outputs modifications while the code is actually unchanged."
},
{
"code": null,
"e": 926,
"s": 774,
"text": "Even though progress has been made recently, editing capabilities, like advanced search-and-replace, are still very limited in the Jupyter environment."
},
{
"code": null,
"e": 1184,
"s": 926,
"text": "When the project gets larger, it is common to have several notebooks open simultaneously. Navigating from notebook to notebook is a pain, especially if they lurk in an ocean of internet tabs. The browser is for googling, not for development for code’s sake!"
},
{
"code": null,
"e": 1744,
"s": 1184,
"text": "I was therefore actively looking for alternatives and luckily, I met a bunch of cool dudes that taught me the old-school way of code development. It relies on the vim + tmux combo, which combines a powerful terminal-embedded editor with a multiplexer. Together they provide advanced editing capabilities but also interactivity, as required for data exploration. In addition, this workflow can be fully operated with the keyboard, resulting in a substantial amount of time saved since you no longer need to constantly switch between the keyboard and the mouse."
},
{
"code": null,
"e": 2128,
"s": 1744,
"text": "You may wonder why I didn’t consider using an IDE like Pycharm. Well, there are two main reasons for that. Firstly, IDEs are not really portable and, as a consultant, I tend to work on many different environments. Secondly, and more importantly, it looks so much cooler to work on a dark screen where you can execute code and move from pane to pane at (almost) the speed of thoughts."
},
{
"code": null,
"e": 2340,
"s": 2128,
"text": "This post first aims at guiding you through the setup of a basic, but functional, data science environment based on vim + tmux. I will also showcase how such a setup can boost your productivity in your projects."
},
{
"code": null,
"e": 2506,
"s": 2340,
"text": "Disclaimer: You will need basic familiarities with vim to follow this post. If you are a complete novice, maybe first take a look at this article and then come back."
},
{
"code": null,
"e": 2749,
"s": 2506,
"text": "Tmux is a command-line tool that enables multiple windows and panes within a single terminal window. Technically, it is called a multiplexer. Installation is as simple as sudo apt-get install tmux. You can then create your first session with:"
},
{
"code": null,
"e": 2775,
"s": 2749,
"text": "tmux new -s mycoolproject"
},
{
"code": null,
"e": 3007,
"s": 2775,
"text": "Within a session, you can control windows and panes using the prefix command ctrl+b and some specific keys. For instance, ctrl+b “ produces a horizontal split of the windows. You can then navigate between panes using ctrl+b arrows."
},
{
"code": null,
"e": 3367,
"s": 3007,
"text": "A big advantage of tmux is that it allows us to run multiple sessions in parallel. This is very convenient for quickly switching between different projects without risking to mixed-up your scripts. You can detach from your current session using ctrl+b d, list the existing sessions with tmux ls and attach to a different session with tmux a -t <session name>."
},
{
"code": null,
"e": 3558,
"s": 3367,
"text": "It is fairly easy to customize tmux, you simply need to edit the config file .tmux.conf located in your home directory. For instance, many people like to rebind the prefix command to ctrl+a."
},
{
"code": null,
"e": 3746,
"s": 3558,
"text": "I only aimed at providing a brief overview of tmux here, but if you want to learn more, there are plenty of great tutorials out there. It is also worth to take a look at this cheat sheet."
},
{
"code": null,
"e": 3957,
"s": 3746,
"text": "I like Vim. Really. Vim is one of those things like black coffee, Sunday morning jogging, or Godard movies that can feel a bit harsh at first, but that becomes more and more enjoyable through time and practice."
},
{
"code": null,
"e": 4140,
"s": 3957,
"text": "Some say that the learning curve is steep. It’s true. But it is also extremely rewarding when you start to master new shortcuts or macros that considerably improve your productivity."
},
{
"code": null,
"e": 4563,
"s": 4140,
"text": "Vim is a highly customizable text editor directly embedded in the terminal. Vim is present by default on all Unix-like systems. No installation needed. The basic configuration has limited capabilities but you can quickly add features (like syntax highlighting, auto-completion, etc..) by tuning or adding plugins to the .vimrc, the configuration file located in your home directory that is loaded when starting the editor."
},
{
"code": null,
"e": 4774,
"s": 4563,
"text": "I’ve made a simple .vimrc available in this repo. It will help you to replicate the steps described below. However, I strongly recommend to set-up your own config file in order to better feel the spirit of vim."
},
{
"code": null,
"e": 4832,
"s": 4774,
"text": "We will use three plugins in the course of this tutorial:"
},
{
"code": null,
"e": 4879,
"s": 4832,
"text": "vimux, which enables vim to interact with tmux"
},
{
"code": null,
"e": 4964,
"s": 4879,
"text": "vim-pyShell, a wrapper around vimux specifically designed to ease the use of ipython"
},
{
"code": null,
"e": 5025,
"s": 4964,
"text": "vim-cellmode, a matlab-like code block execution for ipython"
},
{
"code": null,
"e": 5160,
"s": 5025,
"text": "The easiest way to install plugins is through a plugin manager. I personally use vim-plug, but there are plenty of other good options."
},
{
"code": null,
"e": 5229,
"s": 5160,
"text": "Vim-plug is easy to install. It only requires a single bash command:"
},
{
"code": null,
"e": 5322,
"s": 5229,
"text": "curl -fLo ~/.vim/autoload/plug.vim https://raw.github.com/junegunn/vim-plug/master/plug.vim"
},
{
"code": null,
"e": 5471,
"s": 5322,
"text": "You then just need to specify the desired plugins in your .vimrc between call plug#begin() and call plug#end() as illustrated in the snapshot below."
},
{
"code": null,
"e": 5595,
"s": 5471,
"text": "To install the plugins, execute the command :PlugInstall with your .vimrc open. Then restart vim to source the config file."
},
{
"code": null,
"e": 5692,
"s": 5595,
"text": "Once our plugins are up and running, we can start to send instructions from vim to the terminal."
},
{
"code": null,
"e": 5996,
"s": 5692,
"text": "Within a tmux session, open a python script with vim. In normal mode, you can fire an ipython terminal by calling the dedicated function from the newly installed plugins with the command :call StartPyShell(). By default, this will create a pane at the bottom of the screen and starts an ipython session."
},
{
"code": null,
"e": 6028,
"s": 5996,
"text": "Code can be executed either by:"
},
{
"code": null,
"e": 6160,
"s": 6028,
"text": "sending instructions line by line. To do this, move your cursor to the desired line and run the command :call RunPyShellSendLine()."
},
{
"code": null,
"e": 6265,
"s": 6160,
"text": "sending code blocks delimited with ##{/##}. In this case, go to the block and call RunTmuxPythonCell(0)."
},
{
"code": null,
"e": 6356,
"s": 6265,
"text": "This is already pretty cool, but it actually requires quite some typing. Can we do better?"
},
{
"code": null,
"e": 6525,
"s": 6356,
"text": "Automating repetitive tasks. This is the secret for shortening development time and hence boost your productivity. And the good news is that vim is really good at that."
},
{
"code": null,
"e": 6875,
"s": 6525,
"text": "The main idea consists in creating mappings for the most common tasks. Let’s take a closer look at how to actually implement mappings. Again, this is done in the .vimrc. In the snippet below, lines 2 and 3 map the shortcuts ,ss and ,sk to ipython start and stop commands, respectively, while the second block defines the mappings for code execution."
},
{
"code": null,
"e": 7079,
"s": 6875,
"text": "It is well known that most of the time in data science is devoted to data preparation. This step heavily relies on dataframe manipulations. Hence, defining mappings associated with basic operations like:"
},
{
"code": null,
"e": 7123,
"s": 7079,
"text": "printing the dataframe first elements: ,sdh"
},
{
"code": null,
"e": 7157,
"s": 7123,
"text": "printing the dataframe info: ,sdi"
},
{
"code": null,
"e": 7201,
"s": 7157,
"text": "plotting the content of the dataframe: ,spp"
},
{
"code": null,
"e": 7233,
"s": 7201,
"text": "displaying the histograms: ,sph"
},
{
"code": null,
"e": 7272,
"s": 7233,
"text": "showing the content of a variable: ,so"
},
{
"code": null,
"e": 7311,
"s": 7272,
"text": "getting the length of an iterable: ,sl"
},
{
"code": null,
"e": 7559,
"s": 7311,
"text": "will save you a lot of time. In addition, you are not polluting your script with numerous prints and outputs since the inspection is performed through passing the variable/object under the cursor to a backend function. No additional typing needed."
},
{
"code": null,
"e": 7595,
"s": 7559,
"text": "Let’s see those mappings in action!"
},
{
"code": null,
"e": 7962,
"s": 7595,
"text": "Combining the advanced editing capabilities of vim with few well-designed mappings has really enhanced my productivity. This workflow helps me to meet the tight deadlines inherent to my job. It is true that it requires a substantial initial investment, but I am convinced that the pay-back is much higher, in terms of time saved but also in terms of working comfort."
},
{
"code": null,
"e": 8111,
"s": 7962,
"text": "What keeps amazing me with vim is the endless customization possibilities. So be creative, start to hack the .vimrc and implement your own mappings!"
}
] |
SAP ABAP - Quick Guide
|
ABAP stands for Advanced Business Application Programming, a 4GL (4th generation) language. Currently it is positioned, along with Java, as the main language for SAP application server programming.
Let's start with the high level architecture of SAP system. The 3-tier Client/Server architecture of a typical SAP system is depicted as follows.
The Presentation layer consists of any input device that can be used to control SAP system. This could be a web browser, a mobile device and so on. All the central processing takes place in Application server. The Application server is not just one system in itself, but it can be multiple instances of the processing system. The server communicates with the Database layer that is usually kept on a separate server, mainly for performance reasons and also for security. Communication happens between each layer of the system, from the Presentation layer to the Database and then back up the chain.
Note − ABAP programs run at the application server level. Technical distribution of software is independent of its physical location. It means basically all three levels can be installed on top of each other on one computer or each level can be installed on a different computer or a server.
ABAP programs reside inside the SAP database. They execute under the control of the runtime system that is a part of the SAP kernel. The run-time system processes all ABAP statements, controlling the flow logic and responding to user events.
So, unlike C++ and Java, ABAP programs are not stored in separate external files. Inside the database, ABAP code exists in two forms −
Source code that can be viewed and edited with the ABAP workbench tools.
Source code that can be viewed and edited with the ABAP workbench tools.
Generated code, which is a binary representation. If you are familiar with Java, this generated code is somewhat comparable with Java byte code.
Generated code, which is a binary representation. If you are familiar with Java, this generated code is somewhat comparable with Java byte code.
The run-time system can be considered as a virtual machine, just similar to Java virtual machine. A key component of the ABAP run-time system is the database interface that turns database independent statements (Open SQL) into the statements understood by the underlying database (Native SQL). SAP can work with a wide variety of databases and the same ABAP program can run on all of those.
Reports are a good starting point for familiarizing yourself with general ABAP principles and tools. ABAP reports are used in many areas. In this chapter, we will see how easy it is to write a simple ABAP Report.
Let's get started with the common "Hello World" example.
Each ABAP statement starts with an ABAP keyword and ends with a period. Keywords must be separated by at least one space. It does not matter whether or not you use one or several lines for an ABAP statement.
You need to enter your code using the ABAP Editor that is a part of ABAP Tools delivered with the SAP NetWeaver Application Server ABAP (also known as ‘AS ABAP’).
‘AS ABAP’ is an application server with its own database, ABAP run-time environment, and ABAP development tools such as ABAP Editor. The AS ABAP offers a development platform that is independent of hardware, operating system, and database.
Step 1 − Start the transaction SE38 to navigate to the ABAP Editor (discussed in the next chapter). Let's start creating a report that is one of the many ABAP objects.
Step 2 − On the initial screen of the editor, specify the name of your report in the input field PROGRAM. You may specify the name as ZHELLO1. The preceding Z is important for the name. Z ensures that your report resides in the customer namespace.
The customer namespace includes all objects with the prefix Y or Z. It is always used when customers or partners create objects (like a report) to differentiate these objects from objects of SAP and to prevent name conflicts with objects.
Step 3 − You may type the report name in lower case letters, but the editor will change it to upper case. So the names of ABAP objects are ‘Not’ case sensitive.
Step 4 − After specifying the name of the report, click the CREATE button. A popup window ABAP: PROGRAM ATTRIBUTES will pop up and you will provide more information about your report.
Step 5 − Choose "Executable Program" as the report type, enter the title “My First ABAP Report” and then select SAVE to continue. The CREATE OBJECT DIRECTORY ENTRY window will pop up next. Select the button LOCAL OBJECT and the popup will close.
You can complete your first report by entering the WRITE statement below the REPORT statement, so that the complete report contains just two lines as follows −
REPORT ZHELLO1.
WRITE 'Hello World'.
We can use the keyboard (Ctrl + S) or the save icon (right hand side beside the command field) to save the report. ABAP development takes place in AS ABAP.
Starting the report is as simple as saving it. Click the ACTIVATION button (left hand side next to the start icon) and start the report by using the icon DIRECT PROCESSING or the F8 function key. The title "My First ABAP Report" along with the output “Hello World” is displayed as well. Here is the output −
My First ABAP Report
Hello World
As long as you do not activate a new report or activate a change to an existing report, it is not relevant to their users. This is important in a central development environment where you may work on objects that other developers use in their projects.
If you look at the field Program and double-click on the value ZHELLO1, the ABAP editor will display the code for your report. This is called Forward Navigation. Double clicking on an object's name opens that object in the appropriate tool.
In order to understand SAP ABAP, you need to have basic knowledge of screens like Login, ABAP Editor, Logout and so on. This chapter focuses on screen navigation and the standard toolbar functionality.
After you log on to SAP server, SAP login screen will prompt for User ID and Password. You need to provide a valid user ID and Password and press Enter (the user id and password is provided by system administrator). Following is the login screen.
Following is the SAP screen toolbar.
Menu Bar − Menu bar is the top line of dialog window.
Standard Toolbar − Most standard functions such as Top of Page, End of Page, Page Up, Page Down and Save are available in this toolbar.
Title Bar − Title Bar displays the name of the application/business process you are currently in.
Application Toolbar − Application specific menu options are available here.
Command Field − We can start an application without navigating through the menu transactions and some logical codes are assigned to business processes. Transaction codes are entered in the command field to directly start the application.
You may just start the transaction SE38 (enter SE38 in Command Field) to navigate to the ABAP Editor.
Exit keys are used to exit the program/module or to log off. They are also used to go back to the last accessed screen.
Following are the standard exit keys used in SAP as shown in the image.
Following are the options for checking, activating and processing the reports.
It’s always a good practice to Exit from your ABAP Editor or/and logoff from the SAP system after finishing your work.
ABAP source program consists of comments and ABAP statements. Every statement in ABAP begins with a keyword and ends with a period, and ABAP is ‘Not’ case sensitive.
The first non-comment line in a program begins with the word REPORT. The Report will always be the first line of any executable program created. The statement is followed by the program name which was created previously. The line is then terminated with a full stop.
The syntax is −
REPORT [Program_Name].
[Statements...].
This allows the statement to take up as many lines in the editor as it needs. For example, the REPORT may look like this −
REPORT Z_Test123_01.
Statements consist of a command and any variables and options, ending with a period. As long as the period appears at the end of the statement, no problems will arise. It is this period that marks where the statement finishes.
Let’s write the code.
On the line below the REPORT statement, just type this statement: Write ‘ABAP Tutorial’.
REPORT Z_Test123_01.
Write 'This is ABAP Tutorial'.
Four things to consider while writing statements −
The write statement writes whatever is in quotes to the output window.
The write statement writes whatever is in quotes to the output window.
The ABAP editor converts all text to uppercase except text strings, which are surrounded by single quotation marks.
The ABAP editor converts all text to uppercase except text strings, which are surrounded by single quotation marks.
Unlike some older programming languages, ABAP does not care where a statement begins on a line. You may take advantage of this and improve the readability of your program by using indentation to indicate blocks of code.
Unlike some older programming languages, ABAP does not care where a statement begins on a line. You may take advantage of this and improve the readability of your program by using indentation to indicate blocks of code.
ABAP has no restrictions on the layout of statements. That is, multiple statements can be placed on a single line, or a single statement may stretch across multiple lines.
ABAP has no restrictions on the layout of statements. That is, multiple statements can be placed on a single line, or a single statement may stretch across multiple lines.
Consecutive statements can be chained together if the beginning of each statement is identical. This is done with the colon (:) operator and commas, which are used to terminate the individual statements, much as periods end normal statements.
Following is an example of a program that could save some key stroking −
WRITE 'Hello'.
WRITE 'ABAP'.
WRITE 'World'.
Using the colon notation, it could be rewritten this way −
WRITE: 'Hello',
'ABAP',
'World'.
Like any other ABAP statement, the layout doesn’t matter. This is an equally correct statement −
WRITE: 'Hello', 'ABAP', 'World'.
Inline comments may be declared anywhere in a program by one of the two methods −
Full line comments are indicated by placing an asterisk (*) in the first position of the line, in which case the entire line is considered by the system to be a comment. Comments don’t need to be terminated by a period because they may not extend across more than one line −
Full line comments are indicated by placing an asterisk (*) in the first position of the line, in which case the entire line is considered by the system to be a comment. Comments don’t need to be terminated by a period because they may not extend across more than one line −
* This is the comment line
Partial line comments are indicated by entering a double quote (") after a statement. All text following the double quote is considered by the system to be a comment. You need not terminate partial line comments by a period because they may not extend across more than one line −
Partial line comments are indicated by entering a double quote (") after a statement. All text following the double quote is considered by the system to be a comment. You need not terminate partial line comments by a period because they may not extend across more than one line −
WRITE 'Hello'. "Here is the partial comment
Note − Commented code is not capitalized by the ABAP editor.
The NO-ZERO command follows the DATA statement. It suppresses all leading zeros of a number field containing blanks. The output is usually easier for the users to read.
REPORT Z_Test123_01.
DATA: W_NUR(10) TYPE N.
MOVE 50 TO W_NUR.
WRITE W_NUR NO-ZERO.
The above code produces the following output −
50
Note − Without NO-ZERO command, the output is: 0000000050
The SKIP command helps in inserting blank lines on the page.
The message command is as follows −
WRITE 'This is the 1st line'.
SKIP.
WRITE 'This is the 2nd line'.
The above message command produces the following output −
This is the 1st line
This is the 2nd line
We may use the SKIP command to insert multiple blank lines.
SKIP number_of_lines.
The output would be several blank lines defined by the number of lines. The SKIP command can also position the cursor on a desired line on the page.
SKIP TO LINE line_number.
This command is used to dynamically move the cursor up and down the page. Usually, a WRITE statement occurs after this command to put output on that desired line.
The ULINE command automatically inserts a horizontal line across the output. It’s also possible to control the position and length of the line. The syntax is pretty simple −
ULINE.
The message command is as follows −
WRITE 'This is Underlined'.
ULINE.
The above code produces the following output −
This is Underlined (and a horizontal line below this).
The MESSAGE command displays messages defined by a message ID specified in the REPORT statement at the beginning of the program. The message ID is a 2 character code that defines which set of 1,000 messages the program will access when the MESSAGE command is used.
The messages are numbered from 000 to 999. Associated with each number is a message text up to a maximum of 80 characters. When message number is called, the corresponding text is displayed.
Following are the characters for use with the Message command −
Error messages are normally used to stop users from doing things they are not supposed to do. Warning messages are generally used to remind the users of the consequences of their actions. Information messages give the users useful information.
When we create a message for message the ID AB, the MESSAGE command - MESSAGE E011 gives the following output −
EAB011 This report does not support sub-number summarization.
While programming in ABAP, we need to use a variety of variables to store various information. Variables are nothing but reserved memory locations to store values. This means that when you create a variable you reserve some space in memory. You may like to store information of various data types like character, integer, floating point, etc. Based on the data type of a variable, the operating system allocates memory and decides what can be stored in the reserved memory.
ABAP offers the programmer a rich assortment of fixed length as well as variable length data types. Following table lists down ABAP elementary data types −
Some of the fields and numbers can be modified using one or more names as the following −
byte
numeric
character-like
The following table shows the data type, how much memory it takes to store the value in memory, and the minimum and maximum value that could be stored in such type of variables.
REPORT YR_SEP_12.
DATA text_line TYPE C LENGTH 40.
text_line = 'A Chapter on Data Types'.
Write text_line.
DATA text_string TYPE STRING.
text_string = 'A Program in ABAP'.
Write / text_string.
DATA d_date TYPE D.
d_date = SY-DATUM.
Write / d_date.
In this example, we have a character string of type C with a predefined length 40. STRING is a data type that can be used for any character string of variable length (text strings). Type STRING data objects should generally be used for character-like content where fixed length is not important.
The above code produces the following output −
A Chapter on Data Types
A Program in ABAP
12092015
The DATE type is used for the storage of date information and can store eight digits as shown above.
The complex types are classified into Structure types and Table types. In the structure types, elementary types and structures (i.e. structure embedded in a structure) are grouped together. You may consider only the grouping of elementary types. But you must be aware of the availability of nesting of structures.
When the elementary types are grouped together, the data item can be accessed as a grouped data item or the individual elementary type data items (structure fields) can be accessed. The table types are better known as arrays in other programming languages. Arrays can be simple or structure arrays. In ABAP, arrays are called internal tables and they can be declared and operated upon in many ways when compared to other programming languages. The following table shows the parameters according to which internal tables are characterized.
Line or row type
Row of an internal table can be of elementary, complex or reference type.
Key
Specifies a field or a group of fields as a key of an internal table that identifies the table rows. A key contains the fields of elementary types.
Access method
Describes how ABAP programs access individual table entries.
Reference types are used to refer to instances of classes, interfaces, and run-time data items. The ABAP OOP run-time type services (RTTS) enables declaration of data items at run-time.
Variables are named data objects used to store values within the allotted memory area of a program. As the name suggests, users can change the content of variables with the help of ABAP statements. Each variable in ABAP has a specific type, which determines the size and layout of the variable's memory; the range of values that can be stored within that memory; and the set of operations that can be applied to the variable.
You must declare all variables before they can be used. The basic form of a variable declaration is −
DATA <f> TYPE <type> VALUE <val>.
Here <f> specifies the name of a variable. The name of the variable can be up to 30 characters long. <type> specifies the type of variable. Any data type with fully specified technical attributes is known as <type>. The <val> specifies the initial value of the of <f> variable. In case you define an elementary fixed-length variable, the DATA statement automatically populates the value of the variable with the type-specific initial value. Other possible values for <val> can be a literal, constant, or an explicit clause, such as Is INITIAL.
Following are valid examples of variable declarations.
DATA d1(2) TYPE C.
DATA d2 LIKE d1.
DATA minimum_value TYPE I VALUE 10.
In the above code snippet, d1 is a variable of C type, d2 is a variable of d1 type, and minimum_value is a variable of ABAP integer type I.
This chapter will explain various variable types available in ABAP. There are three kinds of variables in ABAP −
Static Variables
Reference Variables
System Variables
Static variables are declared in subroutines, function modules, and static methods.
Static variables are declared in subroutines, function modules, and static methods.
The lifetime is linked to the context of the declaration.
The lifetime is linked to the context of the declaration.
With ‘CLASS-DATA’ statement, you can declare variables within the classes.
With ‘CLASS-DATA’ statement, you can declare variables within the classes.
The ‘PARAMETERS’ statement can be used to declare the elementary data objects that are linked to input fields on a selection screen.
The ‘PARAMETERS’ statement can be used to declare the elementary data objects that are linked to input fields on a selection screen.
You can also declare the internal tables that are linked to input fields on a selection screen by using ‘SELECT-OPTIONS’ statement.
You can also declare the internal tables that are linked to input fields on a selection screen by using ‘SELECT-OPTIONS’ statement.
Following are the conventions used while naming a variable −
You cannot use special characters such as "t" and "," to name variables.
You cannot use special characters such as "t" and "," to name variables.
The name of the predefined data objects can’t be changed.
The name of the predefined data objects can’t be changed.
The name of the variable can’t be the same as any ABAP keyword or clause.
The name of the variable can’t be the same as any ABAP keyword or clause.
The name of the variables must convey the meaning of the variable without the need for further comments.
The name of the variables must convey the meaning of the variable without the need for further comments.
Hyphens are reserved to represent the components of structures. Therefore, you are supposed to avoid hyphens in variable names.
Hyphens are reserved to represent the components of structures. Therefore, you are supposed to avoid hyphens in variable names.
The underscore character can be used to separate compound words.
The underscore character can be used to separate compound words.
This program shows how to declare a variable using the PARAMETERS statement −
REPORT ZTest123_01.
PARAMETERS: NAME(10) TYPE C,
CLASS TYPE I,
SCORE TYPE P DECIMALS 2,
CONNECT TYPE MARA-MATNR.
Here, NAME represents a parameter of 10 characters, CLASS specifies a parameter of integer type with the default size in bytes, SCORE represents a packed type parameter with values up to two decimal places, and CONNECT refers to the MARA-MATNF type of ABAP Dictionary.
The above code produces the following output −
The syntax for declaring reference variables is −
DATA <ref> TYPE REF TO <type> VALUE IS INITIAL.
REF TO addition declares a reference variable ref.
REF TO addition declares a reference variable ref.
The specification after REF TO specifies the static type of the reference variable.
The specification after REF TO specifies the static type of the reference variable.
The static type restricts the set of objects to which <ref> can refer.
The static type restricts the set of objects to which <ref> can refer.
The dynamic type of reference variable is the data type or class to which it currently refers.
The dynamic type of reference variable is the data type or class to which it currently refers.
The static type is always more general or the same as the dynamic type.
The static type is always more general or the same as the dynamic type.
The TYPE addition is used to create a bound reference type and as a start value, and only IS INITIAL can be specified after the VALUE addition.
The TYPE addition is used to create a bound reference type and as a start value, and only IS INITIAL can be specified after the VALUE addition.
CLASS C1 DEFINITION.
PUBLIC SECTION.
DATA Bl TYPE I VALUE 1.
ENDCLASS. DATA: Oref TYPE REF TO C1 ,
Dref1 LIKE REF TO Oref,
Dref2 TYPE REF TO I .
CREATE OBJECT Oref.
GET REFERENCE OF Oref INTO Dref1.
CREATE DATA Dref2.
Dref2→* = Dref1→*→Bl.
In the above code snippet, an object reference Oref and two data reference variables Dref1 and Dref2 are declared.
In the above code snippet, an object reference Oref and two data reference variables Dref1 and Dref2 are declared.
Both data reference variables are fully typed and can be dereferenced using the dereferencing operator →* at operand positions.
Both data reference variables are fully typed and can be dereferenced using the dereferencing operator →* at operand positions.
ABAP system variables are accessible from all ABAP programs.
ABAP system variables are accessible from all ABAP programs.
These fields are actually filled by the run-time environment.
These fields are actually filled by the run-time environment.
The values in these fields indicate the state of the system at any given point of time.
The values in these fields indicate the state of the system at any given point of time.
You can find the complete list of system variables in the SYST table in SAP.
You can find the complete list of system variables in the SYST table in SAP.
Individual fields of the SYST structure can be accessed by using either “SYST-” or “SY-”.
Individual fields of the SYST structure can be accessed by using either “SYST-” or “SY-”.
REPORT Z_Test123_01.
WRITE:/'SY-ABCDE', SY-ABCDE,
/'SY-DATUM', SY-DATUM,
/'SY-DBSYS', SY-DBSYS,
/'SY-HOST ', SY-HOST,
/'SY-LANGU', SY-LANGU,
/'SY-MANDT', SY-MANDT,
/'SY-OPSYS', SY-OPSYS,
/'SY-SAPRL', SY-SAPRL,
/'SY-SYSID', SY-SYSID,
/'SY-TCODE', SY-TCODE,
/'SY-UNAME', SY-UNAME,
/'SY-UZEIT', SY-UZEIT.
The above code produces the following output −
SY-ABCDE ABCDEFGHIJKLMNOPQRSTUVWXYZ
SY-DATUM 12.09.2015
SY-DBSYS ORACLE
SY-HOST sapserver
SY-LANGU EN
SY-MANDT 800
SY-OPSYS Windows NT
SY-SAPRL 700
SY-SYSID DMO
SY-TCODE SE38
SY-UNAME SAPUSER
SY-UZEIT 14:25:48
Literals are unnamed data objects that you create within the source code of a program. They are fully defined by their value. You can’t change the value of a literal. Constants are named data objects created statically by using declarative statements. A constant is declared by assigning a value to it that is stored in the program's memory area. The value assigned to a constant can’t be changed during the execution of the program. These fixed values can also be considered as literals. There are two types of literals − numeric and character.
Number literals are sequences of digits which can have a prefixed sign. In number literals, there are no decimal separators and no notation with mantissa and exponent.
Following are some examples of numeric literals −
183.
-97.
+326.
Character literals are sequences of alphanumeric characters in the source code of an ABAP program enclosed in single quotation marks. Character literals enclosed in quotation marks have the predefined ABAP type C and are described as text field literals. Literals enclosed in “back quotes” have the ABAP type STRING and are described as string literals. The field length is defined by the number of characters.
Note − In text field literals, trailing blanks are ignored, but in string literals they are taken into account.
Following are some examples of character literals.
REPORT YR_SEP_12.
Write 'Tutorials Point'.
Write / 'ABAP Tutorial'.
REPORT YR_SEP_12.
Write `Tutorials Point `.
Write / `ABAP Tutorial `.
The output is same in both the above cases −
Tutorials Point
ABAP Tutorial
Note − When we try to change the value of the constant, a syntax or run-time error may occur. Constants that you declare in the declaration part of a class or an interface belong to the static attributes of that class or interface.
We can declare the named data objects with the help of CONSTANTS statement.
Following is the syntax −
CONSTANTS <f> TYPE <type> VALUE <val>.
The CONSTANTS statement is similar to the DATA statement.
<f> specifies a name for the constant. TYPE <type> represents a constant named <f>, which inherits the same technical attributes as the existing data type <type>. VALUE <val> assigns an initial value to the declared constant name <f>.
Note − We should use the VALUE clause in the CONSTANTS statement. The clause ‘VALUE’ is used to assign an initial value to the constant during its declaration.
We have 3 types of constants such as elementary, complex and reference constants. The following statement shows how to define constants by using the CONSTANTS statement −
REPORT YR_SEP_12.
CONSTANTS PQR TYPE P DECIMALS 4 VALUE '1.2356'.
Write: / 'The value of PQR is:', PQR.
The output is −
The value of PQR is: 1.2356
Here it refers to elementary data type and is known as elementary constant.
Following is an example for complex constants −
BEGIN OF EMPLOYEE,
Name(25) TYPE C VALUE 'Management Team',
Organization(40) TYPE C VALUE 'Tutorials Point Ltd',
Place(10) TYPE C VALUE 'India',
END OF EMPLOYEE.
In the above code snippet, EMPLOYEE is a complex constant that is composed of the Name, Organization and Place fields.
The following statement declares a constant reference −
CONSTANTS null_pointer TYPE REF TO object VALUE IS INITIAL.
We can use the constant reference in comparisons or we may pass it on to procedures.
ABAP provides a rich set of operators to manipulate variables. All ABAP operators are classified into four categories −
Arithmetic Operators
Comparison Operators
Bitwise Operators
Character String Operators
Arithmetic operators are used in mathematical expressions in the same way that they are used in algebra. The following list describes arithmetic operators. Assume integer variable A holds 20 and variable B holds 40.
+ (Addition)
Adds values on either side of the operator. Example: A + B will give 60.
− (Subtraction)
Subtracts right hand operand from left hand operand. Example: A − B will give -20.
* (Multiplication)
Multiplies values on either side of the operator. Example: A * B will give 800.
/ (Division)
Divides left hand operand by right hand operand. Example: B / A will give 2.
MOD (Modulus)
Divides left hand operand by right hand operand and returns the remainder. Example: B MOD A will give 0.
REPORT YS_SEP_08.
DATA: A TYPE I VALUE 150,
B TYPE I VALUE 50,
Result TYPE I.
Result = A / B.
WRITE / Result.
The above code produces the following output −
3
Let’s discuss the various types of comparison operators for different operands.
= (equality test). Alternate form is EQ.
Checks if the values of two operands are equal or not, if yes then condition becomes true. Example (A = B) is not true.
<> (Inequality test). Alternate form is NE.
Checks if the values of two operands are equal or not. If the values are not equal then the condition becomes true. Example (A <> B) is true.
> (Greater than test). Alternate form is GT.
Checks if the value of left operand is greater than the value of right operand. If yes then condition becomes true. Example (A > B) is not true.
< (Less than test). Alternate form is LT.
Checks if the value of left operand is less than the value of right operand. If yes, then condition becomes true. Example (A < B) is true.
>= (Greater than or equals) Alternate form is GE.
Checks if the value of left operand is greater than or equal to the value of right Operand. If yes, then condition becomes true. Example (A >= B) is not true.
<= (Less than or equals test). Alternate form is LE.
Checks if the value of left operand is less than or equal to the value of right operand. If yes, then condition becomes true. Example (A <= B) is true.
a1 BETWEEN a2 AND a3 (Interval test)
Checks whether a1 lies in between a2 and a3 (inclusive). If yes, then the condition becomes true. Example (A BETWEEN B AND C) is true.
IS INITIAL
The condition becomes true if the contents of the variable have not changed and it has been automatically assigned its initial value. Example (A IS INITIAL) is not true
IS NOT INITIAL
The condition becomes true if the contents of the variable have changed. Example (A IS NOT INITIAL) is true.
Note − If the data type or length of the variables does not match then automatic conversion is performed. Automatic type adjustment is performed for either one or both of the values while comparing two values of different data types. The conversion type is decided by the data type and the preference order of the data type.
Following is the order of preference −
If one field is of type I, then the other is converted to type I.
If one field is of type I, then the other is converted to type I.
If one field is of type P, then the other is converted to type P.
If one field is of type P, then the other is converted to type P.
If one field is of type D, then the other is converted to type D. But C and N types are not converted and they are compared directly. Similar is the case with type T.
If one field is of type D, then the other is converted to type D. But C and N types are not converted and they are compared directly. Similar is the case with type T.
If one field is of type N and the other is of type C or X, both the fields are converted to type P.
If one field is of type N and the other is of type C or X, both the fields are converted to type P.
If one field is of type C and the other is of type X, the X type is converted to type C.
If one field is of type C and the other is of type X, the X type is converted to type C.
REPORT YS_SEP_08.
DATA: A TYPE I VALUE 115,
B TYPE I VALUE 119.
IF A LT B.
WRITE: / 'A is less than B'.
ENDIF
The above code produces the following output −
A is less than B
REPORT YS_SEP_08.
DATA: A TYPE I.
IF A IS INITIAL.
WRITE: / 'A is assigned'.
ENDIF.
The above code produces the following output −
A is assigned.
ABAP also provides a series of bitwise logical operators that can be used to build Boolean algebraic expressions. The bitwise operators can be combined in complex expressions using parentheses and so on.
BIT-NOT
Unary operator that flips all the bits in a hexadecimal number to the opposite value. For instance, applying this operator to a hexadecimal number having the bit level value 10101010 (e.g. 'AA') would give 01010101.
BIT-AND
This binary operator compares each field bit by bit using the Boolean AND operator.
BIT-XOR
Binary operator that compares each field bit by bit using the Boolean XOR (exclusive OR) operator.
BIT-OR
Binary operator that compares each field bit by bit using the Boolean OR operator.
For example, following is the truth table that shows the values generated when applying the Boolean AND, OR, or XOR operators against the two bit values contained in field A and field B.
Following is a list of character string operators −
CO (Contains Only)
Checks whether A is solely composed of the characters in B.
CN (Not Contains ONLY)
Checks whether A contains characters that are not in B.
CA (Contains ANY)
Checks whether A contains at least one character of B.
NA (NOT Contains Any)
Checks whether A does not contain any character of B.
CS (Contains a String)
Checks whether A contains the character string B.
NS (NOT Contains a String)
Checks whether A does not contain the character string B.
CP (Contains a Pattern)
It checks whether A contains the pattern in B.
NP (NOT Contains a Pattern)
It checks whether A does not contain the pattern in B.
REPORT YS_SEP_08.
DATA: P(10) TYPE C VALUE 'APPLE',
Q(10) TYPE C VALUE 'CHAIR'.
IF P CA Q.
WRITE: / 'P contains at least one character of Q'.
ENDIF.
The above code produces the following output −
P contains at least one character of Q.
There may be a situation when you need to execute a block of code several number of times. In general, statements are executed sequentially: The first statement in a function is executed first, followed by the second, and so on.
Programming languages provide various control structures that allow for more complicated execution paths. A loop statement allows us to execute a statement or group of statements multiple times and following is the general form of a loop statement in most of the programming languages.
ABAP programming language provides the following types of loop to handle looping requirements.
Repeats a statement or group of statements when a given condition is true. It tests the condition before executing the loop body.
The DO statement is useful for repeating particular task a specific number of times.
You may use one or more loops inside any another WHILE or DO loop.
Loop control statements change execution from its normal sequence. ABAP includes control statements that allow loops to be ended prematurely. It supports the following control statements.
Causes the loop to skip the remainder of its body and starts the next loop pass.
If the condition is false, then the remaining statements after the CHECK are just ignored and the system starts the next loop pass.
Terminates the loop entirely and transfers execution to the statement immediately following the loop.
Decision making structures have one or more conditions to be evaluated or tested by the program, along with a statement or statements that are to be executed, if the condition is determined to be true, and optionally, other statements to be executed, if the condition is determined to be false.
Following is the general form of a typical decision-making structure found in most of the programming languages −
ABAP programming language provides the following types of decision-making statements.
An IF statement consists of a logical expression followed by one or more statements.
An IF statement can be followed by an optional ELSE statement that executes when the expression is false.
You may use one IF or ELSEIF statement inside another IF or ELSEIF statement.
CASE statement is used when we need to compare two or more fields or variables.
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.
ABAP implicitly references the Gregorian calendar, valid across most of the world. We can convert the output to country specific calendars. A date is a time specified to a precise day, week or month with respect to a calendar. A time is specified to a precise second or minute with respect to a day. ABAP always saves time in 24-hour format. The output can have a country specific format. Dates and time are usually interpreted as local dates that are valid in the current time zone.
ABAP provides two built-in types to work with dates and time −
D data type
T data type
Following is the basic format −
DATA: date TYPE D,
time TYPE T.
DATA: year TYPE I,
month TYPE I,
day TYPE I,
hour TYPE I,
minute TYPE I,
second TYPE I.
Both of these types are fixed-length character types that have the form YYYYMMDD and HHMMSS, respectively.
In addition to these built-in types, the other two types TIMESTAMP and TIMESTAMPL are being used in many standard application tables to store a timestamp in the UTC format. Following table shows the basic date and time types available in ABAP.
D
A built-in fixed-length date type of the form YYYYMMDD. For example, the value 20100913 represents the date September 13, 2010.
T
A built-in fixed-length time type of the form HHMMSS. For example, the value 102305 represents time 10:23:05 AM.
TIMESTAMP (Type P – Length 8 No decimals)
This type is used to represent short timestamps in YYYYMMDDhhmmss form. For instance, the value 20100913102305 represents the date September 13, 2010 at 10:23:05 AM.
TIMESTAMPL (Type P - Length 11 Decimals 7)
TIMESTAMPL represents long timestamps in YYYYMMDDhhmmss,mmmuuun form. Here the additional digits ‘mmmuuun’ represent the fractions of a second.
The following code snippets retrieve the current system date and time.
REPORT YR_SEP_15.
DATA: date_1 TYPE D.
date_1 = SY-DATUM.
Write: / 'Present Date is:', date_1 DD/MM/YYYY.
date_1 = date_1 + 06.
Write: / 'Date after 6 Days is:', date_1 DD/MM/YYYY.
The above code produces the following output −
Present Date is: 21.09.2015
Date after 6 Days is: 27.09.2015
The variable date_1 is assigned the value of the current system date SY-DATUM. Next, we increment the date value by 6. In terms of a date calculation in ABAP, this implies that we’re increasing the day component of the date object by 6 days. The ABAP runtime environment is smart enough to roll over the date value whenever it reaches the end of a month.
Time calculations work similar to date calculations. The following code increments the current system time by 75 seconds using basic time arithmetic.
REPORT YR_SEP_15.
DATA: time_1 TYPE T.
time_1 = SY-UZEIT.
Write /(60) time_1 USING EDIT MASK
'Now the Time is: __:__:__'.
time_1 = time_1 + 75.
Write /(60) time_1 USING EDIT MASK
'A Minute and a Quarter from Now, it is: __:__:__'.
The above code produces the following output −
Now the Time is 11:45:05
A Minute and a Quarter from Now, it is: 11:46:20
You can retrieve the current system time and store it in a timestamp variable using GET TIME STAMP as shown in the following code. The GET TIME STAMP statement stores the timestamp in a long-hand or a short-hand format according to the type of the timestamp data object used. Timestamp value is encoded using the UTC standard.
REPORT YR_SEP_12.
DATA: stamp_1 TYPE TIMESTAMP,
stamp_2 TYPE TIMESTAMPL.
GET TIME STAMP FIELD stamp_1.
Write: / 'The short time stamp is:', stamp_1
TIME ZONE SY-ZONLO.
GET TIME STAMP FIELD stamp_2.
Write: / 'The long time stamp is:', stamp_2
TIME ZONE SY-ZONLO.
The above code produces the following output −
The short time stamp is: 18.09.2015 11:19:40
The long time stamp is: 18.09.2015 11:19:40,9370000
In the above example, we are displaying the timestamp using the TIME ZONE addition of the WRITE statement. This addition formats the output of the timestamp according to the rules for the time zone specified. The system field SY-ZONLO is used to display the local time zone configured in the user’s preferences.
ABAP offers various types of formatting options to format the output of programs. For example, you can create a list that includes various items in different colors or formatting styles.
The WRITE statement is a formatting statement used to display data on a screen. There are different formatting options for the WRITE statement. The syntax of the WRITE statement is −
WRITE <format> <f> <options>.
In this syntax, <format> represents the output format specification, which can be a forward slash (/) that indicates the display of the output starting from a new line. In addition to the forward slash, the format specification includes a column number and column length. For example, the WRITE/04 (6) statement shows that a new line begins with column 4 and the column length is 6, whereas the WRITE 20 statement shows the current line with column 20. The parameter <f> represents a data variable or numbered text.
The following table describes various clauses used for formatting −
LEFT-JUSTIFIED
Specifies that the output is left-justified.
CENTERED
Denotes that the output is centered.
RIGHT-JUSTIFIED
Specifies that the output is right-justified.
UNDER <g>
The output starts directly under the field <g>.
NO-GAP
Specifies that the blank after field <f> is rejected.
USING EDIT MASK <m>
Denotes the specification of the format template <m>. Using No EDIT Mask: This specifies that the format template specified in the ABAP Dictionary is deactivated.
NO-ZERO
If a field contains only zeroes, then they are replaced by blanks.
Following are the formatting options for Numeric Type fields −
NO-SIGN
Specifies that no leading sign is displayed on the screen.
EXPONENT <e>
Specifies that in type F (the floating point fields), the exponent is defined in <e>.
ROUND <r>
The type P fields (packed numeric data types) are first multiplied by 10**(-r) and then rounded off to an integer value.
CURRENCY <c>
Denotes that the formatting is done according to the currency <c> value that is stored in the TCURX database table.
UNIT <u>
Specifies that the number of decimal places is fixed according to the <u> unit as specified in the T006 database table for type P.
DECIMALS <d>
Specifies that the number of digits <d> must be displayed after the decimal point.
For instance, the following table shows different formatting options for the date fields −
Here, DD stands for the date in two figures, MM stands for the month in two figures, YY stands for the year in two figures, and YYYY stands for the year in four figures.
Let’s take a look at an example of ABAP code that implements some of the above formatting options −
REPORT ZTest123_01.
DATA: n(9) TYPE C VALUE 'Tutorials',
m(5) TYPE C VALUE 'Point'.
WRITE: n, m.
WRITE: / n,
/ m UNDER n.
WRITE: / n NO-GAP, m.
DATA time TYPE T VALUE '112538'.
WRITE: / time,
/(8) time Using EDIT MASK '__:__:__'.
The above code produces the following output −
Tutorials Point
Tutorials
Point
TutorialsPoint
112538
11:25:38
An exception is a problem that arises during the execution of a program. When an exception occurs the normal flow of the program is disrupted and the program application terminates abnormally, which is not recommended, therefore these exceptions are to be handled.
Exceptions provide a way to transfer control from one part of a program to another. ABAP exception handling is built upon three keywords − RAISE, TRY, CATCH and CLEANUP. Assuming a block will raise an exception, a method catches an exception using a combination of the TRY and CATCH keywords. A TRY - CATCH block is placed around the code that might generate an exception. Following is the syntax for using TRY – CATCH −
TRY.
Try Block <Code that raises an exception>
CATCH
Catch Block <exception handler M>
. . .
. . .
. . .
CATCH
Catch Block <exception handler R>
CLEANUP.
Cleanup block <to restore consistent state>
ENDTRY.
RAISE − Exceptions are raised to indicate that some exceptional situation has occurred. Usually, an exception handler tries to repair the error or find an alternative solution.
TRY − The TRY block contains the application coding whose exceptions are to be handled. This statement block is processed sequentially. It can contain further control structures and calls of procedures or other ABAP programs. It is followed by one or more catch blocks.
CATCH − A program catches an exception with an exception handler at the place in a program where you want to handle the problem. The CATCH keyword indicates the catching of an exception.
CLEANUP − The statements of the CLEANUP block are executed whenever an exception occurs in a TRY block that is not caught by the handler of the same TRY - ENDTRY construct. Within the CLEANUP clause, the system can restore an object to a consistent state or release external resources. That is, cleanup work can be executed for the context of the TRY block.
Exceptions can be raised at any point in a method, a function module, a subroutine, and so on. There are two ways an exception can be raised −
Exceptions raised by ABAP runtime system.
For instance Y = 1 / 0. This will result in a run time error of type CX_SY_ZERODIVIDE.
Exceptions raised by ABAP runtime system.
For instance Y = 1 / 0. This will result in a run time error of type CX_SY_ZERODIVIDE.
Exceptions raised by programmer.
Raise and create an exception object simultaneously. Raise an exception with an exception object that already exists in the first scenario. The syntax is: RAISE EXCEPTION exep.
Exceptions raised by programmer.
Raise and create an exception object simultaneously. Raise an exception with an exception object that already exists in the first scenario. The syntax is: RAISE EXCEPTION exep.
Handlers are used to catch exceptions.
Let’s take a look at a code snippet −
DATA: result TYPE P LENGTH 8 DECIMALS 2,
exref TYPE REF TO CX_ROOT,
msgtxt TYPE STRING.
PARAMETERS: Num1 TYPE I, Num2 TYPE I.
TRY.
result = Num1 / Num2.
CATCH CX_SY_ZERODIVIDE INTO exref.
msgtxt = exref→GET_TEXT( ).
CATCH CX_SY_CONVERSION_NO_NUMBER INTO exref.
msgtxt = exref→GET_TEXT( ).
In the above code snippet, we are trying to divide Num1 by Num2 to get the result in a float type variable.
Two types of exceptions could be generated.
Number conversion error.
Number conversion error.
Divide by zero exception. Handlers catch CX_SY_CONVERSION_NO_NUMBER exception and also the CX_SY_ZERODIVIDE exception. Here the GET_TEXT( ) method of the exception class is used to get the description of the exception.
Divide by zero exception. Handlers catch CX_SY_CONVERSION_NO_NUMBER exception and also the CX_SY_ZERODIVIDE exception. Here the GET_TEXT( ) method of the exception class is used to get the description of the exception.
Here are the five attributes and methods of exceptions −
Textid
Used to define different texts for exceptions and also affects the result of the method get_text.
Previous
This attribute can store the original exception that allows you to build a chain of exceptions.
get_text
This returns the textual representation as a string as per the system language of the exception.
get_longtext
This returns the long variant of the textual representation of the exception as a string.
get_source_position
Gives the program name and line number reached where the exception was raised.
REPORT ZExceptionsDemo.
PARAMETERS Num_1 TYPE I.
DATA res_1 TYPE P DECIMALS 2.
DATA orf_1 TYPE REF TO CX_ROOT.
DATA txt_1 TYPE STRING.
start-of-selection.
Write: / 'Square Root and Division with:', Num_1.
write: /.
TRY.
IF ABS( Num_1 ) > 150.
RAISE EXCEPTION TYPE CX_DEMO_ABS_TOO_LARGE.
ENDIF.
TRY.
res_1 = SQRT( Num_1 ).
Write: / 'Result of square root:', res_1.
res_1 = 1 / Num_1.
Write: / 'Result of division:', res_1.
CATCH CX_SY_ZERODIVIDE INTO orf_1.
txt_1 = orf_1→GET_TEXT( ).
CLEANUP.
CLEAR res_1.
ENDTRY.
CATCH CX_SY_ARITHMETIC_ERROR INTO orf_1.
txt_1 = orf_1→GET_TEXT( ).
CATCH CX_ROOT INTO orf_1.
txt_1 = orf_1→GET_TEXT( ).
ENDTRY.
IF NOT txt_1 IS INITIAL.
Write / txt_1.
ENDIF.
Write: / 'Final Result is:', res_1.
In this example, if the number is greater than 150, the exception CX_DEMO_ABS_TOO_LARGE is raised. The above code produces the following output for the number 160.
Square Root and Division with: 160
The absolute value of number is too high
Final Result is: 0.00
As you are aware, SQL can be divided into two parts −
DML (Data Manipulation Language)
DDL (Data Definition Language)
DML part consists of query and update commands such as SELECT, INSERT, UPDATE, DELETE, etc. and ABAP programs handle the DML part of SQL. DDL part consists of commands such as CREATE TABLE, CREATE INDEX, DROP TABLE, ALTER TABLE, etc. and ABAP Dictionary handles the DDL part of SQL.
ABAP Dictionary can be viewed as metadata (i.e. data about data) that resides in the SAP database along with the metadata maintained by the database. The Dictionary is used to create and manage data definitions and to create Tables, Data Elements, Domains, Views and Types.
The basic types in ABAP Dictionary are as follows −
Data elements describe an elementary type by defining the data type, length and possibly decimal places.
Data elements describe an elementary type by defining the data type, length and possibly decimal places.
Structures with components that can have any type.
Structures with components that can have any type.
Table types describe the structure of an internal table.
Table types describe the structure of an internal table.
Various objects in the Dictionary environment can be referenced in ABAP programs. The Dictionary is known as the global area. The objects in the Dictionary are global to all ABAP programs and the data in ABAP programs can be declared by reference to these Dictionary global objects.
The Dictionary supports the definition of user-defined types and these types are used in ABAP programs. They also define the structure of database objects such as tables, views and indexes. These objects are created automatically in the underlying database in their Dictionary definitions when the objects are activated. The Dictionary also provides editing tools like Search Help and locking tool like Lock Objects.
ABAP Dictionary achieves the following −
Enforces data integrity.
Manages data definitions without redundancy.
Integrates tightly with rest of the ABAP development workbench.
Any complex user-defined type can be built from the 3 basic types in the Dictionary. Customer data is stored in a structure ‘Customer’ with the components Name, Address and Telephone as depicted in the following image. Name is also a structure with components, First name and Last name. Both of these components are elementary because their type is defined by a data element.
The type of component Address is defined by a structure whose components are also structures, and the Telephone component is defined by a table type because a customer can have more than one telephone number. Types are used in ABAP programs and also to define the types of interface parameters of function modules.
The three basic objects for defining data in the ABAP Dictionary are Domains, Data elements and Tables. The domain is used for the technical definition of a table field such as field type and length, and the data element is used for the semantic definition (short description). A data element describes the meaning of a domain in a certain business context. It contains primarily the field help and the field labels in the screen.
The domain is assigned to the data element, which in turn is assigned to the table fields or structure fields. For instance, the MATNR domain (CHAR material number) is assigned to data elements such as MATNR_N, MATNN and MATNR_D, and these are assigned to many table fields and structure fields.
Before you create a new domain, check whether any existing domains have the same technical specifications required in your table field. If so, we are supposed to use that existing domain. Let’s discuss the procedure for creating the domain.
Step 1 − Go to Transaction SE11.
Step 2 − Select the radio button for Domain in the initial screen of the ABAP Dictionary, and enter the name of the domain as shown in the following screenshot. Click the CREATE button. You may create domains under the customer namespaces, and the name of the object always starts with ‘Z’ or ‘Y’.
Step 3 − Enter the description in the short text field of the maintenance screen of the domain. In this case, it is “Customer Domain”. Note − You cannot enter any other attribute until you have entered this attribute.
Step 4 − Enter the Data Type, No. of Characters, and Decimal Places in the Format block of the Definition tab. Press the key on Output Length and it proposes and displays the output length. If you overwrite the proposed output length, you may see a warning while activating the domain. You may fill in the Convers. Routine, Sign and Lower Case fields if required. But these are always optional attributes.
Step 5 − Select the Value Range tab. If the domain is restricted to having only fixed values then enter the fixed values or intervals. Define the value table if the system has to propose this table as a check table while defining a foreign key for the fields referring to this domain. But all these are optional attributes.
Step 6 − Save your changes. The Create Object Directory Entry pop-up appears and asks for a package. You may enter the package name in which you are working. If you do not have any package then you may create it in the Object Navigator or you can save your domain using the Local Object button.
Step 7 − Activate your domain. Click on the Activate icon (matchstick icon) or press CTRL + F3 to activate the domain. A pop-up window appears, listing the 2 currently inactive objects as shown in the following snapshot −
Step 8 − At this point, the top entry labeled ‘DOMA’ with the name ZSEP_18 is to be activated. As this is highlighted, click the green tick button. This window disappears and the status bar will display the message ‘Object activated’.
If error messages or warnings occurred when you activated the domain, the activation log is displayed automatically. The activation log displays information about activation flow. You can also call the activation log with Utilities(M) → Activation log.
Data elements describe the individual fields in the ABAP Data Dictionary. They are the smallest indivisible units of the complex types, and they are used to define the type of table field, structure component or row type of a table. Information about the meaning of a table field and also information about editing the corresponding screen field could be assigned to a data element. This information is automatically available to all the screen fields that refer to the data element. Data elements describe either elementary types or reference types.
Before creating a new data element, you need to check whether any existing data elements have the same semantic specifications required in your table field. If so, you may use that existing data element. You can assign the data element with a predefined type, domain, or reference type.
Following is the procedure for creating the data element −
Step 1 − Go to Transaction SE11.
Step 2 − Select the radio button for Data type in the initial screen of the ABAP Dictionary, and enter the name of the data element as shown below.
Step 3 − Click the CREATE button. You may create data elements under the customer namespaces, and the name of the object always starts with ‘Z’ or ‘Y’.
Step 4 − Check the Data element radio button on the CREATE TYPE pop-up that appears with three radio buttons.
Step 5 − Click the green checkmark icon. You are directed to the maintenance screen of the data element.
Step 6 − Enter the description in the short text field of the maintenance screen of the data element. In this case, it is “Customer Data Element”. Note − You cannot enter any other attribute until you have entered this attribute.
Step 7 − Assign the data element with the type. You can create an elementary data element by checking elementary type or a reference data element by checking Reference type. You can assign a data element to a Domain or Predefined Type within Elementary Type and with Name of Reference Type or Reference to Predefined Type within Reference Type.
Step 8 − Enter the fields for short text, medium text, long text, and heading in the Field Label tab. You can press Enter and the length is automatically generated for these labels.
Step 9 − Save your changes. The Create Object Directory Entry pop-up appears and asks for a package. You may enter the package name in which you are working. If you do not have any package then you may create it in the Object Navigator or you can save your data element using the Local Object button.
Step 10 − Activate your data element. Click the Activate icon (matchstick icon) or press CTRL + F3 to activate the data element. A pop-up window appears, listing the 2 currently inactive objects as shown in the following screenshot.
Step 11 − At this point, the top entry labeled ‘DTEL’ with the name Z_CUST is to be activated. As this is highlighted, click the green tick button. This window disappears and the status bar will display the message ‘Object activated’.
If error messages or warnings occurred when you activated the data element, the activation log is displayed automatically. The activation log displays information about activation flow. You can also call the activation log with Utilities(M) → Activation log.
Tables can be defined independent of the database in ABAP Dictionary. When a table is activated in ABAP Dictionary, similar copy of its fields is created in the database as well. The tables defined in ABAP Dictionary are translated automatically into the format that is compatible with the database because the definition of the table depends on the database used by the SAP system.
A table can contain one or more fields, each defined with its data type and length. The large amount of data stored in a table is distributed among the several fields defined in the table.
A table consists of many fields, and each field contains many elements. The following table lists the different elements of table fields −
Field name
This is the name given to a field that can contain a maximum of 16 characters. The field name may be composed of digits, letters, and underscores. It must begin with a letter.
Key flag
Determines whether or not a field belongs to a key field.
Field type
Assigns a data type to a field.
Field length
The number of characters that can be entered in a field.
Decimal places
Defines the number of digits permissible after the decimal point. This element is used only for numeric data types.
Short text
Describes the meaning of the corresponding field.
Step 1 − Go to transaction SE11, select the ‘Database table’ radio button, and enter a name for the table to be created. In our case, we have entered the name ZCUSTOMERS1. Click the Create button. The Dictionary: Maintain Table screen appears. Here the ‘Delivery and Maintenance’ tab is selected by default.
Step 2 − Enter an explanatory short text in the Short Description field.
Step 3 − Click the Search Help icon beside the Delivery Class field. Select ‘A [Application table (master and transaction data)]’ option.
Step 4 − Select the ‘Display/Maintenance Allowed’ option from the ‘Data Browser/Table view Maintenance’ drop-down menu. The Dictionary: Maintenance Table screen appears.
Step 5 − Select the Fields tab. The screen containing the options related to the Fields tab appears.
Step 6 − Enter the names of table fields in the Field column. A field name may contain letters, digits, and underscores, but it must always begin with a letter and must not be longer than 16 characters.
The fields that are to be created must also have data elements because they take the attributes, such as data type, length, decimal places, and short text, from the defined data element.
Step 7 − Select the Key column if you want the field to be a part of the table key. Let’s create fields such as CLIENT, CUSTOMER, NAME, TITLE and DOB.
Step 8 − The first field is an important one and it identifies the client which the records are associated with. Enter ‘Client’ as the Field and ‘MANDT’ as the Data Element. The system automatically fills in the Data Type, Length, Decimals and Short Description. The ‘Client’ field is made a key field by checking the ‘Key’ box.
Step 9 − The next field is ‘Customer’. Check the box to make it a key field and enter the new Data Element ‘ZCUSTNUM’. Click the Save button.
Step 10 − As the Data Element ‘ZCUSTNUM’ doesn’t yet exist, it has to be created. Doubleclick the new Data Element and the ‘Create Data Element’ window appears. Answer ‘Yes’ to this and a ‘Maintain Data Element’ window appears.
Step 11 − Enter ‘Customer Number’ in the Short Description area. The Elementary data type called ‘Domain’ should be defined for the new Data element. So enter ‘ZCUSTD1’, double-click it and agree to save the changes made. Choose ‘Yes’ to create the domain and type into the ‘Short Description’ box a description of the domain.
The ‘Definition’ tab opens automatically. The first field is ‘Data Type’.
Step 12 − Click inside the box and select ‘NUMC’ type from the drop-down menu. Enter the number 8 in the ‘No. of characters’ field (a maximum of 8 characters) and enter 0 in ‘Decimal places’ area. The Output length of 8 must be selected and then press Enter. The ‘NUMC’ field’s description must re-appear, confirming that this is a valid entry.
Step 13 − Click Save button and Activate the object.
Step 14 − Press F3 to return to the ‘Maintain/Change Data Element’ screen. Create four Field labels as shown in the following snapshot. After this, Save and Activate the element.
Step 15 − Press the back button to return to the table maintenance screen. The Customer column has the correct Data Type, Length, Decimals and Short Description. This indicates the successful creation of a Data element and also the Domain used.
Similarly, we need to create three additional fields such as NAME, TITLE and DOB.
Step 16 − Select ‘Technical settings’ from the toolbar. Choose APPL0 for the ‘Data class’ and the first size category 0 for the ‘Size’ category’ field. In case of buffering options, ‘Buffering not allowed’ has to be selected.
Step 17 − Click Save. Go back to the table and Activate it. The following screen appears.
The table ‘ZCUSTOMERS1’ is activated.
Structure is a data object that is made up of components of any data type stored one after the other in the memory.
Structures are useful for painting screen fields, and for manipulating data that has a consistent format defined by a discrete number of fields.
A structure may have only a single record at run-time, but a table can have many records.
Step 1 − Go to transaction SE11.
Step 2 − Click on the ‘Data type’ option on the screen. Enter the name 'ZSTR_CUSTOMER1' and click on Create button.
Step 3 − Select the option 'Structure' in the next screen and press Enter. You can see 'Maintain / Change Structure' wizard.
Step 4 − Enter the Short Description as shown in the following snapshot.
Step 5 − Enter the Component (Field Name) and Component Type (Data Element).
Note: Here the component names start with Z as per the SAP recommendation. Let's use data elements that we have already created in the database table.
Step 6 − You need to Save, Check and Activate after providing all the components and component types.
The following screen appears −
Step 7 − As this 'ZSTR_CUSTOMER1' is highlighted, click the green tick button. This window disappears and the status bar will display the message ‘Active’.
The structure is now activated as shown in the following snapshot −
A View acts like a database table only. But it will not occupy storage space. A view acts similar to a virtual table - a table that does not have any physical existence. A view is created by combining the data of one or more tables containing information about an application object. Using views, you can represent a subset of the data contained in a table or you can join multiple tables into a single virtual table.
Data related to an application object is distributed among multiple tables by using database views. They use the inner join condition to join the data of different tables. A maintenance view is used to display and modify the data stored in an application object. Every maintenance view has a maintenance status associated with it.
We use projection view to mask unwanted fields and display only relevant fields in a table. Projection views must be defined over a single transparent table. A projection view contains exactly one table. We can't define selection conditions for projection views.
Step 1 − Select the View radio button on the initial screen of ABAP Dictionary. Enter the name of the view to be created and then click Create button. We entered the name of the view as ZVIEW_TEST.
Step 2 − Select the projection view radio button while choosing view type and click Copy button. The ‘Dictionary: Change View’ screen appears.
Step 3 − Enter a short description in the Short Description field and the name of the table to be used in the Basis Table field as shown in the following snapshot.
Step 4 − Click the ‘Table fields’ button to include the fields of ZCUSTOMERS1 table in the projection view.
Step 5 − The Field Selection from Table ZCUSTOMERS1 screen appears. Select the fields that you wish to include in the projection view as shown in the following snapshot.
Step 6 − After clicking the Copy button, all the selected fields for the projection view are displayed on the ‘Dictionary: Change View’ screen.
Step 7 − Select Maintenance Status tab to define an access method. Choose read-only radio button and ‘Display/Maintenance Allowed with Restrictions’ option from the dropdown menu of ‘Data Browser/Table View Maintenance’.
Step 8 − Save and Activate it. In the ‘Dictionary: Change View’ screen select Utilities(M) > Contents to display the selection screen for ZVIEW_TEST.
Step 9 − Click the Execute icon. The output of the projection view appears as shown in the following screenshot.
The table ZCUSTOMERS1 consists of 5 fields. Here the displayed fields are 3 (Client, Customer Number and Name) with 4 entries. Customer numbers are from 100001 to 100004 with appropriate names.
Search Help, another repository object of ABAP Dictionary, is used to display all the possible values for a field in the form of a list. This list is also known as a hit list. You can select the values that are to be entered in the fields from this hit list instead of manually entering the value, which is tedious and error prone.
Step 1 − Go to transaction SE11. Select the radio button for Search help. Enter the name of the search help to be created. Let's enter the name ZSRCH1. Click on the Create button.
Step 2 − The system will prompt for the search help type to be created. Select the Elementary search help, which is default. The screen to create elementary search help as shown in the following screenshot appears.
Step 3 − In the selection method, we need to indicate whether our source of data is a table or a view. In our case it happens to be a table. The table is ZCUSTOMERS1. It is selected from a selection list.
Step 4 − After the selection method is entered, the next field is the Dialog type. This controls the appearance of the restrictive dialog box. There is a drop-down list with three options. Let's select the option 'Display values immediately'.
Step 5 − Next is the parameter area. For each Search help parameter or field, these column fields have to be entered as per the requirements.
Search help parameter − This is a field from the source of data. The fields from the table are listed in the selection list. The fields participating in the search help would be entered, one field in each row. Let's include the two fields CUSTOMER and NAME. How these two fields participate is indicated in the rest of the columns.
Search help parameter − This is a field from the source of data. The fields from the table are listed in the selection list. The fields participating in the search help would be entered, one field in each row. Let's include the two fields CUSTOMER and NAME. How these two fields participate is indicated in the rest of the columns.
Import − This field is a checkbox for indicating whether a Search help parameter is an import parameter. The export or import is with reference to the search help.
Import − This field is a checkbox for indicating whether a Search help parameter is an import parameter. The export or import is with reference to the search help.
Export − This field is a checkbox for indicating whether a Search help parameter is an export parameter. The export will be transfer of field values from the selection list to screen fields.
Export − This field is a checkbox for indicating whether a Search help parameter is an export parameter. The export will be transfer of field values from the selection list to screen fields.
LPos − Its value controls the physical position of Search help parameter or field in the selection list. If you enter a value 1, the field will appear in the first position in the selection list and so on.
LPos − Its value controls the physical position of Search help parameter or field in the selection list. If you enter a value 1, the field will appear in the first position in the selection list and so on.
SPos − It controls the physical position of Search Help parameter or field in the restrictive dialog box. If you enter a value of 1, the field will appear in the first position in the restrictive dialog box and so on.
SPos − It controls the physical position of Search Help parameter or field in the restrictive dialog box. If you enter a value of 1, the field will appear in the first position in the restrictive dialog box and so on.
Data element − Every Search Help parameter or field by default is assigned a data element that was assigned to it in the source of data (Table or View). This data element name appears in display mode.
Data element − Every Search Help parameter or field by default is assigned a data element that was assigned to it in the source of data (Table or View). This data element name appears in display mode.
Step 6 − Perform a consistency check and activate the search help. Press F8 to execute. The 'Test Search Help ZSRCH1' screen appears as shown in the following screenshot.
Step 7 − Let's enter the number 100004 in the CUSTOMER's 'Ready for inp' screen field. Press Enter.
The customer number, 100004, and the name ‘STEPHEN’ is displayed.
Lock Object is a feature offered by ABAP Dictionary that is used to synchronize access to the same data by more than one program. Data records are accessed with the help of specific programs. Lock objects are used in SAP to avoid the inconsistency when data is inserted into or changed in the database. Tables whose data records are to be locked must be defined in a Lock Object, along with their key fields.
Following are the two main functions accomplished with the lock mechanism −
A program can communicate with other programs about data records that it is just reading or changing.
A program can communicate with other programs about data records that it is just reading or changing.
A program can prevent itself from reading data that has just been changed by another program.
A program can prevent itself from reading data that has just been changed by another program.
A lock request is first generated by the program. Then this request goes to the Enqueue server and the lock is created in the lock table. The Enqueue server sets the lock and the program is finally ready to access data.
Step 1 − Go to transaction SE11. The following screen opens.
Step 2 − Click ‘Lock Object’ radio button. Enter the name of lock object starting with E and click the Create button. Here we use EZLOCK12.
Step 3 − Enter the short description field and click on Tables tab.
Step 4 − Enter the table name in Name field and select the lock mode as Write Lock.
Step 5 − Click on Lock parameter tab, the following screen will appear.
Step 6 − Save and activate. Automatically 2 function modules will generate. To check function modules, we can use Go to → Lock Modules.
Step 7 − Click Lock Modules and the following screen will open.
The lock object is created successfully.
The key fields of a table included in a Lock Object are called lock arguments and they are used as input parameters in function modules. These arguments are used to set and remove the locks generated by the Lock Object definition.
It is a good practice to keep your programs as self-contained and easy to read as possible. Just try to split large and complicated tasks into smaller and simpler ones by placing each task in its individual module, on which the developer can concentrate on without other distractions.
In SAP ABAP environment, modularization involves the organization of programs into modular units, also known as logical blocks. It reduces redundancy and increases program readability even as you are creating it and subsequently during the maintenance cycle. Modularization also enables reusability of the same code again. ABAP has made it necessary for developers to modularize, i.e. organizing the programs relatively more, than in the OOPS-based languages that have relatively more built-in modular features. Once a small, modularized section of code is complete, debugged and so on, it does not subsequently have to be returned to, and developers can then move on and focus on other issues.
ABAP programs are made up of processing blocks known as modularizing processing blocks. They are −
The processing blocks called from outside the program and from the ABAP run-time environment (i.e., event blocks and dialog modules).
The processing blocks called from outside the program and from the ABAP run-time environment (i.e., event blocks and dialog modules).
Processing blocks called from ABAP programs.
Processing blocks called from ABAP programs.
Apart from the modularization with processing blocks, source code modules are used to modularize your source code through macros and include programs.
Modularization at source code level −
Local Macros
Global Include programs
Modularization through processing blocks called from ABAP programs −
Subroutines
Function modules
Modularizing a source code means placing a sequence of ABAP statements in a module. The modularized source code can be called in a program as per the requirement of the user. Source code modules enhance the readability and understandability of ABAP programs. Creating individual source code modules also prevents one from having to repeatedly write the same statements again and again that in turn makes the code easier to understand for anyone going through it for the first time.
A subroutine is a reusable section of code. It is a modularization unit within the program where a function is encapsulated in the form of source code. You page out a part of a program to a subroutine to get a better overview of the main program, and to use the corresponding sequence of statements many times as depicted in the following diagram.
We have program X with 3 different source code blocks. Each block has the same ABAP statements. Basically, they are the same code blocks. To make this code easier to maintain, we can encapsulate the code into a subroutine. We can call this subroutine in our programs as many times as we wish. A subroutine can be defined using Form and EndForm statements.
Following is the general syntax of a subroutine definition.
FORM <subroutine_name>.
<statements>
ENDFORM.
We can call a subroutine by using PERFORM statement. The control jumps to the first executable statement in the subroutine <subroutine_name>. When ENDFORM is encountered, control jumps back to the statement following the PERFORM statement.
Step 1 − Go to transaction SE80. Open the existing program and then right-click on program. In this case, it is 'ZSUBTEST'.
Step 2 − Select Create and then select Subroutine. Write the subroutine name in the field and then click the continue button. The subroutine name is 'Sub_Display' as shown in the following screenshot.
Step 3 − Write the code in FORM and ENDFORM statement block. The subroutine has been created successfully.
We need to include PERFORM statement to call the subroutine. Let’s take a look at the code −
REPORT ZSUBTEST.
PERFORM Sub_Display.
* Form Sub_Display
* --> p1 text
* <-- p2 text
FORM Sub_Display.
Write: 'This is Subroutine'.
Write: / 'Subroutine created successfully'.
ENDFORM. " Sub_Display
Step 4 − Save, activate and execute the program. The above code produces the following output −
Subroutine Test:
This is Subroutine
Subroutine created successfully
Hence, using subroutines makes your program more function-oriented. It splits the program's task into sub-functions, so that each subroutine is responsible for one subfunction. Your program becomes easier to maintain as changes to functions often only have to be implemented in the subroutine.
If we want to reuse the same set of statements more than once in a program, we need to include them in a macro. For example, a macro can be useful for long calculations or for writing complex WRITE statements. We can only use a macro within a program in which it is defined. Macro definition should occur before the macro is used in the program.
Macros are designed based on placeholders. Placeholder works like pointers in C language. You can define a macro within the DEFINE...END-OF-DEFINITION statement.
Following is the basic syntax of a macro definition −
DEFINE <macro_name>. <statements>
END-OF-DEFINITION.
......
<macro_name> [<param1> <param2>....].
It is necessary to define a macro first before invoking it. The <param1>.... replaces the placeholders &1...in the ABAP statements contained in the macro definition.
The maximum number of placeholders in a macro definition is nine. That is, when a program is executed, the SAP system replaces the macro by appropriate statements and the placeholders &1, &2,....&9 are replaced by the parameters param1, param2,....param9. We may invoke a macro within another macro, but not the same macro.
Go to transaction SE38. Create a new program ZMACRO_TEST along with the description in the short text field, and also with appropriate attributes such as Type and Status as shown in the following screenshot −
Following is the code −
REPORT ZMACRO_TEST.
DEFINE mac_test.
WRITE: 'This is Macro &1'.
END-OF-DEFINITION.
PARAMETERS: s1 type C as checkbox.
PARAMETERS: s2 type C as checkbox.
PARAMETERS: s3 type C as checkbox default 'X'.
START-OF-SELECTION.
IF s1 = 'X'.
mac_test 1. ENDIF.
IF s2 = 'X'.
mac_test 2.
ENDIF.
IF s3 = 'X'.
mac_test 3.
ENDIF.
We have 3 checkboxes. While executing the program, let’s select the S2 checkbox.
The above code produces the following output −
A Macro Program
This is Macro 2
If all checkboxes are selected, the code produces the following output −
A Macro Program
This is Macro 1 This is Macro 2 This is Macro 3
Function modules make up a major part of a SAP system, because for years SAP has modularized code using function modules, allowing for code reuse, by themselves, their developers and also by their customers.
Function modules are sub-programs that contain a set of reusable statements with importing and exporting parameters. Unlike Include programs, function modules can be executed independently. SAP system contains several predefined function modules that can be called from any ABAP program. The function group acts as a kind of container for a number of function modules that would logically belong together. For instance, the function modules for an HR payroll system would be put together into a function group.
To look at how to create function modules, the function builder must be explored. You can find the function builder with transaction code SE37. Just type a part of a function module name with a wild card character to demonstrate the way function modules can be searched for. Type *amount* and then press the F4 key.
The results of the search will be displayed in a new window. The function modules are displayed in the lines with blue background and their function groups in pink lines. You may look further at the function group ISOC by using the Object Navigator screen (Transaction SE80). You can see a list of function modules and also other objects held in the function group. Let's consider the function module SPELL_AMOUNT. This function module converts numeric figures into words.
Step 1 − Go to transaction SE38 and create a new program called Z_SPELLAMOUNT.
Step 2 − Enter some code so that a parameter can be set up where a value could be entered and passed on to the function module. The text element text-001 here reads ‘Enter a Value’.
Step 3 − To write the code for this, use CTRL+F6. After this, a window appears where ‘CALL FUNCTION’ is the first option in a list. Enter 'spell_amount' in the text box and click the continue button.
Step 4 − Some code is generated automatically. But we need to enhance the IF statement to include a code to WRITE a message to the screen to say "The function module returned a value of: sy-subrc” and add the ELSE statement so as to write the correct result out when the function module is successful. Here, a new variable must be set up to hold the value returned from the function module. Let's call this as 'result'.
Following is the code −
REPORT Z_SPELLAMOUNT.
data result like SPELL.
selection-screen begin of line.
selection-screen comment 1(15) text-001.
parameter num_1 Type I.
selection-screen end of line.
CALL FUNCTION 'SPELL_AMOUNT'
EXPORTING
AMOUNT = num_1
IMPORTING
IN_WORDS = result.
IF SY-SUBRC <> 0.
Write: 'Value returned is:', SY-SUBRC.
else.
Write: 'Amount in words is:', result-word.
ENDIF.
Step 5 − The variable which the function module returns is called IN_WORDS. Set up the corresponding variable in the program called ‘result’. Define IN_WORDS by using the LIKE statement to refer to a structure called SPELL.
Step 6 − Save, activate and execute the program. Enter a value as shown in the following screenshot and press F8.
The above code produces the following output −
Spelling the Amount
Amount in words is:
FIVE THOUSAND SIX HUNDRED EIGHTY
Include programs are global repository objects used to modularize the source code. They allow you to use the same source code in different programs. Include programs also allow you to manage complex programs in an orderly way. In order to use an include program in another program, we use the following syntax −
INCLUDE <program_name>.
INCLUDE statement has the same effect as copying the source code of the include program <program_name> into another program. As include program can’t run independently, it has to be built into other programs. You may also nest include programs.
Following are a couple of restrictions while writing the code for Include programs −
Include programs can't call themselves.
Include programs must contain complete statements.
Following are the steps to create and use an Include program −
Step 1 − Create the program (Z_TOBEINCLUDED) to be included in ABAP Editor. Code to be included in ABAP Editor is −
PROGRAM Z_TOBEINCLUDED.
Write: / 'This program is started by:', SY-UNAME,
/ 'The Date is:', SY-DATUM,
/ 'Time is', SY-UZEIT.
Step 2 − Set the Type of the program to INCLUDE program, as shown in the following screenshot.
Step 3 − Click the ‘Save’ button and save the program in a package named ZINCL_PCKG.
Step 4 − Create another program where the program Z_TOBEINCLUDED has to be used. Here we have created another program named Z_INCLUDINGTEST and assigned the type for the program as Executable program.
Step 5 − The coding for Z_INCLUDINGTEST program includes the Z_TOBEINCLUDED program with the help of the INCLUDE statement as shown in the following code.
REPORT Z_INCLUDINGTEST.
INCLUDE Z_TOBEINCLUDED.
Step 6 − Save, activate and execute the program.
The above code produces the following output −
This program is started by: SAPUSER
The Date is: 06.10.2015
Time is 13:25:11
Open SQL indicates the subset of ABAP statements that enable direct access to the data in the central database of the current AS ABAP. Open SQL statements map the Data Manipulation Language functionality of SQL in ABAP that is supported by all database systems.
The statements of Open SQL are converted to database specific SQL in the Open SQL interface of the database interface. They are then transferred to the database system and executed. Open SQL statements can be used to access database tables that are declared in the ABAP Dictionary. The central database of AS ABAP is accessed by default and also access to other databases is possible via secondary database connections.
Whenever any of these statements are used in an ABAP program, it is important to check whether the action executed has been successful. If one tries to insert a record into a database table and it is not inserted correctly, it is very essential to know so that the appropriate action can be taken in the program. This can done using a system field that has already been used, that is SY-SUBRC. When a statement is executed successfully, the SY-SUBRC field will contain a value of 0, so this can be checked for and one can continue with the program if it appears.
The DATA statement is used to declare a work area. Let's give this the name 'wa_customers1'. Rather than declaring one data type for this, several fields that make up the table can be declared. The easiest way to do this is using the LIKE statement.
The wa_customers1 work area is declared here LIKE the ZCUSTOMERS1 table, taking on the same structure without becoming a table itself. This work area can only store one record. Once it has been declared, the INSERT statement can be used to insert the work area and the record it holds into the table. The code here will read as 'INSERT ZCUSTOMERS1 FROM wa_customers1'.
The work area has to be filled with some data. Use the field names from the ZCUSTOMERS1 table. This can be done by forward navigation, double clicking the table name in the code or by opening a new session and using the transaction SE11. The fields of the table can then be copied and pasted into the ABAP editor.
Following is the code snippet −
DATA wa_customers1 LIKE ZCUSTOMERS1.
wa_customers1-customer = '100006'.
wa_customers1-name = 'DAVE'.
wa_customers1-title = 'MR'.
wa_customers1-dob = '19931017'.
INSERT ZCUSTOMERS1 FROM wa_customers1.
CHECK statement can then be used as follows. It means that if the record is inserted correctly, the system will state this. If not, then the SY-SUBRC code which will not equal zero will be displayed. Following is the code snippet −
IF SY-SUBRC = 0.
WRITE 'Record Inserted Successfully'.
ELSE.
WRITE: 'The return code is ', SY-SUBRC.
ENDIF.
Check the program, save, activate the code, and then test it. The output window should display as 'Record Inserted Successfully'.
CLEAR statement allows a field or variable to be cleared out for the insertion of new data in its place, allowing it to be reused. CLEAR statement is generally used in programs and it allows existing fields to be used many times.
In the previous code snippet, the work area structure has been filled with data to create a new record to be inserted into the ZCUSTOMERS1 table and then a validation check is performed. If we want to insert a new record, CLEAR statement must be used so that it can then be filled again with the new data.
If you want to update one or more existing records in a table at the same time then use UPDATE statement. Similar to INSERT statement, a work area is declared, filled with the new data that is then put into the record as the program is executed. The record previously created with the INSERT statement will be updated here. Just edit the text stored in the NAME and TITLE fields. Then on a new line, the same structure as for the INSERT statement is used, and this time by using the UPDATE statement as shown in the following code snippet −
DATA wa_customers1 LIKE ZCUSTOMERS1.
wa_customers1-customer = '100006'.
wa_customers1-name = 'RICHARD'.
wa_customers1-title = 'MR'.
wa_customers1-dob = '19931017'.
UPDATE ZCUSTOMERS1 FROM wa_customers1.
As UPDATE statement gets executed, you can view the Data Browser in the ABAP Dictionary to see that the record has been updated successfully.
MODIFY statement can be considered as a combination of the INSERT and UPDATE statements. It can be used to either insert a new record or modify an existing record. It follows a similar syntax to the previous two statements in modifying the record from the data entered into a work area.
When this statement is executed, the key fields involved will be checked against those in the table. If a record with these key field values already exist, it will be updated. If not, then a new record will be created.
Following is the code snippet for creating a new record −
CLEAR wa_customers1.
DATA wa_customers1 LIKE ZCUSTOMERS1.
wa_customers1-customer = '100007'.
wa_customers1-name = 'RALPH'.
wa_customers1-title = 'MR'.
wa_customers1-dob = '19910921'.
MODIFY ZCUSTOMERS1 FROM wa_customers1.
In this example, CLEAR statement is used so that a new entry can be put into the work area, and then customer (number) 100007 is added. Since this is a new, unique key field value, a new record will be inserted, and another validation check is executed.
When this is executed and the data is viewed in the Data Browser, a new record will have been created for the customer number 100007 (RALPH).
The above code produces the following output (table contents) −
The term ‘Native SQL’ refers to all statements that can be statically transferred to the Native SQL interface of the database interface. Native SQL statements do not fall within the language scope of ABAP and do not follow the ABAP syntax. ABAP merely contains statements for isolating program sections in which Native SQL statements can be listed.
In native SQL, mainly database-specific SQL statements can be used. These are transferred unchanged from the native SQL interface to a database system and executed. The full SQL language scope of the relevant database can be used and the addressed database tables do not have to be declared in the ABAP Dictionary. There is also a small set of SAP specific Native SQL statements that are handled in a specific way by the native SQL interface.
To use a Native SQL statement, you have to precede it with the EXEC SQL statement and end with ENDEXEC statement.
Following is the syntax −
EXEC SQL PERFORMING <form>.
<Native SQL statement>
ENDEXEC.
These statements define an area in an ABAP program where one or more Native SQL statements can be listed. The statements entered are passed to the Native SQL interface and then processed as follows −
All SQL statements that are valid for the program interface of the addressed database system can be listed between EXEC and ENDEXEC, in particular the DDL (data definition language) statements.
All SQL statements that are valid for the program interface of the addressed database system can be listed between EXEC and ENDEXEC, in particular the DDL (data definition language) statements.
These SQL statements are passed from the Native SQL interface to the database system largely unchanged. The syntax rules are specified by the database system, especially the case sensitivity rules for database objects.
These SQL statements are passed from the Native SQL interface to the database system largely unchanged. The syntax rules are specified by the database system, especially the case sensitivity rules for database objects.
If the syntax allows a separator between individual statements, you may include many Native SQL statements between EXEC and ENDEXEC.
If the syntax allows a separator between individual statements, you may include many Native SQL statements between EXEC and ENDEXEC.
SAP specific Native SQL language elements can be specified between EXEC and ENDEXEC. These statements are not passed directly from the Native SQL interface to the database, but they are transformed appropriately.
SAP specific Native SQL language elements can be specified between EXEC and ENDEXEC. These statements are not passed directly from the Native SQL interface to the database, but they are transformed appropriately.
SPFLI is a standard SAP Table that is used to store Flight schedule information. This is available within R/3 SAP systems depending on the version and release level. You can view this information when you enter the Table name SPFLI into the relevant SAP transaction such as SE11 or SE80. You can also view the data contained in this database table by using these two transactions.
REPORT ZDEMONATIVE_SQL.
DATA: BEGIN OF wa,
connid TYPE SPFLI-connid,
cityfrom TYPE SPFLI-cityfrom,
cityto TYPE SPFLI-cityto,
END OF wa.
DATA c1 TYPE SPFLI-carrid VALUE 'LH'.
EXEC SQL PERFORMING loop_output.
SELECT connid, cityfrom, cityto
INTO :wa
FROM SPFLI
WHERE carrid = :c1
ENDEXEC.
FORM loop_output.
WRITE: / wa-connid, wa-cityfrom, wa-cityto.
ENDFORM.
The above code produces the following output −
0400 FRANKFURT NEW YORK
2402 FRANKFURT BERLIN
0402 FRANKFURT NEW YORK
Internal table is actually a temporary table, which contains the records of an ABAP program that it is being executed. An internal table exists only during the run-time of a SAP program. They are used to process large volumes of data by using ABAP language. We need to declare an internal table in an ABAP program when you need to retrieve data from database tables.
Data in an internal table is stored in rows and columns. Each row is called a line and each column is called a field. In an internal table, all the records have the same structure and key. The individual records of an internal table are accessed with an index or a key. As internal table exists till the associated program is being executed, the records of the internal table are discarded when the execution of the program is terminated. So internal tables can be used as temporary storage areas or temporary buffers where data can be modified as required. These tables occupy memory only at run-time and not at the time of their declaration.
Internal tables only exist when a program is running, so when the code is written, the internal table must be structured in such a way that the program can make use of it. You will find that internal tables operate in the same way as structures. The main difference being that structures only have one line, while an internal table can have as many lines as required.
An internal table can be made up of a number of fields, corresponding to the columns of a table, just as in the ABAP dictionary a table was created using a number of fields. Key fields can also be used with internal tables, and while creating these internal tables they offer slightly more flexibility. With internal tables, one can specify a non-unique key, allowing any number of non-unique records to be stored, and allowing duplicate records to be stored if required.
The size of an internal table or the number of lines it contains is not fixed. The size of an internal table changes according to the requirement of the program associated with the internal table. But it is recommended to keep internal tables as small as possible. This is to avoid the system running slowly as it struggles to process enormous amounts of data.
Internal tables are used for many purposes −
They can be used to hold results of calculations that could be used later in the program.
They can be used to hold results of calculations that could be used later in the program.
An internal table can also hold records and data so that this can be accessed quickly rather than having to access this data from database tables.
An internal table can also hold records and data so that this can be accessed quickly rather than having to access this data from database tables.
They are hugely versatile. They can be defined using any number of other defined structures.
They are hugely versatile. They can be defined using any number of other defined structures.
Assume that a user wants to create a list of contact numbers of various customers from one or several large tables. The user first creates an internal table, selects the relevant data from customer tables and then places the data in the internal table. Other users can access and use this internal table directly to retrieve the desired information, instead of writing database queries to perform each operation during the run-time of the program.
DATA statement is used to declare an internal table. The program must be told where the table begins and ends. So use the BEGIN OF statement and then declare the table name. After this, the OCCURS addition is used, followed by a number, here 0. OCCURS tells SAP that an internal table is being created, and the 0 states that it will not contain any records initially. It will then expand as it is filled with data.
Following is the syntax −
DATA: BEGIN OF <internal_tab> Occurs 0,
Let’s create the fields on a new line. For instance, create ‘name’ which is declared as LIKE ZCUSTOMERS1-name. Create another field called ‘dob’, LIKE ZCUSTOMERS1-dob. It is useful initially to give the field names in internal tables the same names as other fields that have been created elsewhere. Finally, declare the end of the internal table with “END OF <internal_tab>.” as shown in the following code −
DATA: BEGIN OF itab01 Occurs 0,
name LIKE ZCUSTOMERS1-name,
dob LIKE ZCUSTOMERS1-dob,
END OF itab01.
Here ‘itab01’ is commonly used shorthand when creating temporary tables in SAP. The OCCURS clause is used to define the body of an internal table by declaring the fields for the table. When the OCCURS clause is used, you can specify a numeric constant ‘n’ to determine additional default memory if required. The default size of memory that is used by the OCCUR 0 clause is 8 KB. The structure of the internal table is now created, and the code can be written to fill it with records.
An internal table can be created with or without using a header line. To create an internal table with a header line, use either the BEGIN OF clause before the OCCURS clause or the WITH HEADER LINE clause after the OCCURS clause in the definition of the internal table. To create an internal table without a header line, use the OCCURS clause without the BEGIN OF clause.
You can also create an internal table as a local data type (a data type used only in the context of the current program) by using the TYPES statement. This statement uses the TYPE or LIKE clause to refer to an existing table.
The syntax to create an internal table as a local data type is −
TYPES <internal_tab> TYPE|LIKE <internal_tab_type> OF
<line_type_itab> WITH <key> INITIAL SIZE <size_number>.
Here the <internal_tab_type> specifies a table type for an internal table <internal_tab> and <line_type_itab> specifies the type for a line of an internal table. In TYPES statement, you can use the TYPE clause to specify the line type of an internal table as a data type and LIKE clause to specify the line type as a data object. Specifying a key for an internal table is optional and if the user does not specify a key, the SAP system defines a table type with an arbitrary key.
INITIAL SIZE <size_number> creates an internal table object by allocating an initial amount of memory to it. In the preceding syntax, the INITIAL SIZE clause reserves a memory space for size_number table lines. Whenever an internal table object is declared, the size of the table does not belong to the data type of the table.
Note − Much less memory is consumed when an internal table is populated for the first time.
Step 1 − Open the ABAP Editor by executing the SE38 transaction code. The initial screen of ABAP Editor appears.
Step 2 − In the initial screen, enter a name for the program, select the Source code radio button and click the Create button to create a new program.
Step 3 − In the 'ABAP: Program Attributes' dialog box, enter a short description for the program in the Title field, select the 'Executable program' option from the Type drop-down menu in the Attributes group box. Click the Save button.
Step 4 − Write the following code in ABAP editor.
REPORT ZINTERNAL_DEMO.
TYPES: BEGIN OF CustomerLine,
Cust_ID TYPE C,
Cust_Name(20) TYPE C,
END OF CustomerLine.
TYPES mytable TYPE SORTED TABLE OF CustomerLine
WITH UNIQUE KEY Cust_ID.
WRITE:/'The mytable is an Internal Table'.
Step 5 − Save, activate and execute the program as usual.
In this example, mytable is an internal table and a unique key is defined on the Cust_ID field.
The above code produces the following output −
The mytable is an Internal Table.
In internal tables, populating includes features such as selection, insertion and append. This chapter focuses on INSERT and APPEND statements.
INSERT statement is used to insert a single line or a group of lines into an internal table.
Following is the syntax to add a single line to an internal table −
INSERT <work_area_itab> INTO <internal_tab> INDEX <index_num>.
In this syntax, the INSERT statement inserts a new line in the internal_tab internal table. A new line can be inserted by using the work_area_itab INTO expression before the internal_tab parameter. When the work_area_itab INTO expression is used, the new line is taken from the work_area_itab work area and inserted into the internal_tab table. However, when the work_area_itab INTO expression is not used to insert a line, the line is taken from the header line of the internal_tab table.
When a new line is inserted in an internal table by using the INDEX clause, the index number of the lines after the inserted line is incremented by 1. If an internal table contains <index_num> - 1 lines, the new line is added at the end of the table. When the SAP system successfully adds a line to an internal table, the SY-SUBRC variable is set to 0.
Following is a sample program that uses the insert statement.
REPORT ZCUSLIST1.
DATA: BEGIN OF itable1 OCCURS 4,
F1 LIKE SY-INDEX,
END OF itable1.
DO 4 TIMES.
itable1-F1 = sy-index.
APPEND itable1.
ENDDO.
itable1-F1 = -96.
INSERT itable1 INDEX 2.
LOOP AT itable1.
Write / itable1-F1.
ENDLOOP.
LOOP AT itable1 Where F1 ≥ 3.
itable1-F1 = -78.
INSERT itable1.
ENDLOOP.
Skip.
LOOP AT itable1.
Write / itable1-F1.
ENDLOOP.
The above code produces the following outp −
1
96-
2
3
4
1
96-
2
78-
3
78-
4
In the above example, the DO loop appends 4 rows containing the numbers 1 through 4 to it. The header line component itable1-F1 has been assigned a value of -96. Insert statement inserts the header line as new row into the body before row 3. The existing row 3 becomes row 4 after the insert. The LOOP AT statement retrieves those rows from the internal table that have an F1 value greater than or equal to 3. Before each row, Insert statement inserts a new row from the header line of it. Prior to the insert, the F1 component has been changed to contain -78.
After each insert statement is executed, the system re-indexes all rows below the one inserted. This introduces overhead when you insert rows near the top of a large internal table. If you need to insert a block of rows into a large internal table, prepare another table with the rows to be inserted and use insert lines instead.
When inserting a new row inside itable1 inside of a loop at itable1, it doesn’t affect the internal table instantly. It actually becomes effective on the next loop pass. While inserting a row after the current row, the table is re-indexed at the ENDLOOP. The sy-tabix is incremented and the next loop processes the row pointed to by sy-tabix. For instance, if you are in the second loop pass and you insert a record before row 3. When endloop is executed, the new row becomes row 3 and the old row 3 becomes row 4 and so on. Sy-tabix is incremented by 1, and the next loop pass processes the newly inserted record.
The APPEND statement is used to add a single row or line to an existing internal table. This statement copies a single line from a work area and inserts it after the last existing line in an internal table. The work area can be either a header line or any other field string with the same structure as a line of an internal table. Following is the syntax of the APPEND statement that is used to append a single line in an internal table −
APPEND <record_for_itab> TO <internal_tab>.
In this syntax, the <record_for_itab> expression can be represented by the <work_area_itab> work area, which is convertible to a line type or by the INITIAL LINE clause. If the user uses a <work_area_itab> work area, the SAP system adds a new line to the <internal_tab> internal table and populates it with the content of the work area. The INITIAL LINE clause appends a blank line that contains the initial value for each field of the table structure. After each APPEND statement, the SY-TABIX variable contains the index number of the appended line.
Appending lines to standard and sorted tables with a non-unique key works regardless of whether the lines with the same key already exist in the table. In other words, duplicate entries may occur. However, a run-time error occurs if the user attempts to add a duplicate entry to a sorted table with a unique key or if the user violates the sort order of a sorted table by appending the lines to it.
REPORT ZCUSLIST1.
DATA: BEGIN OF linv Occurs 0,
Name(20) TYPE C,
ID_Number TYPE I,
END OF linv.
DATA table1 LIKE TABLE OF linv.
linv-Name = 'Melissa'.
linv-ID_Number = 105467.
APPEND linv TO table1.
LOOP AT table1 INTO linv.
Write: / linv-name, linv-ID_Number.
ENDLOOP.
The above code produces the following output −
Melissa 105467
When we read a record from an internal table with a header line, that record is moved from the table itself into the header line. It is then the header line that our program works with. The same applies while creating a new record. It is the header line with which you work with and from which the new record is sent to the table body itself.
To copy the records, we can use a SELECT statement to select all of the records from the table and then use MOVE statement that will move the records from the original table into the new internal table into the fields where the names correspond.
Following is the syntax for MOVE statement −
MOVE <table_field> TO <internal_tab_field>.
REPORT ZCUSLIST1.
TABLES: ZCUSTOMERS1.
DATA: BEGIN OF itab01 Occurs 0,
name LIKE ZCUSTOMERS1-name,
dob LIKE ZCUSTOMERS1-dob,
END OF itab01.
Select * FROM ZCUSTOMERS1.
MOVE ZCUSTOMERS1-name TO itab01-name.
MOVE ZCUSTOMERS1-dob TO itab01-dob.
ENDSELECT.
Write: / itab01-name, itab01-dob.
The above code produces the following output −
MARGARET 02.11.1994
The select loop fills each field one at a time, using the MOVE statement to move the data from one table’s field to the other. In the above example, MOVE statements were used to move the contents of the ZCUSTOMERS1 table to the corresponding fields in the internal table. You can accomplish this action with just one line of code. You can use the MOVECORRESPONDING statement.
Following is the syntax for MOVE-CORRESPONDING statement −
MOVE-CORRESPONDING <table_name> TO <internal_tab>.
It tells the system to move the data from the fields of ZCUSTOMERS1 to their corresponding fields in itab01.
REPORT ZCUSTOMERLIST.
TABLES: ZCUSTOMERS1.
DATA: Begin of itab01 occurs 0,
customer LIKE ZCUSTOMERS1-customer,
name LIKE ZCUSTOMERS1-name,
title LIKE ZCUSTOMERS1-title,
dob LIKE ZCUSTOMERS1-dob,
END OF itab01.
SELECT * from ZCUSTOMERS1.
MOVE-Corresponding ZCUSTOMERS1 TO itab01.
APPEND itab01.
ENDSELECT.
LOOP AT itab01.
Write: / itab01-name, itab01-dob.
ENDLOOP.
The above code produces the following output −
MARK 21.05.1981
JAMES 14.08.1977
AURIELE 19.06.1990
STEPHEN 22.07.1985
MARGARET 02.11.1994
This is made possible by the fact that both have matching field names. When making use of this statement, you need to make sure that both fields have matching data types and lengths. It has been done here with the LIKE statement previously.
We can read the lines of a table by using the following syntax of the READ TABLE statement −
READ TABLE <internal_table> FROM <work_area_itab>.
In this syntax, the <work_area_itab> expression represents a work area that is compatible with the line type of the <internal_table> table. We can specify a search key, but not a table key, within the READ statement by using the WITH KEY clause, as shown in the following syntax −
READ TABLE <internal_table> WITH KEY = <internal_tab_field>.
Here the entire line of the internal table is used as a search key. The content of the entire line of the table is compared with the content of the <internal_tab_field> field. If the values of the <internal_tab_field> field are not compatible with the line type of the table, these values are converted according to the line type of the table. The search key allows you to find entries in internal tables that do not have a structured line type, that is, where the line is a single field or an internal table type.
The following syntax of the READ statement is used to specify a work area or field symbol by using the COMPARING clause −
READ TABLE <internal_table> <key> INTO <work_area_itab>
[COMPARING <F1> <F2>...<Fn>].
When the COMPARING clause is used, the specified table fields <F1>, <F2>....<Fn> of the structured line type are compared with the corresponding fields of the work area before being transported. If the ALL FIELDS clause is specified, the SAP system compares all the components. When the SAP system finds an entry on the basis of a key, the value of the SY-SUBRC variable is set to 0. In addition, the value of the SY-SUBRC variable is set to 2 or 4 if the content of the compared fields is not the same or if the SAP system cannot find an entry. However, the SAP system copies the entry into the target work area whenever it finds an entry, regardless of the result of the comparison.
REPORT ZREAD_DEMO.
*/Creating an internal table
DATA: BEGIN OF Record1,
ColP TYPE I,
ColQ TYPE I,
END OF Record1.
DATA mytable LIKE HASHED TABLE OF Record1 WITH UNIQUE KEY ColP.
DO 6 Times.
Record1-ColP = SY-INDEX.
Record1-ColQ = SY-INDEX + 5.
INSERT Record1 INTO TABLE mytable.
ENDDO.
Record1-ColP = 4.
Record1-ColQ = 12.
READ TABLE mytable FROM Record1 INTO Record1 COMPARING ColQ.
WRITE: 'SY-SUBRC =', SY-SUBRC.
SKIP.
WRITE: / Record1-ColP, Record1-ColQ.
The above code produces the following output −
SY-SUBRC = 2
4 9
In the above example, mytable is an internal table of the hashed table type, with Record1 as the work area and ColP as the unique key. Initially, mytable is populated with six lines, where the ColP field contains the values of the SY-INDEX variable and the ColQ field contains (SY-INDEX + 5) values.
The Record1 work area is populated with 4 and 12 as values for the ColP and ColQ fields respectively. The READ statement reads the line of the table after comparing the value of the ColP key field with the value in the Record1 work area by using the COMPARING clause, and then copies the content of the read line in the work area. The value of the SY-SUBRC variable is displayed as 2 because when the value in the ColP field is 4, the value in the ColQ is not 12, but 9.
The DELETE statement is used to delete one or more records from an internal table. The records of an internal table are deleted either by specifying a table key or condition or by finding duplicate entries. If an internal table has a non-unique key and contains duplicate entries, the first entry from the table is deleted.
Following is the syntax to use the DELETE statement to delete a record or line from an internal table −
DELETE TABLE <internal_table> FROM <work_area_itab>.
In the above syntax, the <work_area_itab> expression is a work area and it should be compatible with the type of the <internal_table> internal table. The delete operation is performed on the basis of a default key that could be taken from the work area components.
You may also specify a table key explicitly in the DELETE TABLE statement by using the following syntax −
DELETE TABLE <internal_table> WITH TABLE KEY <K1> = <F1>............ <Kn> = <Fn>.
In this syntax, <F1>, <F2>....<Fn> are the fields of an internal table and <K1>, <K2>....<Kn> are the key fields of the table. The DELETE statement is used to delete the records or lines of the <internal_table> table based on the expressions <K1> = <F1>, <K2> = <F2>...<Kn> = <Fn>.
Note − If the data types of the <F1>, <F2>....<Fn> fields are not compatible with the <K1>, <K2>...<Kn> key fields then the SAP system automatically converts them into the compatible format.
REPORT ZDELETE_DEMO.
DATA: BEGIN OF Line1,
ColP TYPE I,
ColQ TYPE I,
END OF Line1.
DATA mytable LIKE HASHED TABLE OF Line1
WITH UNIQUE KEY ColP.
DO 8 TIMES.
Line1-ColP = SY-INDEX.
Line1-ColQ = SY-INDEX + 4.
INSERT Line1 INTO TABLE mytable.
ENDDO.
Line1-ColP = 1.
DELETE TABLE mytable: FROM Line1,
WITH TABLE KEY ColP = 3.
LOOP AT mytable INTO Line1.
WRITE: / Line1-ColP, Line1-ColQ.
ENDLOOP.
The above code produces the following output −
2 6
4 8
5 9
6 10
7 11
8 12
In this example, mytable has two fields, ColP and ColQ. Initially, mytable is populated with eight lines, where the ColP contains the values 1, 2, 3, 4, 5, 6, 7 and 8. The ColQ contains the values 5, 6, 7, 8, 9, 10, 11 and 12 because the ColP values are incremented by 4 every time.
The DELETE statement is used to delete the lines from mytable where the value of the ColP key field is either 1 or 3. After deletion, the ColP field of mytable contains the values 2, 4, 5, 6, 7 and 8, as shown in the output. The ColQ field contains the values 6, 8, 9, 10, 11 and 12.
Object orientation simplifies software design to make it easier to understand, maintain, and reuse. Object Oriented Programming (OOP) represents a different way of thinking in writing software. The beauty of OOP lies in its simplicity. The expressiveness of OOP makes it easier to deliver quality software components on time.
As solutions are designed in terms of real-world objects, it becomes much easier for programmers and business analysts to exchange ideas and information about a design that uses a common domain language. These improvements in communication help to reveal hidden requirements, identify risks, and improve the quality of software being developed. The object-oriented approach focuses on objects that represent abstract or concrete things of the real world. These objects are defined by their character and properties that are represented by their internal structure and their attributes (data). The behavior of these objects is described by methods (i.e. functionality).
Let’s compare the procedural and object oriented programming −
ABAP was initially developed as a procedural language (just similar to earlier procedural programming language like COBOL). But ABAP has now adapted the principles of object oriented paradigms with the introduction of ABAP Objects. The object-oriented concepts in ABAP such as class, object, inheritance, and polymorphism, are essentially the same as those of other modern object-oriented languages such as Java or C++.
As object orientation begins to take shape, each class assumes specific role assignments. This division of labor helps to simplify the overall programming model, allowing each class to specialize in solving a particular piece of the problem at hand. Such classes have high cohesion and the operations of each class are closely related in some intuitive way.
The key features of object orientation are −
Effective programming structure.
Real-world entities can be modeled very well.
Stress on data security and access.
Minimizes code redundancy.
Data abstraction and encapsulation.
An object is a special kind of variable that has distinct characteristics and behaviors. The characteristics or attributes of an object are used to describe the state of an object, and behaviors or methods represent the actions performed by an object.
An object is a pattern or instance of a class. It represents a real-world entity such as a person or a programming entity like variables and constants. For example, accounts and students are examples of real-world entities. But hardware and software components of a computer are examples of programming entities.
An object has the following three main characteristics −
Has a state.
Has a unique identity.
May or may not display the behavior.
The state of an object can be described as a set of attributes and their values. For example, a bank account has a set of attributes such as Account Number, Name, Account Type, Balance, and values of all these attributes. The behavior of an object refers to the changes that occur in its attributes over a period of time.
Each object has a unique identity that can be used to distinguish it from other objects. Two objects may exhibit the same behavior and they may or may not have the same state, but they never have the same identity. Two persons may have the same name, age, and gender but they are not identical. Similarly, the identity of an object will never change throughout its lifetime.
Objects can interact with one another by sending messages. Objects contain data and code to manipulate the data. An object can also be used as a user-defined data type with the help of a class. Objects are also called variables of the type class. After defining a class, you can create any number of objects belonging to that class. Each object is associated with the data of the type class with which it has been created.
The object creation usually includes the following steps −
Creating a reference variable with reference to the class. The syntax for which is −
Creating a reference variable with reference to the class. The syntax for which is −
DATA: <object_name> TYPE REF TO <class_name>.
Creating an object from the reference variable. The syntax for which is −
Creating an object from the reference variable. The syntax for which is −
CREATE Object: <object_name>.
REPORT ZDEMO_OBJECT.
CLASS Class1 Definition.
Public Section.
DATA: text1(45) VALUE 'ABAP Objects.'.
METHODS: Display1.
ENDCLASS.
CLASS Class1 Implementation.
METHOD Display1.
Write:/ 'This is the Display method.'.
ENDMETHOD.
ENDCLASS.
START-OF-SELECTION.
DATA: Class1 TYPE REF TO Class1.
CREATE Object: Class1.
Write:/ Class1->text1.
CALL METHOD: Class1->Display1.
The above code produces the following output −
ABAP Objects.
This is the Display method.
A class is used to specify the form of an object and it combines data representation and methods for manipulating that data into one neat package. The data and functions within a class are called members of the class.
When you define a class, you define a blueprint for a data type. This doesn't actually define any data, but it does define what the class name means, what an object of the class will consist of, and what operations can be performed on such an object. That is, it defines the abstract characteristics of an object, such as attributes, fields, and properties.
The following syntax shows how to define a class −
CLASS <class_name> DEFINITION.
..........
..........
ENDCLASS.
A class definition starts with the keyword CLASS followed by the class name, DEFINITION and the class body. The definition of a class can contain various components of the class such as attributes, methods, and events. When we declare a method in the class declaration, the method implementation must be included in the class implementation. The following syntax shows how to implement a class −
CLASS <class_name> IMPLEMENTATION.
...........
..........
ENDCLASS.
Note − Implementation of a class contains the implementation of all its methods. In ABAP Objects, the structure of a class contains components such as attributes, methods, events, types, and constants.
Attributes are data fields of a class that can have any data type such as C, I, F, and N. They are declared in the class declaration. These attributes can be divided into 2 categories: instance and static attributes. An instance attribute defines the instance specific state of an object. The states are different for different objects. An instance attribute is declared by using the DATA statement.
Static attributes define a common state of a class that is shared by all the instances of the class. That is, if you change a static attribute in one object of a class, the change is visible to all other objects of the class as well. A static attribute is declared by using the CLASS-DATA statement.
A method is a function or procedure that represents the behavior of an object in the class. The methods of the class can access any attribute of the class. The definition of a method can also contain parameters, so that you can supply the values to these parameters when methods are called. The definition of a method is declared in the class declaration and implemented in the implementation part of a class. The METHOD and ENDMETHOD statements are used to define the implementation part of a method. The following syntax shows how to implement a method −
METHOD <m_name>.
..........
..........
ENDMETHOD.
In this syntax, <m_name> represents the name of a method. Note − You can call a method by using the CALL METHOD statement.
Class components can be defined in public, private, or protected visibility sections that control how these components could be accessed. The private visibility section is used to deny access to components from outside of the class. Such components can only be accessed from inside the class such as a method.
Components defined in the public visibility section can be accessed from any context. By default all the members of a class would be private. Practically, we define data in private section and related methods in public section so that they can be called from outside of the class as shown in the following program.
The attributes and methods declared in Public section in a class can be accessed by that class and any other class, sub-class of the program.
The attributes and methods declared in Public section in a class can be accessed by that class and any other class, sub-class of the program.
When the attributes and methods are declared in Protected section in a class, those can be accessed by that class and sub classes (derived classes) only.
When the attributes and methods are declared in Protected section in a class, those can be accessed by that class and sub classes (derived classes) only.
When the attributes and methods are declared in Private section in a class, those can be accessed by only that class and not by any other class.
When the attributes and methods are declared in Private section in a class, those can be accessed by only that class and not by any other class.
Report ZAccess1.
CLASS class1 Definition.
PUBLIC Section.
Data: text1 Type char25 Value 'Public Data'.
Methods meth1.
PROTECTED Section.
Data: text2 Type char25 Value 'Protected Data'.
PRIVATE Section.
Data: text3 Type char25 Value 'Private Data'.
ENDCLASS.
CLASS class1 Implementation.
Method meth1.
Write: / 'Public Method:',
/ text1,
/ text2,
/ text3.
Skip.
EndMethod.
ENDCLASS.
Start-Of-Selection.
Data: Objectx Type Ref To class1.
Create Object: Objectx.
CALL Method: Objectx→meth1.
Write: / Objectx→text1.
The above code produces the following output −
Public Method:
Public Data
Protected Data
Private Data
Public Data
A Static attribute is declared with the statement CLASS-DATA. All the objects or instances can use the static attribute of the class. Static attributes are accessed directly with the help of class name like class_name⇒name_1 = 'Some Text'.
Following is a program where we want to print a text with line number 4 to 8 times. We define a class class1 and in the public section we declare CLASS-DATA (static attribute) and a method. After implementing the class and method, we directly access the static attribute in Start-Of-Selection event. Then we just create the instance of the class and call the method.
Report ZStatic1.
CLASS class1 Definition.
PUBLIC Section.
CLASS-DATA: name1 Type char45,
data1 Type I.
Methods: meth1.
ENDCLASS.
CLASS class1 Implementation.
Method meth1.
Do 4 Times.
data1 = 1 + data1.
Write: / data1, name1.
EndDo.
Skip.
EndMethod.
ENDCLASS.
Start-Of-Selection.
class1⇒name1 = 'ABAP Object Oriented Programming'.
class1⇒data1 = 0.
Data: Object1 Type Ref To class1,
Object2 Type Ref To class1.
Create Object: Object1, Object2.
CALL Method: Object1→meth1,
Object2→meth1.
The above code produces the following output −
Constructors are special methods that are called automatically, either while creating an object or accessing the components of a class. Constructor gets triggered whenever an object is created, but we need to call a method to trigger the general method. In the following example, we have declared two public methods method1 and constructor. Both these methods have different operations. While creating an object of the class, the constructor method triggers its operation.
Report ZConstructor1.
CLASS class1 Definition.
PUBLIC Section.
Methods: method1, constructor.
ENDCLASS.
CLASS class1 Implementation.
Method method1.
Write: / 'This is Method1'.
EndMethod.
Method constructor.
Write: / 'Constructor Triggered'.
EndMethod.
ENDCLASS.
Start-Of-Selection.
Data Object1 Type Ref To class1.
Create Object Object1.
The above code produces the following output −
Constructor Triggered
When you declare a variable of any type in public section of a class, you can use it in any other implementation. A variable can be declared with an initial value in public section. We may declare the variable again inside a method with a different value. When we write the variable inside the method, the system will print the changed value. To reflect the previous value of the variable, we have to use ‘ME’ operator.
In this program, we have declared a public variable text1 and initiated with a value. We have declared the same variable again, but instantiated with different value. Inside the method, we are writing that variable with ‘ME’ operator to get the previously initiated value. We get the changed value by declaring directly.
Report ZMEOperator1.
CLASS class1 Definition.
PUBLIC Section.
Data text1 Type char25 Value 'This is CLASS Attribute'.
Methods method1.
ENDCLASS.
CLASS class1 Implementation.
Method method1.
Data text1 Type char25 Value 'This is METHOD Attribute'.
Write: / ME→text1,
/ text1.
ENDMethod.
ENDCLASS.
Start-Of-Selection.
Data objectx Type Ref To class1.
Create Object objectx.
CALL Method objectx→method1.
The above code produces the following output −
This is CLASS Attribute
This is METHOD Attribute
One of the most important concepts in object oriented programming is that of inheritance. Inheritance allows us to define a class in terms of another class, which makes it easier to create and maintain an application. This also provides an opportunity to reuse the code functionality and fast implementation time.
When creating a class, instead of writing completely new data members and methods, the programmer can designate that the new class should inherit the members of an existing class. This existing class is called the base class or super class, and the new class is referred to as the derived class or sub class.
An object of one class can acquire the properties of another class.
An object of one class can acquire the properties of another class.
Derived class inherits the data and methods of a super class. However, they can overwrite methods and also add new methods.
Derived class inherits the data and methods of a super class. However, they can overwrite methods and also add new methods.
The main advantage of inheritance is reusability.
The main advantage of inheritance is reusability.
The inheritance relationship is specified using the ‘INHERITING FROM’ addition to the class definition statement.
Following is the syntax −
CLASS <subclass> DEFINITION INHERITING FROM <superclass>.
Report ZINHERITAN_1.
CLASS Parent Definition.
PUBLIC Section.
Data: w_public(25) Value 'This is public data'.
Methods: ParentM.
ENDCLASS.
CLASS Child Definition Inheriting From Parent.
PUBLIC Section.
Methods: ChildM.
ENDCLASS.
CLASS Parent Implementation.
Method ParentM.
Write /: w_public.
EndMethod. ENDCLASS.
CLASS Child Implementation.
Method ChildM.
Skip.
Write /: 'Method in child class', w_public.
EndMethod.
ENDCLASS.
Start-of-selection.
Data: Parent Type Ref To Parent,
Child Type Ref To Child.
Create Object: Parent, Child.
Call Method: Parent→ParentM,
child→ChildM.
The above code produces the following output −
This is public data
Method in child class
This is public data
A derived class can access all the non-private members of its base class. Thus super class members that should not be accessible to the member functions of sub classes should be declared private in the super class. We can summarize the different access types according to who can access them in the following way −
When deriving a class from a super class, it can be inherited through public, protected or private inheritance. The type of inheritance is specified by the access specifier as explained above. We hardly use protected or private inheritance, but public inheritance is commonly used. The following rules are applied while using different types of inheritance.
Public Inheritance − When deriving a class from a public super class, public members of the super class become public members of the sub class and protected members of the super class become protected members of the sub class. Super class's private members are never accessible directly from a sub class, but can be accessed through calls to the public and protected members of the super class.
Public Inheritance − When deriving a class from a public super class, public members of the super class become public members of the sub class and protected members of the super class become protected members of the sub class. Super class's private members are never accessible directly from a sub class, but can be accessed through calls to the public and protected members of the super class.
Protected Inheritance − When deriving from a protected super class, public and protected members of the super class become protected members of the sub class.
Protected Inheritance − When deriving from a protected super class, public and protected members of the super class become protected members of the sub class.
Private Inheritance − When deriving from a private super class, public and protected members of the super class become private members of the sub class.
Private Inheritance − When deriving from a private super class, public and protected members of the super class become private members of the sub class.
The methods of the super class can be re-implemented in the sub class. Few rules of redefining methods −
The redefinition statement for the inherited method must be in the same section as the definition of the original method.
The redefinition statement for the inherited method must be in the same section as the definition of the original method.
If you redefine a method, you do not need to enter its interface again in the subclass, but only the name of the method.
If you redefine a method, you do not need to enter its interface again in the subclass, but only the name of the method.
Within the redefined method, you can access components of the direct super class using the super reference.
Within the redefined method, you can access components of the direct super class using the super reference.
The pseudo reference super can only be used in redefined methods.
The pseudo reference super can only be used in redefined methods.
Report Zinheri_Redefine.
CLASS super_class Definition.
Public Section.
Methods: Addition1 importing g_a TYPE I
g_b TYPE I
exporting g_c TYPE I.
ENDCLASS.
CLASS super_class Implementation.
Method Addition1.
g_c = g_a + g_b.
EndMethod.
ENDCLASS.
CLASS sub_class Definition Inheriting From super_class.
Public Section.
METHODS: Addition1 Redefinition.
ENDCLASS.
CLASS sub_class Implementation.
Method Addition1.
g_c = g_a + g_b + 10.
EndMethod.
ENDCLASS.
Start-Of-Selection.
Parameters: P_a Type I, P_b TYPE I.
Data: H_Addition1 TYPE I.
Data: H_Sub TYPE I.
Data: Ref1 TYPE Ref TO sub_class.
Create Object Ref1.
Call Method Ref1→Addition1 exporting g_a = P_a
g_b = P_b
Importing g_c = H_Addition1.
Write:/ H_Addition1.
After executing F8, if we enter the values 9 and 10, the above code produces the following output −
Redefinition Demo
29
The term polymorphism literally means ‘many forms’. From an object-oriented perspective, polymorphism works in conjunction with inheritance to make it possible for various types within an inheritance tree to be used interchangeably. That is, polymorphism occurs when there is a hierarchy of classes and they are related by inheritance. ABAP polymorphism means that a call to a method will cause a different method to be executed depending on the type of object that invokes the method.
The following program contains an abstract class 'class_prgm', 2 sub classes (class_procedural and class_OO), and a test driver class 'class_type_approach'. In this implementation, the class method 'start' allow us to display the type of programming and its approach. If you look closely at the signature of method 'start', you will observe that it receives an importing parameter of type class_prgm. However, in the Start-Of-Selection event, this method has been called at run-time with objects of type class_procedural and class_OO.
Report ZPolymorphism1.
CLASS class_prgm Definition Abstract.
PUBLIC Section.
Methods: prgm_type Abstract,
approach1 Abstract.
ENDCLASS.
CLASS class_procedural Definition
Inheriting From class_prgm.
PUBLIC Section.
Methods: prgm_type Redefinition,
approach1 Redefinition.
ENDCLASS.
CLASS class_procedural Implementation.
Method prgm_type.
Write: 'Procedural programming'.
EndMethod. Method approach1.
Write: 'top-down approach'.
EndMethod. ENDCLASS.
CLASS class_OO Definition
Inheriting From class_prgm.
PUBLIC Section.
Methods: prgm_type Redefinition,
approach1 Redefinition.
ENDCLASS.
CLASS class_OO Implementation.
Method prgm_type.
Write: 'Object oriented programming'.
EndMethod.
Method approach1.
Write: 'bottom-up approach'.
EndMethod.
ENDCLASS.
CLASS class_type_approach Definition.
PUBLIC Section.
CLASS-METHODS:
start Importing class1_prgm
Type Ref To class_prgm.
ENDCLASS.
CLASS class_type_approach IMPLEMENTATION.
Method start.
CALL Method class1_prgm→prgm_type.
Write: 'follows'.
CALL Method class1_prgm→approach1.
EndMethod.
ENDCLASS.
Start-Of-Selection.
Data: class_1 Type Ref To class_procedural,
class_2 Type Ref To class_OO.
Create Object class_1.
Create Object class_2.
CALL Method class_type_approach⇒start
Exporting
class1_prgm = class_1.
New-Line.
CALL Method class_type_approach⇒start
Exporting
class1_prgm = class_2.
The above code produces the following output −
Procedural programming follows top-down approach
Object oriented programming follows bottom-up approach
ABAP run-time environment performs an implicit narrowing cast during the assignment of the importing parameter class1_prgm. This feature helps the 'start' method to be implemented generically. The dynamic type information associated with an object reference variable allows the ABAP run-time environment to dynamically bind a method call with the implementation defined in the object pointed to by the object reference variable. For instance, the importing parameter 'class1_prgm' for method 'start' in the 'class_type_approach' class refers to an abstract type that could never be instantiated on its own.
Whenever the method is called with a concrete sub class implementation such as class_procedural or class_OO, the dynamic type of the class1_prgm reference parameter is bound to one of these concrete types. Therefore, the calls to methods 'prgm_type' and 'approach1' refer to the implementations provided in the class_procedural or class_OO sub classes rather than the undefined abstract implementations provided in class 'class_prgm'.
Encapsulation is an Object Oriented Programming (OOP) concept that binds together data and functions that manipulate the data, and keeps both safe from outside interference and misuse. Data encapsulation led to the important OOP concept of data hiding. Encapsulation is a mechanism of bundling the data and the functions that use them, and data abstraction is a mechanism of exposing only the interfaces and hiding the implementation details from the user.
ABAP supports the properties of encapsulation and data hiding through the creation of user-defined types called classes. As discussed earlier, a class can contain private, protected and public members. By default, all items defined in a class are private.
Encapsulation actually means one attribute and method could be modified in different classes. Hence data and method can have different form and logic that can be hidden to separate class.
Let's consider encapsulation by interface. Interface is used when we need to create one method with different functionality in different classes. Here the name of the method need not be changed. The same method will have to be implemented in different class implementations.
The following program contains an Interface inter_1. We have declared attribute and a method method1. We have also defined two classes like Class1 and Class2. So we have to implement the method ‘method1’ in both of the class implementations. We have implemented the method ‘method1’ differently in different classes. In the start-ofselection, we create two objects Object1 and Object2 for two classes. Then, we call the method by different objects to get the function declared in separate classes.
Report ZEncap1.
Interface inter_1.
Data text1 Type char35.
Methods method1.
EndInterface.
CLASS Class1 Definition.
PUBLIC Section.
Interfaces inter_1.
ENDCLASS.
CLASS Class2 Definition.
PUBLIC Section.
Interfaces inter_1.
ENDCLASS.
CLASS Class1 Implementation.
Method inter_1~method1.
inter_1~text1 = 'Class 1 Interface method'.
Write / inter_1~text1.
EndMethod.
ENDCLASS.
CLASS Class2 Implementation.
Method inter_1~method1.
inter_1~text1 = 'Class 2 Interface method'.
Write / inter_1~text1.
EndMethod.
ENDCLASS.
Start-Of-Selection.
Data: Object1 Type Ref To Class1,
Object2 Type Ref To Class2.
Create Object: Object1, Object2.
CALL Method: Object1→inter_1~method1,
Object2→inter_1~method1.
The above code produces the following output −
Class 1 Interface method
Class 2 Interface method
Encapsulated classes do not have a lot of dependencies on the outside world. Moreover, the interactions that they do have with external clients are controlled through a stabilized public interface. That is, an encapsulated class and its clients are loosely coupled. For the most part, classes with well-defined interfaces can be plugged into another context. When designed correctly, encapsulated classes become reusable software assets.
Most of us have learned through bitter experience to make class members private by default unless we really need to expose them. That is just good encapsulation. This wisdom is applied most frequently to data members and it also applies equally to all members.
Similar to classes in ABAP, interfaces act as data types for objects. The components of interfaces are same as the components of classes. Unlike the declaration of classes, the declaration of an interface does not include the visibility sections. This is because the components defined in the declaration of an interface are always integrated in the public visibility section of the classes.
Interfaces are used when two similar classes have a method with the same name, but the functionalities are different from each other. Interfaces might appear similar to classes, but the functions defined in an interface are implemented in a class to extend the scope of that class. Interfaces along with the inheritance feature provide a base for polymorphism. This is because a method defined in an interface can behave differently in different classes.
Following is the general format to create an interface −
INTERFACE <intf_name>.
DATA.....
CLASS-DATA.....
METHODS.....
CLASS-METHODS.....
ENDINTERFACE.
In this syntax, <intf_name> represents the name of an interface. The DATA and CLASSDATA statements can be used to define the instance and static attributes of the interface respectively. The METHODS and CLASS-METHODS statements can be used to define the instance and static methods of the interface respectively. As the definition of an interface does not include the implementation class, it is not necessary to add the DEFINITION clause in the declaration of an interface.
Note − All the methods of an interface are abstract. They are fully declared including their parameter interface, but not implemented in the interface. All the classes that want to use an interface must implement all the methods of the interface. Otherwise, the class becomes an abstract class.
We use the following syntax in the implementation part of the class −
INTERFACE <intf_name>.
In this syntax, <intf_name> represents the name of an interface. Note that this syntax must be used in the public section of the class.
The following syntax is used to implement the methods of an interface inside the implementation of a class −
METHOD <intf_name~method_m>.
<statements>.
ENDMETHOD.
In this syntax, <intf_name~method_m> represents the fully declared name of a method of the <intf_name> interface.
Report ZINTERFACE1.
INTERFACE my_interface1.
Methods msg.
ENDINTERFACE.
CLASS num_counter Definition.
PUBLIC Section.
INTERFACES my_interface1.
Methods add_number.
PRIVATE Section.
Data num Type I.
ENDCLASS.
CLASS num_counter Implementation.
Method my_interface1~msg.
Write: / 'The number is', num.
EndMethod.
Method add_number.
ADD 7 TO num.
EndMethod.
ENDCLASS.
CLASS drive1 Definition.
PUBLIC Section.
INTERFACES my_interface1.
Methods speed1.
PRIVATE Section.
Data wheel1 Type I.
ENDCLASS.
CLASS drive1 Implementation.
Method my_interface1~msg.
Write: / 'Total number of wheels is', wheel1.
EndMethod.
Method speed1.
Add 4 To wheel1.
EndMethod.
ENDCLASS.
Start-Of-Selection.
Data object1 Type Ref To num_counter.
Create Object object1.
CALL Method object1→add_number.
CALL Method object1→my_interface1~msg.
Data object2 Type Ref To drive1.
Create Object object2.
CALL Method object2→speed1.
CALL Method object2→my_interface1~msg.
The above code produces the following output −
The number is 7
Total number of wheels is 4
In the above example, my_interface1 is the name of an interface that contains the 'msg' method. Next, two classes, num_counter and drive1 are defined and implemented. Both these classes implement the 'msg' method and also specific methods that define the behavior of their respective instances, such as the add_number and speed1 methods.
Note − The add_number and speed1 methods are specific to the respective classes.
An event is a set of outcomes that are defined in a class to trigger the event handlers in other classes. When an event is triggered, we can call any number of event handler methods. The link between a trigger and its handler method is actually decided dynamically at run-time.
In a normal method call, a calling program determines which method of an object or a class needs to be called. As fixed handler method is not registered for every event, in case of event handling, the handler method determines the event that needs to be triggered.
An event of a class can trigger an event handler method of the same class by using the RAISE EVENT statement. For an event, the event handler method can be defined in the same or different class by using the FOR EVENT clause, as shown in the following syntax −
FOR EVENT <event_name> OF <class_name>.
Similar to the methods of a class, an event can have parameter interface but it has only output parameters. The output parameters are passed to the event handler method by the RAISE EVENT statement that receives them as input parameters. An event is linked to its handler method dynamically in a program by using the SET HANDLER statement.
When an event is triggered, appropriate event handler methods are supposed to be executed in all the handling classes.
REPORT ZEVENT1.
CLASS CL_main DEFINITION.
PUBLIC SECTION.
DATA: num1 TYPE I.
METHODS: PRO IMPORTING num2 TYPE I.
EVENTS: CUTOFF.
ENDCLASS.
CLASS CL_eventhandler DEFINITION.
PUBLIC SECTION.
METHODS: handling_CUTOFF FOR EVENT CUTOFF OF CL_main.
ENDCLASS.
START-OF-SELECTION.
DATA: main1 TYPE REF TO CL_main.
DATA: eventhandler1 TYPE REF TO CL_eventhandler.
CREATE OBJECT main1.
CREATE OBJECT eventhandler1.
SET HANDLER eventhandler1→handling_CUTOFF FOR main1.
main1→PRO( 4 ).
CLASS CL_main IMPLEMENTATION.
METHOD PRO.
num1 = num2.
IF num2 ≥ 2.
RAISE EVENT CUTOFF.
ENDIF.
ENDMETHOD.
ENDCLASS.
CLASS CL_eventhandler IMPLEMENTATION.
METHOD handling_CUTOFF.
WRITE: 'Handling the CutOff'.
WRITE: / 'Event has been processed'.
ENDMETHOD. ENDCLASS.
The above code produces the following output −
Handling the CutOff
Event has been processed
A report is a presentation of data in an organized structure. Many database management systems include a report writer that enables you to design and generate reports. SAP applications support report creation.
A classical report is created by using the output data in the WRITE statement inside a loop. They do not contain any sub-reports. SAP also provides some standard reports such as RSCLTCOP that is used to copy tables across clients and RSPARAM that is used to display instance parameters.
These reports consist of only one screen as an output. We can use various events such as INITIALIZATON & TOP-OF-PAGE to create a classical report, and each event has its own importance during the creation of a classical report. Each of these events is associated to a specific user action and is triggered only when the user performs that action.
Following is a table describing the events and descriptions −
INITIALIZATON
Triggered before displaying the selection screen.
AT SELECTION-SCREEN
Triggered after processing of the user input on the selection screen. This event verifies the user input prior to the execution of a program. After processing the user input, the selection screen remains in the active mode.
START-OF-SELECTION
Triggered only after the processing of the selection screen is over; that is, when the user clicks the Execute icon on the selection screen.
END-OF-SELECTION
Triggered after the last statement in the START-OF-SELECTON event is executed.
TOP-OF-PAGE
Triggered by the first WRITE statement to display the data on a new page.
END-OF-PAGE
Triggered to display the text at the end of a page in a report. Note, that this event is the last event while creating a report, and should be combined with the LINE-COUNT clause of the REPORT statement.
Let's create a classical report. We will display the information stored in the standard database MARA (contains general material data) by using a sequence of statements in ABAP editor.
REPORT ZREPORT2
LINE-SIZE 75
LINE-COUNT 30(3)
NO STANDARD PAGE HEADING.
Tables: MARA.
TYPES: Begin of itab,
MATNR TYPE MARA-MATNR,
MBRSH TYPE MARA-MBRSH,
MEINS TYPE MARA-MEINS,
MTART TYPE MARA-MTART,
End of itab.
DATA: wa_ma TYPE itab,
it_ma TYPE STANDARD TABLE OF itab.
SELECT-OPTIONS: MATS FOR MARA-MATNR OBLIGATORY.
INITIALIZATION.
MATS-LOW = '1'.
MATS-HIGH = '500'.
APPEND MATS.
AT SELECTION-SCREEN. .
IF MATS-LOW = ' '.
MESSAGE I000(ZKMESSAGE).
ELSEIF MATS-HIGH = ' '.
MESSAGE I001(ZKMESSAGE).
ENDIF.
TOP-OF-PAGE.
WRITE:/ 'CLASSICAL REPORT CONTAINING GENERAL MATERIAL DATA
FROM THE TABLE MARA' COLOR 7.
ULINE.
WRITE:/ 'MATERIAL' COLOR 1,
24 'INDUSTRY' COLOR 2,
38 'UNITS' COLOR 3,
53 'MATERIAL TYPE' COLOR 4.
ULINE.
END-OF-PAGE.
START-OF-SELECTION.
SELECT MATNR MBRSH MEINS MTART FROM MARA
INTO TABLE it_ma WHERE MATNR IN MATS.
LOOP AT it_ma into wa_ma.
WRITE:/ wa_ma-MATNR,
25 wa_ma-MBRSH,
40 wa_ma-MEINS,
55 wa_ma-MTART.
ENDLOOP.
END-OF-SELECTION.
ULINE.
WRITE:/ 'CLASSICAL REPORT HAS BEEN CREATED' COLOR 7.
ULINE.
SKIP.
The above code produces the following output containing the general material data from the standard table MARA −
Dialog programming deals with the development of multiple objects. All these objects are linked hierarchically to the main program and they are executed in a sequence. Dialog program development makes use of tools in the ABAP workbench. These are the same tools used in standard SAP application development.
Here are the main components of dialog programs −
Screens
Module pools
Subroutines
Menus
Transactions
Dialog programs should be developed by the object browser (transaction: SE80) so that all objects become linked to the main program without having to explicitly point each object. Advanced navigation techniques enhance the process of moving from one object to the other.
Screens are made up of screen attributes, screen layout, fields and flow logic. The module pool consists of modularized syntax that is placed inside include programs of the dialog program. These modules can be invoked by the flow logic, which is processed by the dialog processor.
Step 1 − Within the transaction SE80, select ‘Program’ from the dropdown and enter a Z name for your custom SAP program as ‘ZSCREENEX’.
Step 2 − Press Enter, choose ‘With TOP INCL’ and click the ‘Yes’ button.
Step 3 − Enter a name for your top include as ‘ZSCRTOP’ and click the green tick mark.
Step 4 − Within the attributes screen, simply enter a title and click the save button.
Step 1 − To add a screen to the program, right-click on the program name and select the options Create → Screen.
Step 2 − Enter a screen number as '0211' and click the green tick mark.
Step 3 − In the next screen, enter a short title, set to normal screen type and click the save button on the top application toolbar.
Step 1 − Click the layout button within the application toolbar and the Screen Painter window appears.
Step 2 − Add a Text Field and enter some text such as "Hello World".
Step 3 − Save and activate the screen.
Step 1 − To create a transaction code for your program, simply right click on the program name and choose the option Create → Transaction and enter a transaction code as 'ZTRANEX'.
Step 2 − Enter the transaction text, program and screen you have just created (ZSCREENEX & 0211), and tick the ‘SAPGUI for Windows’ checkbox in the ‘GUI support’ section.
Save and activate everything. You can execute the program. As the program executes, the text you entered is displayed on the screen as shown in the following screenshot.
SAP Smart Forms tool can be used to print and send documents. This tool is useful in developing forms, PDF files, e-mails and documents for the Internet. The tool provides an interface to build and maintain the layout and logic of a form. SAP also delivers a selection of forms for business processes such as those used in Customer Relationship Management (CRM), Sales and Distribution (SD), Financial Accounting (FI) and Human Resources (HR).
The tool allows you to modify forms by using simple graphical tools instead of using any programming tool. It means that a user with no programming knowledge can configure these forms with data for a business process effortlessly.
In a Smart Form, data is retrieved from static and dynamic tables. The table heading and subtotal are specified by the triggered events and the data is then sorted before the final output. A Smart Form allows you to incorporate graphics that can be displayed either as part of the form or as the background. You can also suppress a background graphic if required while taking a printout of a form.
Some examples of standard Smart Forms available in SAP system are as follows −
SF_EXAMPLE_01 represents an invoice with a table output for flight booking for a customer.
SF_EXAMPLE_01 represents an invoice with a table output for flight booking for a customer.
SF_EXAMPLE_02 represents an invoice similar to SF_EXAMPLE_01, but with subtotals.
SF_EXAMPLE_02 represents an invoice similar to SF_EXAMPLE_01, but with subtotals.
SF_EXAMPLE_03 specifies an invoice similar to SF_EXAMPLE_02, but one in which several customers can be selected in an application program.
SF_EXAMPLE_03 specifies an invoice similar to SF_EXAMPLE_02, but one in which several customers can be selected in an application program.
Let’s create a form by using the SAP Smart Forms tool. You will also learn how to add a node in the Smart Form and test the form in this tutorial. Here we begin with creating a copy of the SF_EXAMPLE_01 form. The SF_EXAMPLE_01 form is a standard Smart Form available in the SAP system.
Step 1 − Smart Form Builder is the main interface used to build a Smart Form. It is available on the initial screen of SAP Smart Forms. We need to type the 'SMARTFORMS' transaction code in the Command field to open the initial screen of SAP Smart Forms. In this screen, enter the form name, SF_EXAMPLE_01, in the Form field.
Step 2 − Select Smart Forms → Copy or click the Copy icon to open the Copy Form or Text dialog box.
Step 3 − In the Target Object field, enter a name for the new form. The name must begin with the Y or Z letter. In this case, the name of the form is 'ZSMM1'.
Step 4 − Click the Continue icon or press the ENTER key in the Copy Form or Text dialog box so that the ZSMM1 form is created as a copy of the predefined form SF_EXAMPLE_01.
Step 5 − Click the Save icon. The name of the form is displayed in the Form field on the initial screen of SAP Smart Forms.
Step 6 − Click the Create button on the initial screen of SAP Smart Forms. The ZSMM1 form appears in Form Builder.
Step 7 − The first draft page is created with a MAIN window. All the components of the new form are based on the SF_EXAMPLE_01 predefined form. You can just click a node in the Navigation menu to view its content.
Step 1 − Open a form in the change mode of the SAP Form Builder screen and right-click the Main Window option in the First Page node and select Create → Text from the context menu.
Step 2 − Modify the text in the Text field to 'My_Text' and the text in the Meaning field to 'Text_Demo'. Enter the text 'Hello TutorialsPoint.....' in the text-editing box in the center frame of Form Builder as shown in the following snapshot −
Step 3 − Click the Save button to save the node..
Step 4 − Activate and test the node by clicking the Activate and Test icons, respectively. The initial screen of Function Builder appears.
Step 5 − Activate and test the function module by clicking the Activate and Execute icons. The parameters of the function module are displayed in the initial screen of Function Builder.
Step 6 − Execute the function module by clicking the Execute icon. The Print dialog box appears.
Step 7 − Specify the output device as 'LP01' and click the Print preview button.
The above steps will produce the following output −
The SAPscript tool of the SAP system can be used to build and manage business forms such as invoices and purchase orders. The SAPscript tool provides numerous templates that simplify the designing of a business form to a great extent.
The SAP system comes with standard SAPscript forms that are delivered with the SAP standard client (generally as client 000). Following are a few examples of standard SAPscript forms delivered with client 000 −
RVORDER01
Sales Order Confirmation Form
RVDELNOTE
Packing List
RVINVOICE01
Invoice
MEDRUCK
Purchase Order
F110_PRENUM_CHCK
Prenumbered Check
The structure of a SAPscript form consists of 2 main components −
Content − This can be either text (business data) or graphics (company logo).
Layout − This is defined by a set of windows in which the form content appears.
The Form Painter tool provides the graphical layout of a SAPscript form and various functionalities to manipulate the form. In the following example, we are going to create an invoice form after copying its layout structure from a standard SAPscript form RVINVOICE01, and display its layout by accessing the Form Painter tool.
Step 1 − Open the Form Painter. You may request the screen either by navigating the SAP menu or by using the SE71 transaction code.
Step 2 − In the Form Painter, request screen, enter a name and language for a SAPscript form in the Form and Language fields, respectively. Let’s enter 'RVINVOICE01' and 'EN' respectively in these fields.
Step 3 − Select the Page Layout radio button in the Sub objects group box.
Step 4 − Select Utilities → Copy from Client to create a copy of the RVINVOICE01 form. The 'Copy Forms Between Clients' screen appears.
Step 5 − In the 'Copy Forms Between Clients' screen, enter the original name of the form, 'RVINVOICE01', in the Form Name field, the number of the source client '000' in the Source Client field, and the name of the target form as 'ZINV_01' in the Target Form field. Make sure that other settings remain unchanged.
Step 6 − Next, click the Execute icon in the 'Copy Forms Between Clients' screen. The 'Create Object Directory Entry' dialog box appears. Click the Save icon.
The ZINV_01 form is copied from the RVINVOICE01 form and displayed in the 'Copy Forms Between Clients screen' as depicted in the following snapshot −
Step 7 − Click the back icon twice and navigate back to the Form Painter: Request screen, which contains the name of the copied form ZINV_01.
Step 8 − After clicking the Display button, the 'Form ZINV_01: Layout of Page FIRST' window and the 'Form: Change Page Layout: ZINV_01' screen appears as shown in the following screenshot.
Step 9 − The 'Form ZINV_01: Layout of Page FIRST' window shows the initial layout of the form. The layout of the form contains five windows: HEADER, ADDRESS, INFO, INFO1, and MAIN. The description of these windows can be accessed in PC Editor.
For instance, by just selecting the MAIN window and clicking the Text icon in the 'Form: Change Page Layout: ZINV_01' screen, you can view all the margin values as shown in the following screenshot −
Customer exits could be considered as hooks to the SAP standard programs. We do not need an access key to write the code and there is no need to modify the SAP standard program. These exits don't have any functionality and they are empty. Business logic could be added in order to meet various client requirements. However, Customer Exits are not available for all programs.
Following are the steps to find customer exits as far as standard transactions are concerned. Let’s identify customer exits available in MM01 (Material Master Creation).
Step 1 − Go to transaction MM01 and identify the program name of MM01 by going to Menu bar → System → Status as shown in the above screenshot.
Step 2 − Get the program name from the popup screen. The program name is 'SAPLMGMM'.
Step 3 − Go to transaction SE38, enter the program name and click Display.
Step 4 − Navigate to Go to → Properties and find out the package of this program name.
The package name is 'MGA'.
Step 5 − Go to transaction code SMOD that is usually used to identify customer exits. Navigate to Utilities → Find (or) you may directly press Ctrl + F on the transaction code SMOD.
Step 6 − After going to the ‘Find Exits’ screen, enter the package name we got earlier and press F8 (Execute) button.
The above steps produce the following output with the list of exits available in the Material Master Creation.
User exits are used in an extraction if the standard SAP extractors do not provide the expected data or the required functionality, for instance in authorizations or time checks. User exits are commonly used in Sales and Distribution (SD) modules. There are many exits provided by SAP in the areas of sales, transportation, shipping and billing. A user exit is designed to make some changes when standard SAP is not capable of fulfilling all the requirements.
To be able to access what exits are available in each area of sales, go to IMG using this path: IMG → Sales and Distribution → System Modifications → User Exits. The documentation for each exit in the areas of SD is explained thoroughly.
For instance, if you want to find user exits in Sales Document Processing (contract, quotation or sales order), follow the path mentioned above and continue to expand the node User Exits in Sales → User Exits. Click on icon documentation to see all user exits available in Sales Document Processing.
USEREXIT_FIELD_MODIFICATION
Used to modify screen attributes.
USEREXIT_SAVE_DOCUMENT
Helps in performing operations when the user hits Save.
USEREXIT_SAVE_DOCUMENT_PREPARE
Very useful to check input fields, put any value in the field or show a popup to users and to confirm the document.
USEREXIT_MOVE_FIELD_TO_VBAK
Used when user header changes are moved to header work area.
USEREXIT_MOVE_FIELD_TO_VBAP
Used when user item changes are moved to SAP item work area.
A User Exit serves the same purpose as Customer Exits but they are available only for the SD module. The exit is implemented as a call to a Function Module. User Exits are modifications to SAP standard programs.
REPORT ZUSEREXIT1.
TABLES:
TSTC, TSTCT,
TADIR, TRDIR, TFDIR, ENLFDIR,
MODSAPT, MODACT.
DATA:
JTAB LIKE TADIR OCCURS 0 WITH HEADER LINE,
field1(30),
v_devclass LIKE TADIR-devclass.
PARAMETERS:
P_TCODE LIKE TSTC-tcode OBLIGATORY.
SELECT SINGLE *
FROM TSTC
WHERE tcode EQ P_TCODE.
IF SY-SUBRC EQ 0.
SELECT SINGLE *
FROM TADIR
WHERE pgmid = 'R3TR' AND
object = 'PROG' AND
obj_name = TSTC-pgmna.
MOVE TADIR-devclass TO v_devclass.
IF SY-SUBRC NE 0.
SELECT SINGLE *
FROM TRDIR
WHERE name = TSTC-pgmna.
IF TRDIR-subc EQ 'F'.
SELECT SINGLE *
FROM TFDIR
WHERE pname = TSTC-pgmna.
SELECT SINGLE *
FROM ENLFDIR
WHERE funcname = TFDIR-funcname.
SELECT SINGLE *
FROM TADIR
WHERE pgmid = 'R3TR' AND
object = 'FUGR' AND
obj_name EQ ENLFDIR-area.
MOVE TADIR-devclass TO v_devclass.
ENDIF.
ENDIF.
SELECT *
FROM TADIR
INTO TABLE JTAB
WHERE pgmid = 'R3TR' AND
object = 'SMOD' AND
devclass = v_devclass.
SELECT SINGLE *
FROM TSTCT
WHERE sprsl EQ SY-LANGU AND
tcode EQ P_TCODE.
FORMAT COLOR COL_POSITIVE INTENSIFIED OFF.
WRITE:/(19) 'Transaction Code - ',
20(20) P_TCODE,
45(50) TSTCT-ttext.
SKIP.
IF NOT JTAB[] IS INITIAL.
WRITE:/(95) SY-ULINE.
FORMAT COLOR COL_HEADING INTENSIFIED ON.
WRITE:/1 SY-VLINE,
2 'Exit Name',
21 SY-VLINE ,
22 'Description',
95 SY-VLINE.
WRITE:/(95) SY-ULINE.
LOOP AT JTAB.
SELECT SINGLE * FROM MODSAPT
WHERE sprsl = SY-LANGU AND
name = JTAB-obj_name.
FORMAT COLOR COL_NORMAL INTENSIFIED OFF.
WRITE:/1 SY-VLINE,
2 JTAB-obj_name HOTSPOT ON,
21 SY-VLINE ,
22 MODSAPT-modtext,
95 SY-VLINE.
ENDLOOP.
WRITE:/(95) SY-ULINE.
DESCRIBE TABLE JTAB.
SKIP.
FORMAT COLOR COL_TOTAL INTENSIFIED ON.
WRITE:/ 'No of Exits:' , SY-TFILL.
ELSE.
FORMAT COLOR COL_NEGATIVE INTENSIFIED ON.
WRITE:/(95) 'User Exit doesn’t exist'.
ENDIF.
ELSE.
FORMAT COLOR COL_NEGATIVE INTENSIFIED ON.
WRITE:/(95) 'Transaction Code Does Not Exist'.
ENDIF.
AT LINE-SELECTION.
GET CURSOR FIELD field1.
CHECK field1(4) EQ 'JTAB'.
SET PARAMETER ID 'MON' FIELD sy-lisel+1(10).
CALL TRANSACTION 'SMOD' AND SKIP FIRST SCREEN.
While processing, enter the transaction code ‘ME01’ and press F8 (Execute) button. The above code produces the following output −
In some cases, special functions need to be predefined in a software application to enhance the functionality of various applications. There are many Microsoft Excel add-ins to improve the functionality of MS Excel. Similarly, SAP facilitates some predefined functions by providing Business Add-Ins known as BADIs.
A BADI is an enhancement technique that facilitates a SAP programmer, a user, or a specific industry to add some additional code to the existing program in SAP system. We can use standard or customized logic to improve the SAP system. A BADI must first be defined and then implemented to enhance SAP application. While defining a BADI, an interface is created. BADI is implemented by this interface, which in turn is implemented by one or more adaptor classes.
The BADI technique is different from other enhancement techniques in two ways −
Enhancement technique can be implemented only once.
This enhancement technique can be used by many customers simultaneously.
You can also create filter BADIs, which means BADIs are defined on the basis of filtered data that is not possible with enhancement techniques. The concept of BADIs has been redefined in SAP Release 7.0 with the following goals −
Enhancing the standard applications in a SAP system by adding two new elements in the ABAP language, that is ‘GET BADI’ and ‘CALL BADI’.
Enhancing the standard applications in a SAP system by adding two new elements in the ABAP language, that is ‘GET BADI’ and ‘CALL BADI’.
Offering more flexibility features such as contexts and filters for the enhancement of standard applications in a SAP system.
Offering more flexibility features such as contexts and filters for the enhancement of standard applications in a SAP system.
When a BADI is created, it contains an interface and other additional components, such as function codes for menu enhancements and screen enhancements. A BADI creation allows customers to include their own enhancements in the standard SAP application. The enhancement, interface, and generated classes are located in an appropriate application development namespace.
Hence, a BADI can be considered as an enhancement technique that uses ABAP objects to create ‘predefined points’ in the SAP components. These predefined points are then implemented by individual industry solutions, country variants, partners and customers to suit their specific requirements. SAP actually introduced the BADI enhancement technique with the Release 4.6A, and the technique has been re-implemented again in the Release 7.0.
Web Dynpro (WD) for ABAP is the SAP standard user interface technology developed by SAP AG. It can be used in the development of web-based applications in the SAP ABAP environment that utilizes SAP development tools and concepts. It provides a front-end web user interface to connect directly to backend SAP R/3 systems to access data and functions for reporting.
Web Dynpro for ABAP consists of a run-time environment and a graphical development environment with specific development tools that are integrated in the ABAP Workbench (transaction: SE80).
The following illustration shows the overall architecture of Web Dynpro −
Following are a few points to keep in mind regarding Web Dynpro −
Web Dynpro is the SAP NetWeaver programming model for user interfaces.
Web Dynpro is the SAP NetWeaver programming model for user interfaces.
All Web Dynpro applications are structured as per the Model View Controller (MVC) programming model.
All Web Dynpro applications are structured as per the Model View Controller (MVC) programming model.
The model defines an interface to the main system and the Web Dynpro application can have an access to system data.
The model defines an interface to the main system and the Web Dynpro application can have an access to system data.
The view is responsible for showing the data in the web browser.
The view is responsible for showing the data in the web browser.
The controller resides between the view and the model. The controller formats the model data to be displayed in the view. It processes the user entries made by the user and returns them to the model.
The controller resides between the view and the model. The controller formats the model data to be displayed in the view. It processes the user entries made by the user and returns them to the model.
Web Dynpro offers the following advantages for application developers −
The use of graphical tools significantly reduces the implementation effort.
The use of graphical tools significantly reduces the implementation effort.
Reuse and better maintainability by using components.
Reuse and better maintainability by using components.
The layout and navigation is easily changed using the Web Dynpro tools.
The layout and navigation is easily changed using the Web Dynpro tools.
User interface accessibility is supported.
User interface accessibility is supported.
Full integration in the ABAP development environment.
Full integration in the ABAP development environment.
The component is the global unit of the Web Dynpro application project. Creating a Web Dynpro component is the initial step in developing a new Web Dynpro application. Once the component is created, it acts as a node in the Web Dynpro object list. You may create any number of component views in a component and assemble them in any number of the corresponding Web Dynpro windows.
At least one Web Dynpro window is contained in each Web Dynpro component. The Web Dynpro window embeds all the views that are displayed within the front-end web application. The window is processed in the window editors of the ABAP Workbench.
Note
The component view displays all the administrative details for the application including the description, the name of the person who created it, the creation date, and the assigned development package.
The component view displays all the administrative details for the application including the description, the name of the person who created it, the creation date, and the assigned development package.
The Web Dynpro application is the independent object in the object list of the ABAP Workbench. The interaction between the window and the application is created by the interface view of a given window.
The Web Dynpro application is the independent object in the object list of the ABAP Workbench. The interaction between the window and the application is created by the interface view of a given window.
25 Lectures
6 hours
Sanjo Thomas
26 Lectures
2 hours
Neha Gupta
30 Lectures
2.5 hours
Sumit Agarwal
30 Lectures
4 hours
Sumit Agarwal
14 Lectures
1.5 hours
Neha Malik
13 Lectures
1.5 hours
Neha Malik
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 3096,
"s": 2898,
"text": "ABAP stands for Advanced Business Application Programming, a 4GL (4th generation) language. Currently it is positioned, along with Java, as the main language for SAP application server programming."
},
{
"code": null,
"e": 3242,
"s": 3096,
"text": "Let's start with the high level architecture of SAP system. The 3-tier Client/Server architecture of a typical SAP system is depicted as follows."
},
{
"code": null,
"e": 3841,
"s": 3242,
"text": "The Presentation layer consists of any input device that can be used to control SAP system. This could be a web browser, a mobile device and so on. All the central processing takes place in Application server. The Application server is not just one system in itself, but it can be multiple instances of the processing system. The server communicates with the Database layer that is usually kept on a separate server, mainly for performance reasons and also for security. Communication happens between each layer of the system, from the Presentation layer to the Database and then back up the chain."
},
{
"code": null,
"e": 4133,
"s": 3841,
"text": "Note − ABAP programs run at the application server level. Technical distribution of software is independent of its physical location. It means basically all three levels can be installed on top of each other on one computer or each level can be installed on a different computer or a server."
},
{
"code": null,
"e": 4375,
"s": 4133,
"text": "ABAP programs reside inside the SAP database. They execute under the control of the runtime system that is a part of the SAP kernel. The run-time system processes all ABAP statements, controlling the flow logic and responding to user events."
},
{
"code": null,
"e": 4510,
"s": 4375,
"text": "So, unlike C++ and Java, ABAP programs are not stored in separate external files. Inside the database, ABAP code exists in two forms −"
},
{
"code": null,
"e": 4583,
"s": 4510,
"text": "Source code that can be viewed and edited with the ABAP workbench tools."
},
{
"code": null,
"e": 4656,
"s": 4583,
"text": "Source code that can be viewed and edited with the ABAP workbench tools."
},
{
"code": null,
"e": 4801,
"s": 4656,
"text": "Generated code, which is a binary representation. If you are familiar with Java, this generated code is somewhat comparable with Java byte code."
},
{
"code": null,
"e": 4946,
"s": 4801,
"text": "Generated code, which is a binary representation. If you are familiar with Java, this generated code is somewhat comparable with Java byte code."
},
{
"code": null,
"e": 5337,
"s": 4946,
"text": "The run-time system can be considered as a virtual machine, just similar to Java virtual machine. A key component of the ABAP run-time system is the database interface that turns database independent statements (Open SQL) into the statements understood by the underlying database (Native SQL). SAP can work with a wide variety of databases and the same ABAP program can run on all of those."
},
{
"code": null,
"e": 5550,
"s": 5337,
"text": "Reports are a good starting point for familiarizing yourself with general ABAP principles and tools. ABAP reports are used in many areas. In this chapter, we will see how easy it is to write a simple ABAP Report."
},
{
"code": null,
"e": 5607,
"s": 5550,
"text": "Let's get started with the common \"Hello World\" example."
},
{
"code": null,
"e": 5815,
"s": 5607,
"text": "Each ABAP statement starts with an ABAP keyword and ends with a period. Keywords must be separated by at least one space. It does not matter whether or not you use one or several lines for an ABAP statement."
},
{
"code": null,
"e": 5978,
"s": 5815,
"text": "You need to enter your code using the ABAP Editor that is a part of ABAP Tools delivered with the SAP NetWeaver Application Server ABAP (also known as ‘AS ABAP’)."
},
{
"code": null,
"e": 6218,
"s": 5978,
"text": "‘AS ABAP’ is an application server with its own database, ABAP run-time environment, and ABAP development tools such as ABAP Editor. The AS ABAP offers a development platform that is independent of hardware, operating system, and database."
},
{
"code": null,
"e": 6386,
"s": 6218,
"text": "Step 1 − Start the transaction SE38 to navigate to the ABAP Editor (discussed in the next chapter). Let's start creating a report that is one of the many ABAP objects."
},
{
"code": null,
"e": 6634,
"s": 6386,
"text": "Step 2 − On the initial screen of the editor, specify the name of your report in the input field PROGRAM. You may specify the name as ZHELLO1. The preceding Z is important for the name. Z ensures that your report resides in the customer namespace."
},
{
"code": null,
"e": 6873,
"s": 6634,
"text": "The customer namespace includes all objects with the prefix Y or Z. It is always used when customers or partners create objects (like a report) to differentiate these objects from objects of SAP and to prevent name conflicts with objects."
},
{
"code": null,
"e": 7034,
"s": 6873,
"text": "Step 3 − You may type the report name in lower case letters, but the editor will change it to upper case. So the names of ABAP objects are ‘Not’ case sensitive."
},
{
"code": null,
"e": 7218,
"s": 7034,
"text": "Step 4 − After specifying the name of the report, click the CREATE button. A popup window ABAP: PROGRAM ATTRIBUTES will pop up and you will provide more information about your report."
},
{
"code": null,
"e": 7464,
"s": 7218,
"text": "Step 5 − Choose \"Executable Program\" as the report type, enter the title “My First ABAP Report” and then select SAVE to continue. The CREATE OBJECT DIRECTORY ENTRY window will pop up next. Select the button LOCAL OBJECT and the popup will close."
},
{
"code": null,
"e": 7624,
"s": 7464,
"text": "You can complete your first report by entering the WRITE statement below the REPORT statement, so that the complete report contains just two lines as follows −"
},
{
"code": null,
"e": 7662,
"s": 7624,
"text": "REPORT ZHELLO1. \nWRITE 'Hello World'."
},
{
"code": null,
"e": 7818,
"s": 7662,
"text": "We can use the keyboard (Ctrl + S) or the save icon (right hand side beside the command field) to save the report. ABAP development takes place in AS ABAP."
},
{
"code": null,
"e": 8126,
"s": 7818,
"text": "Starting the report is as simple as saving it. Click the ACTIVATION button (left hand side next to the start icon) and start the report by using the icon DIRECT PROCESSING or the F8 function key. The title \"My First ABAP Report\" along with the output “Hello World” is displayed as well. Here is the output −"
},
{
"code": null,
"e": 8162,
"s": 8126,
"text": "My First ABAP Report \nHello World \n"
},
{
"code": null,
"e": 8415,
"s": 8162,
"text": "As long as you do not activate a new report or activate a change to an existing report, it is not relevant to their users. This is important in a central development environment where you may work on objects that other developers use in their projects."
},
{
"code": null,
"e": 8656,
"s": 8415,
"text": "If you look at the field Program and double-click on the value ZHELLO1, the ABAP editor will display the code for your report. This is called Forward Navigation. Double clicking on an object's name opens that object in the appropriate tool."
},
{
"code": null,
"e": 8858,
"s": 8656,
"text": "In order to understand SAP ABAP, you need to have basic knowledge of screens like Login, ABAP Editor, Logout and so on. This chapter focuses on screen navigation and the standard toolbar functionality."
},
{
"code": null,
"e": 9105,
"s": 8858,
"text": "After you log on to SAP server, SAP login screen will prompt for User ID and Password. You need to provide a valid user ID and Password and press Enter (the user id and password is provided by system administrator). Following is the login screen."
},
{
"code": null,
"e": 9142,
"s": 9105,
"text": "Following is the SAP screen toolbar."
},
{
"code": null,
"e": 9196,
"s": 9142,
"text": "Menu Bar − Menu bar is the top line of dialog window."
},
{
"code": null,
"e": 9332,
"s": 9196,
"text": "Standard Toolbar − Most standard functions such as Top of Page, End of Page, Page Up, Page Down and Save are available in this toolbar."
},
{
"code": null,
"e": 9430,
"s": 9332,
"text": "Title Bar − Title Bar displays the name of the application/business process you are currently in."
},
{
"code": null,
"e": 9506,
"s": 9430,
"text": "Application Toolbar − Application specific menu options are available here."
},
{
"code": null,
"e": 9744,
"s": 9506,
"text": "Command Field − We can start an application without navigating through the menu transactions and some logical codes are assigned to business processes. Transaction codes are entered in the command field to directly start the application."
},
{
"code": null,
"e": 9846,
"s": 9744,
"text": "You may just start the transaction SE38 (enter SE38 in Command Field) to navigate to the ABAP Editor."
},
{
"code": null,
"e": 9966,
"s": 9846,
"text": "Exit keys are used to exit the program/module or to log off. They are also used to go back to the last accessed screen."
},
{
"code": null,
"e": 10038,
"s": 9966,
"text": "Following are the standard exit keys used in SAP as shown in the image."
},
{
"code": null,
"e": 10117,
"s": 10038,
"text": "Following are the options for checking, activating and processing the reports."
},
{
"code": null,
"e": 10236,
"s": 10117,
"text": "It’s always a good practice to Exit from your ABAP Editor or/and logoff from the SAP system after finishing your work."
},
{
"code": null,
"e": 10402,
"s": 10236,
"text": "ABAP source program consists of comments and ABAP statements. Every statement in ABAP begins with a keyword and ends with a period, and ABAP is ‘Not’ case sensitive."
},
{
"code": null,
"e": 10669,
"s": 10402,
"text": "The first non-comment line in a program begins with the word REPORT. The Report will always be the first line of any executable program created. The statement is followed by the program name which was created previously. The line is then terminated with a full stop."
},
{
"code": null,
"e": 10685,
"s": 10669,
"text": "The syntax is −"
},
{
"code": null,
"e": 10730,
"s": 10685,
"text": "REPORT [Program_Name]. \n \n[Statements...]. \n"
},
{
"code": null,
"e": 10853,
"s": 10730,
"text": "This allows the statement to take up as many lines in the editor as it needs. For example, the REPORT may look like this −"
},
{
"code": null,
"e": 10875,
"s": 10853,
"text": "REPORT Z_Test123_01. "
},
{
"code": null,
"e": 11102,
"s": 10875,
"text": "Statements consist of a command and any variables and options, ending with a period. As long as the period appears at the end of the statement, no problems will arise. It is this period that marks where the statement finishes."
},
{
"code": null,
"e": 11124,
"s": 11102,
"text": "Let’s write the code."
},
{
"code": null,
"e": 11213,
"s": 11124,
"text": "On the line below the REPORT statement, just type this statement: Write ‘ABAP Tutorial’."
},
{
"code": null,
"e": 11267,
"s": 11213,
"text": "REPORT Z_Test123_01.\n\nWrite 'This is ABAP Tutorial'. "
},
{
"code": null,
"e": 11318,
"s": 11267,
"text": "Four things to consider while writing statements −"
},
{
"code": null,
"e": 11389,
"s": 11318,
"text": "The write statement writes whatever is in quotes to the output window."
},
{
"code": null,
"e": 11460,
"s": 11389,
"text": "The write statement writes whatever is in quotes to the output window."
},
{
"code": null,
"e": 11576,
"s": 11460,
"text": "The ABAP editor converts all text to uppercase except text strings, which are surrounded by single quotation marks."
},
{
"code": null,
"e": 11692,
"s": 11576,
"text": "The ABAP editor converts all text to uppercase except text strings, which are surrounded by single quotation marks."
},
{
"code": null,
"e": 11912,
"s": 11692,
"text": "Unlike some older programming languages, ABAP does not care where a statement begins on a line. You may take advantage of this and improve the readability of your program by using indentation to indicate blocks of code."
},
{
"code": null,
"e": 12132,
"s": 11912,
"text": "Unlike some older programming languages, ABAP does not care where a statement begins on a line. You may take advantage of this and improve the readability of your program by using indentation to indicate blocks of code."
},
{
"code": null,
"e": 12304,
"s": 12132,
"text": "ABAP has no restrictions on the layout of statements. That is, multiple statements can be placed on a single line, or a single statement may stretch across multiple lines."
},
{
"code": null,
"e": 12476,
"s": 12304,
"text": "ABAP has no restrictions on the layout of statements. That is, multiple statements can be placed on a single line, or a single statement may stretch across multiple lines."
},
{
"code": null,
"e": 12719,
"s": 12476,
"text": "Consecutive statements can be chained together if the beginning of each statement is identical. This is done with the colon (:) operator and commas, which are used to terminate the individual statements, much as periods end normal statements."
},
{
"code": null,
"e": 12792,
"s": 12719,
"text": "Following is an example of a program that could save some key stroking −"
},
{
"code": null,
"e": 12839,
"s": 12792,
"text": "WRITE 'Hello'. \nWRITE 'ABAP'. \nWRITE 'World'. "
},
{
"code": null,
"e": 12898,
"s": 12839,
"text": "Using the colon notation, it could be rewritten this way −"
},
{
"code": null,
"e": 12947,
"s": 12898,
"text": "WRITE: 'Hello', \n 'ABAP', \n 'World'."
},
{
"code": null,
"e": 13044,
"s": 12947,
"text": "Like any other ABAP statement, the layout doesn’t matter. This is an equally correct statement −"
},
{
"code": null,
"e": 13077,
"s": 13044,
"text": "WRITE: 'Hello', 'ABAP', 'World'."
},
{
"code": null,
"e": 13159,
"s": 13077,
"text": "Inline comments may be declared anywhere in a program by one of the two methods −"
},
{
"code": null,
"e": 13434,
"s": 13159,
"text": "Full line comments are indicated by placing an asterisk (*) in the first position of the line, in which case the entire line is considered by the system to be a comment. Comments don’t need to be terminated by a period because they may not extend across more than one line −"
},
{
"code": null,
"e": 13709,
"s": 13434,
"text": "Full line comments are indicated by placing an asterisk (*) in the first position of the line, in which case the entire line is considered by the system to be a comment. Comments don’t need to be terminated by a period because they may not extend across more than one line −"
},
{
"code": null,
"e": 13737,
"s": 13709,
"text": "* This is the comment line\n"
},
{
"code": null,
"e": 14017,
"s": 13737,
"text": "Partial line comments are indicated by entering a double quote (\") after a statement. All text following the double quote is considered by the system to be a comment. You need not terminate partial line comments by a period because they may not extend across more than one line −"
},
{
"code": null,
"e": 14297,
"s": 14017,
"text": "Partial line comments are indicated by entering a double quote (\") after a statement. All text following the double quote is considered by the system to be a comment. You need not terminate partial line comments by a period because they may not extend across more than one line −"
},
{
"code": null,
"e": 14341,
"s": 14297,
"text": "WRITE 'Hello'. \"Here is the partial comment"
},
{
"code": null,
"e": 14402,
"s": 14341,
"text": "Note − Commented code is not capitalized by the ABAP editor."
},
{
"code": null,
"e": 14571,
"s": 14402,
"text": "The NO-ZERO command follows the DATA statement. It suppresses all leading zeros of a number field containing blanks. The output is usually easier for the users to read."
},
{
"code": null,
"e": 14669,
"s": 14571,
"text": "REPORT Z_Test123_01. \n\nDATA: W_NUR(10) TYPE N.\n MOVE 50 TO W_NUR.\n WRITE W_NUR NO-ZERO."
},
{
"code": null,
"e": 14716,
"s": 14669,
"text": "The above code produces the following output −"
},
{
"code": null,
"e": 14720,
"s": 14716,
"text": "50\n"
},
{
"code": null,
"e": 14778,
"s": 14720,
"text": "Note − Without NO-ZERO command, the output is: 0000000050"
},
{
"code": null,
"e": 14839,
"s": 14778,
"text": "The SKIP command helps in inserting blank lines on the page."
},
{
"code": null,
"e": 14875,
"s": 14839,
"text": "The message command is as follows −"
},
{
"code": null,
"e": 14944,
"s": 14875,
"text": "WRITE 'This is the 1st line'. \nSKIP. \nWRITE 'This is the 2nd line'. "
},
{
"code": null,
"e": 15002,
"s": 14944,
"text": "The above message command produces the following output −"
},
{
"code": null,
"e": 15045,
"s": 15002,
"text": "This is the 1st line \nThis is the 2nd line"
},
{
"code": null,
"e": 15105,
"s": 15045,
"text": "We may use the SKIP command to insert multiple blank lines."
},
{
"code": null,
"e": 15128,
"s": 15105,
"text": "SKIP number_of_lines. "
},
{
"code": null,
"e": 15277,
"s": 15128,
"text": "The output would be several blank lines defined by the number of lines. The SKIP command can also position the cursor on a desired line on the page."
},
{
"code": null,
"e": 15304,
"s": 15277,
"text": "SKIP TO LINE line_number. "
},
{
"code": null,
"e": 15467,
"s": 15304,
"text": "This command is used to dynamically move the cursor up and down the page. Usually, a WRITE statement occurs after this command to put output on that desired line."
},
{
"code": null,
"e": 15641,
"s": 15467,
"text": "The ULINE command automatically inserts a horizontal line across the output. It’s also possible to control the position and length of the line. The syntax is pretty simple −"
},
{
"code": null,
"e": 15649,
"s": 15641,
"text": "ULINE.\n"
},
{
"code": null,
"e": 15685,
"s": 15649,
"text": "The message command is as follows −"
},
{
"code": null,
"e": 15720,
"s": 15685,
"text": "WRITE 'This is Underlined'.\nULINE."
},
{
"code": null,
"e": 15767,
"s": 15720,
"text": "The above code produces the following output −"
},
{
"code": null,
"e": 15823,
"s": 15767,
"text": "This is Underlined (and a horizontal line below this).\n"
},
{
"code": null,
"e": 16088,
"s": 15823,
"text": "The MESSAGE command displays messages defined by a message ID specified in the REPORT statement at the beginning of the program. The message ID is a 2 character code that defines which set of 1,000 messages the program will access when the MESSAGE command is used."
},
{
"code": null,
"e": 16279,
"s": 16088,
"text": "The messages are numbered from 000 to 999. Associated with each number is a message text up to a maximum of 80 characters. When message number is called, the corresponding text is displayed."
},
{
"code": null,
"e": 16343,
"s": 16279,
"text": "Following are the characters for use with the Message command −"
},
{
"code": null,
"e": 16587,
"s": 16343,
"text": "Error messages are normally used to stop users from doing things they are not supposed to do. Warning messages are generally used to remind the users of the consequences of their actions. Information messages give the users useful information."
},
{
"code": null,
"e": 16699,
"s": 16587,
"text": "When we create a message for message the ID AB, the MESSAGE command - MESSAGE E011 gives the following output −"
},
{
"code": null,
"e": 16762,
"s": 16699,
"text": "EAB011 This report does not support sub-number summarization.\n"
},
{
"code": null,
"e": 17236,
"s": 16762,
"text": "While programming in ABAP, we need to use a variety of variables to store various information. Variables are nothing but reserved memory locations to store values. This means that when you create a variable you reserve some space in memory. You may like to store information of various data types like character, integer, floating point, etc. Based on the data type of a variable, the operating system allocates memory and decides what can be stored in the reserved memory."
},
{
"code": null,
"e": 17392,
"s": 17236,
"text": "ABAP offers the programmer a rich assortment of fixed length as well as variable length data types. Following table lists down ABAP elementary data types −"
},
{
"code": null,
"e": 17482,
"s": 17392,
"text": "Some of the fields and numbers can be modified using one or more names as the following −"
},
{
"code": null,
"e": 17487,
"s": 17482,
"text": "byte"
},
{
"code": null,
"e": 17495,
"s": 17487,
"text": "numeric"
},
{
"code": null,
"e": 17510,
"s": 17495,
"text": "character-like"
},
{
"code": null,
"e": 17688,
"s": 17510,
"text": "The following table shows the data type, how much memory it takes to store the value in memory, and the minimum and maximum value that could be stored in such type of variables."
},
{
"code": null,
"e": 17947,
"s": 17688,
"text": "REPORT YR_SEP_12. \nDATA text_line TYPE C LENGTH 40. \ntext_line = 'A Chapter on Data Types'. \nWrite text_line. \n\nDATA text_string TYPE STRING. \ntext_string = 'A Program in ABAP'. \nWrite / text_string. \n\nDATA d_date TYPE D. \nd_date = SY-DATUM. \nWrite / d_date."
},
{
"code": null,
"e": 18243,
"s": 17947,
"text": "In this example, we have a character string of type C with a predefined length 40. STRING is a data type that can be used for any character string of variable length (text strings). Type STRING data objects should generally be used for character-like content where fixed length is not important."
},
{
"code": null,
"e": 18290,
"s": 18243,
"text": "The above code produces the following output −"
},
{
"code": null,
"e": 18345,
"s": 18290,
"text": "A Chapter on Data Types \nA Program in ABAP \n12092015 \n"
},
{
"code": null,
"e": 18446,
"s": 18345,
"text": "The DATE type is used for the storage of date information and can store eight digits as shown above."
},
{
"code": null,
"e": 18760,
"s": 18446,
"text": "The complex types are classified into Structure types and Table types. In the structure types, elementary types and structures (i.e. structure embedded in a structure) are grouped together. You may consider only the grouping of elementary types. But you must be aware of the availability of nesting of structures."
},
{
"code": null,
"e": 19299,
"s": 18760,
"text": "When the elementary types are grouped together, the data item can be accessed as a grouped data item or the individual elementary type data items (structure fields) can be accessed. The table types are better known as arrays in other programming languages. Arrays can be simple or structure arrays. In ABAP, arrays are called internal tables and they can be declared and operated upon in many ways when compared to other programming languages. The following table shows the parameters according to which internal tables are characterized."
},
{
"code": null,
"e": 19316,
"s": 19299,
"text": "Line or row type"
},
{
"code": null,
"e": 19390,
"s": 19316,
"text": "Row of an internal table can be of elementary, complex or reference type."
},
{
"code": null,
"e": 19394,
"s": 19390,
"text": "Key"
},
{
"code": null,
"e": 19542,
"s": 19394,
"text": "Specifies a field or a group of fields as a key of an internal table that identifies the table rows. A key contains the fields of elementary types."
},
{
"code": null,
"e": 19556,
"s": 19542,
"text": "Access method"
},
{
"code": null,
"e": 19617,
"s": 19556,
"text": "Describes how ABAP programs access individual table entries."
},
{
"code": null,
"e": 19803,
"s": 19617,
"text": "Reference types are used to refer to instances of classes, interfaces, and run-time data items. The ABAP OOP run-time type services (RTTS) enables declaration of data items at run-time."
},
{
"code": null,
"e": 20229,
"s": 19803,
"text": "Variables are named data objects used to store values within the allotted memory area of a program. As the name suggests, users can change the content of variables with the help of ABAP statements. Each variable in ABAP has a specific type, which determines the size and layout of the variable's memory; the range of values that can be stored within that memory; and the set of operations that can be applied to the variable."
},
{
"code": null,
"e": 20331,
"s": 20229,
"text": "You must declare all variables before they can be used. The basic form of a variable declaration is −"
},
{
"code": null,
"e": 20366,
"s": 20331,
"text": "DATA <f> TYPE <type> VALUE <val>. "
},
{
"code": null,
"e": 20910,
"s": 20366,
"text": "Here <f> specifies the name of a variable. The name of the variable can be up to 30 characters long. <type> specifies the type of variable. Any data type with fully specified technical attributes is known as <type>. The <val> specifies the initial value of the of <f> variable. In case you define an elementary fixed-length variable, the DATA statement automatically populates the value of the variable with the type-specific initial value. Other possible values for <val> can be a literal, constant, or an explicit clause, such as Is INITIAL."
},
{
"code": null,
"e": 20965,
"s": 20910,
"text": "Following are valid examples of variable declarations."
},
{
"code": null,
"e": 21042,
"s": 20965,
"text": "DATA d1(2) TYPE C. \nDATA d2 LIKE d1. \nDATA minimum_value TYPE I VALUE 10. "
},
{
"code": null,
"e": 21182,
"s": 21042,
"text": "In the above code snippet, d1 is a variable of C type, d2 is a variable of d1 type, and minimum_value is a variable of ABAP integer type I."
},
{
"code": null,
"e": 21295,
"s": 21182,
"text": "This chapter will explain various variable types available in ABAP. There are three kinds of variables in ABAP −"
},
{
"code": null,
"e": 21312,
"s": 21295,
"text": "Static Variables"
},
{
"code": null,
"e": 21332,
"s": 21312,
"text": "Reference Variables"
},
{
"code": null,
"e": 21349,
"s": 21332,
"text": "System Variables"
},
{
"code": null,
"e": 21433,
"s": 21349,
"text": "Static variables are declared in subroutines, function modules, and static methods."
},
{
"code": null,
"e": 21517,
"s": 21433,
"text": "Static variables are declared in subroutines, function modules, and static methods."
},
{
"code": null,
"e": 21575,
"s": 21517,
"text": "The lifetime is linked to the context of the declaration."
},
{
"code": null,
"e": 21633,
"s": 21575,
"text": "The lifetime is linked to the context of the declaration."
},
{
"code": null,
"e": 21708,
"s": 21633,
"text": "With ‘CLASS-DATA’ statement, you can declare variables within the classes."
},
{
"code": null,
"e": 21783,
"s": 21708,
"text": "With ‘CLASS-DATA’ statement, you can declare variables within the classes."
},
{
"code": null,
"e": 21916,
"s": 21783,
"text": "The ‘PARAMETERS’ statement can be used to declare the elementary data objects that are linked to input fields on a selection screen."
},
{
"code": null,
"e": 22049,
"s": 21916,
"text": "The ‘PARAMETERS’ statement can be used to declare the elementary data objects that are linked to input fields on a selection screen."
},
{
"code": null,
"e": 22181,
"s": 22049,
"text": "You can also declare the internal tables that are linked to input fields on a selection screen by using ‘SELECT-OPTIONS’ statement."
},
{
"code": null,
"e": 22313,
"s": 22181,
"text": "You can also declare the internal tables that are linked to input fields on a selection screen by using ‘SELECT-OPTIONS’ statement."
},
{
"code": null,
"e": 22374,
"s": 22313,
"text": "Following are the conventions used while naming a variable −"
},
{
"code": null,
"e": 22447,
"s": 22374,
"text": "You cannot use special characters such as \"t\" and \",\" to name variables."
},
{
"code": null,
"e": 22520,
"s": 22447,
"text": "You cannot use special characters such as \"t\" and \",\" to name variables."
},
{
"code": null,
"e": 22578,
"s": 22520,
"text": "The name of the predefined data objects can’t be changed."
},
{
"code": null,
"e": 22636,
"s": 22578,
"text": "The name of the predefined data objects can’t be changed."
},
{
"code": null,
"e": 22710,
"s": 22636,
"text": "The name of the variable can’t be the same as any ABAP keyword or clause."
},
{
"code": null,
"e": 22784,
"s": 22710,
"text": "The name of the variable can’t be the same as any ABAP keyword or clause."
},
{
"code": null,
"e": 22889,
"s": 22784,
"text": "The name of the variables must convey the meaning of the variable without the need for further comments."
},
{
"code": null,
"e": 22994,
"s": 22889,
"text": "The name of the variables must convey the meaning of the variable without the need for further comments."
},
{
"code": null,
"e": 23122,
"s": 22994,
"text": "Hyphens are reserved to represent the components of structures. Therefore, you are supposed to avoid hyphens in variable names."
},
{
"code": null,
"e": 23250,
"s": 23122,
"text": "Hyphens are reserved to represent the components of structures. Therefore, you are supposed to avoid hyphens in variable names."
},
{
"code": null,
"e": 23315,
"s": 23250,
"text": "The underscore character can be used to separate compound words."
},
{
"code": null,
"e": 23380,
"s": 23315,
"text": "The underscore character can be used to separate compound words."
},
{
"code": null,
"e": 23458,
"s": 23380,
"text": "This program shows how to declare a variable using the PARAMETERS statement −"
},
{
"code": null,
"e": 23576,
"s": 23458,
"text": "REPORT ZTest123_01. \nPARAMETERS: NAME(10) TYPE C, \nCLASS TYPE I, \nSCORE TYPE P DECIMALS 2, \nCONNECT TYPE MARA-MATNR. "
},
{
"code": null,
"e": 23845,
"s": 23576,
"text": "Here, NAME represents a parameter of 10 characters, CLASS specifies a parameter of integer type with the default size in bytes, SCORE represents a packed type parameter with values up to two decimal places, and CONNECT refers to the MARA-MATNF type of ABAP Dictionary."
},
{
"code": null,
"e": 23892,
"s": 23845,
"text": "The above code produces the following output −"
},
{
"code": null,
"e": 23942,
"s": 23892,
"text": "The syntax for declaring reference variables is −"
},
{
"code": null,
"e": 23992,
"s": 23942,
"text": "DATA <ref> TYPE REF TO <type> VALUE IS INITIAL. \n"
},
{
"code": null,
"e": 24043,
"s": 23992,
"text": "REF TO addition declares a reference variable ref."
},
{
"code": null,
"e": 24094,
"s": 24043,
"text": "REF TO addition declares a reference variable ref."
},
{
"code": null,
"e": 24178,
"s": 24094,
"text": "The specification after REF TO specifies the static type of the reference variable."
},
{
"code": null,
"e": 24262,
"s": 24178,
"text": "The specification after REF TO specifies the static type of the reference variable."
},
{
"code": null,
"e": 24333,
"s": 24262,
"text": "The static type restricts the set of objects to which <ref> can refer."
},
{
"code": null,
"e": 24404,
"s": 24333,
"text": "The static type restricts the set of objects to which <ref> can refer."
},
{
"code": null,
"e": 24499,
"s": 24404,
"text": "The dynamic type of reference variable is the data type or class to which it currently refers."
},
{
"code": null,
"e": 24594,
"s": 24499,
"text": "The dynamic type of reference variable is the data type or class to which it currently refers."
},
{
"code": null,
"e": 24666,
"s": 24594,
"text": "The static type is always more general or the same as the dynamic type."
},
{
"code": null,
"e": 24738,
"s": 24666,
"text": "The static type is always more general or the same as the dynamic type."
},
{
"code": null,
"e": 24882,
"s": 24738,
"text": "The TYPE addition is used to create a bound reference type and as a start value, and only IS INITIAL can be specified after the VALUE addition."
},
{
"code": null,
"e": 25026,
"s": 24882,
"text": "The TYPE addition is used to create a bound reference type and as a start value, and only IS INITIAL can be specified after the VALUE addition."
},
{
"code": null,
"e": 25275,
"s": 25026,
"text": "CLASS C1 DEFINITION. \nPUBLIC SECTION. \nDATA Bl TYPE I VALUE 1. \nENDCLASS. DATA: Oref TYPE REF TO C1 , \nDref1 LIKE REF TO Oref, \nDref2 TYPE REF TO I . \nCREATE OBJECT Oref. \nGET REFERENCE OF Oref INTO Dref1. \nCREATE DATA Dref2. \nDref2→* = Dref1→*→Bl."
},
{
"code": null,
"e": 25390,
"s": 25275,
"text": "In the above code snippet, an object reference Oref and two data reference variables Dref1 and Dref2 are declared."
},
{
"code": null,
"e": 25505,
"s": 25390,
"text": "In the above code snippet, an object reference Oref and two data reference variables Dref1 and Dref2 are declared."
},
{
"code": null,
"e": 25633,
"s": 25505,
"text": "Both data reference variables are fully typed and can be dereferenced using the dereferencing operator →* at operand positions."
},
{
"code": null,
"e": 25761,
"s": 25633,
"text": "Both data reference variables are fully typed and can be dereferenced using the dereferencing operator →* at operand positions."
},
{
"code": null,
"e": 25822,
"s": 25761,
"text": "ABAP system variables are accessible from all ABAP programs."
},
{
"code": null,
"e": 25883,
"s": 25822,
"text": "ABAP system variables are accessible from all ABAP programs."
},
{
"code": null,
"e": 25945,
"s": 25883,
"text": "These fields are actually filled by the run-time environment."
},
{
"code": null,
"e": 26007,
"s": 25945,
"text": "These fields are actually filled by the run-time environment."
},
{
"code": null,
"e": 26095,
"s": 26007,
"text": "The values in these fields indicate the state of the system at any given point of time."
},
{
"code": null,
"e": 26183,
"s": 26095,
"text": "The values in these fields indicate the state of the system at any given point of time."
},
{
"code": null,
"e": 26260,
"s": 26183,
"text": "You can find the complete list of system variables in the SYST table in SAP."
},
{
"code": null,
"e": 26337,
"s": 26260,
"text": "You can find the complete list of system variables in the SYST table in SAP."
},
{
"code": null,
"e": 26427,
"s": 26337,
"text": "Individual fields of the SYST structure can be accessed by using either “SYST-” or “SY-”."
},
{
"code": null,
"e": 26517,
"s": 26427,
"text": "Individual fields of the SYST structure can be accessed by using either “SYST-” or “SY-”."
},
{
"code": null,
"e": 26897,
"s": 26517,
"text": "REPORT Z_Test123_01. \n\nWRITE:/'SY-ABCDE', SY-ABCDE, \n /'SY-DATUM', SY-DATUM, \n /'SY-DBSYS', SY-DBSYS, \n /'SY-HOST ', SY-HOST, \n /'SY-LANGU', SY-LANGU,\n /'SY-MANDT', SY-MANDT,\n /'SY-OPSYS', SY-OPSYS,\n /'SY-SAPRL', SY-SAPRL,\n /'SY-SYSID', SY-SYSID,\n /'SY-TCODE', SY-TCODE,\n /'SY-UNAME', SY-UNAME,\n /'SY-UZEIT', SY-UZEIT."
},
{
"code": null,
"e": 26944,
"s": 26897,
"text": "The above code produces the following output −"
},
{
"code": null,
"e": 27185,
"s": 26944,
"text": "SY-ABCDE ABCDEFGHIJKLMNOPQRSTUVWXYZ \nSY-DATUM 12.09.2015 \nSY-DBSYS ORACLE \nSY-HOST sapserver \nSY-LANGU EN \nSY-MANDT 800 \nSY-OPSYS Windows NT \nSY-SAPRL 700 \nSY-SYSID DMO \nSY-TCODE SE38 \nSY-UNAME SAPUSER \nSY-UZEIT 14:25:48\n"
},
{
"code": null,
"e": 27731,
"s": 27185,
"text": "Literals are unnamed data objects that you create within the source code of a program. They are fully defined by their value. You can’t change the value of a literal. Constants are named data objects created statically by using declarative statements. A constant is declared by assigning a value to it that is stored in the program's memory area. The value assigned to a constant can’t be changed during the execution of the program. These fixed values can also be considered as literals. There are two types of literals − numeric and character."
},
{
"code": null,
"e": 27899,
"s": 27731,
"text": "Number literals are sequences of digits which can have a prefixed sign. In number literals, there are no decimal separators and no notation with mantissa and exponent."
},
{
"code": null,
"e": 27949,
"s": 27899,
"text": "Following are some examples of numeric literals −"
},
{
"code": null,
"e": 27968,
"s": 27949,
"text": "183. \n-97. \n+326.\n"
},
{
"code": null,
"e": 28379,
"s": 27968,
"text": "Character literals are sequences of alphanumeric characters in the source code of an ABAP program enclosed in single quotation marks. Character literals enclosed in quotation marks have the predefined ABAP type C and are described as text field literals. Literals enclosed in “back quotes” have the ABAP type STRING and are described as string literals. The field length is defined by the number of characters."
},
{
"code": null,
"e": 28491,
"s": 28379,
"text": "Note − In text field literals, trailing blanks are ignored, but in string literals they are taken into account."
},
{
"code": null,
"e": 28542,
"s": 28491,
"text": "Following are some examples of character literals."
},
{
"code": null,
"e": 28614,
"s": 28542,
"text": "REPORT YR_SEP_12. \nWrite 'Tutorials Point'. \nWrite / 'ABAP Tutorial'. "
},
{
"code": null,
"e": 28687,
"s": 28614,
"text": "REPORT YR_SEP_12. \nWrite `Tutorials Point `. \nWrite / `ABAP Tutorial `. "
},
{
"code": null,
"e": 28732,
"s": 28687,
"text": "The output is same in both the above cases −"
},
{
"code": null,
"e": 28765,
"s": 28732,
"text": "Tutorials Point \nABAP Tutorial\n"
},
{
"code": null,
"e": 28997,
"s": 28765,
"text": "Note − When we try to change the value of the constant, a syntax or run-time error may occur. Constants that you declare in the declaration part of a class or an interface belong to the static attributes of that class or interface."
},
{
"code": null,
"e": 29073,
"s": 28997,
"text": "We can declare the named data objects with the help of CONSTANTS statement."
},
{
"code": null,
"e": 29099,
"s": 29073,
"text": "Following is the syntax −"
},
{
"code": null,
"e": 29138,
"s": 29099,
"text": "CONSTANTS <f> TYPE <type> VALUE <val>."
},
{
"code": null,
"e": 29196,
"s": 29138,
"text": "The CONSTANTS statement is similar to the DATA statement."
},
{
"code": null,
"e": 29431,
"s": 29196,
"text": "<f> specifies a name for the constant. TYPE <type> represents a constant named <f>, which inherits the same technical attributes as the existing data type <type>. VALUE <val> assigns an initial value to the declared constant name <f>."
},
{
"code": null,
"e": 29591,
"s": 29431,
"text": "Note − We should use the VALUE clause in the CONSTANTS statement. The clause ‘VALUE’ is used to assign an initial value to the constant during its declaration."
},
{
"code": null,
"e": 29762,
"s": 29591,
"text": "We have 3 types of constants such as elementary, complex and reference constants. The following statement shows how to define constants by using the CONSTANTS statement −"
},
{
"code": null,
"e": 29868,
"s": 29762,
"text": "REPORT YR_SEP_12. \nCONSTANTS PQR TYPE P DECIMALS 4 VALUE '1.2356'. \nWrite: / 'The value of PQR is:', PQR."
},
{
"code": null,
"e": 29884,
"s": 29868,
"text": "The output is −"
},
{
"code": null,
"e": 29913,
"s": 29884,
"text": "The value of PQR is: 1.2356\n"
},
{
"code": null,
"e": 29989,
"s": 29913,
"text": "Here it refers to elementary data type and is known as elementary constant."
},
{
"code": null,
"e": 30037,
"s": 29989,
"text": "Following is an example for complex constants −"
},
{
"code": null,
"e": 30207,
"s": 30037,
"text": "BEGIN OF EMPLOYEE, \nName(25) TYPE C VALUE 'Management Team', \nOrganization(40) TYPE C VALUE 'Tutorials Point Ltd', \nPlace(10) TYPE C VALUE 'India', \nEND OF EMPLOYEE."
},
{
"code": null,
"e": 30326,
"s": 30207,
"text": "In the above code snippet, EMPLOYEE is a complex constant that is composed of the Name, Organization and Place fields."
},
{
"code": null,
"e": 30382,
"s": 30326,
"text": "The following statement declares a constant reference −"
},
{
"code": null,
"e": 30443,
"s": 30382,
"text": "CONSTANTS null_pointer TYPE REF TO object VALUE IS INITIAL.\n"
},
{
"code": null,
"e": 30528,
"s": 30443,
"text": "We can use the constant reference in comparisons or we may pass it on to procedures."
},
{
"code": null,
"e": 30648,
"s": 30528,
"text": "ABAP provides a rich set of operators to manipulate variables. All ABAP operators are classified into four categories −"
},
{
"code": null,
"e": 30669,
"s": 30648,
"text": "Arithmetic Operators"
},
{
"code": null,
"e": 30690,
"s": 30669,
"text": "Comparison Operators"
},
{
"code": null,
"e": 30708,
"s": 30690,
"text": "Bitwise Operators"
},
{
"code": null,
"e": 30735,
"s": 30708,
"text": "Character String Operators"
},
{
"code": null,
"e": 30951,
"s": 30735,
"text": "Arithmetic operators are used in mathematical expressions in the same way that they are used in algebra. The following list describes arithmetic operators. Assume integer variable A holds 20 and variable B holds 40."
},
{
"code": null,
"e": 30964,
"s": 30951,
"text": "+ (Addition)"
},
{
"code": null,
"e": 31037,
"s": 30964,
"text": "Adds values on either side of the operator. Example: A + B will give 60."
},
{
"code": null,
"e": 31053,
"s": 31037,
"text": "− (Subtraction)"
},
{
"code": null,
"e": 31136,
"s": 31053,
"text": "Subtracts right hand operand from left hand operand. Example: A − B will give -20."
},
{
"code": null,
"e": 31155,
"s": 31136,
"text": "* (Multiplication)"
},
{
"code": null,
"e": 31235,
"s": 31155,
"text": "Multiplies values on either side of the operator. Example: A * B will give 800."
},
{
"code": null,
"e": 31248,
"s": 31235,
"text": "/ (Division)"
},
{
"code": null,
"e": 31325,
"s": 31248,
"text": "Divides left hand operand by right hand operand. Example: B / A will give 2."
},
{
"code": null,
"e": 31339,
"s": 31325,
"text": "MOD (Modulus)"
},
{
"code": null,
"e": 31444,
"s": 31339,
"text": "Divides left hand operand by right hand operand and returns the remainder. Example: B MOD A will give 0."
},
{
"code": null,
"e": 31560,
"s": 31444,
"text": "REPORT YS_SEP_08. \nDATA: A TYPE I VALUE 150, \nB TYPE I VALUE 50, \nResult TYPE I. \nResult = A / B. \nWRITE / Result."
},
{
"code": null,
"e": 31607,
"s": 31560,
"text": "The above code produces the following output −"
},
{
"code": null,
"e": 31610,
"s": 31607,
"text": "3\n"
},
{
"code": null,
"e": 31690,
"s": 31610,
"text": "Let’s discuss the various types of comparison operators for different operands."
},
{
"code": null,
"e": 31732,
"s": 31690,
"text": "= (equality test). Alternate form is EQ."
},
{
"code": null,
"e": 31852,
"s": 31732,
"text": "Checks if the values of two operands are equal or not, if yes then condition becomes true. Example (A = B) is not true."
},
{
"code": null,
"e": 31897,
"s": 31852,
"text": "<> (Inequality test). Alternate form is NE."
},
{
"code": null,
"e": 32039,
"s": 31897,
"text": "Checks if the values of two operands are equal or not. If the values are not equal then the condition becomes true. Example (A <> B) is true."
},
{
"code": null,
"e": 32084,
"s": 32039,
"text": "> (Greater than test). Alternate form is GT."
},
{
"code": null,
"e": 32229,
"s": 32084,
"text": "Checks if the value of left operand is greater than the value of right operand. If yes then condition becomes true. Example (A > B) is not true."
},
{
"code": null,
"e": 32271,
"s": 32229,
"text": "< (Less than test). Alternate form is LT."
},
{
"code": null,
"e": 32410,
"s": 32271,
"text": "Checks if the value of left operand is less than the value of right operand. If yes, then condition becomes true. Example (A < B) is true."
},
{
"code": null,
"e": 32460,
"s": 32410,
"text": ">= (Greater than or equals) Alternate form is GE."
},
{
"code": null,
"e": 32619,
"s": 32460,
"text": "Checks if the value of left operand is greater than or equal to the value of right Operand. If yes, then condition becomes true. Example (A >= B) is not true."
},
{
"code": null,
"e": 32672,
"s": 32619,
"text": "<= (Less than or equals test). Alternate form is LE."
},
{
"code": null,
"e": 32824,
"s": 32672,
"text": "Checks if the value of left operand is less than or equal to the value of right operand. If yes, then condition becomes true. Example (A <= B) is true."
},
{
"code": null,
"e": 32862,
"s": 32824,
"text": "a1 BETWEEN a2 AND a3 (Interval test)"
},
{
"code": null,
"e": 32997,
"s": 32862,
"text": "Checks whether a1 lies in between a2 and a3 (inclusive). If yes, then the condition becomes true. Example (A BETWEEN B AND C) is true."
},
{
"code": null,
"e": 33008,
"s": 32997,
"text": "IS INITIAL"
},
{
"code": null,
"e": 33177,
"s": 33008,
"text": "The condition becomes true if the contents of the variable have not changed and it has been automatically assigned its initial value. Example (A IS INITIAL) is not true"
},
{
"code": null,
"e": 33192,
"s": 33177,
"text": "IS NOT INITIAL"
},
{
"code": null,
"e": 33301,
"s": 33192,
"text": "The condition becomes true if the contents of the variable have changed. Example (A IS NOT INITIAL) is true."
},
{
"code": null,
"e": 33626,
"s": 33301,
"text": "Note − If the data type or length of the variables does not match then automatic conversion is performed. Automatic type adjustment is performed for either one or both of the values while comparing two values of different data types. The conversion type is decided by the data type and the preference order of the data type."
},
{
"code": null,
"e": 33665,
"s": 33626,
"text": "Following is the order of preference −"
},
{
"code": null,
"e": 33731,
"s": 33665,
"text": "If one field is of type I, then the other is converted to type I."
},
{
"code": null,
"e": 33797,
"s": 33731,
"text": "If one field is of type I, then the other is converted to type I."
},
{
"code": null,
"e": 33863,
"s": 33797,
"text": "If one field is of type P, then the other is converted to type P."
},
{
"code": null,
"e": 33929,
"s": 33863,
"text": "If one field is of type P, then the other is converted to type P."
},
{
"code": null,
"e": 34096,
"s": 33929,
"text": "If one field is of type D, then the other is converted to type D. But C and N types are not converted and they are compared directly. Similar is the case with type T."
},
{
"code": null,
"e": 34263,
"s": 34096,
"text": "If one field is of type D, then the other is converted to type D. But C and N types are not converted and they are compared directly. Similar is the case with type T."
},
{
"code": null,
"e": 34363,
"s": 34263,
"text": "If one field is of type N and the other is of type C or X, both the fields are converted to type P."
},
{
"code": null,
"e": 34463,
"s": 34363,
"text": "If one field is of type N and the other is of type C or X, both the fields are converted to type P."
},
{
"code": null,
"e": 34552,
"s": 34463,
"text": "If one field is of type C and the other is of type X, the X type is converted to type C."
},
{
"code": null,
"e": 34641,
"s": 34552,
"text": "If one field is of type C and the other is of type X, the X type is converted to type C."
},
{
"code": null,
"e": 34777,
"s": 34641,
"text": "REPORT YS_SEP_08. \n\nDATA: A TYPE I VALUE 115,\n B TYPE I VALUE 119.\n IF A LT B.\n WRITE: / 'A is less than B'.\n ENDIF"
},
{
"code": null,
"e": 34824,
"s": 34777,
"text": "The above code produces the following output −"
},
{
"code": null,
"e": 34843,
"s": 34824,
"text": "A is less than B \n"
},
{
"code": null,
"e": 34947,
"s": 34843,
"text": "REPORT YS_SEP_08. \n\nDATA: A TYPE I.\n IF A IS INITIAL.\n WRITE: / 'A is assigned'.\n ENDIF."
},
{
"code": null,
"e": 34994,
"s": 34947,
"text": "The above code produces the following output −"
},
{
"code": null,
"e": 35010,
"s": 34994,
"text": "A is assigned.\n"
},
{
"code": null,
"e": 35214,
"s": 35010,
"text": "ABAP also provides a series of bitwise logical operators that can be used to build Boolean algebraic expressions. The bitwise operators can be combined in complex expressions using parentheses and so on."
},
{
"code": null,
"e": 35222,
"s": 35214,
"text": "BIT-NOT"
},
{
"code": null,
"e": 35438,
"s": 35222,
"text": "Unary operator that flips all the bits in a hexadecimal number to the opposite value. For instance, applying this operator to a hexadecimal number having the bit level value 10101010 (e.g. 'AA') would give 01010101."
},
{
"code": null,
"e": 35446,
"s": 35438,
"text": "BIT-AND"
},
{
"code": null,
"e": 35530,
"s": 35446,
"text": "This binary operator compares each field bit by bit using the Boolean AND operator."
},
{
"code": null,
"e": 35538,
"s": 35530,
"text": "BIT-XOR"
},
{
"code": null,
"e": 35637,
"s": 35538,
"text": "Binary operator that compares each field bit by bit using the Boolean XOR (exclusive OR) operator."
},
{
"code": null,
"e": 35644,
"s": 35637,
"text": "BIT-OR"
},
{
"code": null,
"e": 35727,
"s": 35644,
"text": "Binary operator that compares each field bit by bit using the Boolean OR operator."
},
{
"code": null,
"e": 35914,
"s": 35727,
"text": "For example, following is the truth table that shows the values generated when applying the Boolean AND, OR, or XOR operators against the two bit values contained in field A and field B."
},
{
"code": null,
"e": 35966,
"s": 35914,
"text": "Following is a list of character string operators −"
},
{
"code": null,
"e": 35985,
"s": 35966,
"text": "CO (Contains Only)"
},
{
"code": null,
"e": 36045,
"s": 35985,
"text": "Checks whether A is solely composed of the characters in B."
},
{
"code": null,
"e": 36068,
"s": 36045,
"text": "CN (Not Contains ONLY)"
},
{
"code": null,
"e": 36124,
"s": 36068,
"text": "Checks whether A contains characters that are not in B."
},
{
"code": null,
"e": 36142,
"s": 36124,
"text": "CA (Contains ANY)"
},
{
"code": null,
"e": 36197,
"s": 36142,
"text": "Checks whether A contains at least one character of B."
},
{
"code": null,
"e": 36219,
"s": 36197,
"text": "NA (NOT Contains Any)"
},
{
"code": null,
"e": 36273,
"s": 36219,
"text": "Checks whether A does not contain any character of B."
},
{
"code": null,
"e": 36296,
"s": 36273,
"text": "CS (Contains a String)"
},
{
"code": null,
"e": 36346,
"s": 36296,
"text": "Checks whether A contains the character string B."
},
{
"code": null,
"e": 36373,
"s": 36346,
"text": "NS (NOT Contains a String)"
},
{
"code": null,
"e": 36431,
"s": 36373,
"text": "Checks whether A does not contain the character string B."
},
{
"code": null,
"e": 36455,
"s": 36431,
"text": "CP (Contains a Pattern)"
},
{
"code": null,
"e": 36502,
"s": 36455,
"text": "It checks whether A contains the pattern in B."
},
{
"code": null,
"e": 36530,
"s": 36502,
"text": "NP (NOT Contains a Pattern)"
},
{
"code": null,
"e": 36585,
"s": 36530,
"text": "It checks whether A does not contain the pattern in B."
},
{
"code": null,
"e": 36761,
"s": 36585,
"text": "REPORT YS_SEP_08. \nDATA: P(10) TYPE C VALUE 'APPLE',\n Q(10) TYPE C VALUE 'CHAIR'.\n IF P CA Q.\n\t\n WRITE: / 'P contains at least one character of Q'.\n ENDIF."
},
{
"code": null,
"e": 36808,
"s": 36761,
"text": "The above code produces the following output −"
},
{
"code": null,
"e": 36849,
"s": 36808,
"text": "P contains at least one character of Q.\n"
},
{
"code": null,
"e": 37078,
"s": 36849,
"text": "There may be a situation when you need to execute a block of code several number of times. In general, statements are executed sequentially: The first statement in a function is executed first, followed by the second, and so on."
},
{
"code": null,
"e": 37364,
"s": 37078,
"text": "Programming languages provide various control structures that allow for more complicated execution paths. A loop statement allows us to execute a statement or group of statements multiple times and following is the general form of a loop statement in most of the programming languages."
},
{
"code": null,
"e": 37459,
"s": 37364,
"text": "ABAP programming language provides the following types of loop to handle looping requirements."
},
{
"code": null,
"e": 37589,
"s": 37459,
"text": "Repeats a statement or group of statements when a given condition is true. It tests the condition before executing the loop body."
},
{
"code": null,
"e": 37674,
"s": 37589,
"text": "The DO statement is useful for repeating particular task a specific number of times."
},
{
"code": null,
"e": 37741,
"s": 37674,
"text": "You may use one or more loops inside any another WHILE or DO loop."
},
{
"code": null,
"e": 37929,
"s": 37741,
"text": "Loop control statements change execution from its normal sequence. ABAP includes control statements that allow loops to be ended prematurely. It supports the following control statements."
},
{
"code": null,
"e": 38010,
"s": 37929,
"text": "Causes the loop to skip the remainder of its body and starts the next loop pass."
},
{
"code": null,
"e": 38142,
"s": 38010,
"text": "If the condition is false, then the remaining statements after the CHECK are just ignored and the system starts the next loop pass."
},
{
"code": null,
"e": 38244,
"s": 38142,
"text": "Terminates the loop entirely and transfers execution to the statement immediately following the loop."
},
{
"code": null,
"e": 38539,
"s": 38244,
"text": "Decision making structures have one or more conditions to be evaluated or tested by the program, along with a statement or statements that are to be executed, if the condition is determined to be true, and optionally, other statements to be executed, if the condition is determined to be false."
},
{
"code": null,
"e": 38653,
"s": 38539,
"text": "Following is the general form of a typical decision-making structure found in most of the programming languages −"
},
{
"code": null,
"e": 38739,
"s": 38653,
"text": "ABAP programming language provides the following types of decision-making statements."
},
{
"code": null,
"e": 38824,
"s": 38739,
"text": "An IF statement consists of a logical expression followed by one or more statements."
},
{
"code": null,
"e": 38930,
"s": 38824,
"text": "An IF statement can be followed by an optional ELSE statement that executes when the expression is false."
},
{
"code": null,
"e": 39008,
"s": 38930,
"text": "You may use one IF or ELSEIF statement inside another IF or ELSEIF statement."
},
{
"code": null,
"e": 39088,
"s": 39008,
"text": "CASE statement is used when we need to compare two or more fields or variables."
},
{
"code": null,
"e": 39170,
"s": 39088,
"text": "Strings, which are widely used in ABAP programming, are a sequence of characters."
},
{
"code": null,
"e": 39345,
"s": 39170,
"text": "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."
},
{
"code": null,
"e": 39519,
"s": 39345,
"text": "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'."
},
{
"code": null,
"e": 39550,
"s": 39519,
"text": "Data my_Char(5) VALUE 'Hello'."
},
{
"code": null,
"e": 39603,
"s": 39550,
"text": "Following program is an example of creating strings."
},
{
"code": null,
"e": 39669,
"s": 39603,
"text": "REPORT YT_SEP_15. \nDATA my_Char(5) VALUE 'Hello'. \nWrite my_Char."
},
{
"code": null,
"e": 39716,
"s": 39669,
"text": "The above code produces the following output −"
},
{
"code": null,
"e": 39723,
"s": 39716,
"text": "Hello\n"
},
{
"code": null,
"e": 39883,
"s": 39723,
"text": "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."
},
{
"code": null,
"e": 40046,
"s": 39883,
"text": "REPORT YT_SEP_15. \nDATA: title_1(10) VALUE 'Tutorials',\n length_1 TYPE I. \n\t\nlength_1 = STRLEN( title_1 ). \nWrite: / 'The Length of the Title is:', length_1."
},
{
"code": null,
"e": 40093,
"s": 40046,
"text": "The above code produces the following output −"
},
{
"code": null,
"e": 40125,
"s": 40093,
"text": "The Length of the Title is: 9 \n"
},
{
"code": null,
"e": 40191,
"s": 40125,
"text": "ABAP supports a wide range of statements that manipulate strings."
},
{
"code": null,
"e": 40203,
"s": 40191,
"text": "CONCATENATE"
},
{
"code": null,
"e": 40250,
"s": 40203,
"text": "Two strings are joined to form a third string."
},
{
"code": null,
"e": 40259,
"s": 40250,
"text": "CONDENSE"
},
{
"code": null,
"e": 40304,
"s": 40259,
"text": "This statement deletes the space characters."
},
{
"code": null,
"e": 40311,
"s": 40304,
"text": "STRLEN"
},
{
"code": null,
"e": 40347,
"s": 40311,
"text": "Used to find the length of a field."
},
{
"code": null,
"e": 40355,
"s": 40347,
"text": "REPLACE"
},
{
"code": null,
"e": 40396,
"s": 40355,
"text": "Used to make replacements in characters."
},
{
"code": null,
"e": 40403,
"s": 40396,
"text": "SEARCH"
},
{
"code": null,
"e": 40441,
"s": 40403,
"text": "To run searches in character strings."
},
{
"code": null,
"e": 40447,
"s": 40441,
"text": "SHIFT"
},
{
"code": null,
"e": 40500,
"s": 40447,
"text": "Used to move the contents of a string left or right."
},
{
"code": null,
"e": 40506,
"s": 40500,
"text": "SPLIT"
},
{
"code": null,
"e": 40569,
"s": 40506,
"text": "Used to split the contents of a field into two or more fields."
},
{
"code": null,
"e": 40645,
"s": 40569,
"text": "The following example makes use of some of the above mentioned statements −"
},
{
"code": null,
"e": 41174,
"s": 40645,
"text": "REPORT YT_SEP_15. \nDATA: title_1(10) VALUE 'Tutorials', \n title_2(10) VALUE 'Point',\n spaced_title(30) VALUE 'Tutorials Point Limited',\n sep,\n dest1(30),\n dest2(30).\n\t\nCONCATENATE title_1 title_2 INTO dest1. \nWrite: / 'Concatenation:', dest1. \n\nCONCATENATE title_1 title_2 INTO dest2 SEPARATED BY sep. \nWrite: / 'Concatenation with Space:', dest2. \n\nCONDENSE spaced_title.\nWrite: / 'Condense with Gaps:', spaced_title. \n\nCONDENSE spaced_title NO-GAPS. \nWrite: / 'Condense with No Gaps:', spaced_title."
},
{
"code": null,
"e": 41221,
"s": 41174,
"text": "The above code produces the following output −"
},
{
"code": null,
"e": 41386,
"s": 41221,
"text": "Concatenation: TutorialsPoint \nConcatenation with Space: Tutorials Point \nCondense with Gaps: Tutorials Point Limited \nCondense with No Gaps: TutorialsPointLimited\n"
},
{
"code": null,
"e": 41393,
"s": 41386,
"text": "Note −"
},
{
"code": null,
"e": 41468,
"s": 41393,
"text": "In case of Concatenation, the ‘sep’ inserts a space in between the fields."
},
{
"code": null,
"e": 41543,
"s": 41468,
"text": "In case of Concatenation, the ‘sep’ inserts a space in between the fields."
},
{
"code": null,
"e": 41645,
"s": 41543,
"text": "The CONDENSE statement removes blank spaces between the fields, but leaving only 1 character’s space."
},
{
"code": null,
"e": 41747,
"s": 41645,
"text": "The CONDENSE statement removes blank spaces between the fields, but leaving only 1 character’s space."
},
{
"code": null,
"e": 41832,
"s": 41747,
"text": "‘NO-GAPS’ is an optional addition to the CONDENSE statement that removes all spaces."
},
{
"code": null,
"e": 41917,
"s": 41832,
"text": "‘NO-GAPS’ is an optional addition to the CONDENSE statement that removes all spaces."
},
{
"code": null,
"e": 42401,
"s": 41917,
"text": "ABAP implicitly references the Gregorian calendar, valid across most of the world. We can convert the output to country specific calendars. A date is a time specified to a precise day, week or month with respect to a calendar. A time is specified to a precise second or minute with respect to a day. ABAP always saves time in 24-hour format. The output can have a country specific format. Dates and time are usually interpreted as local dates that are valid in the current time zone."
},
{
"code": null,
"e": 42464,
"s": 42401,
"text": "ABAP provides two built-in types to work with dates and time −"
},
{
"code": null,
"e": 42476,
"s": 42464,
"text": "D data type"
},
{
"code": null,
"e": 42488,
"s": 42476,
"text": "T data type"
},
{
"code": null,
"e": 42520,
"s": 42488,
"text": "Following is the basic format −"
},
{
"code": null,
"e": 42658,
"s": 42520,
"text": "DATA: date TYPE D, \n time TYPE T. \n\t\nDATA: year TYPE I, \nmonth TYPE I, \nday TYPE I, \nhour TYPE I, \nminute TYPE I, \nsecond TYPE I."
},
{
"code": null,
"e": 42765,
"s": 42658,
"text": "Both of these types are fixed-length character types that have the form YYYYMMDD and HHMMSS, respectively."
},
{
"code": null,
"e": 43009,
"s": 42765,
"text": "In addition to these built-in types, the other two types TIMESTAMP and TIMESTAMPL are being used in many standard application tables to store a timestamp in the UTC format. Following table shows the basic date and time types available in ABAP."
},
{
"code": null,
"e": 43011,
"s": 43009,
"text": "D"
},
{
"code": null,
"e": 43139,
"s": 43011,
"text": "A built-in fixed-length date type of the form YYYYMMDD. For example, the value 20100913 represents the date September 13, 2010."
},
{
"code": null,
"e": 43141,
"s": 43139,
"text": "T"
},
{
"code": null,
"e": 43254,
"s": 43141,
"text": "A built-in fixed-length time type of the form HHMMSS. For example, the value 102305 represents time 10:23:05 AM."
},
{
"code": null,
"e": 43296,
"s": 43254,
"text": "TIMESTAMP (Type P – Length 8 No decimals)"
},
{
"code": null,
"e": 43463,
"s": 43296,
"text": "This type is used to represent short timestamps in YYYYMMDDhhmmss form. For instance, the value 20100913102305 represents the date September 13, 2010 at 10:23:05 AM."
},
{
"code": null,
"e": 43506,
"s": 43463,
"text": "TIMESTAMPL (Type P - Length 11 Decimals 7)"
},
{
"code": null,
"e": 43650,
"s": 43506,
"text": "TIMESTAMPL represents long timestamps in YYYYMMDDhhmmss,mmmuuun form. Here the additional digits ‘mmmuuun’ represent the fractions of a second."
},
{
"code": null,
"e": 43721,
"s": 43650,
"text": "The following code snippets retrieve the current system date and time."
},
{
"code": null,
"e": 43909,
"s": 43721,
"text": "REPORT YR_SEP_15. \nDATA: date_1 TYPE D. \n\ndate_1 = SY-DATUM. \nWrite: / 'Present Date is:', date_1 DD/MM/YYYY. \n\ndate_1 = date_1 + 06. \nWrite: / 'Date after 6 Days is:', date_1 DD/MM/YYYY."
},
{
"code": null,
"e": 43956,
"s": 43909,
"text": "The above code produces the following output −"
},
{
"code": null,
"e": 44019,
"s": 43956,
"text": "Present Date is: 21.09.2015 \nDate after 6 Days is: 27.09.2015\n"
},
{
"code": null,
"e": 44374,
"s": 44019,
"text": "The variable date_1 is assigned the value of the current system date SY-DATUM. Next, we increment the date value by 6. In terms of a date calculation in ABAP, this implies that we’re increasing the day component of the date object by 6 days. The ABAP runtime environment is smart enough to roll over the date value whenever it reaches the end of a month."
},
{
"code": null,
"e": 44524,
"s": 44374,
"text": "Time calculations work similar to date calculations. The following code increments the current system time by 75 seconds using basic time arithmetic."
},
{
"code": null,
"e": 44770,
"s": 44524,
"text": "REPORT YR_SEP_15. \nDATA: time_1 TYPE T. \n time_1 = SY-UZEIT. \n\nWrite /(60) time_1 USING EDIT MASK \n'Now the Time is: __:__:__'. \ntime_1 = time_1 + 75. \n\nWrite /(60) time_1 USING EDIT MASK \n'A Minute and a Quarter from Now, it is: __:__:__'."
},
{
"code": null,
"e": 44817,
"s": 44770,
"text": "The above code produces the following output −"
},
{
"code": null,
"e": 44893,
"s": 44817,
"text": "Now the Time is 11:45:05 \nA Minute and a Quarter from Now, it is: 11:46:20\n"
},
{
"code": null,
"e": 45220,
"s": 44893,
"text": "You can retrieve the current system time and store it in a timestamp variable using GET TIME STAMP as shown in the following code. The GET TIME STAMP statement stores the timestamp in a long-hand or a short-hand format according to the type of the timestamp data object used. Timestamp value is encoded using the UTC standard."
},
{
"code": null,
"e": 45492,
"s": 45220,
"text": "REPORT YR_SEP_12. \nDATA: stamp_1 TYPE TIMESTAMP,\n \nstamp_2 TYPE TIMESTAMPL. \nGET TIME STAMP FIELD stamp_1. \nWrite: / 'The short time stamp is:', stamp_1 \n\nTIME ZONE SY-ZONLO. \nGET TIME STAMP FIELD stamp_2. \nWrite: / 'The long time stamp is:', stamp_2 \nTIME ZONE SY-ZONLO."
},
{
"code": null,
"e": 45539,
"s": 45492,
"text": "The above code produces the following output −"
},
{
"code": null,
"e": 45638,
"s": 45539,
"text": "The short time stamp is: 18.09.2015 11:19:40 \nThe long time stamp is: 18.09.2015 11:19:40,9370000\n"
},
{
"code": null,
"e": 45950,
"s": 45638,
"text": "In the above example, we are displaying the timestamp using the TIME ZONE addition of the WRITE statement. This addition formats the output of the timestamp according to the rules for the time zone specified. The system field SY-ZONLO is used to display the local time zone configured in the user’s preferences."
},
{
"code": null,
"e": 46137,
"s": 45950,
"text": "ABAP offers various types of formatting options to format the output of programs. For example, you can create a list that includes various items in different colors or formatting styles."
},
{
"code": null,
"e": 46320,
"s": 46137,
"text": "The WRITE statement is a formatting statement used to display data on a screen. There are different formatting options for the WRITE statement. The syntax of the WRITE statement is −"
},
{
"code": null,
"e": 46351,
"s": 46320,
"text": "WRITE <format> <f> <options>.\n"
},
{
"code": null,
"e": 46867,
"s": 46351,
"text": "In this syntax, <format> represents the output format specification, which can be a forward slash (/) that indicates the display of the output starting from a new line. In addition to the forward slash, the format specification includes a column number and column length. For example, the WRITE/04 (6) statement shows that a new line begins with column 4 and the column length is 6, whereas the WRITE 20 statement shows the current line with column 20. The parameter <f> represents a data variable or numbered text."
},
{
"code": null,
"e": 46935,
"s": 46867,
"text": "The following table describes various clauses used for formatting −"
},
{
"code": null,
"e": 46950,
"s": 46935,
"text": "LEFT-JUSTIFIED"
},
{
"code": null,
"e": 46995,
"s": 46950,
"text": "Specifies that the output is left-justified."
},
{
"code": null,
"e": 47004,
"s": 46995,
"text": "CENTERED"
},
{
"code": null,
"e": 47041,
"s": 47004,
"text": "Denotes that the output is centered."
},
{
"code": null,
"e": 47057,
"s": 47041,
"text": "RIGHT-JUSTIFIED"
},
{
"code": null,
"e": 47103,
"s": 47057,
"text": "Specifies that the output is right-justified."
},
{
"code": null,
"e": 47113,
"s": 47103,
"text": "UNDER <g>"
},
{
"code": null,
"e": 47161,
"s": 47113,
"text": "The output starts directly under the field <g>."
},
{
"code": null,
"e": 47168,
"s": 47161,
"text": "NO-GAP"
},
{
"code": null,
"e": 47222,
"s": 47168,
"text": "Specifies that the blank after field <f> is rejected."
},
{
"code": null,
"e": 47242,
"s": 47222,
"text": "USING EDIT MASK <m>"
},
{
"code": null,
"e": 47405,
"s": 47242,
"text": "Denotes the specification of the format template <m>. Using No EDIT Mask: This specifies that the format template specified in the ABAP Dictionary is deactivated."
},
{
"code": null,
"e": 47413,
"s": 47405,
"text": "NO-ZERO"
},
{
"code": null,
"e": 47480,
"s": 47413,
"text": "If a field contains only zeroes, then they are replaced by blanks."
},
{
"code": null,
"e": 47543,
"s": 47480,
"text": "Following are the formatting options for Numeric Type fields −"
},
{
"code": null,
"e": 47551,
"s": 47543,
"text": "NO-SIGN"
},
{
"code": null,
"e": 47610,
"s": 47551,
"text": "Specifies that no leading sign is displayed on the screen."
},
{
"code": null,
"e": 47623,
"s": 47610,
"text": "EXPONENT <e>"
},
{
"code": null,
"e": 47709,
"s": 47623,
"text": "Specifies that in type F (the floating point fields), the exponent is defined in <e>."
},
{
"code": null,
"e": 47719,
"s": 47709,
"text": "ROUND <r>"
},
{
"code": null,
"e": 47840,
"s": 47719,
"text": "The type P fields (packed numeric data types) are first multiplied by 10**(-r) and then rounded off to an integer value."
},
{
"code": null,
"e": 47853,
"s": 47840,
"text": "CURRENCY <c>"
},
{
"code": null,
"e": 47969,
"s": 47853,
"text": "Denotes that the formatting is done according to the currency <c> value that is stored in the TCURX database table."
},
{
"code": null,
"e": 47978,
"s": 47969,
"text": "UNIT <u>"
},
{
"code": null,
"e": 48109,
"s": 47978,
"text": "Specifies that the number of decimal places is fixed according to the <u> unit as specified in the T006 database table for type P."
},
{
"code": null,
"e": 48122,
"s": 48109,
"text": "DECIMALS <d>"
},
{
"code": null,
"e": 48205,
"s": 48122,
"text": "Specifies that the number of digits <d> must be displayed after the decimal point."
},
{
"code": null,
"e": 48296,
"s": 48205,
"text": "For instance, the following table shows different formatting options for the date fields −"
},
{
"code": null,
"e": 48466,
"s": 48296,
"text": "Here, DD stands for the date in two figures, MM stands for the month in two figures, YY stands for the year in two figures, and YYYY stands for the year in four figures."
},
{
"code": null,
"e": 48566,
"s": 48466,
"text": "Let’s take a look at an example of ABAP code that implements some of the above formatting options −"
},
{
"code": null,
"e": 48809,
"s": 48566,
"text": "REPORT ZTest123_01.\n \nDATA: n(9) TYPE C VALUE 'Tutorials', \nm(5) TYPE C VALUE 'Point'. \n\nWRITE: n, m. \nWRITE: / n, \n/ m UNDER n. \n\nWRITE: / n NO-GAP, m. \nDATA time TYPE T VALUE '112538'. \n\nWRITE: / time, \n/(8) time Using EDIT MASK '__:__:__'."
},
{
"code": null,
"e": 48856,
"s": 48809,
"text": "The above code produces the following output −"
},
{
"code": null,
"e": 48926,
"s": 48856,
"text": "Tutorials Point \nTutorials \nPoint \nTutorialsPoint \n112538 \n11:25:38\n"
},
{
"code": null,
"e": 49191,
"s": 48926,
"text": "An exception is a problem that arises during the execution of a program. When an exception occurs the normal flow of the program is disrupted and the program application terminates abnormally, which is not recommended, therefore these exceptions are to be handled."
},
{
"code": null,
"e": 49612,
"s": 49191,
"text": "Exceptions provide a way to transfer control from one part of a program to another. ABAP exception handling is built upon three keywords − RAISE, TRY, CATCH and CLEANUP. Assuming a block will raise an exception, a method catches an exception using a combination of the TRY and CATCH keywords. A TRY - CATCH block is placed around the code that might generate an exception. Following is the syntax for using TRY – CATCH −"
},
{
"code": null,
"e": 49848,
"s": 49612,
"text": "TRY. \nTry Block <Code that raises an exception> \n \nCATCH \nCatch Block <exception handler M> \n. . . \n. . . \n. . . \nCATCH \nCatch Block <exception handler R>\n \nCLEANUP. \n Cleanup block <to restore consistent state>\n \nENDTRY.\n"
},
{
"code": null,
"e": 50025,
"s": 49848,
"text": "RAISE − Exceptions are raised to indicate that some exceptional situation has occurred. Usually, an exception handler tries to repair the error or find an alternative solution."
},
{
"code": null,
"e": 50295,
"s": 50025,
"text": "TRY − The TRY block contains the application coding whose exceptions are to be handled. This statement block is processed sequentially. It can contain further control structures and calls of procedures or other ABAP programs. It is followed by one or more catch blocks."
},
{
"code": null,
"e": 50482,
"s": 50295,
"text": "CATCH − A program catches an exception with an exception handler at the place in a program where you want to handle the problem. The CATCH keyword indicates the catching of an exception."
},
{
"code": null,
"e": 50840,
"s": 50482,
"text": "CLEANUP − The statements of the CLEANUP block are executed whenever an exception occurs in a TRY block that is not caught by the handler of the same TRY - ENDTRY construct. Within the CLEANUP clause, the system can restore an object to a consistent state or release external resources. That is, cleanup work can be executed for the context of the TRY block."
},
{
"code": null,
"e": 50983,
"s": 50840,
"text": "Exceptions can be raised at any point in a method, a function module, a subroutine, and so on. There are two ways an exception can be raised −"
},
{
"code": null,
"e": 51112,
"s": 50983,
"text": "Exceptions raised by ABAP runtime system.\nFor instance Y = 1 / 0. This will result in a run time error of type CX_SY_ZERODIVIDE."
},
{
"code": null,
"e": 51154,
"s": 51112,
"text": "Exceptions raised by ABAP runtime system."
},
{
"code": null,
"e": 51241,
"s": 51154,
"text": "For instance Y = 1 / 0. This will result in a run time error of type CX_SY_ZERODIVIDE."
},
{
"code": null,
"e": 51451,
"s": 51241,
"text": "Exceptions raised by programmer.\nRaise and create an exception object simultaneously. Raise an exception with an exception object that already exists in the first scenario. The syntax is: RAISE EXCEPTION exep."
},
{
"code": null,
"e": 51484,
"s": 51451,
"text": "Exceptions raised by programmer."
},
{
"code": null,
"e": 51661,
"s": 51484,
"text": "Raise and create an exception object simultaneously. Raise an exception with an exception object that already exists in the first scenario. The syntax is: RAISE EXCEPTION exep."
},
{
"code": null,
"e": 51700,
"s": 51661,
"text": "Handlers are used to catch exceptions."
},
{
"code": null,
"e": 51738,
"s": 51700,
"text": "Let’s take a look at a code snippet −"
},
{
"code": null,
"e": 52037,
"s": 51738,
"text": "DATA: result TYPE P LENGTH 8 DECIMALS 2, \nexref TYPE REF TO CX_ROOT, \nmsgtxt TYPE STRING. \nPARAMETERS: Num1 TYPE I, Num2 TYPE I. \nTRY. \nresult = Num1 / Num2. \nCATCH CX_SY_ZERODIVIDE INTO exref. \nmsgtxt = exref→GET_TEXT( ). \n\nCATCH CX_SY_CONVERSION_NO_NUMBER INTO exref. \nmsgtxt = exref→GET_TEXT( )."
},
{
"code": null,
"e": 52145,
"s": 52037,
"text": "In the above code snippet, we are trying to divide Num1 by Num2 to get the result in a float type variable."
},
{
"code": null,
"e": 52189,
"s": 52145,
"text": "Two types of exceptions could be generated."
},
{
"code": null,
"e": 52214,
"s": 52189,
"text": "Number conversion error."
},
{
"code": null,
"e": 52239,
"s": 52214,
"text": "Number conversion error."
},
{
"code": null,
"e": 52458,
"s": 52239,
"text": "Divide by zero exception. Handlers catch CX_SY_CONVERSION_NO_NUMBER exception and also the CX_SY_ZERODIVIDE exception. Here the GET_TEXT( ) method of the exception class is used to get the description of the exception."
},
{
"code": null,
"e": 52677,
"s": 52458,
"text": "Divide by zero exception. Handlers catch CX_SY_CONVERSION_NO_NUMBER exception and also the CX_SY_ZERODIVIDE exception. Here the GET_TEXT( ) method of the exception class is used to get the description of the exception."
},
{
"code": null,
"e": 52734,
"s": 52677,
"text": "Here are the five attributes and methods of exceptions −"
},
{
"code": null,
"e": 52741,
"s": 52734,
"text": "Textid"
},
{
"code": null,
"e": 52839,
"s": 52741,
"text": "Used to define different texts for exceptions and also affects the result of the method get_text."
},
{
"code": null,
"e": 52848,
"s": 52839,
"text": "Previous"
},
{
"code": null,
"e": 52944,
"s": 52848,
"text": "This attribute can store the original exception that allows you to build a chain of exceptions."
},
{
"code": null,
"e": 52953,
"s": 52944,
"text": "get_text"
},
{
"code": null,
"e": 53050,
"s": 52953,
"text": "This returns the textual representation as a string as per the system language of the exception."
},
{
"code": null,
"e": 53063,
"s": 53050,
"text": "get_longtext"
},
{
"code": null,
"e": 53153,
"s": 53063,
"text": "This returns the long variant of the textual representation of the exception as a string."
},
{
"code": null,
"e": 53173,
"s": 53153,
"text": "get_source_position"
},
{
"code": null,
"e": 53252,
"s": 53173,
"text": "Gives the program name and line number reached where the exception was raised."
},
{
"code": null,
"e": 54015,
"s": 53252,
"text": "REPORT ZExceptionsDemo. \nPARAMETERS Num_1 TYPE I. \n\nDATA res_1 TYPE P DECIMALS 2. \nDATA orf_1 TYPE REF TO CX_ROOT. \nDATA txt_1 TYPE STRING. \n\nstart-of-selection. \nWrite: / 'Square Root and Division with:', Num_1. \nwrite: /. \n\nTRY. \nIF ABS( Num_1 ) > 150. \nRAISE EXCEPTION TYPE CX_DEMO_ABS_TOO_LARGE. \nENDIF.\n \nTRY. \nres_1 = SQRT( Num_1 ). \nWrite: / 'Result of square root:', res_1. \nres_1 = 1 / Num_1. \n\nWrite: / 'Result of division:', res_1. \nCATCH CX_SY_ZERODIVIDE INTO orf_1. \ntxt_1 = orf_1→GET_TEXT( ). \nCLEANUP. \nCLEAR res_1. \nENDTRY. \n\nCATCH CX_SY_ARITHMETIC_ERROR INTO orf_1. \ntxt_1 = orf_1→GET_TEXT( ).\n\nCATCH CX_ROOT INTO orf_1. \ntxt_1 = orf_1→GET_TEXT( ). \nENDTRY. \nIF NOT txt_1 IS INITIAL. \nWrite / txt_1. \nENDIF. \nWrite: / 'Final Result is:', res_1."
},
{
"code": null,
"e": 54179,
"s": 54015,
"text": "In this example, if the number is greater than 150, the exception CX_DEMO_ABS_TOO_LARGE is raised. The above code produces the following output for the number 160."
},
{
"code": null,
"e": 54281,
"s": 54179,
"text": "Square Root and Division with: 160 \nThe absolute value of number is too high \nFinal Result is: 0.00\n"
},
{
"code": null,
"e": 54335,
"s": 54281,
"text": "As you are aware, SQL can be divided into two parts −"
},
{
"code": null,
"e": 54368,
"s": 54335,
"text": "DML (Data Manipulation Language)"
},
{
"code": null,
"e": 54399,
"s": 54368,
"text": "DDL (Data Definition Language)"
},
{
"code": null,
"e": 54682,
"s": 54399,
"text": "DML part consists of query and update commands such as SELECT, INSERT, UPDATE, DELETE, etc. and ABAP programs handle the DML part of SQL. DDL part consists of commands such as CREATE TABLE, CREATE INDEX, DROP TABLE, ALTER TABLE, etc. and ABAP Dictionary handles the DDL part of SQL."
},
{
"code": null,
"e": 54956,
"s": 54682,
"text": "ABAP Dictionary can be viewed as metadata (i.e. data about data) that resides in the SAP database along with the metadata maintained by the database. The Dictionary is used to create and manage data definitions and to create Tables, Data Elements, Domains, Views and Types."
},
{
"code": null,
"e": 55008,
"s": 54956,
"text": "The basic types in ABAP Dictionary are as follows −"
},
{
"code": null,
"e": 55113,
"s": 55008,
"text": "Data elements describe an elementary type by defining the data type, length and possibly decimal places."
},
{
"code": null,
"e": 55218,
"s": 55113,
"text": "Data elements describe an elementary type by defining the data type, length and possibly decimal places."
},
{
"code": null,
"e": 55269,
"s": 55218,
"text": "Structures with components that can have any type."
},
{
"code": null,
"e": 55320,
"s": 55269,
"text": "Structures with components that can have any type."
},
{
"code": null,
"e": 55377,
"s": 55320,
"text": "Table types describe the structure of an internal table."
},
{
"code": null,
"e": 55434,
"s": 55377,
"text": "Table types describe the structure of an internal table."
},
{
"code": null,
"e": 55717,
"s": 55434,
"text": "Various objects in the Dictionary environment can be referenced in ABAP programs. The Dictionary is known as the global area. The objects in the Dictionary are global to all ABAP programs and the data in ABAP programs can be declared by reference to these Dictionary global objects."
},
{
"code": null,
"e": 56134,
"s": 55717,
"text": "The Dictionary supports the definition of user-defined types and these types are used in ABAP programs. They also define the structure of database objects such as tables, views and indexes. These objects are created automatically in the underlying database in their Dictionary definitions when the objects are activated. The Dictionary also provides editing tools like Search Help and locking tool like Lock Objects."
},
{
"code": null,
"e": 56175,
"s": 56134,
"text": "ABAP Dictionary achieves the following −"
},
{
"code": null,
"e": 56200,
"s": 56175,
"text": "Enforces data integrity."
},
{
"code": null,
"e": 56245,
"s": 56200,
"text": "Manages data definitions without redundancy."
},
{
"code": null,
"e": 56309,
"s": 56245,
"text": "Integrates tightly with rest of the ABAP development workbench."
},
{
"code": null,
"e": 56685,
"s": 56309,
"text": "Any complex user-defined type can be built from the 3 basic types in the Dictionary. Customer data is stored in a structure ‘Customer’ with the components Name, Address and Telephone as depicted in the following image. Name is also a structure with components, First name and Last name. Both of these components are elementary because their type is defined by a data element."
},
{
"code": null,
"e": 57000,
"s": 56685,
"text": "The type of component Address is defined by a structure whose components are also structures, and the Telephone component is defined by a table type because a customer can have more than one telephone number. Types are used in ABAP programs and also to define the types of interface parameters of function modules."
},
{
"code": null,
"e": 57431,
"s": 57000,
"text": "The three basic objects for defining data in the ABAP Dictionary are Domains, Data elements and Tables. The domain is used for the technical definition of a table field such as field type and length, and the data element is used for the semantic definition (short description). A data element describes the meaning of a domain in a certain business context. It contains primarily the field help and the field labels in the screen."
},
{
"code": null,
"e": 57727,
"s": 57431,
"text": "The domain is assigned to the data element, which in turn is assigned to the table fields or structure fields. For instance, the MATNR domain (CHAR material number) is assigned to data elements such as MATNR_N, MATNN and MATNR_D, and these are assigned to many table fields and structure fields."
},
{
"code": null,
"e": 57968,
"s": 57727,
"text": "Before you create a new domain, check whether any existing domains have the same technical specifications required in your table field. If so, we are supposed to use that existing domain. Let’s discuss the procedure for creating the domain."
},
{
"code": null,
"e": 58001,
"s": 57968,
"text": "Step 1 − Go to Transaction SE11."
},
{
"code": null,
"e": 58299,
"s": 58001,
"text": "Step 2 − Select the radio button for Domain in the initial screen of the ABAP Dictionary, and enter the name of the domain as shown in the following screenshot. Click the CREATE button. You may create domains under the customer namespaces, and the name of the object always starts with ‘Z’ or ‘Y’."
},
{
"code": null,
"e": 58517,
"s": 58299,
"text": "Step 3 − Enter the description in the short text field of the maintenance screen of the domain. In this case, it is “Customer Domain”. Note − You cannot enter any other attribute until you have entered this attribute."
},
{
"code": null,
"e": 58923,
"s": 58517,
"text": "Step 4 − Enter the Data Type, No. of Characters, and Decimal Places in the Format block of the Definition tab. Press the key on Output Length and it proposes and displays the output length. If you overwrite the proposed output length, you may see a warning while activating the domain. You may fill in the Convers. Routine, Sign and Lower Case fields if required. But these are always optional attributes."
},
{
"code": null,
"e": 59247,
"s": 58923,
"text": "Step 5 − Select the Value Range tab. If the domain is restricted to having only fixed values then enter the fixed values or intervals. Define the value table if the system has to propose this table as a check table while defining a foreign key for the fields referring to this domain. But all these are optional attributes."
},
{
"code": null,
"e": 59542,
"s": 59247,
"text": "Step 6 − Save your changes. The Create Object Directory Entry pop-up appears and asks for a package. You may enter the package name in which you are working. If you do not have any package then you may create it in the Object Navigator or you can save your domain using the Local Object button."
},
{
"code": null,
"e": 59764,
"s": 59542,
"text": "Step 7 − Activate your domain. Click on the Activate icon (matchstick icon) or press CTRL + F3 to activate the domain. A pop-up window appears, listing the 2 currently inactive objects as shown in the following snapshot −"
},
{
"code": null,
"e": 59999,
"s": 59764,
"text": "Step 8 − At this point, the top entry labeled ‘DOMA’ with the name ZSEP_18 is to be activated. As this is highlighted, click the green tick button. This window disappears and the status bar will display the message ‘Object activated’."
},
{
"code": null,
"e": 60252,
"s": 59999,
"text": "If error messages or warnings occurred when you activated the domain, the activation log is displayed automatically. The activation log displays information about activation flow. You can also call the activation log with Utilities(M) → Activation log."
},
{
"code": null,
"e": 60803,
"s": 60252,
"text": "Data elements describe the individual fields in the ABAP Data Dictionary. They are the smallest indivisible units of the complex types, and they are used to define the type of table field, structure component or row type of a table. Information about the meaning of a table field and also information about editing the corresponding screen field could be assigned to a data element. This information is automatically available to all the screen fields that refer to the data element. Data elements describe either elementary types or reference types."
},
{
"code": null,
"e": 61090,
"s": 60803,
"text": "Before creating a new data element, you need to check whether any existing data elements have the same semantic specifications required in your table field. If so, you may use that existing data element. You can assign the data element with a predefined type, domain, or reference type."
},
{
"code": null,
"e": 61149,
"s": 61090,
"text": "Following is the procedure for creating the data element −"
},
{
"code": null,
"e": 61182,
"s": 61149,
"text": "Step 1 − Go to Transaction SE11."
},
{
"code": null,
"e": 61330,
"s": 61182,
"text": "Step 2 − Select the radio button for Data type in the initial screen of the ABAP Dictionary, and enter the name of the data element as shown below."
},
{
"code": null,
"e": 61482,
"s": 61330,
"text": "Step 3 − Click the CREATE button. You may create data elements under the customer namespaces, and the name of the object always starts with ‘Z’ or ‘Y’."
},
{
"code": null,
"e": 61592,
"s": 61482,
"text": "Step 4 − Check the Data element radio button on the CREATE TYPE pop-up that appears with three radio buttons."
},
{
"code": null,
"e": 61697,
"s": 61592,
"text": "Step 5 − Click the green checkmark icon. You are directed to the maintenance screen of the data element."
},
{
"code": null,
"e": 61927,
"s": 61697,
"text": "Step 6 − Enter the description in the short text field of the maintenance screen of the data element. In this case, it is “Customer Data Element”. Note − You cannot enter any other attribute until you have entered this attribute."
},
{
"code": null,
"e": 62272,
"s": 61927,
"text": "Step 7 − Assign the data element with the type. You can create an elementary data element by checking elementary type or a reference data element by checking Reference type. You can assign a data element to a Domain or Predefined Type within Elementary Type and with Name of Reference Type or Reference to Predefined Type within Reference Type."
},
{
"code": null,
"e": 62454,
"s": 62272,
"text": "Step 8 − Enter the fields for short text, medium text, long text, and heading in the Field Label tab. You can press Enter and the length is automatically generated for these labels."
},
{
"code": null,
"e": 62755,
"s": 62454,
"text": "Step 9 − Save your changes. The Create Object Directory Entry pop-up appears and asks for a package. You may enter the package name in which you are working. If you do not have any package then you may create it in the Object Navigator or you can save your data element using the Local Object button."
},
{
"code": null,
"e": 62988,
"s": 62755,
"text": "Step 10 − Activate your data element. Click the Activate icon (matchstick icon) or press CTRL + F3 to activate the data element. A pop-up window appears, listing the 2 currently inactive objects as shown in the following screenshot."
},
{
"code": null,
"e": 63223,
"s": 62988,
"text": "Step 11 − At this point, the top entry labeled ‘DTEL’ with the name Z_CUST is to be activated. As this is highlighted, click the green tick button. This window disappears and the status bar will display the message ‘Object activated’."
},
{
"code": null,
"e": 63482,
"s": 63223,
"text": "If error messages or warnings occurred when you activated the data element, the activation log is displayed automatically. The activation log displays information about activation flow. You can also call the activation log with Utilities(M) → Activation log."
},
{
"code": null,
"e": 63865,
"s": 63482,
"text": "Tables can be defined independent of the database in ABAP Dictionary. When a table is activated in ABAP Dictionary, similar copy of its fields is created in the database as well. The tables defined in ABAP Dictionary are translated automatically into the format that is compatible with the database because the definition of the table depends on the database used by the SAP system."
},
{
"code": null,
"e": 64054,
"s": 63865,
"text": "A table can contain one or more fields, each defined with its data type and length. The large amount of data stored in a table is distributed among the several fields defined in the table."
},
{
"code": null,
"e": 64193,
"s": 64054,
"text": "A table consists of many fields, and each field contains many elements. The following table lists the different elements of table fields −"
},
{
"code": null,
"e": 64204,
"s": 64193,
"text": "Field name"
},
{
"code": null,
"e": 64380,
"s": 64204,
"text": "This is the name given to a field that can contain a maximum of 16 characters. The field name may be composed of digits, letters, and underscores. It must begin with a letter."
},
{
"code": null,
"e": 64389,
"s": 64380,
"text": "Key flag"
},
{
"code": null,
"e": 64447,
"s": 64389,
"text": "Determines whether or not a field belongs to a key field."
},
{
"code": null,
"e": 64458,
"s": 64447,
"text": "Field type"
},
{
"code": null,
"e": 64490,
"s": 64458,
"text": "Assigns a data type to a field."
},
{
"code": null,
"e": 64503,
"s": 64490,
"text": "Field length"
},
{
"code": null,
"e": 64560,
"s": 64503,
"text": "The number of characters that can be entered in a field."
},
{
"code": null,
"e": 64575,
"s": 64560,
"text": "Decimal places"
},
{
"code": null,
"e": 64691,
"s": 64575,
"text": "Defines the number of digits permissible after the decimal point. This element is used only for numeric data types."
},
{
"code": null,
"e": 64702,
"s": 64691,
"text": "Short text"
},
{
"code": null,
"e": 64752,
"s": 64702,
"text": "Describes the meaning of the corresponding field."
},
{
"code": null,
"e": 65060,
"s": 64752,
"text": "Step 1 − Go to transaction SE11, select the ‘Database table’ radio button, and enter a name for the table to be created. In our case, we have entered the name ZCUSTOMERS1. Click the Create button. The Dictionary: Maintain Table screen appears. Here the ‘Delivery and Maintenance’ tab is selected by default."
},
{
"code": null,
"e": 65133,
"s": 65060,
"text": "Step 2 − Enter an explanatory short text in the Short Description field."
},
{
"code": null,
"e": 65271,
"s": 65133,
"text": "Step 3 − Click the Search Help icon beside the Delivery Class field. Select ‘A [Application table (master and transaction data)]’ option."
},
{
"code": null,
"e": 65441,
"s": 65271,
"text": "Step 4 − Select the ‘Display/Maintenance Allowed’ option from the ‘Data Browser/Table view Maintenance’ drop-down menu. The Dictionary: Maintenance Table screen appears."
},
{
"code": null,
"e": 65542,
"s": 65441,
"text": "Step 5 − Select the Fields tab. The screen containing the options related to the Fields tab appears."
},
{
"code": null,
"e": 65745,
"s": 65542,
"text": "Step 6 − Enter the names of table fields in the Field column. A field name may contain letters, digits, and underscores, but it must always begin with a letter and must not be longer than 16 characters."
},
{
"code": null,
"e": 65932,
"s": 65745,
"text": "The fields that are to be created must also have data elements because they take the attributes, such as data type, length, decimal places, and short text, from the defined data element."
},
{
"code": null,
"e": 66083,
"s": 65932,
"text": "Step 7 − Select the Key column if you want the field to be a part of the table key. Let’s create fields such as CLIENT, CUSTOMER, NAME, TITLE and DOB."
},
{
"code": null,
"e": 66412,
"s": 66083,
"text": "Step 8 − The first field is an important one and it identifies the client which the records are associated with. Enter ‘Client’ as the Field and ‘MANDT’ as the Data Element. The system automatically fills in the Data Type, Length, Decimals and Short Description. The ‘Client’ field is made a key field by checking the ‘Key’ box."
},
{
"code": null,
"e": 66554,
"s": 66412,
"text": "Step 9 − The next field is ‘Customer’. Check the box to make it a key field and enter the new Data Element ‘ZCUSTNUM’. Click the Save button."
},
{
"code": null,
"e": 66782,
"s": 66554,
"text": "Step 10 − As the Data Element ‘ZCUSTNUM’ doesn’t yet exist, it has to be created. Doubleclick the new Data Element and the ‘Create Data Element’ window appears. Answer ‘Yes’ to this and a ‘Maintain Data Element’ window appears."
},
{
"code": null,
"e": 67109,
"s": 66782,
"text": "Step 11 − Enter ‘Customer Number’ in the Short Description area. The Elementary data type called ‘Domain’ should be defined for the new Data element. So enter ‘ZCUSTD1’, double-click it and agree to save the changes made. Choose ‘Yes’ to create the domain and type into the ‘Short Description’ box a description of the domain."
},
{
"code": null,
"e": 67183,
"s": 67109,
"text": "The ‘Definition’ tab opens automatically. The first field is ‘Data Type’."
},
{
"code": null,
"e": 67528,
"s": 67183,
"text": "Step 12 − Click inside the box and select ‘NUMC’ type from the drop-down menu. Enter the number 8 in the ‘No. of characters’ field (a maximum of 8 characters) and enter 0 in ‘Decimal places’ area. The Output length of 8 must be selected and then press Enter. The ‘NUMC’ field’s description must re-appear, confirming that this is a valid entry."
},
{
"code": null,
"e": 67581,
"s": 67528,
"text": "Step 13 − Click Save button and Activate the object."
},
{
"code": null,
"e": 67760,
"s": 67581,
"text": "Step 14 − Press F3 to return to the ‘Maintain/Change Data Element’ screen. Create four Field labels as shown in the following snapshot. After this, Save and Activate the element."
},
{
"code": null,
"e": 68005,
"s": 67760,
"text": "Step 15 − Press the back button to return to the table maintenance screen. The Customer column has the correct Data Type, Length, Decimals and Short Description. This indicates the successful creation of a Data element and also the Domain used."
},
{
"code": null,
"e": 68087,
"s": 68005,
"text": "Similarly, we need to create three additional fields such as NAME, TITLE and DOB."
},
{
"code": null,
"e": 68313,
"s": 68087,
"text": "Step 16 − Select ‘Technical settings’ from the toolbar. Choose APPL0 for the ‘Data class’ and the first size category 0 for the ‘Size’ category’ field. In case of buffering options, ‘Buffering not allowed’ has to be selected."
},
{
"code": null,
"e": 68403,
"s": 68313,
"text": "Step 17 − Click Save. Go back to the table and Activate it. The following screen appears."
},
{
"code": null,
"e": 68441,
"s": 68403,
"text": "The table ‘ZCUSTOMERS1’ is activated."
},
{
"code": null,
"e": 68557,
"s": 68441,
"text": "Structure is a data object that is made up of components of any data type stored one after the other in the memory."
},
{
"code": null,
"e": 68702,
"s": 68557,
"text": "Structures are useful for painting screen fields, and for manipulating data that has a consistent format defined by a discrete number of fields."
},
{
"code": null,
"e": 68792,
"s": 68702,
"text": "A structure may have only a single record at run-time, but a table can have many records."
},
{
"code": null,
"e": 68825,
"s": 68792,
"text": "Step 1 − Go to transaction SE11."
},
{
"code": null,
"e": 68941,
"s": 68825,
"text": "Step 2 − Click on the ‘Data type’ option on the screen. Enter the name 'ZSTR_CUSTOMER1' and click on Create button."
},
{
"code": null,
"e": 69066,
"s": 68941,
"text": "Step 3 − Select the option 'Structure' in the next screen and press Enter. You can see 'Maintain / Change Structure' wizard."
},
{
"code": null,
"e": 69139,
"s": 69066,
"text": "Step 4 − Enter the Short Description as shown in the following snapshot."
},
{
"code": null,
"e": 69216,
"s": 69139,
"text": "Step 5 − Enter the Component (Field Name) and Component Type (Data Element)."
},
{
"code": null,
"e": 69367,
"s": 69216,
"text": "Note: Here the component names start with Z as per the SAP recommendation. Let's use data elements that we have already created in the database table."
},
{
"code": null,
"e": 69469,
"s": 69367,
"text": "Step 6 − You need to Save, Check and Activate after providing all the components and component types."
},
{
"code": null,
"e": 69500,
"s": 69469,
"text": "The following screen appears −"
},
{
"code": null,
"e": 69656,
"s": 69500,
"text": "Step 7 − As this 'ZSTR_CUSTOMER1' is highlighted, click the green tick button. This window disappears and the status bar will display the message ‘Active’."
},
{
"code": null,
"e": 69724,
"s": 69656,
"text": "The structure is now activated as shown in the following snapshot −"
},
{
"code": null,
"e": 70142,
"s": 69724,
"text": "A View acts like a database table only. But it will not occupy storage space. A view acts similar to a virtual table - a table that does not have any physical existence. A view is created by combining the data of one or more tables containing information about an application object. Using views, you can represent a subset of the data contained in a table or you can join multiple tables into a single virtual table."
},
{
"code": null,
"e": 70473,
"s": 70142,
"text": "Data related to an application object is distributed among multiple tables by using database views. They use the inner join condition to join the data of different tables. A maintenance view is used to display and modify the data stored in an application object. Every maintenance view has a maintenance status associated with it."
},
{
"code": null,
"e": 70736,
"s": 70473,
"text": "We use projection view to mask unwanted fields and display only relevant fields in a table. Projection views must be defined over a single transparent table. A projection view contains exactly one table. We can't define selection conditions for projection views."
},
{
"code": null,
"e": 70934,
"s": 70736,
"text": "Step 1 − Select the View radio button on the initial screen of ABAP Dictionary. Enter the name of the view to be created and then click Create button. We entered the name of the view as ZVIEW_TEST."
},
{
"code": null,
"e": 71077,
"s": 70934,
"text": "Step 2 − Select the projection view radio button while choosing view type and click Copy button. The ‘Dictionary: Change View’ screen appears."
},
{
"code": null,
"e": 71241,
"s": 71077,
"text": "Step 3 − Enter a short description in the Short Description field and the name of the table to be used in the Basis Table field as shown in the following snapshot."
},
{
"code": null,
"e": 71349,
"s": 71241,
"text": "Step 4 − Click the ‘Table fields’ button to include the fields of ZCUSTOMERS1 table in the projection view."
},
{
"code": null,
"e": 71519,
"s": 71349,
"text": "Step 5 − The Field Selection from Table ZCUSTOMERS1 screen appears. Select the fields that you wish to include in the projection view as shown in the following snapshot."
},
{
"code": null,
"e": 71663,
"s": 71519,
"text": "Step 6 − After clicking the Copy button, all the selected fields for the projection view are displayed on the ‘Dictionary: Change View’ screen."
},
{
"code": null,
"e": 71884,
"s": 71663,
"text": "Step 7 − Select Maintenance Status tab to define an access method. Choose read-only radio button and ‘Display/Maintenance Allowed with Restrictions’ option from the dropdown menu of ‘Data Browser/Table View Maintenance’."
},
{
"code": null,
"e": 72034,
"s": 71884,
"text": "Step 8 − Save and Activate it. In the ‘Dictionary: Change View’ screen select Utilities(M) > Contents to display the selection screen for ZVIEW_TEST."
},
{
"code": null,
"e": 72147,
"s": 72034,
"text": "Step 9 − Click the Execute icon. The output of the projection view appears as shown in the following screenshot."
},
{
"code": null,
"e": 72341,
"s": 72147,
"text": "The table ZCUSTOMERS1 consists of 5 fields. Here the displayed fields are 3 (Client, Customer Number and Name) with 4 entries. Customer numbers are from 100001 to 100004 with appropriate names."
},
{
"code": null,
"e": 72673,
"s": 72341,
"text": "Search Help, another repository object of ABAP Dictionary, is used to display all the possible values for a field in the form of a list. This list is also known as a hit list. You can select the values that are to be entered in the fields from this hit list instead of manually entering the value, which is tedious and error prone."
},
{
"code": null,
"e": 72853,
"s": 72673,
"text": "Step 1 − Go to transaction SE11. Select the radio button for Search help. Enter the name of the search help to be created. Let's enter the name ZSRCH1. Click on the Create button."
},
{
"code": null,
"e": 73068,
"s": 72853,
"text": "Step 2 − The system will prompt for the search help type to be created. Select the Elementary search help, which is default. The screen to create elementary search help as shown in the following screenshot appears."
},
{
"code": null,
"e": 73273,
"s": 73068,
"text": "Step 3 − In the selection method, we need to indicate whether our source of data is a table or a view. In our case it happens to be a table. The table is ZCUSTOMERS1. It is selected from a selection list."
},
{
"code": null,
"e": 73516,
"s": 73273,
"text": "Step 4 − After the selection method is entered, the next field is the Dialog type. This controls the appearance of the restrictive dialog box. There is a drop-down list with three options. Let's select the option 'Display values immediately'."
},
{
"code": null,
"e": 73658,
"s": 73516,
"text": "Step 5 − Next is the parameter area. For each Search help parameter or field, these column fields have to be entered as per the requirements."
},
{
"code": null,
"e": 73990,
"s": 73658,
"text": "Search help parameter − This is a field from the source of data. The fields from the table are listed in the selection list. The fields participating in the search help would be entered, one field in each row. Let's include the two fields CUSTOMER and NAME. How these two fields participate is indicated in the rest of the columns."
},
{
"code": null,
"e": 74322,
"s": 73990,
"text": "Search help parameter − This is a field from the source of data. The fields from the table are listed in the selection list. The fields participating in the search help would be entered, one field in each row. Let's include the two fields CUSTOMER and NAME. How these two fields participate is indicated in the rest of the columns."
},
{
"code": null,
"e": 74486,
"s": 74322,
"text": "Import − This field is a checkbox for indicating whether a Search help parameter is an import parameter. The export or import is with reference to the search help."
},
{
"code": null,
"e": 74650,
"s": 74486,
"text": "Import − This field is a checkbox for indicating whether a Search help parameter is an import parameter. The export or import is with reference to the search help."
},
{
"code": null,
"e": 74841,
"s": 74650,
"text": "Export − This field is a checkbox for indicating whether a Search help parameter is an export parameter. The export will be transfer of field values from the selection list to screen fields."
},
{
"code": null,
"e": 75032,
"s": 74841,
"text": "Export − This field is a checkbox for indicating whether a Search help parameter is an export parameter. The export will be transfer of field values from the selection list to screen fields."
},
{
"code": null,
"e": 75238,
"s": 75032,
"text": "LPos − Its value controls the physical position of Search help parameter or field in the selection list. If you enter a value 1, the field will appear in the first position in the selection list and so on."
},
{
"code": null,
"e": 75444,
"s": 75238,
"text": "LPos − Its value controls the physical position of Search help parameter or field in the selection list. If you enter a value 1, the field will appear in the first position in the selection list and so on."
},
{
"code": null,
"e": 75662,
"s": 75444,
"text": "SPos − It controls the physical position of Search Help parameter or field in the restrictive dialog box. If you enter a value of 1, the field will appear in the first position in the restrictive dialog box and so on."
},
{
"code": null,
"e": 75880,
"s": 75662,
"text": "SPos − It controls the physical position of Search Help parameter or field in the restrictive dialog box. If you enter a value of 1, the field will appear in the first position in the restrictive dialog box and so on."
},
{
"code": null,
"e": 76081,
"s": 75880,
"text": "Data element − Every Search Help parameter or field by default is assigned a data element that was assigned to it in the source of data (Table or View). This data element name appears in display mode."
},
{
"code": null,
"e": 76282,
"s": 76081,
"text": "Data element − Every Search Help parameter or field by default is assigned a data element that was assigned to it in the source of data (Table or View). This data element name appears in display mode."
},
{
"code": null,
"e": 76453,
"s": 76282,
"text": "Step 6 − Perform a consistency check and activate the search help. Press F8 to execute. The 'Test Search Help ZSRCH1' screen appears as shown in the following screenshot."
},
{
"code": null,
"e": 76554,
"s": 76453,
"text": "Step 7 − Let's enter the number 100004 in the CUSTOMER's 'Ready for inp' screen field. Press Enter."
},
{
"code": null,
"e": 76620,
"s": 76554,
"text": "The customer number, 100004, and the name ‘STEPHEN’ is displayed."
},
{
"code": null,
"e": 77029,
"s": 76620,
"text": "Lock Object is a feature offered by ABAP Dictionary that is used to synchronize access to the same data by more than one program. Data records are accessed with the help of specific programs. Lock objects are used in SAP to avoid the inconsistency when data is inserted into or changed in the database. Tables whose data records are to be locked must be defined in a Lock Object, along with their key fields."
},
{
"code": null,
"e": 77105,
"s": 77029,
"text": "Following are the two main functions accomplished with the lock mechanism −"
},
{
"code": null,
"e": 77207,
"s": 77105,
"text": "A program can communicate with other programs about data records that it is just reading or changing."
},
{
"code": null,
"e": 77309,
"s": 77207,
"text": "A program can communicate with other programs about data records that it is just reading or changing."
},
{
"code": null,
"e": 77403,
"s": 77309,
"text": "A program can prevent itself from reading data that has just been changed by another program."
},
{
"code": null,
"e": 77497,
"s": 77403,
"text": "A program can prevent itself from reading data that has just been changed by another program."
},
{
"code": null,
"e": 77717,
"s": 77497,
"text": "A lock request is first generated by the program. Then this request goes to the Enqueue server and the lock is created in the lock table. The Enqueue server sets the lock and the program is finally ready to access data."
},
{
"code": null,
"e": 77778,
"s": 77717,
"text": "Step 1 − Go to transaction SE11. The following screen opens."
},
{
"code": null,
"e": 77918,
"s": 77778,
"text": "Step 2 − Click ‘Lock Object’ radio button. Enter the name of lock object starting with E and click the Create button. Here we use EZLOCK12."
},
{
"code": null,
"e": 77986,
"s": 77918,
"text": "Step 3 − Enter the short description field and click on Tables tab."
},
{
"code": null,
"e": 78070,
"s": 77986,
"text": "Step 4 − Enter the table name in Name field and select the lock mode as Write Lock."
},
{
"code": null,
"e": 78142,
"s": 78070,
"text": "Step 5 − Click on Lock parameter tab, the following screen will appear."
},
{
"code": null,
"e": 78278,
"s": 78142,
"text": "Step 6 − Save and activate. Automatically 2 function modules will generate. To check function modules, we can use Go to → Lock Modules."
},
{
"code": null,
"e": 78342,
"s": 78278,
"text": "Step 7 − Click Lock Modules and the following screen will open."
},
{
"code": null,
"e": 78383,
"s": 78342,
"text": "The lock object is created successfully."
},
{
"code": null,
"e": 78614,
"s": 78383,
"text": "The key fields of a table included in a Lock Object are called lock arguments and they are used as input parameters in function modules. These arguments are used to set and remove the locks generated by the Lock Object definition."
},
{
"code": null,
"e": 78899,
"s": 78614,
"text": "It is a good practice to keep your programs as self-contained and easy to read as possible. Just try to split large and complicated tasks into smaller and simpler ones by placing each task in its individual module, on which the developer can concentrate on without other distractions."
},
{
"code": null,
"e": 79594,
"s": 78899,
"text": "In SAP ABAP environment, modularization involves the organization of programs into modular units, also known as logical blocks. It reduces redundancy and increases program readability even as you are creating it and subsequently during the maintenance cycle. Modularization also enables reusability of the same code again. ABAP has made it necessary for developers to modularize, i.e. organizing the programs relatively more, than in the OOPS-based languages that have relatively more built-in modular features. Once a small, modularized section of code is complete, debugged and so on, it does not subsequently have to be returned to, and developers can then move on and focus on other issues."
},
{
"code": null,
"e": 79693,
"s": 79594,
"text": "ABAP programs are made up of processing blocks known as modularizing processing blocks. They are −"
},
{
"code": null,
"e": 79827,
"s": 79693,
"text": "The processing blocks called from outside the program and from the ABAP run-time environment (i.e., event blocks and dialog modules)."
},
{
"code": null,
"e": 79961,
"s": 79827,
"text": "The processing blocks called from outside the program and from the ABAP run-time environment (i.e., event blocks and dialog modules)."
},
{
"code": null,
"e": 80006,
"s": 79961,
"text": "Processing blocks called from ABAP programs."
},
{
"code": null,
"e": 80051,
"s": 80006,
"text": "Processing blocks called from ABAP programs."
},
{
"code": null,
"e": 80202,
"s": 80051,
"text": "Apart from the modularization with processing blocks, source code modules are used to modularize your source code through macros and include programs."
},
{
"code": null,
"e": 80240,
"s": 80202,
"text": "Modularization at source code level −"
},
{
"code": null,
"e": 80253,
"s": 80240,
"text": "Local Macros"
},
{
"code": null,
"e": 80277,
"s": 80253,
"text": "Global Include programs"
},
{
"code": null,
"e": 80346,
"s": 80277,
"text": "Modularization through processing blocks called from ABAP programs −"
},
{
"code": null,
"e": 80358,
"s": 80346,
"text": "Subroutines"
},
{
"code": null,
"e": 80375,
"s": 80358,
"text": "Function modules"
},
{
"code": null,
"e": 80857,
"s": 80375,
"text": "Modularizing a source code means placing a sequence of ABAP statements in a module. The modularized source code can be called in a program as per the requirement of the user. Source code modules enhance the readability and understandability of ABAP programs. Creating individual source code modules also prevents one from having to repeatedly write the same statements again and again that in turn makes the code easier to understand for anyone going through it for the first time."
},
{
"code": null,
"e": 81205,
"s": 80857,
"text": "A subroutine is a reusable section of code. It is a modularization unit within the program where a function is encapsulated in the form of source code. You page out a part of a program to a subroutine to get a better overview of the main program, and to use the corresponding sequence of statements many times as depicted in the following diagram."
},
{
"code": null,
"e": 81561,
"s": 81205,
"text": "We have program X with 3 different source code blocks. Each block has the same ABAP statements. Basically, they are the same code blocks. To make this code easier to maintain, we can encapsulate the code into a subroutine. We can call this subroutine in our programs as many times as we wish. A subroutine can be defined using Form and EndForm statements."
},
{
"code": null,
"e": 81621,
"s": 81561,
"text": "Following is the general syntax of a subroutine definition."
},
{
"code": null,
"e": 81675,
"s": 81621,
"text": "FORM <subroutine_name>.\n \n<statements> \n \nENDFORM.\n"
},
{
"code": null,
"e": 81915,
"s": 81675,
"text": "We can call a subroutine by using PERFORM statement. The control jumps to the first executable statement in the subroutine <subroutine_name>. When ENDFORM is encountered, control jumps back to the statement following the PERFORM statement."
},
{
"code": null,
"e": 82039,
"s": 81915,
"text": "Step 1 − Go to transaction SE80. Open the existing program and then right-click on program. In this case, it is 'ZSUBTEST'."
},
{
"code": null,
"e": 82240,
"s": 82039,
"text": "Step 2 − Select Create and then select Subroutine. Write the subroutine name in the field and then click the continue button. The subroutine name is 'Sub_Display' as shown in the following screenshot."
},
{
"code": null,
"e": 82347,
"s": 82240,
"text": "Step 3 − Write the code in FORM and ENDFORM statement block. The subroutine has been created successfully."
},
{
"code": null,
"e": 82440,
"s": 82347,
"text": "We need to include PERFORM statement to call the subroutine. Let’s take a look at the code −"
},
{
"code": null,
"e": 82670,
"s": 82440,
"text": "REPORT ZSUBTEST. \nPERFORM Sub_Display.\n\n* Form Sub_Display \n* --> p1 text \n* <-- p2 text \n \nFORM Sub_Display. \nWrite: 'This is Subroutine'. \nWrite: / 'Subroutine created successfully'. \nENDFORM. \" Sub_Display"
},
{
"code": null,
"e": 82766,
"s": 82670,
"text": "Step 4 − Save, activate and execute the program. The above code produces the following output −"
},
{
"code": null,
"e": 82842,
"s": 82766,
"text": "Subroutine Test:\n \nThis is Subroutine\n \nSubroutine created successfully\n"
},
{
"code": null,
"e": 83136,
"s": 82842,
"text": "Hence, using subroutines makes your program more function-oriented. It splits the program's task into sub-functions, so that each subroutine is responsible for one subfunction. Your program becomes easier to maintain as changes to functions often only have to be implemented in the subroutine."
},
{
"code": null,
"e": 83482,
"s": 83136,
"text": "If we want to reuse the same set of statements more than once in a program, we need to include them in a macro. For example, a macro can be useful for long calculations or for writing complex WRITE statements. We can only use a macro within a program in which it is defined. Macro definition should occur before the macro is used in the program."
},
{
"code": null,
"e": 83644,
"s": 83482,
"text": "Macros are designed based on placeholders. Placeholder works like pointers in C language. You can define a macro within the DEFINE...END-OF-DEFINITION statement."
},
{
"code": null,
"e": 83698,
"s": 83644,
"text": "Following is the basic syntax of a macro definition −"
},
{
"code": null,
"e": 83809,
"s": 83698,
"text": "DEFINE <macro_name>. <statements> \nEND-OF-DEFINITION. \n ...... \n \n <macro_name> [<param1> <param2>....].\n"
},
{
"code": null,
"e": 83975,
"s": 83809,
"text": "It is necessary to define a macro first before invoking it. The <param1>.... replaces the placeholders &1...in the ABAP statements contained in the macro definition."
},
{
"code": null,
"e": 84299,
"s": 83975,
"text": "The maximum number of placeholders in a macro definition is nine. That is, when a program is executed, the SAP system replaces the macro by appropriate statements and the placeholders &1, &2,....&9 are replaced by the parameters param1, param2,....param9. We may invoke a macro within another macro, but not the same macro."
},
{
"code": null,
"e": 84508,
"s": 84299,
"text": "Go to transaction SE38. Create a new program ZMACRO_TEST along with the description in the short text field, and also with appropriate attributes such as Type and Status as shown in the following screenshot −"
},
{
"code": null,
"e": 84532,
"s": 84508,
"text": "Following is the code −"
},
{
"code": null,
"e": 84875,
"s": 84532,
"text": "REPORT ZMACRO_TEST. \nDEFINE mac_test. \nWRITE: 'This is Macro &1'. \nEND-OF-DEFINITION. \n\nPARAMETERS: s1 type C as checkbox. \nPARAMETERS: s2 type C as checkbox. \nPARAMETERS: s3 type C as checkbox default 'X'. \n\nSTART-OF-SELECTION. \nIF s1 = 'X'. \n mac_test 1. ENDIF. \nIF s2 = 'X'. \n mac_test 2. \nENDIF.\n \nIF s3 = 'X'. \n mac_test 3. \nENDIF."
},
{
"code": null,
"e": 84956,
"s": 84875,
"text": "We have 3 checkboxes. While executing the program, let’s select the S2 checkbox."
},
{
"code": null,
"e": 85003,
"s": 84956,
"text": "The above code produces the following output −"
},
{
"code": null,
"e": 85039,
"s": 85003,
"text": "A Macro Program \n \nThis is Macro 2\n"
},
{
"code": null,
"e": 85112,
"s": 85039,
"text": "If all checkboxes are selected, the code produces the following output −"
},
{
"code": null,
"e": 85180,
"s": 85112,
"text": "A Macro Program \n \nThis is Macro 1 This is Macro 2 This is Macro 3\n"
},
{
"code": null,
"e": 85388,
"s": 85180,
"text": "Function modules make up a major part of a SAP system, because for years SAP has modularized code using function modules, allowing for code reuse, by themselves, their developers and also by their customers."
},
{
"code": null,
"e": 85899,
"s": 85388,
"text": "Function modules are sub-programs that contain a set of reusable statements with importing and exporting parameters. Unlike Include programs, function modules can be executed independently. SAP system contains several predefined function modules that can be called from any ABAP program. The function group acts as a kind of container for a number of function modules that would logically belong together. For instance, the function modules for an HR payroll system would be put together into a function group."
},
{
"code": null,
"e": 86215,
"s": 85899,
"text": "To look at how to create function modules, the function builder must be explored. You can find the function builder with transaction code SE37. Just type a part of a function module name with a wild card character to demonstrate the way function modules can be searched for. Type *amount* and then press the F4 key."
},
{
"code": null,
"e": 86688,
"s": 86215,
"text": "The results of the search will be displayed in a new window. The function modules are displayed in the lines with blue background and their function groups in pink lines. You may look further at the function group ISOC by using the Object Navigator screen (Transaction SE80). You can see a list of function modules and also other objects held in the function group. Let's consider the function module SPELL_AMOUNT. This function module converts numeric figures into words."
},
{
"code": null,
"e": 86767,
"s": 86688,
"text": "Step 1 − Go to transaction SE38 and create a new program called Z_SPELLAMOUNT."
},
{
"code": null,
"e": 86949,
"s": 86767,
"text": "Step 2 − Enter some code so that a parameter can be set up where a value could be entered and passed on to the function module. The text element text-001 here reads ‘Enter a Value’."
},
{
"code": null,
"e": 87149,
"s": 86949,
"text": "Step 3 − To write the code for this, use CTRL+F6. After this, a window appears where ‘CALL FUNCTION’ is the first option in a list. Enter 'spell_amount' in the text box and click the continue button."
},
{
"code": null,
"e": 87569,
"s": 87149,
"text": "Step 4 − Some code is generated automatically. But we need to enhance the IF statement to include a code to WRITE a message to the screen to say \"The function module returned a value of: sy-subrc” and add the ELSE statement so as to write the correct result out when the function module is successful. Here, a new variable must be set up to hold the value returned from the function module. Let's call this as 'result'."
},
{
"code": null,
"e": 87593,
"s": 87569,
"text": "Following is the code −"
},
{
"code": null,
"e": 87986,
"s": 87593,
"text": "REPORT Z_SPELLAMOUNT. \ndata result like SPELL. \n\nselection-screen begin of line. \nselection-screen comment 1(15) text-001. \n\nparameter num_1 Type I. \nselection-screen end of line. \nCALL FUNCTION 'SPELL_AMOUNT' \nEXPORTING \nAMOUNT = num_1 \nIMPORTING \nIN_WORDS = result. \n\nIF SY-SUBRC <> 0. \n Write: 'Value returned is:', SY-SUBRC. \nelse. \n Write: 'Amount in words is:', result-word. \nENDIF."
},
{
"code": null,
"e": 88210,
"s": 87986,
"text": "Step 5 − The variable which the function module returns is called IN_WORDS. Set up the corresponding variable in the program called ‘result’. Define IN_WORDS by using the LIKE statement to refer to a structure called SPELL."
},
{
"code": null,
"e": 88324,
"s": 88210,
"text": "Step 6 − Save, activate and execute the program. Enter a value as shown in the following screenshot and press F8."
},
{
"code": null,
"e": 88371,
"s": 88324,
"text": "The above code produces the following output −"
},
{
"code": null,
"e": 88447,
"s": 88371,
"text": "Spelling the Amount \nAmount in words is: \nFIVE THOUSAND SIX HUNDRED EIGHTY\n"
},
{
"code": null,
"e": 88759,
"s": 88447,
"text": "Include programs are global repository objects used to modularize the source code. They allow you to use the same source code in different programs. Include programs also allow you to manage complex programs in an orderly way. In order to use an include program in another program, we use the following syntax −"
},
{
"code": null,
"e": 88784,
"s": 88759,
"text": "INCLUDE <program_name>.\n"
},
{
"code": null,
"e": 89029,
"s": 88784,
"text": "INCLUDE statement has the same effect as copying the source code of the include program <program_name> into another program. As include program can’t run independently, it has to be built into other programs. You may also nest include programs."
},
{
"code": null,
"e": 89114,
"s": 89029,
"text": "Following are a couple of restrictions while writing the code for Include programs −"
},
{
"code": null,
"e": 89154,
"s": 89114,
"text": "Include programs can't call themselves."
},
{
"code": null,
"e": 89205,
"s": 89154,
"text": "Include programs must contain complete statements."
},
{
"code": null,
"e": 89268,
"s": 89205,
"text": "Following are the steps to create and use an Include program −"
},
{
"code": null,
"e": 89384,
"s": 89268,
"text": "Step 1 − Create the program (Z_TOBEINCLUDED) to be included in ABAP Editor. Code to be included in ABAP Editor is −"
},
{
"code": null,
"e": 89525,
"s": 89384,
"text": "PROGRAM Z_TOBEINCLUDED. \nWrite: / 'This program is started by:', SY-UNAME,\n / 'The Date is:', SY-DATUM,\n / 'Time is', SY-UZEIT."
},
{
"code": null,
"e": 89620,
"s": 89525,
"text": "Step 2 − Set the Type of the program to INCLUDE program, as shown in the following screenshot."
},
{
"code": null,
"e": 89705,
"s": 89620,
"text": "Step 3 − Click the ‘Save’ button and save the program in a package named ZINCL_PCKG."
},
{
"code": null,
"e": 89906,
"s": 89705,
"text": "Step 4 − Create another program where the program Z_TOBEINCLUDED has to be used. Here we have created another program named Z_INCLUDINGTEST and assigned the type for the program as Executable program."
},
{
"code": null,
"e": 90061,
"s": 89906,
"text": "Step 5 − The coding for Z_INCLUDINGTEST program includes the Z_TOBEINCLUDED program with the help of the INCLUDE statement as shown in the following code."
},
{
"code": null,
"e": 90112,
"s": 90061,
"text": "REPORT Z_INCLUDINGTEST. \nINCLUDE Z_TOBEINCLUDED. "
},
{
"code": null,
"e": 90161,
"s": 90112,
"text": "Step 6 − Save, activate and execute the program."
},
{
"code": null,
"e": 90208,
"s": 90161,
"text": "The above code produces the following output −"
},
{
"code": null,
"e": 90288,
"s": 90208,
"text": "This program is started by: SAPUSER \nThe Date is: 06.10.2015 \nTime is 13:25:11\n"
},
{
"code": null,
"e": 90550,
"s": 90288,
"text": "Open SQL indicates the subset of ABAP statements that enable direct access to the data in the central database of the current AS ABAP. Open SQL statements map the Data Manipulation Language functionality of SQL in ABAP that is supported by all database systems."
},
{
"code": null,
"e": 90970,
"s": 90550,
"text": "The statements of Open SQL are converted to database specific SQL in the Open SQL interface of the database interface. They are then transferred to the database system and executed. Open SQL statements can be used to access database tables that are declared in the ABAP Dictionary. The central database of AS ABAP is accessed by default and also access to other databases is possible via secondary database connections."
},
{
"code": null,
"e": 91533,
"s": 90970,
"text": "Whenever any of these statements are used in an ABAP program, it is important to check whether the action executed has been successful. If one tries to insert a record into a database table and it is not inserted correctly, it is very essential to know so that the appropriate action can be taken in the program. This can done using a system field that has already been used, that is SY-SUBRC. When a statement is executed successfully, the SY-SUBRC field will contain a value of 0, so this can be checked for and one can continue with the program if it appears."
},
{
"code": null,
"e": 91783,
"s": 91533,
"text": "The DATA statement is used to declare a work area. Let's give this the name 'wa_customers1'. Rather than declaring one data type for this, several fields that make up the table can be declared. The easiest way to do this is using the LIKE statement."
},
{
"code": null,
"e": 92152,
"s": 91783,
"text": "The wa_customers1 work area is declared here LIKE the ZCUSTOMERS1 table, taking on the same structure without becoming a table itself. This work area can only store one record. Once it has been declared, the INSERT statement can be used to insert the work area and the record it holds into the table. The code here will read as 'INSERT ZCUSTOMERS1 FROM wa_customers1'."
},
{
"code": null,
"e": 92466,
"s": 92152,
"text": "The work area has to be filled with some data. Use the field names from the ZCUSTOMERS1 table. This can be done by forward navigation, double clicking the table name in the code or by opening a new session and using the transaction SE11. The fields of the table can then be copied and pasted into the ABAP editor."
},
{
"code": null,
"e": 92498,
"s": 92466,
"text": "Following is the code snippet −"
},
{
"code": null,
"e": 92703,
"s": 92498,
"text": "DATA wa_customers1 LIKE ZCUSTOMERS1. \nwa_customers1-customer = '100006'. \nwa_customers1-name = 'DAVE'. \nwa_customers1-title = 'MR'. \nwa_customers1-dob = '19931017'. \nINSERT ZCUSTOMERS1 FROM wa_customers1."
},
{
"code": null,
"e": 92935,
"s": 92703,
"text": "CHECK statement can then be used as follows. It means that if the record is inserted correctly, the system will state this. If not, then the SY-SUBRC code which will not equal zero will be displayed. Following is the code snippet −"
},
{
"code": null,
"e": 93054,
"s": 92935,
"text": "IF SY-SUBRC = 0. \n WRITE 'Record Inserted Successfully'. \nELSE. \n WRITE: 'The return code is ', SY-SUBRC. \nENDIF."
},
{
"code": null,
"e": 93184,
"s": 93054,
"text": "Check the program, save, activate the code, and then test it. The output window should display as 'Record Inserted Successfully'."
},
{
"code": null,
"e": 93414,
"s": 93184,
"text": "CLEAR statement allows a field or variable to be cleared out for the insertion of new data in its place, allowing it to be reused. CLEAR statement is generally used in programs and it allows existing fields to be used many times."
},
{
"code": null,
"e": 93720,
"s": 93414,
"text": "In the previous code snippet, the work area structure has been filled with data to create a new record to be inserted into the ZCUSTOMERS1 table and then a validation check is performed. If we want to insert a new record, CLEAR statement must be used so that it can then be filled again with the new data."
},
{
"code": null,
"e": 94261,
"s": 93720,
"text": "If you want to update one or more existing records in a table at the same time then use UPDATE statement. Similar to INSERT statement, a work area is declared, filled with the new data that is then put into the record as the program is executed. The record previously created with the INSERT statement will be updated here. Just edit the text stored in the NAME and TITLE fields. Then on a new line, the same structure as for the INSERT statement is used, and this time by using the UPDATE statement as shown in the following code snippet −"
},
{
"code": null,
"e": 94469,
"s": 94261,
"text": "DATA wa_customers1 LIKE ZCUSTOMERS1. \nwa_customers1-customer = '100006'. \nwa_customers1-name = 'RICHARD'. \nwa_customers1-title = 'MR'. \nwa_customers1-dob = '19931017'. \nUPDATE ZCUSTOMERS1 FROM wa_customers1."
},
{
"code": null,
"e": 94611,
"s": 94469,
"text": "As UPDATE statement gets executed, you can view the Data Browser in the ABAP Dictionary to see that the record has been updated successfully."
},
{
"code": null,
"e": 94898,
"s": 94611,
"text": "MODIFY statement can be considered as a combination of the INSERT and UPDATE statements. It can be used to either insert a new record or modify an existing record. It follows a similar syntax to the previous two statements in modifying the record from the data entered into a work area."
},
{
"code": null,
"e": 95117,
"s": 94898,
"text": "When this statement is executed, the key fields involved will be checked against those in the table. If a record with these key field values already exist, it will be updated. If not, then a new record will be created."
},
{
"code": null,
"e": 95175,
"s": 95117,
"text": "Following is the code snippet for creating a new record −"
},
{
"code": null,
"e": 95404,
"s": 95175,
"text": "CLEAR wa_customers1.\n \nDATA wa_customers1 LIKE ZCUSTOMERS1. \nwa_customers1-customer = '100007'. \nwa_customers1-name = 'RALPH'. \nwa_customers1-title = 'MR'. \nwa_customers1-dob = '19910921'. \nMODIFY ZCUSTOMERS1 FROM wa_customers1."
},
{
"code": null,
"e": 95658,
"s": 95404,
"text": "In this example, CLEAR statement is used so that a new entry can be put into the work area, and then customer (number) 100007 is added. Since this is a new, unique key field value, a new record will be inserted, and another validation check is executed."
},
{
"code": null,
"e": 95800,
"s": 95658,
"text": "When this is executed and the data is viewed in the Data Browser, a new record will have been created for the customer number 100007 (RALPH)."
},
{
"code": null,
"e": 95864,
"s": 95800,
"text": "The above code produces the following output (table contents) −"
},
{
"code": null,
"e": 96213,
"s": 95864,
"text": "The term ‘Native SQL’ refers to all statements that can be statically transferred to the Native SQL interface of the database interface. Native SQL statements do not fall within the language scope of ABAP and do not follow the ABAP syntax. ABAP merely contains statements for isolating program sections in which Native SQL statements can be listed."
},
{
"code": null,
"e": 96656,
"s": 96213,
"text": "In native SQL, mainly database-specific SQL statements can be used. These are transferred unchanged from the native SQL interface to a database system and executed. The full SQL language scope of the relevant database can be used and the addressed database tables do not have to be declared in the ABAP Dictionary. There is also a small set of SAP specific Native SQL statements that are handled in a specific way by the native SQL interface."
},
{
"code": null,
"e": 96770,
"s": 96656,
"text": "To use a Native SQL statement, you have to precede it with the EXEC SQL statement and end with ENDEXEC statement."
},
{
"code": null,
"e": 96796,
"s": 96770,
"text": "Following is the syntax −"
},
{
"code": null,
"e": 96863,
"s": 96796,
"text": "EXEC SQL PERFORMING <form>. \n <Native SQL statement> \nENDEXEC.\n"
},
{
"code": null,
"e": 97064,
"s": 96863,
"text": "These statements define an area in an ABAP program where one or more Native SQL statements can be listed. The statements entered are passed to the Native SQL interface and then processed as follows −"
},
{
"code": null,
"e": 97258,
"s": 97064,
"text": "All SQL statements that are valid for the program interface of the addressed database system can be listed between EXEC and ENDEXEC, in particular the DDL (data definition language) statements."
},
{
"code": null,
"e": 97452,
"s": 97258,
"text": "All SQL statements that are valid for the program interface of the addressed database system can be listed between EXEC and ENDEXEC, in particular the DDL (data definition language) statements."
},
{
"code": null,
"e": 97671,
"s": 97452,
"text": "These SQL statements are passed from the Native SQL interface to the database system largely unchanged. The syntax rules are specified by the database system, especially the case sensitivity rules for database objects."
},
{
"code": null,
"e": 97890,
"s": 97671,
"text": "These SQL statements are passed from the Native SQL interface to the database system largely unchanged. The syntax rules are specified by the database system, especially the case sensitivity rules for database objects."
},
{
"code": null,
"e": 98023,
"s": 97890,
"text": "If the syntax allows a separator between individual statements, you may include many Native SQL statements between EXEC and ENDEXEC."
},
{
"code": null,
"e": 98156,
"s": 98023,
"text": "If the syntax allows a separator between individual statements, you may include many Native SQL statements between EXEC and ENDEXEC."
},
{
"code": null,
"e": 98369,
"s": 98156,
"text": "SAP specific Native SQL language elements can be specified between EXEC and ENDEXEC. These statements are not passed directly from the Native SQL interface to the database, but they are transformed appropriately."
},
{
"code": null,
"e": 98582,
"s": 98369,
"text": "SAP specific Native SQL language elements can be specified between EXEC and ENDEXEC. These statements are not passed directly from the Native SQL interface to the database, but they are transformed appropriately."
},
{
"code": null,
"e": 98963,
"s": 98582,
"text": "SPFLI is a standard SAP Table that is used to store Flight schedule information. This is available within R/3 SAP systems depending on the version and release level. You can view this information when you enter the Table name SPFLI into the relevant SAP transaction such as SE11 or SE80. You can also view the data contained in this database table by using these two transactions."
},
{
"code": null,
"e": 99383,
"s": 98963,
"text": "REPORT ZDEMONATIVE_SQL. \nDATA: BEGIN OF wa, \n connid TYPE SPFLI-connid,\n cityfrom TYPE SPFLI-cityfrom,\n cityto TYPE SPFLI-cityto, \n END OF wa. \n\t\nDATA c1 TYPE SPFLI-carrid VALUE 'LH'. \nEXEC SQL PERFORMING loop_output.\n SELECT connid, cityfrom, cityto \n INTO :wa \n FROM SPFLI \n WHERE carrid = :c1 \nENDEXEC. \n\nFORM loop_output. \n WRITE: / wa-connid, wa-cityfrom, wa-cityto. \nENDFORM."
},
{
"code": null,
"e": 99430,
"s": 99383,
"text": "The above code produces the following output −"
},
{
"code": null,
"e": 99509,
"s": 99430,
"text": "0400 FRANKFURT NEW YORK \n2402 FRANKFURT BERLIN \n0402 FRANKFURT NEW YORK\n"
},
{
"code": null,
"e": 99876,
"s": 99509,
"text": "Internal table is actually a temporary table, which contains the records of an ABAP program that it is being executed. An internal table exists only during the run-time of a SAP program. They are used to process large volumes of data by using ABAP language. We need to declare an internal table in an ABAP program when you need to retrieve data from database tables."
},
{
"code": null,
"e": 100520,
"s": 99876,
"text": "Data in an internal table is stored in rows and columns. Each row is called a line and each column is called a field. In an internal table, all the records have the same structure and key. The individual records of an internal table are accessed with an index or a key. As internal table exists till the associated program is being executed, the records of the internal table are discarded when the execution of the program is terminated. So internal tables can be used as temporary storage areas or temporary buffers where data can be modified as required. These tables occupy memory only at run-time and not at the time of their declaration."
},
{
"code": null,
"e": 100888,
"s": 100520,
"text": "Internal tables only exist when a program is running, so when the code is written, the internal table must be structured in such a way that the program can make use of it. You will find that internal tables operate in the same way as structures. The main difference being that structures only have one line, while an internal table can have as many lines as required."
},
{
"code": null,
"e": 101360,
"s": 100888,
"text": "An internal table can be made up of a number of fields, corresponding to the columns of a table, just as in the ABAP dictionary a table was created using a number of fields. Key fields can also be used with internal tables, and while creating these internal tables they offer slightly more flexibility. With internal tables, one can specify a non-unique key, allowing any number of non-unique records to be stored, and allowing duplicate records to be stored if required."
},
{
"code": null,
"e": 101721,
"s": 101360,
"text": "The size of an internal table or the number of lines it contains is not fixed. The size of an internal table changes according to the requirement of the program associated with the internal table. But it is recommended to keep internal tables as small as possible. This is to avoid the system running slowly as it struggles to process enormous amounts of data."
},
{
"code": null,
"e": 101766,
"s": 101721,
"text": "Internal tables are used for many purposes −"
},
{
"code": null,
"e": 101856,
"s": 101766,
"text": "They can be used to hold results of calculations that could be used later in the program."
},
{
"code": null,
"e": 101946,
"s": 101856,
"text": "They can be used to hold results of calculations that could be used later in the program."
},
{
"code": null,
"e": 102093,
"s": 101946,
"text": "An internal table can also hold records and data so that this can be accessed quickly rather than having to access this data from database tables."
},
{
"code": null,
"e": 102240,
"s": 102093,
"text": "An internal table can also hold records and data so that this can be accessed quickly rather than having to access this data from database tables."
},
{
"code": null,
"e": 102333,
"s": 102240,
"text": "They are hugely versatile. They can be defined using any number of other defined structures."
},
{
"code": null,
"e": 102426,
"s": 102333,
"text": "They are hugely versatile. They can be defined using any number of other defined structures."
},
{
"code": null,
"e": 102874,
"s": 102426,
"text": "Assume that a user wants to create a list of contact numbers of various customers from one or several large tables. The user first creates an internal table, selects the relevant data from customer tables and then places the data in the internal table. Other users can access and use this internal table directly to retrieve the desired information, instead of writing database queries to perform each operation during the run-time of the program."
},
{
"code": null,
"e": 103289,
"s": 102874,
"text": "DATA statement is used to declare an internal table. The program must be told where the table begins and ends. So use the BEGIN OF statement and then declare the table name. After this, the OCCURS addition is used, followed by a number, here 0. OCCURS tells SAP that an internal table is being created, and the 0 states that it will not contain any records initially. It will then expand as it is filled with data."
},
{
"code": null,
"e": 103315,
"s": 103289,
"text": "Following is the syntax −"
},
{
"code": null,
"e": 103356,
"s": 103315,
"text": "DATA: BEGIN OF <internal_tab> Occurs 0,\n"
},
{
"code": null,
"e": 103765,
"s": 103356,
"text": "Let’s create the fields on a new line. For instance, create ‘name’ which is declared as LIKE ZCUSTOMERS1-name. Create another field called ‘dob’, LIKE ZCUSTOMERS1-dob. It is useful initially to give the field names in internal tables the same names as other fields that have been created elsewhere. Finally, declare the end of the internal table with “END OF <internal_tab>.” as shown in the following code −"
},
{
"code": null,
"e": 103873,
"s": 103765,
"text": "DATA: BEGIN OF itab01 Occurs 0,\n name LIKE ZCUSTOMERS1-name,\n dob LIKE ZCUSTOMERS1-dob, \nEND OF itab01."
},
{
"code": null,
"e": 104357,
"s": 103873,
"text": "Here ‘itab01’ is commonly used shorthand when creating temporary tables in SAP. The OCCURS clause is used to define the body of an internal table by declaring the fields for the table. When the OCCURS clause is used, you can specify a numeric constant ‘n’ to determine additional default memory if required. The default size of memory that is used by the OCCUR 0 clause is 8 KB. The structure of the internal table is now created, and the code can be written to fill it with records."
},
{
"code": null,
"e": 104729,
"s": 104357,
"text": "An internal table can be created with or without using a header line. To create an internal table with a header line, use either the BEGIN OF clause before the OCCURS clause or the WITH HEADER LINE clause after the OCCURS clause in the definition of the internal table. To create an internal table without a header line, use the OCCURS clause without the BEGIN OF clause."
},
{
"code": null,
"e": 104955,
"s": 104729,
"text": "You can also create an internal table as a local data type (a data type used only in the context of the current program) by using the TYPES statement. This statement uses the TYPE or LIKE clause to refer to an existing table."
},
{
"code": null,
"e": 105020,
"s": 104955,
"text": "The syntax to create an internal table as a local data type is −"
},
{
"code": null,
"e": 105135,
"s": 105020,
"text": "TYPES <internal_tab> TYPE|LIKE <internal_tab_type> OF \n <line_type_itab> WITH <key> INITIAL SIZE <size_number>.\n"
},
{
"code": null,
"e": 105615,
"s": 105135,
"text": "Here the <internal_tab_type> specifies a table type for an internal table <internal_tab> and <line_type_itab> specifies the type for a line of an internal table. In TYPES statement, you can use the TYPE clause to specify the line type of an internal table as a data type and LIKE clause to specify the line type as a data object. Specifying a key for an internal table is optional and if the user does not specify a key, the SAP system defines a table type with an arbitrary key."
},
{
"code": null,
"e": 105942,
"s": 105615,
"text": "INITIAL SIZE <size_number> creates an internal table object by allocating an initial amount of memory to it. In the preceding syntax, the INITIAL SIZE clause reserves a memory space for size_number table lines. Whenever an internal table object is declared, the size of the table does not belong to the data type of the table."
},
{
"code": null,
"e": 106034,
"s": 105942,
"text": "Note − Much less memory is consumed when an internal table is populated for the first time."
},
{
"code": null,
"e": 106147,
"s": 106034,
"text": "Step 1 − Open the ABAP Editor by executing the SE38 transaction code. The initial screen of ABAP Editor appears."
},
{
"code": null,
"e": 106298,
"s": 106147,
"text": "Step 2 − In the initial screen, enter a name for the program, select the Source code radio button and click the Create button to create a new program."
},
{
"code": null,
"e": 106535,
"s": 106298,
"text": "Step 3 − In the 'ABAP: Program Attributes' dialog box, enter a short description for the program in the Title field, select the 'Executable program' option from the Type drop-down menu in the Attributes group box. Click the Save button."
},
{
"code": null,
"e": 106585,
"s": 106535,
"text": "Step 4 − Write the following code in ABAP editor."
},
{
"code": null,
"e": 106824,
"s": 106585,
"text": "REPORT ZINTERNAL_DEMO. \nTYPES: BEGIN OF CustomerLine, \nCust_ID TYPE C, \nCust_Name(20) TYPE C, \nEND OF CustomerLine. \n \nTYPES mytable TYPE SORTED TABLE OF CustomerLine \nWITH UNIQUE KEY Cust_ID. \nWRITE:/'The mytable is an Internal Table'. "
},
{
"code": null,
"e": 106882,
"s": 106824,
"text": "Step 5 − Save, activate and execute the program as usual."
},
{
"code": null,
"e": 106978,
"s": 106882,
"text": "In this example, mytable is an internal table and a unique key is defined on the Cust_ID field."
},
{
"code": null,
"e": 107025,
"s": 106978,
"text": "The above code produces the following output −"
},
{
"code": null,
"e": 107060,
"s": 107025,
"text": "The mytable is an Internal Table.\n"
},
{
"code": null,
"e": 107204,
"s": 107060,
"text": "In internal tables, populating includes features such as selection, insertion and append. This chapter focuses on INSERT and APPEND statements."
},
{
"code": null,
"e": 107297,
"s": 107204,
"text": "INSERT statement is used to insert a single line or a group of lines into an internal table."
},
{
"code": null,
"e": 107365,
"s": 107297,
"text": "Following is the syntax to add a single line to an internal table −"
},
{
"code": null,
"e": 107429,
"s": 107365,
"text": "INSERT <work_area_itab> INTO <internal_tab> INDEX <index_num>.\n"
},
{
"code": null,
"e": 107919,
"s": 107429,
"text": "In this syntax, the INSERT statement inserts a new line in the internal_tab internal table. A new line can be inserted by using the work_area_itab INTO expression before the internal_tab parameter. When the work_area_itab INTO expression is used, the new line is taken from the work_area_itab work area and inserted into the internal_tab table. However, when the work_area_itab INTO expression is not used to insert a line, the line is taken from the header line of the internal_tab table."
},
{
"code": null,
"e": 108272,
"s": 107919,
"text": "When a new line is inserted in an internal table by using the INDEX clause, the index number of the lines after the inserted line is incremented by 1. If an internal table contains <index_num> - 1 lines, the new line is added at the end of the table. When the SAP system successfully adds a line to an internal table, the SY-SUBRC variable is set to 0."
},
{
"code": null,
"e": 108334,
"s": 108272,
"text": "Following is a sample program that uses the insert statement."
},
{
"code": null,
"e": 108749,
"s": 108334,
"text": "REPORT ZCUSLIST1. \nDATA: BEGIN OF itable1 OCCURS 4,\n F1 LIKE SY-INDEX,\n END OF itable1.\n\t\n DO 4 TIMES.\n itable1-F1 = sy-index.\n APPEND itable1.\n ENDDO.\n\t\nitable1-F1 = -96. \nINSERT itable1 INDEX 2. \n\nLOOP AT itable1.\n Write / itable1-F1. \nENDLOOP. \n\nLOOP AT itable1 Where F1 ≥ 3.\n itable1-F1 = -78.\n INSERT itable1.\nENDLOOP.\n\nSkip.\nLOOP AT itable1.\n Write / itable1-F1.\nENDLOOP."
},
{
"code": null,
"e": 108794,
"s": 108749,
"text": "The above code produces the following outp −"
},
{
"code": null,
"e": 108854,
"s": 108794,
"text": "\n\t\t1 \n96- \n\t\t2 \n\t\t3 \n 4 \n\t\t1 \n96- \n\t\t2 \n78- \n 3 \n78- \n 4 \n"
},
{
"code": null,
"e": 109415,
"s": 108854,
"text": "In the above example, the DO loop appends 4 rows containing the numbers 1 through 4 to it. The header line component itable1-F1 has been assigned a value of -96. Insert statement inserts the header line as new row into the body before row 3. The existing row 3 becomes row 4 after the insert. The LOOP AT statement retrieves those rows from the internal table that have an F1 value greater than or equal to 3. Before each row, Insert statement inserts a new row from the header line of it. Prior to the insert, the F1 component has been changed to contain -78."
},
{
"code": null,
"e": 109745,
"s": 109415,
"text": "After each insert statement is executed, the system re-indexes all rows below the one inserted. This introduces overhead when you insert rows near the top of a large internal table. If you need to insert a block of rows into a large internal table, prepare another table with the rows to be inserted and use insert lines instead."
},
{
"code": null,
"e": 110360,
"s": 109745,
"text": "When inserting a new row inside itable1 inside of a loop at itable1, it doesn’t affect the internal table instantly. It actually becomes effective on the next loop pass. While inserting a row after the current row, the table is re-indexed at the ENDLOOP. The sy-tabix is incremented and the next loop processes the row pointed to by sy-tabix. For instance, if you are in the second loop pass and you insert a record before row 3. When endloop is executed, the new row becomes row 3 and the old row 3 becomes row 4 and so on. Sy-tabix is incremented by 1, and the next loop pass processes the newly inserted record."
},
{
"code": null,
"e": 110799,
"s": 110360,
"text": "The APPEND statement is used to add a single row or line to an existing internal table. This statement copies a single line from a work area and inserts it after the last existing line in an internal table. The work area can be either a header line or any other field string with the same structure as a line of an internal table. Following is the syntax of the APPEND statement that is used to append a single line in an internal table −"
},
{
"code": null,
"e": 110844,
"s": 110799,
"text": "APPEND <record_for_itab> TO <internal_tab>.\n"
},
{
"code": null,
"e": 111396,
"s": 110844,
"text": "In this syntax, the <record_for_itab> expression can be represented by the <work_area_itab> work area, which is convertible to a line type or by the INITIAL LINE clause. If the user uses a <work_area_itab> work area, the SAP system adds a new line to the <internal_tab> internal table and populates it with the content of the work area. The INITIAL LINE clause appends a blank line that contains the initial value for each field of the table structure. After each APPEND statement, the SY-TABIX variable contains the index number of the appended line."
},
{
"code": null,
"e": 111795,
"s": 111396,
"text": "Appending lines to standard and sorted tables with a non-unique key works regardless of whether the lines with the same key already exist in the table. In other words, duplicate entries may occur. However, a run-time error occurs if the user attempts to add a duplicate entry to a sorted table with a unique key or if the user violates the sort order of a sorted table by appending the lines to it."
},
{
"code": null,
"e": 112088,
"s": 111795,
"text": "REPORT ZCUSLIST1. \nDATA: BEGIN OF linv Occurs 0,\n Name(20) TYPE C,\n ID_Number TYPE I,\nEND OF linv. \n\nDATA table1 LIKE TABLE OF linv. \nlinv-Name = 'Melissa'. \nlinv-ID_Number = 105467. \nAPPEND linv TO table1. \nLOOP AT table1 INTO linv. \n\nWrite: / linv-name, linv-ID_Number. \nENDLOOP."
},
{
"code": null,
"e": 112135,
"s": 112088,
"text": "The above code produces the following output −"
},
{
"code": null,
"e": 112153,
"s": 112135,
"text": "Melissa\t\t105467 \n"
},
{
"code": null,
"e": 112496,
"s": 112153,
"text": "When we read a record from an internal table with a header line, that record is moved from the table itself into the header line. It is then the header line that our program works with. The same applies while creating a new record. It is the header line with which you work with and from which the new record is sent to the table body itself."
},
{
"code": null,
"e": 112742,
"s": 112496,
"text": "To copy the records, we can use a SELECT statement to select all of the records from the table and then use MOVE statement that will move the records from the original table into the new internal table into the fields where the names correspond."
},
{
"code": null,
"e": 112787,
"s": 112742,
"text": "Following is the syntax for MOVE statement −"
},
{
"code": null,
"e": 112832,
"s": 112787,
"text": "MOVE <table_field> TO <internal_tab_field>.\n"
},
{
"code": null,
"e": 113141,
"s": 112832,
"text": "REPORT ZCUSLIST1. \nTABLES: ZCUSTOMERS1. \nDATA: BEGIN OF itab01 Occurs 0,\n name LIKE ZCUSTOMERS1-name,\n dob LIKE ZCUSTOMERS1-dob, \nEND OF itab01. \n\nSelect * FROM ZCUSTOMERS1. \nMOVE ZCUSTOMERS1-name TO itab01-name. \nMOVE ZCUSTOMERS1-dob TO itab01-dob. \nENDSELECT.\n \nWrite: / itab01-name, itab01-dob."
},
{
"code": null,
"e": 113188,
"s": 113141,
"text": "The above code produces the following output −"
},
{
"code": null,
"e": 113213,
"s": 113188,
"text": "MARGARET \t\t02.11.1994 \n"
},
{
"code": null,
"e": 113589,
"s": 113213,
"text": "The select loop fills each field one at a time, using the MOVE statement to move the data from one table’s field to the other. In the above example, MOVE statements were used to move the contents of the ZCUSTOMERS1 table to the corresponding fields in the internal table. You can accomplish this action with just one line of code. You can use the MOVECORRESPONDING statement."
},
{
"code": null,
"e": 113648,
"s": 113589,
"text": "Following is the syntax for MOVE-CORRESPONDING statement −"
},
{
"code": null,
"e": 113701,
"s": 113648,
"text": "MOVE-CORRESPONDING <table_name> TO <internal_tab>. \n"
},
{
"code": null,
"e": 113810,
"s": 113701,
"text": "It tells the system to move the data from the fields of ZCUSTOMERS1 to their corresponding fields in itab01."
},
{
"code": null,
"e": 114211,
"s": 113810,
"text": "REPORT ZCUSTOMERLIST. \nTABLES: ZCUSTOMERS1. \nDATA: Begin of itab01 occurs 0,\n customer LIKE ZCUSTOMERS1-customer,\n name LIKE ZCUSTOMERS1-name,\n title LIKE ZCUSTOMERS1-title,\n dob LIKE ZCUSTOMERS1-dob, \nEND OF itab01. \n\nSELECT * from ZCUSTOMERS1. \nMOVE-Corresponding ZCUSTOMERS1 TO itab01. \nAPPEND itab01. \nENDSELECT. \nLOOP AT itab01. \nWrite: / itab01-name, itab01-dob. \nENDLOOP. "
},
{
"code": null,
"e": 114258,
"s": 114211,
"text": "The above code produces the following output −"
},
{
"code": null,
"e": 114394,
"s": 114258,
"text": "MARK 21.05.1981 \nJAMES 14.08.1977 \nAURIELE 19.06.1990 \nSTEPHEN 22.07.1985 \nMARGARET 02.11.1994 \n"
},
{
"code": null,
"e": 114635,
"s": 114394,
"text": "This is made possible by the fact that both have matching field names. When making use of this statement, you need to make sure that both fields have matching data types and lengths. It has been done here with the LIKE statement previously."
},
{
"code": null,
"e": 114728,
"s": 114635,
"text": "We can read the lines of a table by using the following syntax of the READ TABLE statement −"
},
{
"code": null,
"e": 114780,
"s": 114728,
"text": "READ TABLE <internal_table> FROM <work_area_itab>.\n"
},
{
"code": null,
"e": 115061,
"s": 114780,
"text": "In this syntax, the <work_area_itab> expression represents a work area that is compatible with the line type of the <internal_table> table. We can specify a search key, but not a table key, within the READ statement by using the WITH KEY clause, as shown in the following syntax −"
},
{
"code": null,
"e": 115123,
"s": 115061,
"text": "READ TABLE <internal_table> WITH KEY = <internal_tab_field>.\n"
},
{
"code": null,
"e": 115638,
"s": 115123,
"text": "Here the entire line of the internal table is used as a search key. The content of the entire line of the table is compared with the content of the <internal_tab_field> field. If the values of the <internal_tab_field> field are not compatible with the line type of the table, these values are converted according to the line type of the table. The search key allows you to find entries in internal tables that do not have a structured line type, that is, where the line is a single field or an internal table type."
},
{
"code": null,
"e": 115760,
"s": 115638,
"text": "The following syntax of the READ statement is used to specify a work area or field symbol by using the COMPARING clause −"
},
{
"code": null,
"e": 115850,
"s": 115760,
"text": "READ TABLE <internal_table> <key> INTO <work_area_itab>\n [COMPARING <F1> <F2>...<Fn>].\n"
},
{
"code": null,
"e": 116535,
"s": 115850,
"text": "When the COMPARING clause is used, the specified table fields <F1>, <F2>....<Fn> of the structured line type are compared with the corresponding fields of the work area before being transported. If the ALL FIELDS clause is specified, the SAP system compares all the components. When the SAP system finds an entry on the basis of a key, the value of the SY-SUBRC variable is set to 0. In addition, the value of the SY-SUBRC variable is set to 2 or 4 if the content of the compared fields is not the same or if the SAP system cannot find an entry. However, the SAP system copies the entry into the target work area whenever it finds an entry, regardless of the result of the comparison."
},
{
"code": null,
"e": 117013,
"s": 116535,
"text": "REPORT ZREAD_DEMO. \n*/Creating an internal table \nDATA: BEGIN OF Record1, \nColP TYPE I, \nColQ TYPE I, \nEND OF Record1. \n\nDATA mytable LIKE HASHED TABLE OF Record1 WITH UNIQUE KEY ColP. \nDO 6 Times.\nRecord1-ColP = SY-INDEX. \nRecord1-ColQ = SY-INDEX + 5. \nINSERT Record1 INTO TABLE mytable. \nENDDO. \n\nRecord1-ColP = 4. \nRecord1-ColQ = 12. \nREAD TABLE mytable FROM Record1 INTO Record1 COMPARING ColQ. \n\nWRITE: 'SY-SUBRC =', SY-SUBRC. \nSKIP. \nWRITE: / Record1-ColP, Record1-ColQ."
},
{
"code": null,
"e": 117060,
"s": 117013,
"text": "The above code produces the following output −"
},
{
"code": null,
"e": 117091,
"s": 117060,
"text": "SY-SUBRC = 2 \n\n4 9\n"
},
{
"code": null,
"e": 117391,
"s": 117091,
"text": "In the above example, mytable is an internal table of the hashed table type, with Record1 as the work area and ColP as the unique key. Initially, mytable is populated with six lines, where the ColP field contains the values of the SY-INDEX variable and the ColQ field contains (SY-INDEX + 5) values."
},
{
"code": null,
"e": 117862,
"s": 117391,
"text": "The Record1 work area is populated with 4 and 12 as values for the ColP and ColQ fields respectively. The READ statement reads the line of the table after comparing the value of the ColP key field with the value in the Record1 work area by using the COMPARING clause, and then copies the content of the read line in the work area. The value of the SY-SUBRC variable is displayed as 2 because when the value in the ColP field is 4, the value in the ColQ is not 12, but 9."
},
{
"code": null,
"e": 118186,
"s": 117862,
"text": "The DELETE statement is used to delete one or more records from an internal table. The records of an internal table are deleted either by specifying a table key or condition or by finding duplicate entries. If an internal table has a non-unique key and contains duplicate entries, the first entry from the table is deleted."
},
{
"code": null,
"e": 118290,
"s": 118186,
"text": "Following is the syntax to use the DELETE statement to delete a record or line from an internal table −"
},
{
"code": null,
"e": 118344,
"s": 118290,
"text": "DELETE TABLE <internal_table> FROM <work_area_itab>.\n"
},
{
"code": null,
"e": 118609,
"s": 118344,
"text": "In the above syntax, the <work_area_itab> expression is a work area and it should be compatible with the type of the <internal_table> internal table. The delete operation is performed on the basis of a default key that could be taken from the work area components."
},
{
"code": null,
"e": 118715,
"s": 118609,
"text": "You may also specify a table key explicitly in the DELETE TABLE statement by using the following syntax −"
},
{
"code": null,
"e": 118798,
"s": 118715,
"text": "DELETE TABLE <internal_table> WITH TABLE KEY <K1> = <F1>............ <Kn> = <Fn>.\n"
},
{
"code": null,
"e": 119080,
"s": 118798,
"text": "In this syntax, <F1>, <F2>....<Fn> are the fields of an internal table and <K1>, <K2>....<Kn> are the key fields of the table. The DELETE statement is used to delete the records or lines of the <internal_table> table based on the expressions <K1> = <F1>, <K2> = <F2>...<Kn> = <Fn>."
},
{
"code": null,
"e": 119271,
"s": 119080,
"text": "Note − If the data types of the <F1>, <F2>....<Fn> fields are not compatible with the <K1>, <K2>...<Kn> key fields then the SAP system automatically converts them into the compatible format."
},
{
"code": null,
"e": 119684,
"s": 119271,
"text": "REPORT ZDELETE_DEMO. \nDATA: BEGIN OF Line1, \nColP TYPE I, \nColQ TYPE I, \nEND OF Line1. \nDATA mytable LIKE HASHED TABLE OF Line1 \nWITH UNIQUE KEY ColP. \nDO 8 TIMES. \n\nLine1-ColP = SY-INDEX. \nLine1-ColQ = SY-INDEX + 4. \nINSERT Line1 INTO TABLE mytable. \nENDDO. \n\nLine1-ColP = 1. \nDELETE TABLE mytable: FROM Line1, \nWITH TABLE KEY ColP = 3.\nLOOP AT mytable INTO Line1. \n\nWRITE: / Line1-ColP, Line1-ColQ. \nENDLOOP."
},
{
"code": null,
"e": 119731,
"s": 119684,
"text": "The above code produces the following output −"
},
{
"code": null,
"e": 119812,
"s": 119731,
"text": "2 6 \n4 8 \n5 9 \n6 10 \n7 11 \n8 12\n"
},
{
"code": null,
"e": 120095,
"s": 119812,
"text": "In this example, mytable has two fields, ColP and ColQ. Initially, mytable is populated with eight lines, where the ColP contains the values 1, 2, 3, 4, 5, 6, 7 and 8. The ColQ contains the values 5, 6, 7, 8, 9, 10, 11 and 12 because the ColP values are incremented by 4 every time."
},
{
"code": null,
"e": 120379,
"s": 120095,
"text": "The DELETE statement is used to delete the lines from mytable where the value of the ColP key field is either 1 or 3. After deletion, the ColP field of mytable contains the values 2, 4, 5, 6, 7 and 8, as shown in the output. The ColQ field contains the values 6, 8, 9, 10, 11 and 12."
},
{
"code": null,
"e": 120705,
"s": 120379,
"text": "Object orientation simplifies software design to make it easier to understand, maintain, and reuse. Object Oriented Programming (OOP) represents a different way of thinking in writing software. The beauty of OOP lies in its simplicity. The expressiveness of OOP makes it easier to deliver quality software components on time."
},
{
"code": null,
"e": 121374,
"s": 120705,
"text": "As solutions are designed in terms of real-world objects, it becomes much easier for programmers and business analysts to exchange ideas and information about a design that uses a common domain language. These improvements in communication help to reveal hidden requirements, identify risks, and improve the quality of software being developed. The object-oriented approach focuses on objects that represent abstract or concrete things of the real world. These objects are defined by their character and properties that are represented by their internal structure and their attributes (data). The behavior of these objects is described by methods (i.e. functionality)."
},
{
"code": null,
"e": 121437,
"s": 121374,
"text": "Let’s compare the procedural and object oriented programming −"
},
{
"code": null,
"e": 121857,
"s": 121437,
"text": "ABAP was initially developed as a procedural language (just similar to earlier procedural programming language like COBOL). But ABAP has now adapted the principles of object oriented paradigms with the introduction of ABAP Objects. The object-oriented concepts in ABAP such as class, object, inheritance, and polymorphism, are essentially the same as those of other modern object-oriented languages such as Java or C++."
},
{
"code": null,
"e": 122215,
"s": 121857,
"text": "As object orientation begins to take shape, each class assumes specific role assignments. This division of labor helps to simplify the overall programming model, allowing each class to specialize in solving a particular piece of the problem at hand. Such classes have high cohesion and the operations of each class are closely related in some intuitive way."
},
{
"code": null,
"e": 122260,
"s": 122215,
"text": "The key features of object orientation are −"
},
{
"code": null,
"e": 122293,
"s": 122260,
"text": "Effective programming structure."
},
{
"code": null,
"e": 122339,
"s": 122293,
"text": "Real-world entities can be modeled very well."
},
{
"code": null,
"e": 122375,
"s": 122339,
"text": "Stress on data security and access."
},
{
"code": null,
"e": 122402,
"s": 122375,
"text": "Minimizes code redundancy."
},
{
"code": null,
"e": 122438,
"s": 122402,
"text": "Data abstraction and encapsulation."
},
{
"code": null,
"e": 122690,
"s": 122438,
"text": "An object is a special kind of variable that has distinct characteristics and behaviors. The characteristics or attributes of an object are used to describe the state of an object, and behaviors or methods represent the actions performed by an object."
},
{
"code": null,
"e": 123003,
"s": 122690,
"text": "An object is a pattern or instance of a class. It represents a real-world entity such as a person or a programming entity like variables and constants. For example, accounts and students are examples of real-world entities. But hardware and software components of a computer are examples of programming entities."
},
{
"code": null,
"e": 123060,
"s": 123003,
"text": "An object has the following three main characteristics −"
},
{
"code": null,
"e": 123073,
"s": 123060,
"text": "Has a state."
},
{
"code": null,
"e": 123096,
"s": 123073,
"text": "Has a unique identity."
},
{
"code": null,
"e": 123133,
"s": 123096,
"text": "May or may not display the behavior."
},
{
"code": null,
"e": 123455,
"s": 123133,
"text": "The state of an object can be described as a set of attributes and their values. For example, a bank account has a set of attributes such as Account Number, Name, Account Type, Balance, and values of all these attributes. The behavior of an object refers to the changes that occur in its attributes over a period of time."
},
{
"code": null,
"e": 123830,
"s": 123455,
"text": "Each object has a unique identity that can be used to distinguish it from other objects. Two objects may exhibit the same behavior and they may or may not have the same state, but they never have the same identity. Two persons may have the same name, age, and gender but they are not identical. Similarly, the identity of an object will never change throughout its lifetime."
},
{
"code": null,
"e": 124253,
"s": 123830,
"text": "Objects can interact with one another by sending messages. Objects contain data and code to manipulate the data. An object can also be used as a user-defined data type with the help of a class. Objects are also called variables of the type class. After defining a class, you can create any number of objects belonging to that class. Each object is associated with the data of the type class with which it has been created."
},
{
"code": null,
"e": 124312,
"s": 124253,
"text": "The object creation usually includes the following steps −"
},
{
"code": null,
"e": 124397,
"s": 124312,
"text": "Creating a reference variable with reference to the class. The syntax for which is −"
},
{
"code": null,
"e": 124482,
"s": 124397,
"text": "Creating a reference variable with reference to the class. The syntax for which is −"
},
{
"code": null,
"e": 124529,
"s": 124482,
"text": "DATA: <object_name> TYPE REF TO <class_name>.\n"
},
{
"code": null,
"e": 124603,
"s": 124529,
"text": "Creating an object from the reference variable. The syntax for which is −"
},
{
"code": null,
"e": 124677,
"s": 124603,
"text": "Creating an object from the reference variable. The syntax for which is −"
},
{
"code": null,
"e": 124708,
"s": 124677,
"text": "CREATE Object: <object_name>.\n"
},
{
"code": null,
"e": 125091,
"s": 124708,
"text": "REPORT ZDEMO_OBJECT. \nCLASS Class1 Definition. \nPublic Section. \nDATA: text1(45) VALUE 'ABAP Objects.'. \nMETHODS: Display1. \nENDCLASS. \n\nCLASS Class1 Implementation. \nMETHOD Display1. \nWrite:/ 'This is the Display method.'. \nENDMETHOD. \nENDCLASS. \n\nSTART-OF-SELECTION. \nDATA: Class1 TYPE REF TO Class1. \nCREATE Object: Class1. \nWrite:/ Class1->text1. \nCALL METHOD: Class1->Display1."
},
{
"code": null,
"e": 125138,
"s": 125091,
"text": "The above code produces the following output −"
},
{
"code": null,
"e": 125182,
"s": 125138,
"text": "ABAP Objects. \nThis is the Display method.\n"
},
{
"code": null,
"e": 125400,
"s": 125182,
"text": "A class is used to specify the form of an object and it combines data representation and methods for manipulating that data into one neat package. The data and functions within a class are called members of the class."
},
{
"code": null,
"e": 125758,
"s": 125400,
"text": "When you define a class, you define a blueprint for a data type. This doesn't actually define any data, but it does define what the class name means, what an object of the class will consist of, and what operations can be performed on such an object. That is, it defines the abstract characteristics of an object, such as attributes, fields, and properties."
},
{
"code": null,
"e": 125809,
"s": 125758,
"text": "The following syntax shows how to define a class −"
},
{
"code": null,
"e": 125876,
"s": 125809,
"text": "CLASS <class_name> DEFINITION. \n.......... \n.......... \nENDCLASS.\n"
},
{
"code": null,
"e": 126272,
"s": 125876,
"text": "A class definition starts with the keyword CLASS followed by the class name, DEFINITION and the class body. The definition of a class can contain various components of the class such as attributes, methods, and events. When we declare a method in the class declaration, the method implementation must be included in the class implementation. The following syntax shows how to implement a class −"
},
{
"code": null,
"e": 126344,
"s": 126272,
"text": "CLASS <class_name> IMPLEMENTATION. \n........... \n.......... \nENDCLASS.\n"
},
{
"code": null,
"e": 126546,
"s": 126344,
"text": "Note − Implementation of a class contains the implementation of all its methods. In ABAP Objects, the structure of a class contains components such as attributes, methods, events, types, and constants."
},
{
"code": null,
"e": 126946,
"s": 126546,
"text": "Attributes are data fields of a class that can have any data type such as C, I, F, and N. They are declared in the class declaration. These attributes can be divided into 2 categories: instance and static attributes. An instance attribute defines the instance specific state of an object. The states are different for different objects. An instance attribute is declared by using the DATA statement."
},
{
"code": null,
"e": 127246,
"s": 126946,
"text": "Static attributes define a common state of a class that is shared by all the instances of the class. That is, if you change a static attribute in one object of a class, the change is visible to all other objects of the class as well. A static attribute is declared by using the CLASS-DATA statement."
},
{
"code": null,
"e": 127803,
"s": 127246,
"text": "A method is a function or procedure that represents the behavior of an object in the class. The methods of the class can access any attribute of the class. The definition of a method can also contain parameters, so that you can supply the values to these parameters when methods are called. The definition of a method is declared in the class declaration and implemented in the implementation part of a class. The METHOD and ENDMETHOD statements are used to define the implementation part of a method. The following syntax shows how to implement a method −"
},
{
"code": null,
"e": 127857,
"s": 127803,
"text": "METHOD <m_name>. \n.......... \n.......... \nENDMETHOD.\n"
},
{
"code": null,
"e": 127980,
"s": 127857,
"text": "In this syntax, <m_name> represents the name of a method. Note − You can call a method by using the CALL METHOD statement."
},
{
"code": null,
"e": 128290,
"s": 127980,
"text": "Class components can be defined in public, private, or protected visibility sections that control how these components could be accessed. The private visibility section is used to deny access to components from outside of the class. Such components can only be accessed from inside the class such as a method."
},
{
"code": null,
"e": 128605,
"s": 128290,
"text": "Components defined in the public visibility section can be accessed from any context. By default all the members of a class would be private. Practically, we define data in private section and related methods in public section so that they can be called from outside of the class as shown in the following program."
},
{
"code": null,
"e": 128747,
"s": 128605,
"text": "The attributes and methods declared in Public section in a class can be accessed by that class and any other class, sub-class of the program."
},
{
"code": null,
"e": 128889,
"s": 128747,
"text": "The attributes and methods declared in Public section in a class can be accessed by that class and any other class, sub-class of the program."
},
{
"code": null,
"e": 129043,
"s": 128889,
"text": "When the attributes and methods are declared in Protected section in a class, those can be accessed by that class and sub classes (derived classes) only."
},
{
"code": null,
"e": 129197,
"s": 129043,
"text": "When the attributes and methods are declared in Protected section in a class, those can be accessed by that class and sub classes (derived classes) only."
},
{
"code": null,
"e": 129342,
"s": 129197,
"text": "When the attributes and methods are declared in Private section in a class, those can be accessed by only that class and not by any other class."
},
{
"code": null,
"e": 129487,
"s": 129342,
"text": "When the attributes and methods are declared in Private section in a class, those can be accessed by only that class and not by any other class."
},
{
"code": null,
"e": 130132,
"s": 129487,
"text": "Report ZAccess1. \nCLASS class1 Definition.\n PUBLIC Section.\n Data: text1 Type char25 Value 'Public Data'.\n Methods meth1.\n\t\t\n PROTECTED Section.\n Data: text2 Type char25 Value 'Protected Data'.\n\t\t\n PRIVATE Section. \n Data: text3 Type char25 Value 'Private Data'. \nENDCLASS.\n \nCLASS class1 Implementation. \n Method meth1. \n Write: / 'Public Method:', \n / text1,\n / text2,\n / text3.\n Skip.\n EndMethod.\nENDCLASS. \n\nStart-Of-Selection. \n Data: Objectx Type Ref To class1.\n Create Object: Objectx.\n CALL Method: Objectx→meth1.\n Write: / Objectx→text1."
},
{
"code": null,
"e": 130179,
"s": 130132,
"text": "The above code produces the following output −"
},
{
"code": null,
"e": 130253,
"s": 130179,
"text": "Public Method: \nPublic Data \nProtected Data \nPrivate Data\n \nPublic Data\n"
},
{
"code": null,
"e": 130493,
"s": 130253,
"text": "A Static attribute is declared with the statement CLASS-DATA. All the objects or instances can use the static attribute of the class. Static attributes are accessed directly with the help of class name like class_name⇒name_1 = 'Some Text'."
},
{
"code": null,
"e": 130860,
"s": 130493,
"text": "Following is a program where we want to print a text with line number 4 to 8 times. We define a class class1 and in the public section we declare CLASS-DATA (static attribute) and a method. After implementing the class and method, we directly access the static attribute in Start-Of-Selection event. Then we just create the instance of the class and call the method."
},
{
"code": null,
"e": 131478,
"s": 130860,
"text": "Report ZStatic1. \nCLASS class1 Definition. \n PUBLIC Section.\n CLASS-DATA: name1 Type char45,\n data1 Type I.\n Methods: meth1. \nENDCLASS. \n\nCLASS class1 Implementation. \n Method meth1.\n Do 4 Times.\n data1 = 1 + data1.\n Write: / data1, name1.\n EndDo.\n Skip.\n EndMethod. \nENDCLASS. \n\nStart-Of-Selection. \n class1⇒name1 = 'ABAP Object Oriented Programming'.\n class1⇒data1 = 0.\n Data: Object1 Type Ref To class1,\n Object2 Type Ref To class1.\n\t\t\t\n Create Object: Object1, Object2.\n CALL Method: Object1→meth1, \n Object2→meth1."
},
{
"code": null,
"e": 131525,
"s": 131478,
"text": "The above code produces the following output −"
},
{
"code": null,
"e": 131998,
"s": 131525,
"text": "Constructors are special methods that are called automatically, either while creating an object or accessing the components of a class. Constructor gets triggered whenever an object is created, but we need to call a method to trigger the general method. In the following example, we have declared two public methods method1 and constructor. Both these methods have different operations. While creating an object of the class, the constructor method triggers its operation."
},
{
"code": null,
"e": 132384,
"s": 131998,
"text": "Report ZConstructor1. \nCLASS class1 Definition.\n PUBLIC Section.\n Methods: method1, constructor.\nENDCLASS. \n\nCLASS class1 Implementation.\n Method method1.\n Write: / 'This is Method1'.\n EndMethod.\n\t\n Method constructor.\n Write: / 'Constructor Triggered'.\n EndMethod. \nENDCLASS. \n\nStart-Of-Selection.\n Data Object1 Type Ref To class1.\n Create Object Object1."
},
{
"code": null,
"e": 132431,
"s": 132384,
"text": "The above code produces the following output −"
},
{
"code": null,
"e": 132454,
"s": 132431,
"text": "Constructor Triggered\n"
},
{
"code": null,
"e": 132874,
"s": 132454,
"text": "When you declare a variable of any type in public section of a class, you can use it in any other implementation. A variable can be declared with an initial value in public section. We may declare the variable again inside a method with a different value. When we write the variable inside the method, the system will print the changed value. To reflect the previous value of the variable, we have to use ‘ME’ operator."
},
{
"code": null,
"e": 133195,
"s": 132874,
"text": "In this program, we have declared a public variable text1 and initiated with a value. We have declared the same variable again, but instantiated with different value. Inside the method, we are writing that variable with ‘ME’ operator to get the previously initiated value. We get the changed value by declaring directly."
},
{
"code": null,
"e": 133642,
"s": 133195,
"text": "Report ZMEOperator1. \nCLASS class1 Definition.\n PUBLIC Section. \n\t\nData text1 Type char25 Value 'This is CLASS Attribute'.\n Methods method1. \nENDCLASS. \n\nCLASS class1 Implementation.\n Method method1. \n\t\nData text1 Type char25 Value 'This is METHOD Attribute'.\n Write: / ME→text1,\n / text1.\n ENDMethod.\nENDCLASS. \n\nStart-Of-Selection.\n Data objectx Type Ref To class1.\n Create Object objectx.\n CALL Method objectx→method1."
},
{
"code": null,
"e": 133689,
"s": 133642,
"text": "The above code produces the following output −"
},
{
"code": null,
"e": 133740,
"s": 133689,
"text": "This is CLASS Attribute \nThis is METHOD Attribute\n"
},
{
"code": null,
"e": 134054,
"s": 133740,
"text": "One of the most important concepts in object oriented programming is that of inheritance. Inheritance allows us to define a class in terms of another class, which makes it easier to create and maintain an application. This also provides an opportunity to reuse the code functionality and fast implementation time."
},
{
"code": null,
"e": 134363,
"s": 134054,
"text": "When creating a class, instead of writing completely new data members and methods, the programmer can designate that the new class should inherit the members of an existing class. This existing class is called the base class or super class, and the new class is referred to as the derived class or sub class."
},
{
"code": null,
"e": 134431,
"s": 134363,
"text": "An object of one class can acquire the properties of another class."
},
{
"code": null,
"e": 134499,
"s": 134431,
"text": "An object of one class can acquire the properties of another class."
},
{
"code": null,
"e": 134623,
"s": 134499,
"text": "Derived class inherits the data and methods of a super class. However, they can overwrite methods and also add new methods."
},
{
"code": null,
"e": 134747,
"s": 134623,
"text": "Derived class inherits the data and methods of a super class. However, they can overwrite methods and also add new methods."
},
{
"code": null,
"e": 134797,
"s": 134747,
"text": "The main advantage of inheritance is reusability."
},
{
"code": null,
"e": 134847,
"s": 134797,
"text": "The main advantage of inheritance is reusability."
},
{
"code": null,
"e": 134961,
"s": 134847,
"text": "The inheritance relationship is specified using the ‘INHERITING FROM’ addition to the class definition statement."
},
{
"code": null,
"e": 134987,
"s": 134961,
"text": "Following is the syntax −"
},
{
"code": null,
"e": 135046,
"s": 134987,
"text": "CLASS <subclass> DEFINITION INHERITING FROM <superclass>.\n"
},
{
"code": null,
"e": 135652,
"s": 135046,
"text": "Report ZINHERITAN_1. \nCLASS Parent Definition. \nPUBLIC Section. \nData: w_public(25) Value 'This is public data'. \nMethods: ParentM. \nENDCLASS. \n\nCLASS Child Definition Inheriting From Parent. \nPUBLIC Section. \nMethods: ChildM. \nENDCLASS. \n\nCLASS Parent Implementation. \nMethod ParentM. \nWrite /: w_public. \nEndMethod. ENDCLASS. \n\nCLASS Child Implementation. \nMethod ChildM. \nSkip. \nWrite /: 'Method in child class', w_public.\nEndMethod. \nENDCLASS. \n\nStart-of-selection. \nData: Parent Type Ref To Parent, \nChild Type Ref To Child. \nCreate Object: Parent, Child. \nCall Method: Parent→ParentM, \nchild→ChildM."
},
{
"code": null,
"e": 135699,
"s": 135652,
"text": "The above code produces the following output −"
},
{
"code": null,
"e": 135764,
"s": 135699,
"text": "This is public data \nMethod in child class \nThis is public data\n"
},
{
"code": null,
"e": 136079,
"s": 135764,
"text": "A derived class can access all the non-private members of its base class. Thus super class members that should not be accessible to the member functions of sub classes should be declared private in the super class. We can summarize the different access types according to who can access them in the following way −"
},
{
"code": null,
"e": 136437,
"s": 136079,
"text": "When deriving a class from a super class, it can be inherited through public, protected or private inheritance. The type of inheritance is specified by the access specifier as explained above. We hardly use protected or private inheritance, but public inheritance is commonly used. The following rules are applied while using different types of inheritance."
},
{
"code": null,
"e": 136832,
"s": 136437,
"text": "Public Inheritance − When deriving a class from a public super class, public members of the super class become public members of the sub class and protected members of the super class become protected members of the sub class. Super class's private members are never accessible directly from a sub class, but can be accessed through calls to the public and protected members of the super class."
},
{
"code": null,
"e": 137227,
"s": 136832,
"text": "Public Inheritance − When deriving a class from a public super class, public members of the super class become public members of the sub class and protected members of the super class become protected members of the sub class. Super class's private members are never accessible directly from a sub class, but can be accessed through calls to the public and protected members of the super class."
},
{
"code": null,
"e": 137386,
"s": 137227,
"text": "Protected Inheritance − When deriving from a protected super class, public and protected members of the super class become protected members of the sub class."
},
{
"code": null,
"e": 137545,
"s": 137386,
"text": "Protected Inheritance − When deriving from a protected super class, public and protected members of the super class become protected members of the sub class."
},
{
"code": null,
"e": 137698,
"s": 137545,
"text": "Private Inheritance − When deriving from a private super class, public and protected members of the super class become private members of the sub class."
},
{
"code": null,
"e": 137851,
"s": 137698,
"text": "Private Inheritance − When deriving from a private super class, public and protected members of the super class become private members of the sub class."
},
{
"code": null,
"e": 137956,
"s": 137851,
"text": "The methods of the super class can be re-implemented in the sub class. Few rules of redefining methods −"
},
{
"code": null,
"e": 138078,
"s": 137956,
"text": "The redefinition statement for the inherited method must be in the same section as the definition of the original method."
},
{
"code": null,
"e": 138200,
"s": 138078,
"text": "The redefinition statement for the inherited method must be in the same section as the definition of the original method."
},
{
"code": null,
"e": 138321,
"s": 138200,
"text": "If you redefine a method, you do not need to enter its interface again in the subclass, but only the name of the method."
},
{
"code": null,
"e": 138442,
"s": 138321,
"text": "If you redefine a method, you do not need to enter its interface again in the subclass, but only the name of the method."
},
{
"code": null,
"e": 138550,
"s": 138442,
"text": "Within the redefined method, you can access components of the direct super class using the super reference."
},
{
"code": null,
"e": 138658,
"s": 138550,
"text": "Within the redefined method, you can access components of the direct super class using the super reference."
},
{
"code": null,
"e": 138724,
"s": 138658,
"text": "The pseudo reference super can only be used in redefined methods."
},
{
"code": null,
"e": 138790,
"s": 138724,
"text": "The pseudo reference super can only be used in redefined methods."
},
{
"code": null,
"e": 139619,
"s": 138790,
"text": "Report Zinheri_Redefine. \nCLASS super_class Definition. \nPublic Section. \nMethods: Addition1 importing g_a TYPE I\n g_b TYPE I\n\t\t exporting g_c TYPE I.\nENDCLASS. \n\nCLASS super_class Implementation. \nMethod Addition1. \ng_c = g_a + g_b. \nEndMethod. \nENDCLASS. \n\nCLASS sub_class Definition Inheriting From super_class. \nPublic Section. \nMETHODS: Addition1 Redefinition. \nENDCLASS. \n\nCLASS sub_class Implementation. \nMethod Addition1. \ng_c = g_a + g_b + 10. \nEndMethod. \nENDCLASS. \n\nStart-Of-Selection. \nParameters: P_a Type I, P_b TYPE I. \nData: H_Addition1 TYPE I. \nData: H_Sub TYPE I. \nData: Ref1 TYPE Ref TO sub_class. \nCreate Object Ref1. \nCall Method Ref1→Addition1 exporting g_a = P_a \n g_b = P_b\n\t\t Importing g_c = H_Addition1. \nWrite:/ H_Addition1."
},
{
"code": null,
"e": 139719,
"s": 139619,
"text": "After executing F8, if we enter the values 9 and 10, the above code produces the following output −"
},
{
"code": null,
"e": 139742,
"s": 139719,
"text": "Redefinition Demo \n29\n"
},
{
"code": null,
"e": 140228,
"s": 139742,
"text": "The term polymorphism literally means ‘many forms’. From an object-oriented perspective, polymorphism works in conjunction with inheritance to make it possible for various types within an inheritance tree to be used interchangeably. That is, polymorphism occurs when there is a hierarchy of classes and they are related by inheritance. ABAP polymorphism means that a call to a method will cause a different method to be executed depending on the type of object that invokes the method."
},
{
"code": null,
"e": 140763,
"s": 140228,
"text": "The following program contains an abstract class 'class_prgm', 2 sub classes (class_procedural and class_OO), and a test driver class 'class_type_approach'. In this implementation, the class method 'start' allow us to display the type of programming and its approach. If you look closely at the signature of method 'start', you will observe that it receives an importing parameter of type class_prgm. However, in the Start-Of-Selection event, this method has been called at run-time with objects of type class_procedural and class_OO."
},
{
"code": null,
"e": 142172,
"s": 140763,
"text": "Report ZPolymorphism1. \nCLASS class_prgm Definition Abstract. \nPUBLIC Section. \nMethods: prgm_type Abstract, \napproach1 Abstract. \nENDCLASS. \n\nCLASS class_procedural Definition \nInheriting From class_prgm. \nPUBLIC Section. \nMethods: prgm_type Redefinition, \napproach1 Redefinition. \nENDCLASS. \n\nCLASS class_procedural Implementation. \nMethod prgm_type. \nWrite: 'Procedural programming'. \n\nEndMethod. Method approach1. \nWrite: 'top-down approach'. \n\nEndMethod. ENDCLASS. \nCLASS class_OO Definition \nInheriting From class_prgm. \nPUBLIC Section. \nMethods: prgm_type Redefinition, \napproach1 Redefinition. \nENDCLASS. \n\nCLASS class_OO Implementation. \nMethod prgm_type. \nWrite: 'Object oriented programming'. \nEndMethod. \n\nMethod approach1. \nWrite: 'bottom-up approach'.\nEndMethod. \nENDCLASS. \n\nCLASS class_type_approach Definition. \nPUBLIC Section. \nCLASS-METHODS: \nstart Importing class1_prgm \nType Ref To class_prgm. \nENDCLASS. \n\nCLASS class_type_approach IMPLEMENTATION. \nMethod start. \nCALL Method class1_prgm→prgm_type. \nWrite: 'follows'. \n\nCALL Method class1_prgm→approach1. \nEndMethod. \nENDCLASS. \n\nStart-Of-Selection. \nData: class_1 Type Ref To class_procedural, \nclass_2 Type Ref To class_OO. \n\nCreate Object class_1. \nCreate Object class_2. \nCALL Method class_type_approach⇒start \nExporting \n\nclass1_prgm = class_1. \nNew-Line. \nCALL Method class_type_approach⇒start \nExporting \nclass1_prgm = class_2. "
},
{
"code": null,
"e": 142219,
"s": 142172,
"text": "The above code produces the following output −"
},
{
"code": null,
"e": 142326,
"s": 142219,
"text": "Procedural programming follows top-down approach \nObject oriented programming follows bottom-up approach\n"
},
{
"code": null,
"e": 142933,
"s": 142326,
"text": "ABAP run-time environment performs an implicit narrowing cast during the assignment of the importing parameter class1_prgm. This feature helps the 'start' method to be implemented generically. The dynamic type information associated with an object reference variable allows the ABAP run-time environment to dynamically bind a method call with the implementation defined in the object pointed to by the object reference variable. For instance, the importing parameter 'class1_prgm' for method 'start' in the 'class_type_approach' class refers to an abstract type that could never be instantiated on its own."
},
{
"code": null,
"e": 143368,
"s": 142933,
"text": "Whenever the method is called with a concrete sub class implementation such as class_procedural or class_OO, the dynamic type of the class1_prgm reference parameter is bound to one of these concrete types. Therefore, the calls to methods 'prgm_type' and 'approach1' refer to the implementations provided in the class_procedural or class_OO sub classes rather than the undefined abstract implementations provided in class 'class_prgm'."
},
{
"code": null,
"e": 143825,
"s": 143368,
"text": "Encapsulation is an Object Oriented Programming (OOP) concept that binds together data and functions that manipulate the data, and keeps both safe from outside interference and misuse. Data encapsulation led to the important OOP concept of data hiding. Encapsulation is a mechanism of bundling the data and the functions that use them, and data abstraction is a mechanism of exposing only the interfaces and hiding the implementation details from the user."
},
{
"code": null,
"e": 144081,
"s": 143825,
"text": "ABAP supports the properties of encapsulation and data hiding through the creation of user-defined types called classes. As discussed earlier, a class can contain private, protected and public members. By default, all items defined in a class are private."
},
{
"code": null,
"e": 144269,
"s": 144081,
"text": "Encapsulation actually means one attribute and method could be modified in different classes. Hence data and method can have different form and logic that can be hidden to separate class."
},
{
"code": null,
"e": 144544,
"s": 144269,
"text": "Let's consider encapsulation by interface. Interface is used when we need to create one method with different functionality in different classes. Here the name of the method need not be changed. The same method will have to be implemented in different class implementations."
},
{
"code": null,
"e": 145042,
"s": 144544,
"text": "The following program contains an Interface inter_1. We have declared attribute and a method method1. We have also defined two classes like Class1 and Class2. So we have to implement the method ‘method1’ in both of the class implementations. We have implemented the method ‘method1’ differently in different classes. In the start-ofselection, we create two objects Object1 and Object2 for two classes. Then, we call the method by different objects to get the function declared in separate classes."
},
{
"code": null,
"e": 145841,
"s": 145042,
"text": "Report ZEncap1. \nInterface inter_1.\n Data text1 Type char35.\n Methods method1.\nEndInterface.\n\nCLASS Class1 Definition.\n PUBLIC Section.\n Interfaces inter_1.\nENDCLASS. \n\nCLASS Class2 Definition.\n PUBLIC Section.\n Interfaces inter_1. \nENDCLASS.\n\nCLASS Class1 Implementation.\n Method inter_1~method1.\n inter_1~text1 = 'Class 1 Interface method'.\n Write / inter_1~text1.\n EndMethod. \nENDCLASS.\n \nCLASS Class2 Implementation.\n Method inter_1~method1.\n inter_1~text1 = 'Class 2 Interface method'.\n Write / inter_1~text1.\n EndMethod. \nENDCLASS.\n \nStart-Of-Selection.\n Data: Object1 Type Ref To Class1,\n Object2 Type Ref To Class2.\n\t\t\n Create Object: Object1, Object2.\n CALL Method: Object1→inter_1~method1,\n Object2→inter_1~method1. "
},
{
"code": null,
"e": 145888,
"s": 145841,
"text": "The above code produces the following output −"
},
{
"code": null,
"e": 145940,
"s": 145888,
"text": "Class 1 Interface method \nClass 2 Interface method\n"
},
{
"code": null,
"e": 146378,
"s": 145940,
"text": "Encapsulated classes do not have a lot of dependencies on the outside world. Moreover, the interactions that they do have with external clients are controlled through a stabilized public interface. That is, an encapsulated class and its clients are loosely coupled. For the most part, classes with well-defined interfaces can be plugged into another context. When designed correctly, encapsulated classes become reusable software assets."
},
{
"code": null,
"e": 146639,
"s": 146378,
"text": "Most of us have learned through bitter experience to make class members private by default unless we really need to expose them. That is just good encapsulation. This wisdom is applied most frequently to data members and it also applies equally to all members."
},
{
"code": null,
"e": 147031,
"s": 146639,
"text": "Similar to classes in ABAP, interfaces act as data types for objects. The components of interfaces are same as the components of classes. Unlike the declaration of classes, the declaration of an interface does not include the visibility sections. This is because the components defined in the declaration of an interface are always integrated in the public visibility section of the classes."
},
{
"code": null,
"e": 147486,
"s": 147031,
"text": "Interfaces are used when two similar classes have a method with the same name, but the functionalities are different from each other. Interfaces might appear similar to classes, but the functions defined in an interface are implemented in a class to extend the scope of that class. Interfaces along with the inheritance feature provide a base for polymorphism. This is because a method defined in an interface can behave differently in different classes."
},
{
"code": null,
"e": 147543,
"s": 147486,
"text": "Following is the general format to create an interface −"
},
{
"code": null,
"e": 147644,
"s": 147543,
"text": "INTERFACE <intf_name>. \nDATA..... \nCLASS-DATA..... \nMETHODS..... \nCLASS-METHODS..... \nENDINTERFACE.\n"
},
{
"code": null,
"e": 148119,
"s": 147644,
"text": "In this syntax, <intf_name> represents the name of an interface. The DATA and CLASSDATA statements can be used to define the instance and static attributes of the interface respectively. The METHODS and CLASS-METHODS statements can be used to define the instance and static methods of the interface respectively. As the definition of an interface does not include the implementation class, it is not necessary to add the DEFINITION clause in the declaration of an interface."
},
{
"code": null,
"e": 148414,
"s": 148119,
"text": "Note − All the methods of an interface are abstract. They are fully declared including their parameter interface, but not implemented in the interface. All the classes that want to use an interface must implement all the methods of the interface. Otherwise, the class becomes an abstract class."
},
{
"code": null,
"e": 148484,
"s": 148414,
"text": "We use the following syntax in the implementation part of the class −"
},
{
"code": null,
"e": 148509,
"s": 148484,
"text": "INTERFACE <intf_name>. \n"
},
{
"code": null,
"e": 148645,
"s": 148509,
"text": "In this syntax, <intf_name> represents the name of an interface. Note that this syntax must be used in the public section of the class."
},
{
"code": null,
"e": 148754,
"s": 148645,
"text": "The following syntax is used to implement the methods of an interface inside the implementation of a class −"
},
{
"code": null,
"e": 148811,
"s": 148754,
"text": "METHOD <intf_name~method_m>. \n<statements>. \nENDMETHOD.\n"
},
{
"code": null,
"e": 148925,
"s": 148811,
"text": "In this syntax, <intf_name~method_m> represents the fully declared name of a method of the <intf_name> interface."
},
{
"code": null,
"e": 149906,
"s": 148925,
"text": "Report ZINTERFACE1. \nINTERFACE my_interface1. \nMethods msg. \nENDINTERFACE. \n\nCLASS num_counter Definition. \nPUBLIC Section. \nINTERFACES my_interface1. \nMethods add_number. \nPRIVATE Section. \nData num Type I. \nENDCLASS. \n\nCLASS num_counter Implementation. \nMethod my_interface1~msg. \nWrite: / 'The number is', num. \nEndMethod. \n\nMethod add_number. \nADD 7 TO num. \nEndMethod. \nENDCLASS. \n\nCLASS drive1 Definition. \nPUBLIC Section. \nINTERFACES my_interface1. \nMethods speed1.\nPRIVATE Section.\nData wheel1 Type I. \nENDCLASS. \n\nCLASS drive1 Implementation.\nMethod my_interface1~msg.\nWrite: / 'Total number of wheels is', wheel1. \nEndMethod. \n\nMethod speed1. \nAdd 4 To wheel1. \nEndMethod. \nENDCLASS. \n\nStart-Of-Selection. \nData object1 Type Ref To num_counter. \nCreate Object object1. \n\nCALL Method object1→add_number.\nCALL Method object1→my_interface1~msg.\n\nData object2 Type Ref To drive1. \nCreate Object object2.\n \nCALL Method object2→speed1. \nCALL Method object2→my_interface1~msg. "
},
{
"code": null,
"e": 149953,
"s": 149906,
"text": "The above code produces the following output −"
},
{
"code": null,
"e": 149999,
"s": 149953,
"text": "The number is 7 \nTotal number of wheels is 4\n"
},
{
"code": null,
"e": 150337,
"s": 149999,
"text": "In the above example, my_interface1 is the name of an interface that contains the 'msg' method. Next, two classes, num_counter and drive1 are defined and implemented. Both these classes implement the 'msg' method and also specific methods that define the behavior of their respective instances, such as the add_number and speed1 methods."
},
{
"code": null,
"e": 150418,
"s": 150337,
"text": "Note − The add_number and speed1 methods are specific to the respective classes."
},
{
"code": null,
"e": 150696,
"s": 150418,
"text": "An event is a set of outcomes that are defined in a class to trigger the event handlers in other classes. When an event is triggered, we can call any number of event handler methods. The link between a trigger and its handler method is actually decided dynamically at run-time."
},
{
"code": null,
"e": 150961,
"s": 150696,
"text": "In a normal method call, a calling program determines which method of an object or a class needs to be called. As fixed handler method is not registered for every event, in case of event handling, the handler method determines the event that needs to be triggered."
},
{
"code": null,
"e": 151222,
"s": 150961,
"text": "An event of a class can trigger an event handler method of the same class by using the RAISE EVENT statement. For an event, the event handler method can be defined in the same or different class by using the FOR EVENT clause, as shown in the following syntax −"
},
{
"code": null,
"e": 151263,
"s": 151222,
"text": "FOR EVENT <event_name> OF <class_name>.\n"
},
{
"code": null,
"e": 151603,
"s": 151263,
"text": "Similar to the methods of a class, an event can have parameter interface but it has only output parameters. The output parameters are passed to the event handler method by the RAISE EVENT statement that receives them as input parameters. An event is linked to its handler method dynamically in a program by using the SET HANDLER statement."
},
{
"code": null,
"e": 151722,
"s": 151603,
"text": "When an event is triggered, appropriate event handler methods are supposed to be executed in all the handling classes."
},
{
"code": null,
"e": 152488,
"s": 151722,
"text": "REPORT ZEVENT1. \nCLASS CL_main DEFINITION. \nPUBLIC SECTION. \nDATA: num1 TYPE I. \nMETHODS: PRO IMPORTING num2 TYPE I. \nEVENTS: CUTOFF. \nENDCLASS. \n\nCLASS CL_eventhandler DEFINITION. \nPUBLIC SECTION. \nMETHODS: handling_CUTOFF FOR EVENT CUTOFF OF CL_main. \nENDCLASS. \n\nSTART-OF-SELECTION. \nDATA: main1 TYPE REF TO CL_main. \nDATA: eventhandler1 TYPE REF TO CL_eventhandler. \n\nCREATE OBJECT main1. \nCREATE OBJECT eventhandler1. \n\nSET HANDLER eventhandler1→handling_CUTOFF FOR main1. \nmain1→PRO( 4 ).\nCLASS CL_main IMPLEMENTATION.\nMETHOD PRO.\nnum1 = num2.\nIF num2 ≥ 2. \nRAISE EVENT CUTOFF.\nENDIF. \nENDMETHOD.\nENDCLASS.\n\nCLASS CL_eventhandler IMPLEMENTATION.\nMETHOD handling_CUTOFF.\nWRITE: 'Handling the CutOff'. \nWRITE: / 'Event has been processed'. \nENDMETHOD. ENDCLASS."
},
{
"code": null,
"e": 152535,
"s": 152488,
"text": "The above code produces the following output −"
},
{
"code": null,
"e": 152582,
"s": 152535,
"text": "Handling the CutOff \nEvent has been processed\n"
},
{
"code": null,
"e": 152792,
"s": 152582,
"text": "A report is a presentation of data in an organized structure. Many database management systems include a report writer that enables you to design and generate reports. SAP applications support report creation."
},
{
"code": null,
"e": 153079,
"s": 152792,
"text": "A classical report is created by using the output data in the WRITE statement inside a loop. They do not contain any sub-reports. SAP also provides some standard reports such as RSCLTCOP that is used to copy tables across clients and RSPARAM that is used to display instance parameters."
},
{
"code": null,
"e": 153426,
"s": 153079,
"text": "These reports consist of only one screen as an output. We can use various events such as INITIALIZATON & TOP-OF-PAGE to create a classical report, and each event has its own importance during the creation of a classical report. Each of these events is associated to a specific user action and is triggered only when the user performs that action."
},
{
"code": null,
"e": 153488,
"s": 153426,
"text": "Following is a table describing the events and descriptions −"
},
{
"code": null,
"e": 153502,
"s": 153488,
"text": "INITIALIZATON"
},
{
"code": null,
"e": 153552,
"s": 153502,
"text": "Triggered before displaying the selection screen."
},
{
"code": null,
"e": 153572,
"s": 153552,
"text": "AT SELECTION-SCREEN"
},
{
"code": null,
"e": 153796,
"s": 153572,
"text": "Triggered after processing of the user input on the selection screen. This event verifies the user input prior to the execution of a program. After processing the user input, the selection screen remains in the active mode."
},
{
"code": null,
"e": 153815,
"s": 153796,
"text": "START-OF-SELECTION"
},
{
"code": null,
"e": 153956,
"s": 153815,
"text": "Triggered only after the processing of the selection screen is over; that is, when the user clicks the Execute icon on the selection screen."
},
{
"code": null,
"e": 153973,
"s": 153956,
"text": "END-OF-SELECTION"
},
{
"code": null,
"e": 154052,
"s": 153973,
"text": "Triggered after the last statement in the START-OF-SELECTON event is executed."
},
{
"code": null,
"e": 154064,
"s": 154052,
"text": "TOP-OF-PAGE"
},
{
"code": null,
"e": 154138,
"s": 154064,
"text": "Triggered by the first WRITE statement to display the data on a new page."
},
{
"code": null,
"e": 154150,
"s": 154138,
"text": "END-OF-PAGE"
},
{
"code": null,
"e": 154354,
"s": 154150,
"text": "Triggered to display the text at the end of a page in a report. Note, that this event is the last event while creating a report, and should be combined with the LINE-COUNT clause of the REPORT statement."
},
{
"code": null,
"e": 154539,
"s": 154354,
"text": "Let's create a classical report. We will display the information stored in the standard database MARA (contains general material data) by using a sequence of statements in ABAP editor."
},
{
"code": null,
"e": 155632,
"s": 154539,
"text": "REPORT ZREPORT2 \nLINE-SIZE 75 \nLINE-COUNT 30(3) \nNO STANDARD PAGE HEADING. \nTables: MARA. \nTYPES: Begin of itab, \n\nMATNR TYPE MARA-MATNR, \nMBRSH TYPE MARA-MBRSH, \nMEINS TYPE MARA-MEINS, \nMTART TYPE MARA-MTART, \n\nEnd of itab. \n\nDATA: wa_ma TYPE itab,\n it_ma TYPE STANDARD TABLE OF itab.\n\t\t\nSELECT-OPTIONS: MATS FOR MARA-MATNR OBLIGATORY. \nINITIALIZATION. \nMATS-LOW = '1'. \nMATS-HIGH = '500'. \n\nAPPEND MATS. \nAT SELECTION-SCREEN. .\nIF MATS-LOW = ' '. \nMESSAGE I000(ZKMESSAGE). \nELSEIF MATS-HIGH = ' '. \nMESSAGE I001(ZKMESSAGE). \nENDIF. \n\nTOP-OF-PAGE. \nWRITE:/ 'CLASSICAL REPORT CONTAINING GENERAL MATERIAL DATA \nFROM THE TABLE MARA' COLOR 7. \nULINE. \nWRITE:/ 'MATERIAL' COLOR 1, \n\n24 'INDUSTRY' COLOR 2, \n38 'UNITS' COLOR 3, \n53 'MATERIAL TYPE' COLOR 4. \nULINE. \nEND-OF-PAGE. \n\nSTART-OF-SELECTION. \nSELECT MATNR MBRSH MEINS MTART FROM MARA \nINTO TABLE it_ma WHERE MATNR IN MATS. \nLOOP AT it_ma into wa_ma. \nWRITE:/ wa_ma-MATNR, \n\n25 wa_ma-MBRSH, \n40 wa_ma-MEINS, \n55 wa_ma-MTART. \nENDLOOP. \nEND-OF-SELECTION. \n\nULINE. \nWRITE:/ 'CLASSICAL REPORT HAS BEEN CREATED' COLOR 7.\nULINE. \nSKIP. "
},
{
"code": null,
"e": 155745,
"s": 155632,
"text": "The above code produces the following output containing the general material data from the standard table MARA −"
},
{
"code": null,
"e": 156053,
"s": 155745,
"text": "Dialog programming deals with the development of multiple objects. All these objects are linked hierarchically to the main program and they are executed in a sequence. Dialog program development makes use of tools in the ABAP workbench. These are the same tools used in standard SAP application development."
},
{
"code": null,
"e": 156103,
"s": 156053,
"text": "Here are the main components of dialog programs −"
},
{
"code": null,
"e": 156111,
"s": 156103,
"text": "Screens"
},
{
"code": null,
"e": 156124,
"s": 156111,
"text": "Module pools"
},
{
"code": null,
"e": 156136,
"s": 156124,
"text": "Subroutines"
},
{
"code": null,
"e": 156142,
"s": 156136,
"text": "Menus"
},
{
"code": null,
"e": 156155,
"s": 156142,
"text": "Transactions"
},
{
"code": null,
"e": 156426,
"s": 156155,
"text": "Dialog programs should be developed by the object browser (transaction: SE80) so that all objects become linked to the main program without having to explicitly point each object. Advanced navigation techniques enhance the process of moving from one object to the other."
},
{
"code": null,
"e": 156707,
"s": 156426,
"text": "Screens are made up of screen attributes, screen layout, fields and flow logic. The module pool consists of modularized syntax that is placed inside include programs of the dialog program. These modules can be invoked by the flow logic, which is processed by the dialog processor."
},
{
"code": null,
"e": 156843,
"s": 156707,
"text": "Step 1 − Within the transaction SE80, select ‘Program’ from the dropdown and enter a Z name for your custom SAP program as ‘ZSCREENEX’."
},
{
"code": null,
"e": 156916,
"s": 156843,
"text": "Step 2 − Press Enter, choose ‘With TOP INCL’ and click the ‘Yes’ button."
},
{
"code": null,
"e": 157003,
"s": 156916,
"text": "Step 3 − Enter a name for your top include as ‘ZSCRTOP’ and click the green tick mark."
},
{
"code": null,
"e": 157090,
"s": 157003,
"text": "Step 4 − Within the attributes screen, simply enter a title and click the save button."
},
{
"code": null,
"e": 157203,
"s": 157090,
"text": "Step 1 − To add a screen to the program, right-click on the program name and select the options Create → Screen."
},
{
"code": null,
"e": 157275,
"s": 157203,
"text": "Step 2 − Enter a screen number as '0211' and click the green tick mark."
},
{
"code": null,
"e": 157409,
"s": 157275,
"text": "Step 3 − In the next screen, enter a short title, set to normal screen type and click the save button on the top application toolbar."
},
{
"code": null,
"e": 157512,
"s": 157409,
"text": "Step 1 − Click the layout button within the application toolbar and the Screen Painter window appears."
},
{
"code": null,
"e": 157581,
"s": 157512,
"text": "Step 2 − Add a Text Field and enter some text such as \"Hello World\"."
},
{
"code": null,
"e": 157620,
"s": 157581,
"text": "Step 3 − Save and activate the screen."
},
{
"code": null,
"e": 157801,
"s": 157620,
"text": "Step 1 − To create a transaction code for your program, simply right click on the program name and choose the option Create → Transaction and enter a transaction code as 'ZTRANEX'."
},
{
"code": null,
"e": 157972,
"s": 157801,
"text": "Step 2 − Enter the transaction text, program and screen you have just created (ZSCREENEX & 0211), and tick the ‘SAPGUI for Windows’ checkbox in the ‘GUI support’ section."
},
{
"code": null,
"e": 158142,
"s": 157972,
"text": "Save and activate everything. You can execute the program. As the program executes, the text you entered is displayed on the screen as shown in the following screenshot."
},
{
"code": null,
"e": 158586,
"s": 158142,
"text": "SAP Smart Forms tool can be used to print and send documents. This tool is useful in developing forms, PDF files, e-mails and documents for the Internet. The tool provides an interface to build and maintain the layout and logic of a form. SAP also delivers a selection of forms for business processes such as those used in Customer Relationship Management (CRM), Sales and Distribution (SD), Financial Accounting (FI) and Human Resources (HR)."
},
{
"code": null,
"e": 158817,
"s": 158586,
"text": "The tool allows you to modify forms by using simple graphical tools instead of using any programming tool. It means that a user with no programming knowledge can configure these forms with data for a business process effortlessly."
},
{
"code": null,
"e": 159215,
"s": 158817,
"text": "In a Smart Form, data is retrieved from static and dynamic tables. The table heading and subtotal are specified by the triggered events and the data is then sorted before the final output. A Smart Form allows you to incorporate graphics that can be displayed either as part of the form or as the background. You can also suppress a background graphic if required while taking a printout of a form."
},
{
"code": null,
"e": 159294,
"s": 159215,
"text": "Some examples of standard Smart Forms available in SAP system are as follows −"
},
{
"code": null,
"e": 159385,
"s": 159294,
"text": "SF_EXAMPLE_01 represents an invoice with a table output for flight booking for a customer."
},
{
"code": null,
"e": 159476,
"s": 159385,
"text": "SF_EXAMPLE_01 represents an invoice with a table output for flight booking for a customer."
},
{
"code": null,
"e": 159558,
"s": 159476,
"text": "SF_EXAMPLE_02 represents an invoice similar to SF_EXAMPLE_01, but with subtotals."
},
{
"code": null,
"e": 159640,
"s": 159558,
"text": "SF_EXAMPLE_02 represents an invoice similar to SF_EXAMPLE_01, but with subtotals."
},
{
"code": null,
"e": 159779,
"s": 159640,
"text": "SF_EXAMPLE_03 specifies an invoice similar to SF_EXAMPLE_02, but one in which several customers can be selected in an application program."
},
{
"code": null,
"e": 159918,
"s": 159779,
"text": "SF_EXAMPLE_03 specifies an invoice similar to SF_EXAMPLE_02, but one in which several customers can be selected in an application program."
},
{
"code": null,
"e": 160204,
"s": 159918,
"text": "Let’s create a form by using the SAP Smart Forms tool. You will also learn how to add a node in the Smart Form and test the form in this tutorial. Here we begin with creating a copy of the SF_EXAMPLE_01 form. The SF_EXAMPLE_01 form is a standard Smart Form available in the SAP system."
},
{
"code": null,
"e": 160529,
"s": 160204,
"text": "Step 1 − Smart Form Builder is the main interface used to build a Smart Form. It is available on the initial screen of SAP Smart Forms. We need to type the 'SMARTFORMS' transaction code in the Command field to open the initial screen of SAP Smart Forms. In this screen, enter the form name, SF_EXAMPLE_01, in the Form field."
},
{
"code": null,
"e": 160629,
"s": 160529,
"text": "Step 2 − Select Smart Forms → Copy or click the Copy icon to open the Copy Form or Text dialog box."
},
{
"code": null,
"e": 160789,
"s": 160629,
"text": "Step 3 − In the Target Object field, enter a name for the new form. The name must begin with the Y or Z letter. In this case, the name of the form is 'ZSMM1'. "
},
{
"code": null,
"e": 160963,
"s": 160789,
"text": "Step 4 − Click the Continue icon or press the ENTER key in the Copy Form or Text dialog box so that the ZSMM1 form is created as a copy of the predefined form SF_EXAMPLE_01."
},
{
"code": null,
"e": 161087,
"s": 160963,
"text": "Step 5 − Click the Save icon. The name of the form is displayed in the Form field on the initial screen of SAP Smart Forms."
},
{
"code": null,
"e": 161202,
"s": 161087,
"text": "Step 6 − Click the Create button on the initial screen of SAP Smart Forms. The ZSMM1 form appears in Form Builder."
},
{
"code": null,
"e": 161416,
"s": 161202,
"text": "Step 7 − The first draft page is created with a MAIN window. All the components of the new form are based on the SF_EXAMPLE_01 predefined form. You can just click a node in the Navigation menu to view its content."
},
{
"code": null,
"e": 161597,
"s": 161416,
"text": "Step 1 − Open a form in the change mode of the SAP Form Builder screen and right-click the Main Window option in the First Page node and select Create → Text from the context menu."
},
{
"code": null,
"e": 161843,
"s": 161597,
"text": "Step 2 − Modify the text in the Text field to 'My_Text' and the text in the Meaning field to 'Text_Demo'. Enter the text 'Hello TutorialsPoint.....' in the text-editing box in the center frame of Form Builder as shown in the following snapshot −"
},
{
"code": null,
"e": 161893,
"s": 161843,
"text": "Step 3 − Click the Save button to save the node.."
},
{
"code": null,
"e": 162032,
"s": 161893,
"text": "Step 4 − Activate and test the node by clicking the Activate and Test icons, respectively. The initial screen of Function Builder appears."
},
{
"code": null,
"e": 162218,
"s": 162032,
"text": "Step 5 − Activate and test the function module by clicking the Activate and Execute icons. The parameters of the function module are displayed in the initial screen of Function Builder."
},
{
"code": null,
"e": 162315,
"s": 162218,
"text": "Step 6 − Execute the function module by clicking the Execute icon. The Print dialog box appears."
},
{
"code": null,
"e": 162396,
"s": 162315,
"text": "Step 7 − Specify the output device as 'LP01' and click the Print preview button."
},
{
"code": null,
"e": 162448,
"s": 162396,
"text": "The above steps will produce the following output −"
},
{
"code": null,
"e": 162683,
"s": 162448,
"text": "The SAPscript tool of the SAP system can be used to build and manage business forms such as invoices and purchase orders. The SAPscript tool provides numerous templates that simplify the designing of a business form to a great extent."
},
{
"code": null,
"e": 162894,
"s": 162683,
"text": "The SAP system comes with standard SAPscript forms that are delivered with the SAP standard client (generally as client 000). Following are a few examples of standard SAPscript forms delivered with client 000 −"
},
{
"code": null,
"e": 162904,
"s": 162894,
"text": "RVORDER01"
},
{
"code": null,
"e": 162934,
"s": 162904,
"text": "Sales Order Confirmation Form"
},
{
"code": null,
"e": 162944,
"s": 162934,
"text": "RVDELNOTE"
},
{
"code": null,
"e": 162957,
"s": 162944,
"text": "Packing List"
},
{
"code": null,
"e": 162969,
"s": 162957,
"text": "RVINVOICE01"
},
{
"code": null,
"e": 162977,
"s": 162969,
"text": "Invoice"
},
{
"code": null,
"e": 162985,
"s": 162977,
"text": "MEDRUCK"
},
{
"code": null,
"e": 163000,
"s": 162985,
"text": "Purchase Order"
},
{
"code": null,
"e": 163017,
"s": 163000,
"text": "F110_PRENUM_CHCK"
},
{
"code": null,
"e": 163035,
"s": 163017,
"text": "Prenumbered Check"
},
{
"code": null,
"e": 163101,
"s": 163035,
"text": "The structure of a SAPscript form consists of 2 main components −"
},
{
"code": null,
"e": 163179,
"s": 163101,
"text": "Content − This can be either text (business data) or graphics (company logo)."
},
{
"code": null,
"e": 163259,
"s": 163179,
"text": "Layout − This is defined by a set of windows in which the form content appears."
},
{
"code": null,
"e": 163586,
"s": 163259,
"text": "The Form Painter tool provides the graphical layout of a SAPscript form and various functionalities to manipulate the form. In the following example, we are going to create an invoice form after copying its layout structure from a standard SAPscript form RVINVOICE01, and display its layout by accessing the Form Painter tool."
},
{
"code": null,
"e": 163718,
"s": 163586,
"text": "Step 1 − Open the Form Painter. You may request the screen either by navigating the SAP menu or by using the SE71 transaction code."
},
{
"code": null,
"e": 163923,
"s": 163718,
"text": "Step 2 − In the Form Painter, request screen, enter a name and language for a SAPscript form in the Form and Language fields, respectively. Let’s enter 'RVINVOICE01' and 'EN' respectively in these fields."
},
{
"code": null,
"e": 163998,
"s": 163923,
"text": "Step 3 − Select the Page Layout radio button in the Sub objects group box."
},
{
"code": null,
"e": 164134,
"s": 163998,
"text": "Step 4 − Select Utilities → Copy from Client to create a copy of the RVINVOICE01 form. The 'Copy Forms Between Clients' screen appears."
},
{
"code": null,
"e": 164448,
"s": 164134,
"text": "Step 5 − In the 'Copy Forms Between Clients' screen, enter the original name of the form, 'RVINVOICE01', in the Form Name field, the number of the source client '000' in the Source Client field, and the name of the target form as 'ZINV_01' in the Target Form field. Make sure that other settings remain unchanged."
},
{
"code": null,
"e": 164607,
"s": 164448,
"text": "Step 6 − Next, click the Execute icon in the 'Copy Forms Between Clients' screen. The 'Create Object Directory Entry' dialog box appears. Click the Save icon."
},
{
"code": null,
"e": 164757,
"s": 164607,
"text": "The ZINV_01 form is copied from the RVINVOICE01 form and displayed in the 'Copy Forms Between Clients screen' as depicted in the following snapshot −"
},
{
"code": null,
"e": 164899,
"s": 164757,
"text": "Step 7 − Click the back icon twice and navigate back to the Form Painter: Request screen, which contains the name of the copied form ZINV_01."
},
{
"code": null,
"e": 165088,
"s": 164899,
"text": "Step 8 − After clicking the Display button, the 'Form ZINV_01: Layout of Page FIRST' window and the 'Form: Change Page Layout: ZINV_01' screen appears as shown in the following screenshot."
},
{
"code": null,
"e": 165332,
"s": 165088,
"text": "Step 9 − The 'Form ZINV_01: Layout of Page FIRST' window shows the initial layout of the form. The layout of the form contains five windows: HEADER, ADDRESS, INFO, INFO1, and MAIN. The description of these windows can be accessed in PC Editor."
},
{
"code": null,
"e": 165532,
"s": 165332,
"text": "For instance, by just selecting the MAIN window and clicking the Text icon in the 'Form: Change Page Layout: ZINV_01' screen, you can view all the margin values as shown in the following screenshot −"
},
{
"code": null,
"e": 165907,
"s": 165532,
"text": "Customer exits could be considered as hooks to the SAP standard programs. We do not need an access key to write the code and there is no need to modify the SAP standard program. These exits don't have any functionality and they are empty. Business logic could be added in order to meet various client requirements. However, Customer Exits are not available for all programs."
},
{
"code": null,
"e": 166077,
"s": 165907,
"text": "Following are the steps to find customer exits as far as standard transactions are concerned. Let’s identify customer exits available in MM01 (Material Master Creation)."
},
{
"code": null,
"e": 166220,
"s": 166077,
"text": "Step 1 − Go to transaction MM01 and identify the program name of MM01 by going to Menu bar → System → Status as shown in the above screenshot."
},
{
"code": null,
"e": 166305,
"s": 166220,
"text": "Step 2 − Get the program name from the popup screen. The program name is 'SAPLMGMM'."
},
{
"code": null,
"e": 166380,
"s": 166305,
"text": "Step 3 − Go to transaction SE38, enter the program name and click Display."
},
{
"code": null,
"e": 166467,
"s": 166380,
"text": "Step 4 − Navigate to Go to → Properties and find out the package of this program name."
},
{
"code": null,
"e": 166494,
"s": 166467,
"text": "The package name is 'MGA'."
},
{
"code": null,
"e": 166676,
"s": 166494,
"text": "Step 5 − Go to transaction code SMOD that is usually used to identify customer exits. Navigate to Utilities → Find (or) you may directly press Ctrl + F on the transaction code SMOD."
},
{
"code": null,
"e": 166794,
"s": 166676,
"text": "Step 6 − After going to the ‘Find Exits’ screen, enter the package name we got earlier and press F8 (Execute) button."
},
{
"code": null,
"e": 166905,
"s": 166794,
"text": "The above steps produce the following output with the list of exits available in the Material Master Creation."
},
{
"code": null,
"e": 167365,
"s": 166905,
"text": "User exits are used in an extraction if the standard SAP extractors do not provide the expected data or the required functionality, for instance in authorizations or time checks. User exits are commonly used in Sales and Distribution (SD) modules. There are many exits provided by SAP in the areas of sales, transportation, shipping and billing. A user exit is designed to make some changes when standard SAP is not capable of fulfilling all the requirements."
},
{
"code": null,
"e": 167603,
"s": 167365,
"text": "To be able to access what exits are available in each area of sales, go to IMG using this path: IMG → Sales and Distribution → System Modifications → User Exits. The documentation for each exit in the areas of SD is explained thoroughly."
},
{
"code": null,
"e": 167903,
"s": 167603,
"text": "For instance, if you want to find user exits in Sales Document Processing (contract, quotation or sales order), follow the path mentioned above and continue to expand the node User Exits in Sales → User Exits. Click on icon documentation to see all user exits available in Sales Document Processing."
},
{
"code": null,
"e": 167931,
"s": 167903,
"text": "USEREXIT_FIELD_MODIFICATION"
},
{
"code": null,
"e": 167965,
"s": 167931,
"text": "Used to modify screen attributes."
},
{
"code": null,
"e": 167988,
"s": 167965,
"text": "USEREXIT_SAVE_DOCUMENT"
},
{
"code": null,
"e": 168044,
"s": 167988,
"text": "Helps in performing operations when the user hits Save."
},
{
"code": null,
"e": 168075,
"s": 168044,
"text": "USEREXIT_SAVE_DOCUMENT_PREPARE"
},
{
"code": null,
"e": 168191,
"s": 168075,
"text": "Very useful to check input fields, put any value in the field or show a popup to users and to confirm the document."
},
{
"code": null,
"e": 168219,
"s": 168191,
"text": "USEREXIT_MOVE_FIELD_TO_VBAK"
},
{
"code": null,
"e": 168280,
"s": 168219,
"text": "Used when user header changes are moved to header work area."
},
{
"code": null,
"e": 168308,
"s": 168280,
"text": "USEREXIT_MOVE_FIELD_TO_VBAP"
},
{
"code": null,
"e": 168369,
"s": 168308,
"text": "Used when user item changes are moved to SAP item work area."
},
{
"code": null,
"e": 168581,
"s": 168369,
"text": "A User Exit serves the same purpose as Customer Exits but they are available only for the SD module. The exit is implemented as a call to a Function Module. User Exits are modifications to SAP standard programs."
},
{
"code": null,
"e": 171205,
"s": 168581,
"text": "REPORT ZUSEREXIT1. \nTABLES: \n TSTC, TSTCT,\n TADIR, TRDIR, TFDIR, ENLFDIR,\n MODSAPT, MODACT. \n\t\nDATA: \n JTAB LIKE TADIR OCCURS 0 WITH HEADER LINE,\n field1(30),\n v_devclass LIKE TADIR-devclass. \n\t\nPARAMETERS:\n P_TCODE LIKE TSTC-tcode OBLIGATORY. \n\t\nSELECT SINGLE *\n FROM TSTC\n WHERE tcode EQ P_TCODE. \n\t\nIF SY-SUBRC EQ 0.\n SELECT SINGLE *\n FROM TADIR\n\t\n WHERE pgmid = 'R3TR' AND \n object = 'PROG' AND\n obj_name = TSTC-pgmna.\n\t\t\n MOVE TADIR-devclass TO v_devclass.\n\t\n IF SY-SUBRC NE 0.\n SELECT SINGLE * \n FROM TRDIR\n WHERE name = TSTC-pgmna.\n\t\t\n IF TRDIR-subc EQ 'F'.\n SELECT SINGLE *\n FROM TFDIR\n WHERE pname = TSTC-pgmna.\n\t\t\t\n SELECT SINGLE *\n FROM ENLFDIR \n WHERE funcname = TFDIR-funcname.\n\t\t\t\n SELECT SINGLE * \n FROM TADIR\n WHERE pgmid = 'R3TR' AND\n object = 'FUGR' AND \n obj_name EQ ENLFDIR-area.\n MOVE TADIR-devclass TO v_devclass.\n ENDIF.\n ENDIF.\n\t\n SELECT *\n FROM TADIR\n INTO TABLE JTAB\n\t\t\n WHERE pgmid = 'R3TR' AND\n object = 'SMOD' AND\n devclass = v_devclass.\n\t\t\t\n SELECT SINGLE *\n FROM TSTCT\n WHERE sprsl EQ SY-LANGU AND\n tcode EQ P_TCODE.\n\t\t\t\n FORMAT COLOR COL_POSITIVE INTENSIFIED OFF.\n WRITE:/(19) 'Transaction Code - ', \n 20(20) P_TCODE,\n 45(50) TSTCT-ttext.\n SKIP.\n\t\n IF NOT JTAB[] IS INITIAL.\n WRITE:/(95) SY-ULINE.\n FORMAT COLOR COL_HEADING INTENSIFIED ON.\n\t\t\n WRITE:/1 SY-VLINE, \n 2 'Exit Name',\n 21 SY-VLINE , \n 22 'Description',\n 95 SY-VLINE.\n\t\t\t\n WRITE:/(95) SY-ULINE.\n LOOP AT JTAB.\n SELECT SINGLE * FROM MODSAPT\n WHERE sprsl = SY-LANGU AND\n name = JTAB-obj_name.\n\t\t\t\t\n FORMAT COLOR COL_NORMAL INTENSIFIED OFF.\n WRITE:/1 SY-VLINE,\n 2 JTAB-obj_name HOTSPOT ON,\n 21 SY-VLINE ,\n 22 MODSAPT-modtext,\n 95 SY-VLINE.\n ENDLOOP.\n\t\t\n WRITE:/(95) SY-ULINE.\n DESCRIBE TABLE JTAB.\n SKIP.\n FORMAT COLOR COL_TOTAL INTENSIFIED ON.\n WRITE:/ 'No of Exits:' , SY-TFILL.\n\t\t\n ELSE.\n FORMAT COLOR COL_NEGATIVE INTENSIFIED ON.\n WRITE:/(95) 'User Exit doesn’t exist'.\n ENDIF. \nELSE.\n\n FORMAT COLOR COL_NEGATIVE INTENSIFIED ON.\n WRITE:/(95) 'Transaction Code Does Not Exist'. \nENDIF.\n \nAT LINE-SELECTION.\n GET CURSOR FIELD field1.\n CHECK field1(4) EQ 'JTAB'.\n SET PARAMETER ID 'MON' FIELD sy-lisel+1(10).\n CALL TRANSACTION 'SMOD' AND SKIP FIRST SCREEN. "
},
{
"code": null,
"e": 171335,
"s": 171205,
"text": "While processing, enter the transaction code ‘ME01’ and press F8 (Execute) button. The above code produces the following output −"
},
{
"code": null,
"e": 171650,
"s": 171335,
"text": "In some cases, special functions need to be predefined in a software application to enhance the functionality of various applications. There are many Microsoft Excel add-ins to improve the functionality of MS Excel. Similarly, SAP facilitates some predefined functions by providing Business Add-Ins known as BADIs."
},
{
"code": null,
"e": 172111,
"s": 171650,
"text": "A BADI is an enhancement technique that facilitates a SAP programmer, a user, or a specific industry to add some additional code to the existing program in SAP system. We can use standard or customized logic to improve the SAP system. A BADI must first be defined and then implemented to enhance SAP application. While defining a BADI, an interface is created. BADI is implemented by this interface, which in turn is implemented by one or more adaptor classes."
},
{
"code": null,
"e": 172191,
"s": 172111,
"text": "The BADI technique is different from other enhancement techniques in two ways −"
},
{
"code": null,
"e": 172243,
"s": 172191,
"text": "Enhancement technique can be implemented only once."
},
{
"code": null,
"e": 172316,
"s": 172243,
"text": "This enhancement technique can be used by many customers simultaneously."
},
{
"code": null,
"e": 172546,
"s": 172316,
"text": "You can also create filter BADIs, which means BADIs are defined on the basis of filtered data that is not possible with enhancement techniques. The concept of BADIs has been redefined in SAP Release 7.0 with the following goals −"
},
{
"code": null,
"e": 172683,
"s": 172546,
"text": "Enhancing the standard applications in a SAP system by adding two new elements in the ABAP language, that is ‘GET BADI’ and ‘CALL BADI’."
},
{
"code": null,
"e": 172820,
"s": 172683,
"text": "Enhancing the standard applications in a SAP system by adding two new elements in the ABAP language, that is ‘GET BADI’ and ‘CALL BADI’."
},
{
"code": null,
"e": 172946,
"s": 172820,
"text": "Offering more flexibility features such as contexts and filters for the enhancement of standard applications in a SAP system."
},
{
"code": null,
"e": 173072,
"s": 172946,
"text": "Offering more flexibility features such as contexts and filters for the enhancement of standard applications in a SAP system."
},
{
"code": null,
"e": 173439,
"s": 173072,
"text": "When a BADI is created, it contains an interface and other additional components, such as function codes for menu enhancements and screen enhancements. A BADI creation allows customers to include their own enhancements in the standard SAP application. The enhancement, interface, and generated classes are located in an appropriate application development namespace."
},
{
"code": null,
"e": 173878,
"s": 173439,
"text": "Hence, a BADI can be considered as an enhancement technique that uses ABAP objects to create ‘predefined points’ in the SAP components. These predefined points are then implemented by individual industry solutions, country variants, partners and customers to suit their specific requirements. SAP actually introduced the BADI enhancement technique with the Release 4.6A, and the technique has been re-implemented again in the Release 7.0."
},
{
"code": null,
"e": 174242,
"s": 173878,
"text": "Web Dynpro (WD) for ABAP is the SAP standard user interface technology developed by SAP AG. It can be used in the development of web-based applications in the SAP ABAP environment that utilizes SAP development tools and concepts. It provides a front-end web user interface to connect directly to backend SAP R/3 systems to access data and functions for reporting."
},
{
"code": null,
"e": 174432,
"s": 174242,
"text": "Web Dynpro for ABAP consists of a run-time environment and a graphical development environment with specific development tools that are integrated in the ABAP Workbench (transaction: SE80)."
},
{
"code": null,
"e": 174506,
"s": 174432,
"text": "The following illustration shows the overall architecture of Web Dynpro −"
},
{
"code": null,
"e": 174572,
"s": 174506,
"text": "Following are a few points to keep in mind regarding Web Dynpro −"
},
{
"code": null,
"e": 174643,
"s": 174572,
"text": "Web Dynpro is the SAP NetWeaver programming model for user interfaces."
},
{
"code": null,
"e": 174714,
"s": 174643,
"text": "Web Dynpro is the SAP NetWeaver programming model for user interfaces."
},
{
"code": null,
"e": 174815,
"s": 174714,
"text": "All Web Dynpro applications are structured as per the Model View Controller (MVC) programming model."
},
{
"code": null,
"e": 174916,
"s": 174815,
"text": "All Web Dynpro applications are structured as per the Model View Controller (MVC) programming model."
},
{
"code": null,
"e": 175032,
"s": 174916,
"text": "The model defines an interface to the main system and the Web Dynpro application can have an access to system data."
},
{
"code": null,
"e": 175148,
"s": 175032,
"text": "The model defines an interface to the main system and the Web Dynpro application can have an access to system data."
},
{
"code": null,
"e": 175213,
"s": 175148,
"text": "The view is responsible for showing the data in the web browser."
},
{
"code": null,
"e": 175278,
"s": 175213,
"text": "The view is responsible for showing the data in the web browser."
},
{
"code": null,
"e": 175478,
"s": 175278,
"text": "The controller resides between the view and the model. The controller formats the model data to be displayed in the view. It processes the user entries made by the user and returns them to the model."
},
{
"code": null,
"e": 175678,
"s": 175478,
"text": "The controller resides between the view and the model. The controller formats the model data to be displayed in the view. It processes the user entries made by the user and returns them to the model."
},
{
"code": null,
"e": 175750,
"s": 175678,
"text": "Web Dynpro offers the following advantages for application developers −"
},
{
"code": null,
"e": 175826,
"s": 175750,
"text": "The use of graphical tools significantly reduces the implementation effort."
},
{
"code": null,
"e": 175902,
"s": 175826,
"text": "The use of graphical tools significantly reduces the implementation effort."
},
{
"code": null,
"e": 175956,
"s": 175902,
"text": "Reuse and better maintainability by using components."
},
{
"code": null,
"e": 176010,
"s": 175956,
"text": "Reuse and better maintainability by using components."
},
{
"code": null,
"e": 176082,
"s": 176010,
"text": "The layout and navigation is easily changed using the Web Dynpro tools."
},
{
"code": null,
"e": 176154,
"s": 176082,
"text": "The layout and navigation is easily changed using the Web Dynpro tools."
},
{
"code": null,
"e": 176197,
"s": 176154,
"text": "User interface accessibility is supported."
},
{
"code": null,
"e": 176240,
"s": 176197,
"text": "User interface accessibility is supported."
},
{
"code": null,
"e": 176294,
"s": 176240,
"text": "Full integration in the ABAP development environment."
},
{
"code": null,
"e": 176348,
"s": 176294,
"text": "Full integration in the ABAP development environment."
},
{
"code": null,
"e": 176729,
"s": 176348,
"text": "The component is the global unit of the Web Dynpro application project. Creating a Web Dynpro component is the initial step in developing a new Web Dynpro application. Once the component is created, it acts as a node in the Web Dynpro object list. You may create any number of component views in a component and assemble them in any number of the corresponding Web Dynpro windows."
},
{
"code": null,
"e": 176972,
"s": 176729,
"text": "At least one Web Dynpro window is contained in each Web Dynpro component. The Web Dynpro window embeds all the views that are displayed within the front-end web application. The window is processed in the window editors of the ABAP Workbench."
},
{
"code": null,
"e": 176977,
"s": 176972,
"text": "Note"
},
{
"code": null,
"e": 177179,
"s": 176977,
"text": "The component view displays all the administrative details for the application including the description, the name of the person who created it, the creation date, and the assigned development package."
},
{
"code": null,
"e": 177381,
"s": 177179,
"text": "The component view displays all the administrative details for the application including the description, the name of the person who created it, the creation date, and the assigned development package."
},
{
"code": null,
"e": 177583,
"s": 177381,
"text": "The Web Dynpro application is the independent object in the object list of the ABAP Workbench. The interaction between the window and the application is created by the interface view of a given window."
},
{
"code": null,
"e": 177785,
"s": 177583,
"text": "The Web Dynpro application is the independent object in the object list of the ABAP Workbench. The interaction between the window and the application is created by the interface view of a given window."
},
{
"code": null,
"e": 177818,
"s": 177785,
"text": "\n 25 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 177832,
"s": 177818,
"text": " Sanjo Thomas"
},
{
"code": null,
"e": 177865,
"s": 177832,
"text": "\n 26 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 177877,
"s": 177865,
"text": " Neha Gupta"
},
{
"code": null,
"e": 177912,
"s": 177877,
"text": "\n 30 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 177927,
"s": 177912,
"text": " Sumit Agarwal"
},
{
"code": null,
"e": 177960,
"s": 177927,
"text": "\n 30 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 177975,
"s": 177960,
"text": " Sumit Agarwal"
},
{
"code": null,
"e": 178010,
"s": 177975,
"text": "\n 14 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 178022,
"s": 178010,
"text": " Neha Malik"
},
{
"code": null,
"e": 178057,
"s": 178022,
"text": "\n 13 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 178069,
"s": 178057,
"text": " Neha Malik"
},
{
"code": null,
"e": 178076,
"s": 178069,
"text": " Print"
},
{
"code": null,
"e": 178087,
"s": 178076,
"text": " Add Notes"
}
] |
Sum of all natural numbers in range L to R - GeeksforGeeks
|
05 Apr, 2021
Given a range L and R, the task is to find the sum of all natural numbers in range L to R. Examples:
Input: L = 2, R = 5
Output: 14
2 + 3 + 4 + 5 = 14
Input: L = 10, R = 20
Output: 165
A naive approach is to traverse from L to R and add all the elements one by one to get the sum.An efficient approach is to use the formula for the sum of first N natural numbers. The idea of the inclusion-exclusion principle helps to solve the above problem. Find the sum of natural numbers till R and L-1 and then subtract sum(R)-sum(l-1).Below is the implementation of the above approach:
C++
Java
Python3
C#
PHP
Javascript
// C++ program to print the sum// of all numbers in range L and R#include <bits/stdc++.h>using namespace std; // Function to return the sum of// all natural numbersint sumNatural(int n){ int sum = (n * (n + 1)) / 2; return sum;} // Function to return the sum// of all numbers in range L and Rint suminRange(int l, int r){ return sumNatural(r) - sumNatural(l - 1);} // Driver Codeint main(){ int l = 2, r = 5; cout << "Sum of Natural numbers from L to R is " << suminRange(l, r); return 0;}
// Java program to print the sum// of all numbers in range L and R class GFG{// Function to return the sum of// all natural numbersstatic int sumNatural(int n){ int sum = (n * (n + 1)) / 2; return sum;} // Function to return the sum// of all numbers in range L and Rstatic int suminRange(int l, int r){ return sumNatural(r) - sumNatural(l - 1);} // Driver Codepublic static void main(String[] args){ int l = 2, r = 5; System.out.println("Sum of Natural numbers from L to R is "+suminRange(l, r)); }}// This code is contributed by mits
# Python3 program to print the sum of# all numbers in range L and R # Function to return the sum of all natural numbersdef sumNatural(n): sum = (n*(n+1))//2 return sum # Function to return the sum# of all numbers in range L and Rdef suminRange(l, r): return sumNatural(r) - sumNatural(l-1) # Driver Codel =2; r= 5print("Sum of Natural numbers from L to R is ",suminRange(l, r)) # This code is contributed by Shrikant13
// C# program to print the sum// of all numbers in range L and Rusing System; class GFG{// Function to return the sum// of all natural numbersstatic int sumNatural(int n){ int sum = (n * (n + 1)) / 2; return sum;} // Function to return the sum// of all numbers in range L and Rstatic int suminRange(int l, int r){ return sumNatural(r) - sumNatural(l - 1);} // Driver Codestatic public void Main (){ int l = 2, r = 5; Console.WriteLine("Sum of Natural numbers " + "from L to R is " + suminRange(l, r));}} // This code is contributed by akt_mit
<?php// PHP program to print the sum// of all numbers in range L and R // Function to return the sum of// all natural numbersfunction sumNatural($n){ $sum = ($n * ($n + 1)) / 2; return $sum;} // Function to return the sum// of all numbers in range L and Rfunction suminRange($l, $r){ return sumNatural($r) - sumNatural($l - 1);} // Driver Code$l = 2;$r = 5;echo "Sum of Natural numbers " . "from L to R is ", suminRange($l, $r); // This code is contributed by ajit?>
<script>// JavaScript program to print the sum// of all numbers in range L and R // Function to return the sum of// all natural numbersfunction sumNatural(n){ sum = (n * (n + 1)) / 2; return sum;} // Function to return the sum// of all numbers in range L and Rfunction suminRange(l, r){ return sumNatural(r) - sumNatural(l - 1);} // Driver Codelet l = 2;let r = 5;document.write("Sum of Natural numbers from L to R is "+ suminRange(l, r)); // This code is contributed by sravan kumar gottumukkalan </script>
Sum of Natural numbers from L to R is 14
Mithun Kumar
jit_t
shrikanth13
sravankumar8128
series
series-sum
Mathematical
Mathematical
series
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Find all factors of a natural number | Set 1
Check if a number is Palindrome
Program to print prime numbers from 1 to N.
Fizz Buzz Implementation
Program to multiply two matrices
Program to add two binary strings
Find Union and Intersection of two unsorted arrays
Count ways to reach the n'th stair
Add two numbers without using arithmetic operators
Program to convert a given number to words
|
[
{
"code": null,
"e": 24301,
"s": 24273,
"text": "\n05 Apr, 2021"
},
{
"code": null,
"e": 24404,
"s": 24301,
"text": "Given a range L and R, the task is to find the sum of all natural numbers in range L to R. Examples: "
},
{
"code": null,
"e": 24489,
"s": 24404,
"text": "Input: L = 2, R = 5\nOutput: 14\n2 + 3 + 4 + 5 = 14\n\nInput: L = 10, R = 20\nOutput: 165"
},
{
"code": null,
"e": 24884,
"s": 24491,
"text": "A naive approach is to traverse from L to R and add all the elements one by one to get the sum.An efficient approach is to use the formula for the sum of first N natural numbers. The idea of the inclusion-exclusion principle helps to solve the above problem. Find the sum of natural numbers till R and L-1 and then subtract sum(R)-sum(l-1).Below is the implementation of the above approach: "
},
{
"code": null,
"e": 24888,
"s": 24884,
"text": "C++"
},
{
"code": null,
"e": 24893,
"s": 24888,
"text": "Java"
},
{
"code": null,
"e": 24901,
"s": 24893,
"text": "Python3"
},
{
"code": null,
"e": 24904,
"s": 24901,
"text": "C#"
},
{
"code": null,
"e": 24908,
"s": 24904,
"text": "PHP"
},
{
"code": null,
"e": 24919,
"s": 24908,
"text": "Javascript"
},
{
"code": "// C++ program to print the sum// of all numbers in range L and R#include <bits/stdc++.h>using namespace std; // Function to return the sum of// all natural numbersint sumNatural(int n){ int sum = (n * (n + 1)) / 2; return sum;} // Function to return the sum// of all numbers in range L and Rint suminRange(int l, int r){ return sumNatural(r) - sumNatural(l - 1);} // Driver Codeint main(){ int l = 2, r = 5; cout << \"Sum of Natural numbers from L to R is \" << suminRange(l, r); return 0;}",
"e": 25436,
"s": 24919,
"text": null
},
{
"code": "// Java program to print the sum// of all numbers in range L and R class GFG{// Function to return the sum of// all natural numbersstatic int sumNatural(int n){ int sum = (n * (n + 1)) / 2; return sum;} // Function to return the sum// of all numbers in range L and Rstatic int suminRange(int l, int r){ return sumNatural(r) - sumNatural(l - 1);} // Driver Codepublic static void main(String[] args){ int l = 2, r = 5; System.out.println(\"Sum of Natural numbers from L to R is \"+suminRange(l, r)); }}// This code is contributed by mits",
"e": 25986,
"s": 25436,
"text": null
},
{
"code": "# Python3 program to print the sum of# all numbers in range L and R # Function to return the sum of all natural numbersdef sumNatural(n): sum = (n*(n+1))//2 return sum # Function to return the sum# of all numbers in range L and Rdef suminRange(l, r): return sumNatural(r) - sumNatural(l-1) # Driver Codel =2; r= 5print(\"Sum of Natural numbers from L to R is \",suminRange(l, r)) # This code is contributed by Shrikant13",
"e": 26418,
"s": 25986,
"text": null
},
{
"code": "// C# program to print the sum// of all numbers in range L and Rusing System; class GFG{// Function to return the sum// of all natural numbersstatic int sumNatural(int n){ int sum = (n * (n + 1)) / 2; return sum;} // Function to return the sum// of all numbers in range L and Rstatic int suminRange(int l, int r){ return sumNatural(r) - sumNatural(l - 1);} // Driver Codestatic public void Main (){ int l = 2, r = 5; Console.WriteLine(\"Sum of Natural numbers \" + \"from L to R is \" + suminRange(l, r));}} // This code is contributed by akt_mit",
"e": 27045,
"s": 26418,
"text": null
},
{
"code": "<?php// PHP program to print the sum// of all numbers in range L and R // Function to return the sum of// all natural numbersfunction sumNatural($n){ $sum = ($n * ($n + 1)) / 2; return $sum;} // Function to return the sum// of all numbers in range L and Rfunction suminRange($l, $r){ return sumNatural($r) - sumNatural($l - 1);} // Driver Code$l = 2;$r = 5;echo \"Sum of Natural numbers \" . \"from L to R is \", suminRange($l, $r); // This code is contributed by ajit?>",
"e": 27556,
"s": 27045,
"text": null
},
{
"code": "<script>// JavaScript program to print the sum// of all numbers in range L and R // Function to return the sum of// all natural numbersfunction sumNatural(n){ sum = (n * (n + 1)) / 2; return sum;} // Function to return the sum// of all numbers in range L and Rfunction suminRange(l, r){ return sumNatural(r) - sumNatural(l - 1);} // Driver Codelet l = 2;let r = 5;document.write(\"Sum of Natural numbers from L to R is \"+ suminRange(l, r)); // This code is contributed by sravan kumar gottumukkalan </script>",
"e": 28095,
"s": 27556,
"text": null
},
{
"code": null,
"e": 28136,
"s": 28095,
"text": "Sum of Natural numbers from L to R is 14"
},
{
"code": null,
"e": 28151,
"s": 28138,
"text": "Mithun Kumar"
},
{
"code": null,
"e": 28157,
"s": 28151,
"text": "jit_t"
},
{
"code": null,
"e": 28169,
"s": 28157,
"text": "shrikanth13"
},
{
"code": null,
"e": 28185,
"s": 28169,
"text": "sravankumar8128"
},
{
"code": null,
"e": 28192,
"s": 28185,
"text": "series"
},
{
"code": null,
"e": 28203,
"s": 28192,
"text": "series-sum"
},
{
"code": null,
"e": 28216,
"s": 28203,
"text": "Mathematical"
},
{
"code": null,
"e": 28229,
"s": 28216,
"text": "Mathematical"
},
{
"code": null,
"e": 28236,
"s": 28229,
"text": "series"
},
{
"code": null,
"e": 28334,
"s": 28236,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28343,
"s": 28334,
"text": "Comments"
},
{
"code": null,
"e": 28356,
"s": 28343,
"text": "Old Comments"
},
{
"code": null,
"e": 28401,
"s": 28356,
"text": "Find all factors of a natural number | Set 1"
},
{
"code": null,
"e": 28433,
"s": 28401,
"text": "Check if a number is Palindrome"
},
{
"code": null,
"e": 28477,
"s": 28433,
"text": "Program to print prime numbers from 1 to N."
},
{
"code": null,
"e": 28502,
"s": 28477,
"text": "Fizz Buzz Implementation"
},
{
"code": null,
"e": 28535,
"s": 28502,
"text": "Program to multiply two matrices"
},
{
"code": null,
"e": 28569,
"s": 28535,
"text": "Program to add two binary strings"
},
{
"code": null,
"e": 28620,
"s": 28569,
"text": "Find Union and Intersection of two unsorted arrays"
},
{
"code": null,
"e": 28655,
"s": 28620,
"text": "Count ways to reach the n'th stair"
},
{
"code": null,
"e": 28706,
"s": 28655,
"text": "Add two numbers without using arithmetic operators"
}
] |
Extracting information from XML files into a Pandas dataframe | by Parul Pandey | Towards Data Science
|
Real-world data is messy, and we know it. Not only does such data require a lot of cleaning, a lot of times, the format in which we receive data is also not suited for analysis. This means that before the analysis even begins, the data has to undergo a series of transformations to get it into a suitable format — a format that makes it easy to work upon. This happens mostly when the data is either scraped from the web or is provided in the form of documents. I came across a pretty similar dataset, which was in the form of various XML files. In this article, I lay down the steps I took to decipher those files and convert them into an analysis-ready CSV file good enough to be ingested into the pandas' library for further analysis.
This article is part of a complete series on finding good datasets. Here are all the articles included in the series:
Part 1: Getting Datasets for Data Analysis tasks — Advanced Google Search
Part 2: Useful sites for finding datasets for Data Analysis tasks
Part 3: Creating custom image datasets for Deep Learning projects
Part 4: Import HTML tables into Google Sheets effortlessly
Part 5: Extracting tabular data from PDFs made easy with Camelot.
Part 6: Extracting information from XML files into a Pandas dataframe
Part 7: 5 Real-World datasets for honing your Exploratory Data Analysis skills
The entire world is collectively fighting the COVID-19 war, and the year 2021 brings a glimmer of hope. We are all aware of the vaccination drive being conducted by many countries, including my own country India, which began the world’s largest vaccination drive on 16th Jan 2021. But a vaccine takes its final form after going through several phases and trials, and only after it is deemed fit, it is given a green flag to be administered to the general population.
I discovered ClinicalTrials.gov, a database of privately and publicly funded clinical studies conducted around the world. I thought it would be pretty interesting and informative to look at all the clinical trials related to COVID 19 studies presented on the site.
However, the trials’ dataset consists of XML files where each XML file corresponds to one study. Thus, it is not possible to immediately jump to analysis. The data needs to be first into a format that could be read into a pandas dataframe. I have downloaded the dataset and uploaded it on Kaggle for others to look into it. The data is updated every week and provides some great insights into COVID vaccines and medicines' development.
The rest of the article will deal with parsing these XML files in Python. But before that, let’s dive a little deeper into an XML file and its constituents.
XML stands for Extensible Markup Language. As the name suggests, it is a markup language that encodes documents by defining a set of rules in both machine-readable and human-readable format. The language defines a set of rules that are used to encode a document in a specific format. Let’s look at an example of an XML file below:
<?xml version="1.0" encoding="UTF-8"?><class> <student> <name>Negan</name> <age>40</age> <email>imnegan@abc.com</email> <address> <country>US</country> </address> </student></class>
Every XML file has a tree structure where the element at the top is the root element. The child elements are then connected to the root elements. if presented visually, the tree structure of the above XML document would look like this:
XML version = “1.0” encoding = “UTF-8”?: <XML version and the character encoding>
Root element: <Class>
Child elements of Student element: <name>, <age>, <email> & <address>
Sub-child elements: <country>
Let’s now see how we can parse a given XML file and extract its data in a structured way. In this article, we will look at ElementTree a built-in Python library to manipulate XML files. We have already been introduced to the dataset. Here is a glimpse of how it looks on Kaggle:
The dataset consists of few thousand XML files. Each XML file corresponds to one study. The filename is the NCT number, which a unique identifier of a survey in the ClinicalTrials repository.
Let’s start by importing the necessary libraries and looking at the number of files in the dataset.
import xml.etree.ElementTree as ETpath = '../input/covid19-clinical-trials-dataset/COVID-19 CLinical trials studies/'files = os.listdir(path)print(len(files))------------------------------------------------4663
There are 4663 individual files in the dataset. This number above corresponds to the number of XML files in the data, including the number of clinical trial reports. Let’s now look at the first XML file and print out values to understand how the tree is structured.
# Reading the first filefile_path_file1 = os.path.join(path, list_of_files[0])tree = ElementTree.parse(file_path_file1)root = tree.getroot()print(root.tag, root.attrib)--------------------------------------------------------clinical_study {'rank': '4406'}
ElementTree represents the whole XML document as a tree, while Element represents a single node in this tree. Every part of a tree (root included) has a tag that describes the element. Additionally, elements may also contain attributes which, as the name suggests, are additional descriptors. If you’ll look closely at the XML example provided above — clinical study is the root element and has a rank attribute that equals 4406.
We can now look at some of the other child elements by using a simple for loop.
for child in root: print(child.tag, child.attrib)
All the above elements appear to be the different sections of the report. One can also look at the entire document and all the attributes or levels in the tree via the code below.
print(ElementTree.tostring(root, encoding='utf8').decode('utf8'))
We can then choose to include all or a select few elements in our formatted data. These elements will appear as separate columns in the dataframe. We'll now initialize two empty data frames, which will be populated with the above elements. We’ll include id,overall_status, study_type, start_date, enrollment, condition, location_countries, intervention, title, date_processed and sponsors in our dataset.
This gives us a nicely formatted dataframe, just like the ones that we are used to seeing. You can also save it as a CSV file for future reference.
df.head()df_covid.to_csv('COVID_trials.csv')
Now that you have the data in the desired format, you can analyze it to elicit specific details like :
what is the overall status of the studies
The different study types
The timeline of the trials
The number of people enrolled in various studies, and many more such questions.
You can also create a dashboard with the tools of your choice so that it becomes easy to see all the details at once. I have only extracted few attributes in the example above, but there are plenty in the report. Go ahead and experiment with the others, too, to understand more about the data. Like It is mentioned. The dataset is available for public use, and it is waiting to be explored further.
COVID-19 Clinical Trials dataset: Database of COVID-19 related clinical studies being conducted worldwide
|
[
{
"code": null,
"e": 910,
"s": 172,
"text": "Real-world data is messy, and we know it. Not only does such data require a lot of cleaning, a lot of times, the format in which we receive data is also not suited for analysis. This means that before the analysis even begins, the data has to undergo a series of transformations to get it into a suitable format — a format that makes it easy to work upon. This happens mostly when the data is either scraped from the web or is provided in the form of documents. I came across a pretty similar dataset, which was in the form of various XML files. In this article, I lay down the steps I took to decipher those files and convert them into an analysis-ready CSV file good enough to be ingested into the pandas' library for further analysis."
},
{
"code": null,
"e": 1028,
"s": 910,
"text": "This article is part of a complete series on finding good datasets. Here are all the articles included in the series:"
},
{
"code": null,
"e": 1102,
"s": 1028,
"text": "Part 1: Getting Datasets for Data Analysis tasks — Advanced Google Search"
},
{
"code": null,
"e": 1168,
"s": 1102,
"text": "Part 2: Useful sites for finding datasets for Data Analysis tasks"
},
{
"code": null,
"e": 1234,
"s": 1168,
"text": "Part 3: Creating custom image datasets for Deep Learning projects"
},
{
"code": null,
"e": 1293,
"s": 1234,
"text": "Part 4: Import HTML tables into Google Sheets effortlessly"
},
{
"code": null,
"e": 1359,
"s": 1293,
"text": "Part 5: Extracting tabular data from PDFs made easy with Camelot."
},
{
"code": null,
"e": 1429,
"s": 1359,
"text": "Part 6: Extracting information from XML files into a Pandas dataframe"
},
{
"code": null,
"e": 1508,
"s": 1429,
"text": "Part 7: 5 Real-World datasets for honing your Exploratory Data Analysis skills"
},
{
"code": null,
"e": 1975,
"s": 1508,
"text": "The entire world is collectively fighting the COVID-19 war, and the year 2021 brings a glimmer of hope. We are all aware of the vaccination drive being conducted by many countries, including my own country India, which began the world’s largest vaccination drive on 16th Jan 2021. But a vaccine takes its final form after going through several phases and trials, and only after it is deemed fit, it is given a green flag to be administered to the general population."
},
{
"code": null,
"e": 2240,
"s": 1975,
"text": "I discovered ClinicalTrials.gov, a database of privately and publicly funded clinical studies conducted around the world. I thought it would be pretty interesting and informative to look at all the clinical trials related to COVID 19 studies presented on the site."
},
{
"code": null,
"e": 2676,
"s": 2240,
"text": "However, the trials’ dataset consists of XML files where each XML file corresponds to one study. Thus, it is not possible to immediately jump to analysis. The data needs to be first into a format that could be read into a pandas dataframe. I have downloaded the dataset and uploaded it on Kaggle for others to look into it. The data is updated every week and provides some great insights into COVID vaccines and medicines' development."
},
{
"code": null,
"e": 2833,
"s": 2676,
"text": "The rest of the article will deal with parsing these XML files in Python. But before that, let’s dive a little deeper into an XML file and its constituents."
},
{
"code": null,
"e": 3164,
"s": 2833,
"text": "XML stands for Extensible Markup Language. As the name suggests, it is a markup language that encodes documents by defining a set of rules in both machine-readable and human-readable format. The language defines a set of rules that are used to encode a document in a specific format. Let’s look at an example of an XML file below:"
},
{
"code": null,
"e": 3366,
"s": 3164,
"text": "<?xml version=\"1.0\" encoding=\"UTF-8\"?><class> <student> <name>Negan</name> <age>40</age> <email>imnegan@abc.com</email> <address> <country>US</country> </address> </student></class>"
},
{
"code": null,
"e": 3602,
"s": 3366,
"text": "Every XML file has a tree structure where the element at the top is the root element. The child elements are then connected to the root elements. if presented visually, the tree structure of the above XML document would look like this:"
},
{
"code": null,
"e": 3684,
"s": 3602,
"text": "XML version = “1.0” encoding = “UTF-8”?: <XML version and the character encoding>"
},
{
"code": null,
"e": 3706,
"s": 3684,
"text": "Root element: <Class>"
},
{
"code": null,
"e": 3776,
"s": 3706,
"text": "Child elements of Student element: <name>, <age>, <email> & <address>"
},
{
"code": null,
"e": 3806,
"s": 3776,
"text": "Sub-child elements: <country>"
},
{
"code": null,
"e": 4085,
"s": 3806,
"text": "Let’s now see how we can parse a given XML file and extract its data in a structured way. In this article, we will look at ElementTree a built-in Python library to manipulate XML files. We have already been introduced to the dataset. Here is a glimpse of how it looks on Kaggle:"
},
{
"code": null,
"e": 4277,
"s": 4085,
"text": "The dataset consists of few thousand XML files. Each XML file corresponds to one study. The filename is the NCT number, which a unique identifier of a survey in the ClinicalTrials repository."
},
{
"code": null,
"e": 4377,
"s": 4277,
"text": "Let’s start by importing the necessary libraries and looking at the number of files in the dataset."
},
{
"code": null,
"e": 4588,
"s": 4377,
"text": "import xml.etree.ElementTree as ETpath = '../input/covid19-clinical-trials-dataset/COVID-19 CLinical trials studies/'files = os.listdir(path)print(len(files))------------------------------------------------4663"
},
{
"code": null,
"e": 4854,
"s": 4588,
"text": "There are 4663 individual files in the dataset. This number above corresponds to the number of XML files in the data, including the number of clinical trial reports. Let’s now look at the first XML file and print out values to understand how the tree is structured."
},
{
"code": null,
"e": 5110,
"s": 4854,
"text": "# Reading the first filefile_path_file1 = os.path.join(path, list_of_files[0])tree = ElementTree.parse(file_path_file1)root = tree.getroot()print(root.tag, root.attrib)--------------------------------------------------------clinical_study {'rank': '4406'}"
},
{
"code": null,
"e": 5540,
"s": 5110,
"text": "ElementTree represents the whole XML document as a tree, while Element represents a single node in this tree. Every part of a tree (root included) has a tag that describes the element. Additionally, elements may also contain attributes which, as the name suggests, are additional descriptors. If you’ll look closely at the XML example provided above — clinical study is the root element and has a rank attribute that equals 4406."
},
{
"code": null,
"e": 5620,
"s": 5540,
"text": "We can now look at some of the other child elements by using a simple for loop."
},
{
"code": null,
"e": 5674,
"s": 5620,
"text": "for child in root: print(child.tag, child.attrib)"
},
{
"code": null,
"e": 5854,
"s": 5674,
"text": "All the above elements appear to be the different sections of the report. One can also look at the entire document and all the attributes or levels in the tree via the code below."
},
{
"code": null,
"e": 5920,
"s": 5854,
"text": "print(ElementTree.tostring(root, encoding='utf8').decode('utf8'))"
},
{
"code": null,
"e": 6325,
"s": 5920,
"text": "We can then choose to include all or a select few elements in our formatted data. These elements will appear as separate columns in the dataframe. We'll now initialize two empty data frames, which will be populated with the above elements. We’ll include id,overall_status, study_type, start_date, enrollment, condition, location_countries, intervention, title, date_processed and sponsors in our dataset."
},
{
"code": null,
"e": 6473,
"s": 6325,
"text": "This gives us a nicely formatted dataframe, just like the ones that we are used to seeing. You can also save it as a CSV file for future reference."
},
{
"code": null,
"e": 6518,
"s": 6473,
"text": "df.head()df_covid.to_csv('COVID_trials.csv')"
},
{
"code": null,
"e": 6621,
"s": 6518,
"text": "Now that you have the data in the desired format, you can analyze it to elicit specific details like :"
},
{
"code": null,
"e": 6663,
"s": 6621,
"text": "what is the overall status of the studies"
},
{
"code": null,
"e": 6689,
"s": 6663,
"text": "The different study types"
},
{
"code": null,
"e": 6716,
"s": 6689,
"text": "The timeline of the trials"
},
{
"code": null,
"e": 6796,
"s": 6716,
"text": "The number of people enrolled in various studies, and many more such questions."
},
{
"code": null,
"e": 7195,
"s": 6796,
"text": "You can also create a dashboard with the tools of your choice so that it becomes easy to see all the details at once. I have only extracted few attributes in the example above, but there are plenty in the report. Go ahead and experiment with the others, too, to understand more about the data. Like It is mentioned. The dataset is available for public use, and it is waiting to be explored further."
}
] |
Check if both halves of a string are Palindrome or not - GeeksforGeeks
|
02 Feb, 2022
Given a string str, the task is to check whether the given string can be split into two halves, each of which is palindromic. If it is possible, print Yes. Otherwise, print No.Examples:
Input: str = “naan” Output: No Explanation: Since both halves “na” and “an” are not palindrome.Input: momdad Output: Yes Explanation: Since both half “mom” and “dad” are palindromes.
Approach: Follow the steps below to solve the problem:
Iterate over the first ((N / 2) / 2 – 1) indices of the string.
Simultaneously check if both the halves are palindrome or not by the following two conditions: If S[i] is not equal to S[N/2 – 1 – i], then first half is not palindromic.If S[N/2 + i] is not equal to S[N – 1 – i], then second half is not palindromic.
If S[i] is not equal to S[N/2 – 1 – i], then first half is not palindromic.
If S[N/2 + i] is not equal to S[N – 1 – i], then second half is not palindromic.
If none of the above condition is satisfied even once during the iteration, then both halves are palindromic. Print Yes.
Otherwise, print No.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ Program to check whether// both halves of a string is// Palindrome or not#include <bits/stdc++.h>using namespace std; // Function to check if both halves// of a string are palindrome or notvoid checkPalindrome(string S){ // Length of string int N = S.size(); // Initialize both part as true bool first_half = true; bool second_half = true; int cnt = (N / 2) - 1; for (int i = 0; i < ((N / 2) / 2); i++) { // If first half is not palindrome if (S[i] != S[cnt]) { first_half = false; break; } // If second half is not palindrome if (S[N / 2 + i] != S[N / 2 + cnt]) { second_half - false; break; } cnt--; } // If both halves are Palindrome if (first_half && second_half) { cout << "Yes" << endl; } else { cout << "No" << endl; }} int main(){ string S = "momdad"; checkPalindrome(S); return 0;}
// Java Program to check whether// both halves of a string is// Palindrome or notpublic class Main { // Function to check and return if // both halves of a string are // palindromic or not public static void checkPalindrome( String S) { // Length of string int N = S.length(); // Initialize both part as true boolean first_half = true; boolean second_half = true; int cnt = (N / 2) - 1; for (int i = 0; i < (N / 2); i++) { // If first half is not palindrome if (S.charAt(i) != S.charAt(cnt)) { first_half = false; break; } // If second half is not palindrome if (S.charAt(N / 2 + i) != S.charAt(N / 2 + cnt)) { second_half = false; break; } cnt--; } // If both halves are Palindrome if (first_half && second_half) { System.out.println("Yes"); } else { System.out.println("No"); } } // Driver Code public static void main(String[] args) { String S = "momdad"; checkPalindrome(S); }}
# Python3 program to check whether# both halves of a string is# palindrome or not # Function to check if both halves# of a string are palindrome or notdef checkPalindrome(S): # Length of string n = len(S) # Initialize both part as true first_half = True second_half = True cnt = (n // 2) - 1 for i in range(0, int((n / 2) / 2)): # If first half is not palindrome if (S[i] != S[cnt]): first_half = False break # If second half is not palindrome if (S[n // 2 + i] != S[n // 2 + cnt]): second_half = False break cnt -= 1 # If both halves are palindrome if (first_half and second_half): print('Yes', end = '') else: print('No', end = '') # Driver codeif __name__=='__main__': S = 'momdad' checkPalindrome(S) # This code is contributed by virusbuddah_
// C# program to check whether// both halves of a string is// Palindrome or notusing System; class GFG{ // Function to check and return if// both halves of a string are// palindromic or notpublic static void checkPalindrome(String S){ // Length of string int N = S.Length; // Initialize both part as true bool first_half = true; bool second_half = true; int cnt = (N / 2) - 1; for(int i = 0; i < (N / 2); i++) { // If first half is not palindrome if (S[i] != S[cnt]) { first_half = false; break; } // If second half is not palindrome if (S[N / 2 + i] != S[N / 2 + cnt]) { second_half = false; break; } cnt--; } // If both halves are Palindrome if (first_half && second_half) { Console.Write("Yes"); } else { Console.Write("No"); }} // Driver codepublic static void Main(){ String S = "momdad"; checkPalindrome(S);}} // This code is contributed by grand_master
<script> // JavaScript Program to check whether// both halves of a string is// Palindrome or not // Function to check and return if // both halves of a string are // palindromic or not function checkPalindrome( S) { // Length of string var N = S.length; // Initialize both part as true var first_half = true; var second_half = true; var cnt = parseInt((N / 2)) - 1; for (i = 0; i < (N / 2); i++) { // If first half is not palindrome if (S.charAt(i) != S.charAt(cnt)) { first_half = false; break; } // If second half is not palindrome if (S.charAt(N / 2 + i) != S.charAt(N / 2 + cnt)) { second_half = false; break; } cnt--; } // If both halves are Palindrome if (first_half && second_half) { document.write("Yes"); } else { document.write("No"); } } // Driver Code var S = "momdad"; checkPalindrome(S); // This code contributed by aashish1995 </script>
Yes
Time Complexity: O(N) Auxiliary Space: O(1)
virusbuddha
grand_master
aashish1995
sumitgumber28
palindrome
Searching
Strings
Searching
Strings
palindrome
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
k largest(or smallest) elements in an array
Given an array of size n and a number k, find all elements that appear more than n/k times
Median of two sorted arrays of different sizes
Most frequent element in an array
Find the index of an array element in Java
Reverse a string in Java
Write a program to reverse an array or string
Longest Common Subsequence | DP-4
C++ Data Types
Write a program to print all permutations of a given string
|
[
{
"code": null,
"e": 24961,
"s": 24933,
"text": "\n02 Feb, 2022"
},
{
"code": null,
"e": 25149,
"s": 24961,
"text": "Given a string str, the task is to check whether the given string can be split into two halves, each of which is palindromic. If it is possible, print Yes. Otherwise, print No.Examples: "
},
{
"code": null,
"e": 25334,
"s": 25149,
"text": "Input: str = “naan” Output: No Explanation: Since both halves “na” and “an” are not palindrome.Input: momdad Output: Yes Explanation: Since both half “mom” and “dad” are palindromes. "
},
{
"code": null,
"e": 25393,
"s": 25336,
"text": "Approach: Follow the steps below to solve the problem: "
},
{
"code": null,
"e": 25457,
"s": 25393,
"text": "Iterate over the first ((N / 2) / 2 – 1) indices of the string."
},
{
"code": null,
"e": 25708,
"s": 25457,
"text": "Simultaneously check if both the halves are palindrome or not by the following two conditions: If S[i] is not equal to S[N/2 – 1 – i], then first half is not palindromic.If S[N/2 + i] is not equal to S[N – 1 – i], then second half is not palindromic."
},
{
"code": null,
"e": 25784,
"s": 25708,
"text": "If S[i] is not equal to S[N/2 – 1 – i], then first half is not palindromic."
},
{
"code": null,
"e": 25865,
"s": 25784,
"text": "If S[N/2 + i] is not equal to S[N – 1 – i], then second half is not palindromic."
},
{
"code": null,
"e": 25986,
"s": 25865,
"text": "If none of the above condition is satisfied even once during the iteration, then both halves are palindromic. Print Yes."
},
{
"code": null,
"e": 26007,
"s": 25986,
"text": "Otherwise, print No."
},
{
"code": null,
"e": 26059,
"s": 26007,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 26063,
"s": 26059,
"text": "C++"
},
{
"code": null,
"e": 26068,
"s": 26063,
"text": "Java"
},
{
"code": null,
"e": 26076,
"s": 26068,
"text": "Python3"
},
{
"code": null,
"e": 26079,
"s": 26076,
"text": "C#"
},
{
"code": null,
"e": 26090,
"s": 26079,
"text": "Javascript"
},
{
"code": "// C++ Program to check whether// both halves of a string is// Palindrome or not#include <bits/stdc++.h>using namespace std; // Function to check if both halves// of a string are palindrome or notvoid checkPalindrome(string S){ // Length of string int N = S.size(); // Initialize both part as true bool first_half = true; bool second_half = true; int cnt = (N / 2) - 1; for (int i = 0; i < ((N / 2) / 2); i++) { // If first half is not palindrome if (S[i] != S[cnt]) { first_half = false; break; } // If second half is not palindrome if (S[N / 2 + i] != S[N / 2 + cnt]) { second_half - false; break; } cnt--; } // If both halves are Palindrome if (first_half && second_half) { cout << \"Yes\" << endl; } else { cout << \"No\" << endl; }} int main(){ string S = \"momdad\"; checkPalindrome(S); return 0;}",
"e": 27052,
"s": 26090,
"text": null
},
{
"code": "// Java Program to check whether// both halves of a string is// Palindrome or notpublic class Main { // Function to check and return if // both halves of a string are // palindromic or not public static void checkPalindrome( String S) { // Length of string int N = S.length(); // Initialize both part as true boolean first_half = true; boolean second_half = true; int cnt = (N / 2) - 1; for (int i = 0; i < (N / 2); i++) { // If first half is not palindrome if (S.charAt(i) != S.charAt(cnt)) { first_half = false; break; } // If second half is not palindrome if (S.charAt(N / 2 + i) != S.charAt(N / 2 + cnt)) { second_half = false; break; } cnt--; } // If both halves are Palindrome if (first_half && second_half) { System.out.println(\"Yes\"); } else { System.out.println(\"No\"); } } // Driver Code public static void main(String[] args) { String S = \"momdad\"; checkPalindrome(S); }}",
"e": 28261,
"s": 27052,
"text": null
},
{
"code": "# Python3 program to check whether# both halves of a string is# palindrome or not # Function to check if both halves# of a string are palindrome or notdef checkPalindrome(S): # Length of string n = len(S) # Initialize both part as true first_half = True second_half = True cnt = (n // 2) - 1 for i in range(0, int((n / 2) / 2)): # If first half is not palindrome if (S[i] != S[cnt]): first_half = False break # If second half is not palindrome if (S[n // 2 + i] != S[n // 2 + cnt]): second_half = False break cnt -= 1 # If both halves are palindrome if (first_half and second_half): print('Yes', end = '') else: print('No', end = '') # Driver codeif __name__=='__main__': S = 'momdad' checkPalindrome(S) # This code is contributed by virusbuddah_",
"e": 29227,
"s": 28261,
"text": null
},
{
"code": "// C# program to check whether// both halves of a string is// Palindrome or notusing System; class GFG{ // Function to check and return if// both halves of a string are// palindromic or notpublic static void checkPalindrome(String S){ // Length of string int N = S.Length; // Initialize both part as true bool first_half = true; bool second_half = true; int cnt = (N / 2) - 1; for(int i = 0; i < (N / 2); i++) { // If first half is not palindrome if (S[i] != S[cnt]) { first_half = false; break; } // If second half is not palindrome if (S[N / 2 + i] != S[N / 2 + cnt]) { second_half = false; break; } cnt--; } // If both halves are Palindrome if (first_half && second_half) { Console.Write(\"Yes\"); } else { Console.Write(\"No\"); }} // Driver codepublic static void Main(){ String S = \"momdad\"; checkPalindrome(S);}} // This code is contributed by grand_master",
"e": 30282,
"s": 29227,
"text": null
},
{
"code": "<script> // JavaScript Program to check whether// both halves of a string is// Palindrome or not // Function to check and return if // both halves of a string are // palindromic or not function checkPalindrome( S) { // Length of string var N = S.length; // Initialize both part as true var first_half = true; var second_half = true; var cnt = parseInt((N / 2)) - 1; for (i = 0; i < (N / 2); i++) { // If first half is not palindrome if (S.charAt(i) != S.charAt(cnt)) { first_half = false; break; } // If second half is not palindrome if (S.charAt(N / 2 + i) != S.charAt(N / 2 + cnt)) { second_half = false; break; } cnt--; } // If both halves are Palindrome if (first_half && second_half) { document.write(\"Yes\"); } else { document.write(\"No\"); } } // Driver Code var S = \"momdad\"; checkPalindrome(S); // This code contributed by aashish1995 </script>",
"e": 31431,
"s": 30282,
"text": null
},
{
"code": null,
"e": 31435,
"s": 31431,
"text": "Yes"
},
{
"code": null,
"e": 31482,
"s": 31437,
"text": "Time Complexity: O(N) Auxiliary Space: O(1) "
},
{
"code": null,
"e": 31494,
"s": 31482,
"text": "virusbuddha"
},
{
"code": null,
"e": 31507,
"s": 31494,
"text": "grand_master"
},
{
"code": null,
"e": 31519,
"s": 31507,
"text": "aashish1995"
},
{
"code": null,
"e": 31533,
"s": 31519,
"text": "sumitgumber28"
},
{
"code": null,
"e": 31544,
"s": 31533,
"text": "palindrome"
},
{
"code": null,
"e": 31554,
"s": 31544,
"text": "Searching"
},
{
"code": null,
"e": 31562,
"s": 31554,
"text": "Strings"
},
{
"code": null,
"e": 31572,
"s": 31562,
"text": "Searching"
},
{
"code": null,
"e": 31580,
"s": 31572,
"text": "Strings"
},
{
"code": null,
"e": 31591,
"s": 31580,
"text": "palindrome"
},
{
"code": null,
"e": 31689,
"s": 31591,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31698,
"s": 31689,
"text": "Comments"
},
{
"code": null,
"e": 31711,
"s": 31698,
"text": "Old Comments"
},
{
"code": null,
"e": 31755,
"s": 31711,
"text": "k largest(or smallest) elements in an array"
},
{
"code": null,
"e": 31846,
"s": 31755,
"text": "Given an array of size n and a number k, find all elements that appear more than n/k times"
},
{
"code": null,
"e": 31893,
"s": 31846,
"text": "Median of two sorted arrays of different sizes"
},
{
"code": null,
"e": 31927,
"s": 31893,
"text": "Most frequent element in an array"
},
{
"code": null,
"e": 31970,
"s": 31927,
"text": "Find the index of an array element in Java"
},
{
"code": null,
"e": 31995,
"s": 31970,
"text": "Reverse a string in Java"
},
{
"code": null,
"e": 32041,
"s": 31995,
"text": "Write a program to reverse an array or string"
},
{
"code": null,
"e": 32075,
"s": 32041,
"text": "Longest Common Subsequence | DP-4"
},
{
"code": null,
"e": 32090,
"s": 32075,
"text": "C++ Data Types"
}
] |
Python Pandas - Merge DataFrame with indicator value
|
To merge Pandas DataFrame, use the merge() function. In that, you can set the parameter indicator to True or False. If you want to check which dataframe has a specific record, then use −
indicator= True
As shown above, using above parameter as True, adds a column to the output DataFrame called “_merge”.
At first, let us import the pandas library with an alias −
import pandas as pd
Let us create DataFrame1 −
dataFrame1 = pd.DataFrame(
{
"Car": ['BMW', 'Lexus', 'Audi', 'Mustang', 'Bentley', 'Jaguar'],
"Units": [100, 150, 110, 80, 110, 90]
}
)
Create DataFrame2 −
dataFrame2 = pd.DataFrame(
{
"Car": ['BMW', 'Lexus', 'Tesla', 'Mustang', 'Mercedes', 'Jaguar'],
"Reg_Price": [7000, 1500, 5000, 8000, 9000, 6000]
}
)
Now, merge DataFrames with indicator value True −
# merge DataFrames with indicator value
mergedRes = pd.merge(dataFrame1, dataFrame2, how ="left",indicator=True)
Following is the code −
import pandas as pd
# Create DataFrame1
dataFrame1 = pd.DataFrame(
{
"Car": ['BMW', 'Lexus', 'Audi', 'Mustang', 'Bentley', 'Jaguar'],
"Units": [100, 150, 110, 80, 110, 90]
}
)
print"DataFrame1 ...\n",dataFrame1
# Create DataFrame2
dataFrame2 = pd.DataFrame(
{
"Car": ['BMW', 'Lexus', 'Tesla', 'Mustang', 'Mercedes', 'Jaguar'],
"Reg_Price": [7000, 1500, 5000, 8000, 9000, 6000]
}
)
print"\nDataFrame2 ...\n",dataFrame2
# merge DataFrames with indicator value
mergedRes = pd.merge(dataFrame1, dataFrame2, how ="left",indicator=True)
print"\nMerged dataframe...\n", mergedRes
This will produce the following output. Here, “both””in “_merge displays that both the value is in both the DataFrames −
DataFrame1 ...
Car Units
0 BMW 100
1 Lexus 150
2 Audi 110
3 Mustang 80
4 Bentley 110
5 Jaguar 90
DataFrame2 ...
Car Reg_Price
0 BMW 7000
1 Lexus 1500
2 Tesla 5000
3 Mustang 8000
4 Mercedes 9000
5 Jaguar 6000
Merged dataframe...
Car Units Reg_Price _merge
0 BMW 100 7000.0 both
1 Lexus 150 1500.0 both
2 Audi 110 NaN left_only
3 Mustang 80 8000.0 both
4 Bentley 110 NaN left_only
5 Jaguar 90 6000.0 both
|
[
{
"code": null,
"e": 1249,
"s": 1062,
"text": "To merge Pandas DataFrame, use the merge() function. In that, you can set the parameter indicator to True or False. If you want to check which dataframe has a specific record, then use −"
},
{
"code": null,
"e": 1265,
"s": 1249,
"text": "indicator= True"
},
{
"code": null,
"e": 1367,
"s": 1265,
"text": "As shown above, using above parameter as True, adds a column to the output DataFrame called “_merge”."
},
{
"code": null,
"e": 1426,
"s": 1367,
"text": "At first, let us import the pandas library with an alias −"
},
{
"code": null,
"e": 1447,
"s": 1426,
"text": "import pandas as pd\n"
},
{
"code": null,
"e": 1474,
"s": 1447,
"text": "Let us create DataFrame1 −"
},
{
"code": null,
"e": 1630,
"s": 1474,
"text": "dataFrame1 = pd.DataFrame(\n {\n \"Car\": ['BMW', 'Lexus', 'Audi', 'Mustang', 'Bentley', 'Jaguar'],\n \"Units\": [100, 150, 110, 80, 110, 90]\n }\n)\n\n"
},
{
"code": null,
"e": 1650,
"s": 1630,
"text": "Create DataFrame2 −"
},
{
"code": null,
"e": 1819,
"s": 1650,
"text": "dataFrame2 = pd.DataFrame(\n {\n \"Car\": ['BMW', 'Lexus', 'Tesla', 'Mustang', 'Mercedes', 'Jaguar'],\n \"Reg_Price\": [7000, 1500, 5000, 8000, 9000, 6000]\n\n }\n)"
},
{
"code": null,
"e": 1869,
"s": 1819,
"text": "Now, merge DataFrames with indicator value True −"
},
{
"code": null,
"e": 1984,
"s": 1869,
"text": "# merge DataFrames with indicator value\nmergedRes = pd.merge(dataFrame1, dataFrame2, how =\"left\",indicator=True)\n\n"
},
{
"code": null,
"e": 2008,
"s": 1984,
"text": "Following is the code −"
},
{
"code": null,
"e": 2625,
"s": 2008,
"text": "import pandas as pd\n\n# Create DataFrame1\ndataFrame1 = pd.DataFrame(\n {\n \"Car\": ['BMW', 'Lexus', 'Audi', 'Mustang', 'Bentley', 'Jaguar'],\n \"Units\": [100, 150, 110, 80, 110, 90]\n }\n)\n\nprint\"DataFrame1 ...\\n\",dataFrame1\n\n# Create DataFrame2\ndataFrame2 = pd.DataFrame(\n {\n \"Car\": ['BMW', 'Lexus', 'Tesla', 'Mustang', 'Mercedes', 'Jaguar'],\n \"Reg_Price\": [7000, 1500, 5000, 8000, 9000, 6000]\n\n }\n)\n\nprint\"\\nDataFrame2 ...\\n\",dataFrame2\n\n# merge DataFrames with indicator value\nmergedRes = pd.merge(dataFrame1, dataFrame2, how =\"left\",indicator=True)\nprint\"\\nMerged dataframe...\\n\", mergedRes\n\n"
},
{
"code": null,
"e": 2746,
"s": 2625,
"text": "This will produce the following output. Here, “both””in “_merge displays that both the value is in both the DataFrames −"
},
{
"code": null,
"e": 3374,
"s": 2746,
"text": "DataFrame1 ...\n Car Units\n0 BMW 100\n1 Lexus 150\n2 Audi 110\n3 Mustang 80\n4 Bentley 110\n5 Jaguar 90\n\nDataFrame2 ...\n Car Reg_Price\n0 BMW 7000\n1 Lexus 1500\n2 Tesla 5000\n3 Mustang 8000\n4 Mercedes 9000\n5 Jaguar 6000\n\nMerged dataframe...\n Car Units Reg_Price _merge\n0 BMW 100 7000.0 both\n1 Lexus 150 1500.0 both\n2 Audi 110 NaN left_only\n3 Mustang 80 8000.0 both\n4 Bentley 110 NaN left_only\n5 Jaguar 90 6000.0 both"
}
] |
C++ String Library - empty
|
It returns whether the string is empty (i.e. whether its length is 0).
Following is the declaration for std::string::empty.
bool empty() const;
bool empty() const noexcept;
none
it returns true if the string length is 0, false otherwise.
if an exception is thrown, there are no changes in the string.
In below example for std::string::empty.
#include <iostream>
#include <string>
int main () {
std::string content;
std::string line;
std::cout << "Please introduce a text. Enter an empty line to finish:\n";
do {
getline(std::cin,line);
content += line + '\n';
} while (!line.empty());
std::cout << "The text you introduced above was:\n" << content;
return 0;
}
The sample output should be like this −
Please introduce a text. Enter an empty line to finish:
sairamrkshna mammahe
The text you introduced above was:
sairamrkshna mammahe
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2674,
"s": 2603,
"text": "It returns whether the string is empty (i.e. whether its length is 0)."
},
{
"code": null,
"e": 2727,
"s": 2674,
"text": "Following is the declaration for std::string::empty."
},
{
"code": null,
"e": 2747,
"s": 2727,
"text": "bool empty() const;"
},
{
"code": null,
"e": 2776,
"s": 2747,
"text": "bool empty() const noexcept;"
},
{
"code": null,
"e": 2781,
"s": 2776,
"text": "none"
},
{
"code": null,
"e": 2841,
"s": 2781,
"text": "it returns true if the string length is 0, false otherwise."
},
{
"code": null,
"e": 2904,
"s": 2841,
"text": "if an exception is thrown, there are no changes in the string."
},
{
"code": null,
"e": 2945,
"s": 2904,
"text": "In below example for std::string::empty."
},
{
"code": null,
"e": 3298,
"s": 2945,
"text": "#include <iostream>\n#include <string>\n\nint main () {\n std::string content;\n std::string line;\n std::cout << \"Please introduce a text. Enter an empty line to finish:\\n\";\n do {\n getline(std::cin,line);\n content += line + '\\n';\n } while (!line.empty());\n std::cout << \"The text you introduced above was:\\n\" << content;\n return 0;\n}"
},
{
"code": null,
"e": 3338,
"s": 3298,
"text": "The sample output should be like this −"
},
{
"code": null,
"e": 3473,
"s": 3338,
"text": "Please introduce a text. Enter an empty line to finish:\nsairamrkshna mammahe\n\nThe text you introduced above was:\nsairamrkshna mammahe\n"
},
{
"code": null,
"e": 3480,
"s": 3473,
"text": " Print"
},
{
"code": null,
"e": 3491,
"s": 3480,
"text": " Add Notes"
}
] |
Sequential Parallel Transitions
|
Following is the program which demonstrates Sequential Transition in JavaFX. Save this code in a file with the name SequentialTransitionExample.java.
import javafx.animation.PathTransition;
import javafx.animation.ScaleTransition;
import javafx.animation.SequentialTransition;
import javafx.animation.TranslateTransition;
import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.paint.Color;
import javafx.scene.shape.Circle;
import javafx.scene.shape.CubicCurveTo;
import javafx.scene.shape.MoveTo;
import javafx.scene.shape.Path;
import javafx.stage.Stage;
import javafx.util.Duration;
public class SequentialTransitionExample extends Application {
@Override
public void start(Stage stage) {
//Drawing a Circle
Circle circle = new Circle();
//Setting the position of the circle
circle.setCenterX(150.0f);
circle.setCenterY(135.0f);
//Setting the radius of the circle
circle.setRadius(100.0f);
//Setting the color of the circle
circle.setFill(Color.BROWN);
//Setting the stroke width of the circle
circle.setStrokeWidth(20);
//Instantiating the path class
Path path = new Path();
//Creating the MoveTo path element
MoveTo moveTo = new MoveTo(100, 150);
//Creating the Cubic curve path element
CubicCurveTo cubicCurveTo = new CubicCurveTo(400, 40, 175, 250, 500, 150);
//Adding the path elements to Observable list of the Path class
path.getElements().add(moveTo);
path.getElements().add(cubicCurveTo);
//Creating path Transition
PathTransition pathTransition = new PathTransition();
//Setting the duration for the transition
pathTransition.setDuration(Duration.millis(1000));
//Setting the node for the transition
pathTransition.setNode(circle);
//Setting the path for the transition
pathTransition.setPath(path);
//Setting the orientation of the path
pathTransition.setOrientation(
PathTransition.OrientationType.ORTHOGONAL_TO_TAN GENT);
//Setting the cycle count for the transition
pathTransition.setCycleCount(5);
//Setting auto reverse value to false
pathTransition.setAutoReverse(false);
//Playing the animation
pathTransition.play();
//Creating Translate Transition
TranslateTransition translateTransition = new TranslateTransition();
//Setting the duration for the transition
pathTransition.setDuration(Duration.millis(1000));
//Setting the node for the transition
pathTransition.setNode(circle);
//Setting the length of the transition along x axis
translateTransition.setByX(300);
//Setting the cycle count for the stroke
translateTransition.setCycleCount(5);
//Setting auto reverse value to false
translateTransition.setAutoReverse(false);
//Applying scale Transition to the circle
ScaleTransition scaleTransition = new ScaleTransition();
//Setting the duration for the transition
pathTransition.setDuration(Duration.millis(1000));
//Setting the node for the transition
pathTransition.setNode(circle);
//Setting the dimensions for scaling
scaleTransition.setByY(1.5);
scaleTransition.setByX(1.5);
//Setting the cycle count for the translation
scaleTransition.setCycleCount(5);
//Setting auto reverse value to false
scaleTransition.setAutoReverse(false);
//Applying Sequential Translation to the circle
SequentialTransition sequentialTransition = new SequentialTransition(circle,
pathTransition, translateTransition, scaleTransition );
//Playing the animation
sequentialTransition.play();
//Creating a Group object
Group root = new Group(circle);
//Creating a scene object
Scene scene = new Scene(root, 600, 300);
//Setting title to the Stage
stage.setTitle("Seqiential transition example");
//Adding scene to the stage
stage.setScene(scene);
//Displaying the contents of the stage
stage.show();
}
public static void main(String args[]){
launch(args);
}
}
Compile and execute the saved java file from the command prompt using the following commands.
javac SequentialTransitionExample.java
java SequentialTransitionExample
On executing, the above program generates a JavaFX window as shown below.
Following is the program which demonstrates Parallel Transition in JavaFX. Save this code in a file with the name parallelTransitionExample.java.
import javafx.animation.ParallelTransition;
import javafx.animation.PathTransition;
import javafx.animation.ScaleTransition;
import javafx.animation.TranslateTransition;
import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.paint.Color;
import javafx.scene.shape.CubicCurveTo;
import javafx.scene.shape.MoveTo;
import javafx.scene.shape.Path;
import javafx.scene.shape.Rectangle;
import javafx.stage.Stage;
import javafx.util.Duration;
public class parallelTransitionExample extends Application {
@Override
public void start(Stage stage) {
//Drawing a Rectangle
Rectangle rectangle = new Rectangle();
//Setting the position of the rectangle
rectangle.setX(75.0f);
rectangle.setY(75.0f);
//Setting the width of the rectangle
rectangle.setWidth(100.0f);
//Setting the height of the rectangle
rectangle.setHeight(100.0f);
//setting the color of the rectangle
rectangle.setFill(Color.BLUEVIOLET);
//Instantiating the path class
Path path = new Path();
//Creating the MoveTo path element
MoveTo moveTo = new MoveTo(100, 150);
//Creating the Cubic curve path element
CubicCurveTo cubicCurveTo = new CubicCurveTo(400, 40, 175, 250, 500, 150);
//Adding the path elements to Observable list of the Path class
path.getElements().add(moveTo);
path.getElements().add(cubicCurveTo);
//Creating Path Transition
PathTransition pathTransition = new PathTransition();
//Setting the duration of the transition
pathTransition.setDuration(Duration.millis(1000));
//Setting the node for the transition
pathTransition.setNode(rectangle);
//Setting the path for the transition
pathTransition.setPath(path);
//Setting the orientation of the path
pathTransition.setOrientation(
PathTransition.OrientationType.ORTHOGONAL_TO_TAN GENT);
//Setting the cycle count for the transition
pathTransition.setCycleCount(5);
//Setting auto reverse value to false
pathTransition.setAutoReverse(false);
//Playing the animation
pathTransition.play();
//Creating Translate Transition
TranslateTransition translateTransition = new TranslateTransition();
//Setting the duration for the transition
translateTransition.setDuration(Duration.millis(1000));
//Setting the node for the transition
translateTransition.setNode(rectangle);
//Setting the axis and length of the transition
translateTransition.setByX(300);
//Setting the cycle count of the transition
translateTransition.setCycleCount(5);
//Setting auto reverse value to false
translateTransition.setAutoReverse(false);
//Creating scale Transition
ScaleTransition scaleTransition = new ScaleTransition();
//Setting the duration for the transition
translateTransition.setDuration(Duration.millis(1000));
//Setting the node for the transition
translateTransition.setNode(rectangle);
//Setting the dimensions for scaling
scaleTransition.setByY(1.5);
scaleTransition.setByX(1.5);
//Setting the cycle count for the translation
scaleTransition.setCycleCount(5);
//Setting auto reverse value to true
scaleTransition.setAutoReverse(false);
//Applying parallel Translation to the circle
ParallelTransition parallelTransition = new ParallelTransition(
rectangle, pathTransition, translateTransition, scaleTransition );
//Playing the animation
parallelTransition.play();
//Creating a Group object
Group root = new Group(rectangle);
//Creating a scene object
Scene scene = new Scene(root, 600, 300);
//Setting title to the Stage
stage.setTitle("Parallel Transition example");
//Adding scene to the stage
stage.setScene(scene);
//Displaying the contents of the stage
stage.show();
}
public static void main(String args[]){
launch(args);
}
}
Compile and execute the saved java file from the command prompt using the following commands.
javac parallelTransitionExample.java
java parallelTransitionExample
On executing, the above program generates a JavaFX window as shown below.
Following is the program which demonstrates Pause Transition in JavaFX. Save this code in a file with the name PauseTransitionExample.java.
import javafx.animation.PauseTransition;
import javafx.animation.ScaleTransition;
import javafx.animation.SequentialTransition;
import javafx.animation.TranslateTransition;
import javafx.application.Application;
import static javafx.application.Application.launch;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.paint.Color;
import javafx.scene.shape.Circle;
import javafx.stage.Stage;
import javafx.util.Duration;
public class PauseTransitionExample extends Application {
@Override
public void start(Stage stage) {
//Drawing a Circle
Circle circle = new Circle();
//Setting the position of the circle
circle.setCenterX(150.0f);
circle.setCenterY(135.0f);
//Setting the radius of the circle
circle.setRadius(50.0f);
//Setting the color of the circle
circle.setFill(Color.BROWN);
//Setting the stroke width of the circle
circle.setStrokeWidth(20);
//Creating a Pause Transition
PauseTransition pauseTransition = new PauseTransition();
//Setting the duration for the transition
pauseTransition.setDuration(Duration.millis(1000));
//Creating Translate Transition
TranslateTransition translateTransition = new TranslateTransition();
//Setting the duration for the transition
translateTransition.setDuration(Duration.millis(1000));
//Setting the node of the transition
translateTransition.setNode(circle);
//Setting the value of the transition along the x axis
translateTransition.setByX(300);
//Setting the cycle count for the stroke
translateTransition.setCycleCount(5);
//Setting auto reverse value to true
translateTransition.setAutoReverse(false);
//Creating scale Transition
ScaleTransition scaleTransition = new ScaleTransition();
//Setting the duration for the transition
scaleTransition.setDuration(Duration.millis(1000));
//Setting the node for the transition
scaleTransition.setNode(circle);
//Setting the dimensions for scaling
scaleTransition.setByY(1.5);
scaleTransition.setByX(1.5);
//Setting the cycle count for the translation
scaleTransition.setCycleCount(5);
//Setting auto reverse value to true
scaleTransition.setAutoReverse(false);
//Applying Sequential transition to the circle
SequentialTransition sequentialTransition = new SequentialTransition(
circle, translateTransition, pauseTransition, scaleTransition );
//Playing the animation
sequentialTransition.play();
//Creating a Group object
Group root = new Group(circle);
//Creating a scene object
Scene scene = new Scene(root, 600, 300);
//Setting title to the Stage
stage.setTitle("Pause transition example");
//Adding scene to the stage
stage.setScene(scene);
//Displaying the contents of the stage
stage.show();
}
public static void main(String args[]){
launch(args);
}
}
Compile and execute the saved java file from the command prompt using the following commands.
javac PauseTransitionExample.java
java PauseTransitionExample
On executing, the above program generates a JavaFX window as shown below.
33 Lectures
7.5 hours
Syed Raza
64 Lectures
12.5 hours
Emenwa Global, Ejike IfeanyiChukwu
20 Lectures
4 hours
Emenwa Global, Ejike IfeanyiChukwu
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2050,
"s": 1900,
"text": "Following is the program which demonstrates Sequential Transition in JavaFX. Save this code in a file with the name SequentialTransitionExample.java."
},
{
"code": null,
"e": 6516,
"s": 2050,
"text": "import javafx.animation.PathTransition; \nimport javafx.animation.ScaleTransition; \nimport javafx.animation.SequentialTransition; \nimport javafx.animation.TranslateTransition; \n\nimport javafx.application.Application; \n\nimport javafx.scene.Group; \nimport javafx.scene.Scene; \nimport javafx.scene.paint.Color; \nimport javafx.scene.shape.Circle; \nimport javafx.scene.shape.CubicCurveTo; \nimport javafx.scene.shape.MoveTo; \nimport javafx.scene.shape.Path; \n\nimport javafx.stage.Stage; \nimport javafx.util.Duration; \n \npublic class SequentialTransitionExample extends Application { \n @Override \n public void start(Stage stage) { \n //Drawing a Circle \n Circle circle = new Circle(); \n \n //Setting the position of the circle \n circle.setCenterX(150.0f); \n circle.setCenterY(135.0f); \n \n //Setting the radius of the circle \n circle.setRadius(100.0f); \n \n //Setting the color of the circle \n circle.setFill(Color.BROWN); \n \n //Setting the stroke width of the circle \n circle.setStrokeWidth(20); \n \n //Instantiating the path class \n Path path = new Path(); \n \n //Creating the MoveTo path element \n MoveTo moveTo = new MoveTo(100, 150); \n \n //Creating the Cubic curve path element \n CubicCurveTo cubicCurveTo = new CubicCurveTo(400, 40, 175, 250, 500, 150); \n \n //Adding the path elements to Observable list of the Path class \n path.getElements().add(moveTo); \n path.getElements().add(cubicCurveTo); \n \n //Creating path Transition \n PathTransition pathTransition = new PathTransition(); \n \n //Setting the duration for the transition \n pathTransition.setDuration(Duration.millis(1000)); \n \n //Setting the node for the transition \n pathTransition.setNode(circle); \n \n //Setting the path for the transition \n pathTransition.setPath(path); \n \n //Setting the orientation of the path \n pathTransition.setOrientation(\n PathTransition.OrientationType.ORTHOGONAL_TO_TAN GENT); \n \n //Setting the cycle count for the transition \n pathTransition.setCycleCount(5); \n \n //Setting auto reverse value to false \n pathTransition.setAutoReverse(false); \n \n //Playing the animation \n pathTransition.play(); \n \n //Creating Translate Transition \n TranslateTransition translateTransition = new TranslateTransition(); \n \n //Setting the duration for the transition \n pathTransition.setDuration(Duration.millis(1000)); \n \n //Setting the node for the transition \n pathTransition.setNode(circle); \n \n //Setting the length of the transition along x axis \n translateTransition.setByX(300); \n \n //Setting the cycle count for the stroke \n translateTransition.setCycleCount(5); \n \n //Setting auto reverse value to false \n translateTransition.setAutoReverse(false); \n \n //Applying scale Transition to the circle \n ScaleTransition scaleTransition = new ScaleTransition(); \n \n //Setting the duration for the transition \n pathTransition.setDuration(Duration.millis(1000)); \n \n //Setting the node for the transition \n pathTransition.setNode(circle); \n \n //Setting the dimensions for scaling \n scaleTransition.setByY(1.5); \n scaleTransition.setByX(1.5); \n \n //Setting the cycle count for the translation \n scaleTransition.setCycleCount(5); \n \n //Setting auto reverse value to false \n scaleTransition.setAutoReverse(false); \n \n //Applying Sequential Translation to the circle \n SequentialTransition sequentialTransition = new SequentialTransition(circle, \n pathTransition, translateTransition, scaleTransition ); \n \n //Playing the animation \n sequentialTransition.play(); \n \n //Creating a Group object \n Group root = new Group(circle); \n \n //Creating a scene object \n Scene scene = new Scene(root, 600, 300); \n \n //Setting title to the Stage \n stage.setTitle(\"Seqiential transition example\"); \n \n //Adding scene to the stage \n stage.setScene(scene); \n \n //Displaying the contents of the stage \n stage.show(); \n } \n public static void main(String args[]){ \n launch(args); \n } \n}"
},
{
"code": null,
"e": 6610,
"s": 6516,
"text": "Compile and execute the saved java file from the command prompt using the following commands."
},
{
"code": null,
"e": 6684,
"s": 6610,
"text": "javac SequentialTransitionExample.java \njava SequentialTransitionExample\n"
},
{
"code": null,
"e": 6758,
"s": 6684,
"text": "On executing, the above program generates a JavaFX window as shown below."
},
{
"code": null,
"e": 6904,
"s": 6758,
"text": "Following is the program which demonstrates Parallel Transition in JavaFX. Save this code in a file with the name parallelTransitionExample.java."
},
{
"code": null,
"e": 11401,
"s": 6904,
"text": "import javafx.animation.ParallelTransition; \nimport javafx.animation.PathTransition; \nimport javafx.animation.ScaleTransition; \nimport javafx.animation.TranslateTransition; \n\nimport javafx.application.Application; \n\nimport javafx.scene.Group; \nimport javafx.scene.Scene; \nimport javafx.scene.paint.Color; \nimport javafx.scene.shape.CubicCurveTo; \nimport javafx.scene.shape.MoveTo; \nimport javafx.scene.shape.Path; \nimport javafx.scene.shape.Rectangle; \n\nimport javafx.stage.Stage; \nimport javafx.util.Duration; \n \npublic class parallelTransitionExample extends Application { \n @Override \n public void start(Stage stage) { \n //Drawing a Rectangle \n Rectangle rectangle = new Rectangle(); \n \n //Setting the position of the rectangle \n rectangle.setX(75.0f); \n rectangle.setY(75.0f); \n \n //Setting the width of the rectangle \n rectangle.setWidth(100.0f); \n \n //Setting the height of the rectangle \n rectangle.setHeight(100.0f); \n \n //setting the color of the rectangle \n rectangle.setFill(Color.BLUEVIOLET); \n \n //Instantiating the path class \n Path path = new Path(); \n \n //Creating the MoveTo path element \n MoveTo moveTo = new MoveTo(100, 150); \n \n //Creating the Cubic curve path element \n CubicCurveTo cubicCurveTo = new CubicCurveTo(400, 40, 175, 250, 500, 150); \n \n //Adding the path elements to Observable list of the Path class \n path.getElements().add(moveTo); \n path.getElements().add(cubicCurveTo); \n \n //Creating Path Transition \n PathTransition pathTransition = new PathTransition(); \n \n //Setting the duration of the transition \n pathTransition.setDuration(Duration.millis(1000)); \n \n //Setting the node for the transition \n pathTransition.setNode(rectangle); \n \n //Setting the path for the transition \n pathTransition.setPath(path); \n \n //Setting the orientation of the path \n pathTransition.setOrientation(\n PathTransition.OrientationType.ORTHOGONAL_TO_TAN GENT); \n \n //Setting the cycle count for the transition \n pathTransition.setCycleCount(5); \n \n //Setting auto reverse value to false \n pathTransition.setAutoReverse(false); \n \n //Playing the animation \n pathTransition.play(); \n \n //Creating Translate Transition \n TranslateTransition translateTransition = new TranslateTransition(); \n \n //Setting the duration for the transition \n translateTransition.setDuration(Duration.millis(1000)); \n \n //Setting the node for the transition \n translateTransition.setNode(rectangle); \n \n //Setting the axis and length of the transition \n translateTransition.setByX(300); \n \n //Setting the cycle count of the transition \n translateTransition.setCycleCount(5); \n \n //Setting auto reverse value to false \n translateTransition.setAutoReverse(false); \n \n //Creating scale Transition \n ScaleTransition scaleTransition = new ScaleTransition(); \n \n //Setting the duration for the transition \n translateTransition.setDuration(Duration.millis(1000)); \n \n //Setting the node for the transition \n translateTransition.setNode(rectangle); \n \n //Setting the dimensions for scaling \n scaleTransition.setByY(1.5); \n scaleTransition.setByX(1.5); \n \n //Setting the cycle count for the translation \n scaleTransition.setCycleCount(5); \n \n //Setting auto reverse value to true \n scaleTransition.setAutoReverse(false); \n \n //Applying parallel Translation to the circle \n ParallelTransition parallelTransition = new ParallelTransition(\n rectangle, pathTransition, translateTransition, scaleTransition ); \n \n //Playing the animation \n parallelTransition.play(); \n \n //Creating a Group object \n Group root = new Group(rectangle); \n \n //Creating a scene object \n Scene scene = new Scene(root, 600, 300); \n \n //Setting title to the Stage \n stage.setTitle(\"Parallel Transition example\"); \n \n //Adding scene to the stage \n stage.setScene(scene); \n \n //Displaying the contents of the stage \n stage.show(); \n } \n public static void main(String args[]){ \n launch(args); \n } \n}"
},
{
"code": null,
"e": 11495,
"s": 11401,
"text": "Compile and execute the saved java file from the command prompt using the following commands."
},
{
"code": null,
"e": 11566,
"s": 11495,
"text": "javac parallelTransitionExample.java \njava parallelTransitionExample \n"
},
{
"code": null,
"e": 11640,
"s": 11566,
"text": "On executing, the above program generates a JavaFX window as shown below."
},
{
"code": null,
"e": 11780,
"s": 11640,
"text": "Following is the program which demonstrates Pause Transition in JavaFX. Save this code in a file with the name PauseTransitionExample.java."
},
{
"code": null,
"e": 15118,
"s": 11780,
"text": "import javafx.animation.PauseTransition; \nimport javafx.animation.ScaleTransition; \nimport javafx.animation.SequentialTransition; \nimport javafx.animation.TranslateTransition; \n\nimport javafx.application.Application; \nimport static javafx.application.Application.launch; \n\nimport javafx.scene.Group; \nimport javafx.scene.Scene; \nimport javafx.scene.paint.Color; \nimport javafx.scene.shape.Circle; \n \nimport javafx.stage.Stage; \nimport javafx.util.Duration; \n \npublic class PauseTransitionExample extends Application { \n @Override \n public void start(Stage stage) { \n //Drawing a Circle \n Circle circle = new Circle(); \n \n //Setting the position of the circle \n circle.setCenterX(150.0f); \n circle.setCenterY(135.0f); \n \n //Setting the radius of the circle \n circle.setRadius(50.0f); \n \n //Setting the color of the circle \n circle.setFill(Color.BROWN); \n \n //Setting the stroke width of the circle \n circle.setStrokeWidth(20); \n \n //Creating a Pause Transition\n PauseTransition pauseTransition = new PauseTransition(); \n \n //Setting the duration for the transition \n pauseTransition.setDuration(Duration.millis(1000)); \n \n //Creating Translate Transition \n TranslateTransition translateTransition = new TranslateTransition(); \n \n //Setting the duration for the transition \n translateTransition.setDuration(Duration.millis(1000)); \n \n //Setting the node of the transition \n translateTransition.setNode(circle); \n \n //Setting the value of the transition along the x axis \n translateTransition.setByX(300); \n \n //Setting the cycle count for the stroke \n translateTransition.setCycleCount(5); \n \n //Setting auto reverse value to true \n translateTransition.setAutoReverse(false); \n \n //Creating scale Transition \n ScaleTransition scaleTransition = new ScaleTransition(); \n \n //Setting the duration for the transition \n scaleTransition.setDuration(Duration.millis(1000)); \n \n //Setting the node for the transition \n scaleTransition.setNode(circle); \n \n //Setting the dimensions for scaling \n scaleTransition.setByY(1.5); \n scaleTransition.setByX(1.5); \n \n //Setting the cycle count for the translation \n scaleTransition.setCycleCount(5); \n \n //Setting auto reverse value to true \n scaleTransition.setAutoReverse(false); \n \n //Applying Sequential transition to the circle \n SequentialTransition sequentialTransition = new SequentialTransition(\n circle, translateTransition, pauseTransition, scaleTransition );\n \n //Playing the animation \n sequentialTransition.play(); \n \n //Creating a Group object \n Group root = new Group(circle); \n \n //Creating a scene object \n Scene scene = new Scene(root, 600, 300); \n \n //Setting title to the Stage \n stage.setTitle(\"Pause transition example\"); \n \n //Adding scene to the stage \n stage.setScene(scene); \n \n //Displaying the contents of the stage \n stage.show(); \n } \n public static void main(String args[]){ \n launch(args); \n } \n}"
},
{
"code": null,
"e": 15212,
"s": 15118,
"text": "Compile and execute the saved java file from the command prompt using the following commands."
},
{
"code": null,
"e": 15277,
"s": 15212,
"text": "javac PauseTransitionExample.java \njava PauseTransitionExample \n"
},
{
"code": null,
"e": 15351,
"s": 15277,
"text": "On executing, the above program generates a JavaFX window as shown below."
},
{
"code": null,
"e": 15386,
"s": 15351,
"text": "\n 33 Lectures \n 7.5 hours \n"
},
{
"code": null,
"e": 15397,
"s": 15386,
"text": " Syed Raza"
},
{
"code": null,
"e": 15433,
"s": 15397,
"text": "\n 64 Lectures \n 12.5 hours \n"
},
{
"code": null,
"e": 15469,
"s": 15433,
"text": " Emenwa Global, Ejike IfeanyiChukwu"
},
{
"code": null,
"e": 15502,
"s": 15469,
"text": "\n 20 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 15538,
"s": 15502,
"text": " Emenwa Global, Ejike IfeanyiChukwu"
},
{
"code": null,
"e": 15545,
"s": 15538,
"text": " Print"
},
{
"code": null,
"e": 15556,
"s": 15545,
"text": " Add Notes"
}
] |
Java Program to Set Minimum and Maximum Heap Size - GeeksforGeeks
|
09 Jun, 2021
The Heap area is one of the various memory areas present inside the JVM. For every JVM one heap area is available. The Heap area will be created at the time of the JVM startup. Objects and the corresponding instance variable will be stored in the heap area. Every array in java is the object only, hence the array also will be stored in the heap area. The Heap area can be accessed by multi threads hence the data store in heap memory is not threaded safe. The Heap area need not be continuous.
Program to display heap memory statistics:
A java application can communicate with VM by using a runtime object. Runtime class present in java.lang package and it is a singleton class. We can create a runtime object as follows:
Runtime r= Runtime.getRuntime();
Once we get the runtime object we can call the following methods on that object :
maxMemory() : It returns the number of bytes of max memory allocated to the heap.
totalMemory() : It returns the number of bytes of the total memory allocated to the heap.
freeMemory() : It returns the number of bytes of free memory present in the heap
Java
// import required packagesimport java.io.*;import java.lang.*;import java.util.*; // driver classclass heapMemory { // main method public static void main(String[] args) { // creating runtime time object Runtime r = Runtime.getRuntime(); // displaying max memory of heap in bytes System.out.println("Max memory" + " " + r.maxMemory()); // displaying initial memory in bytes System.out.println("Initial memory" + " " + r.totalMemory()); // displaying free memory in bytes System.out.println("Free memory" + " " + r.freeMemory()); // displaying consume memory in bytes System.out.println( "Consume memory" + " " + (r.totalMemory() - r.freeMemory())); }}
Max memory 134217728
Initial memory 134217728
Free memory 132286176
Consume memory 1931552
Heap memory is finite memory but based on our requirements we can set maximum and minimum heap size i.e we can increase or decrease the heap size based on our requirements. We can do this by using the following java commands at runtime.
1. -Xmx to set maximum heap size (max memory)
java -Xmx512m heapMemory
This command sets the maximum heap size as 512Mb.
Java
// import required packagesimport java.io.*;import java.lang.*;import java.util.*; // driver classclass heapMemory { // main method public static void main(String[] args) { double mb = 1000000; // creating runtime time object Runtime r = Runtime.getRuntime(); // displaying max memory of heap in Mb System.out.println("Max memory" + " " + r.maxMemory() / mb); // displaying initial memory in Mb System.out.println("Initial memory" + " " + r.totalMemory() / mb); // displaying free memory in Mb System.out.println("Free memory" + " " + r.freeMemory() / mb); // displaying consume memory in Mb System.out.println( "Consume memory" + " " + (r.totalMemory() - r.freeMemory()) / mb); }}
Max memory 134.217728
Initial memory 134.217728
Free memory 132.285184
Consume memory 1.932544
2. -Xms: we can use this command to set a minimum or initial heap size.
java -Xms64m heapMemory
This command set the minimum size as 64Mb i.e totalMemory().
Java
// import required packagesimport java.io.*;import java.lang.*;import java.util.*; // driver classclass heapMemory { // main method public static void main(String[] args) { double mb = 1000000; // creating runtime time object Runtime r = Runtime.getRuntime(); // displaying max memory of heap in Mb System.out.println("Max memory" + " " + r.maxMemory() / mb); // displaying initial memory in Mb System.out.println("Initial memory" + " " + r.totalMemory() / mb); // displaying free memory in Mb System.out.println("Free memory" + " " + r.freeMemory() / mb); // displaying consume memory in Mb System.out.println( "Consume memory" + " " + (r.totalMemory() - r.freeMemory()) / mb); }}
Max memory 134.217728
Initial memory 134.217728
Free memory 132.285192
Consume memory 1.932536
saurabh1990aror
Java
Java Programs
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Hashtable in Java
Constructors in Java
Different ways of Reading a text file in Java
Comparator Interface in Java with Examples
HashMap containsKey() Method in Java
Convert a String to Character array in Java
Java Programming Examples
Convert Double to Integer in Java
Implementing a Linked List in Java using Class
How to Iterate HashMap in Java?
|
[
{
"code": null,
"e": 23582,
"s": 23554,
"text": "\n09 Jun, 2021"
},
{
"code": null,
"e": 24078,
"s": 23582,
"text": "The Heap area is one of the various memory areas present inside the JVM. For every JVM one heap area is available. The Heap area will be created at the time of the JVM startup. Objects and the corresponding instance variable will be stored in the heap area. Every array in java is the object only, hence the array also will be stored in the heap area. The Heap area can be accessed by multi threads hence the data store in heap memory is not threaded safe. The Heap area need not be continuous."
},
{
"code": null,
"e": 24121,
"s": 24078,
"text": "Program to display heap memory statistics:"
},
{
"code": null,
"e": 24306,
"s": 24121,
"text": "A java application can communicate with VM by using a runtime object. Runtime class present in java.lang package and it is a singleton class. We can create a runtime object as follows:"
},
{
"code": null,
"e": 24339,
"s": 24306,
"text": "Runtime r= Runtime.getRuntime();"
},
{
"code": null,
"e": 24421,
"s": 24339,
"text": "Once we get the runtime object we can call the following methods on that object :"
},
{
"code": null,
"e": 24503,
"s": 24421,
"text": "maxMemory() : It returns the number of bytes of max memory allocated to the heap."
},
{
"code": null,
"e": 24593,
"s": 24503,
"text": "totalMemory() : It returns the number of bytes of the total memory allocated to the heap."
},
{
"code": null,
"e": 24674,
"s": 24593,
"text": "freeMemory() : It returns the number of bytes of free memory present in the heap"
},
{
"code": null,
"e": 24679,
"s": 24674,
"text": "Java"
},
{
"code": "// import required packagesimport java.io.*;import java.lang.*;import java.util.*; // driver classclass heapMemory { // main method public static void main(String[] args) { // creating runtime time object Runtime r = Runtime.getRuntime(); // displaying max memory of heap in bytes System.out.println(\"Max memory\" + \" \" + r.maxMemory()); // displaying initial memory in bytes System.out.println(\"Initial memory\" + \" \" + r.totalMemory()); // displaying free memory in bytes System.out.println(\"Free memory\" + \" \" + r.freeMemory()); // displaying consume memory in bytes System.out.println( \"Consume memory\" + \" \" + (r.totalMemory() - r.freeMemory())); }}",
"e": 25519,
"s": 24679,
"text": null
},
{
"code": null,
"e": 25610,
"s": 25519,
"text": "Max memory 134217728\nInitial memory 134217728\nFree memory 132286176\nConsume memory 1931552"
},
{
"code": null,
"e": 25847,
"s": 25610,
"text": "Heap memory is finite memory but based on our requirements we can set maximum and minimum heap size i.e we can increase or decrease the heap size based on our requirements. We can do this by using the following java commands at runtime."
},
{
"code": null,
"e": 25893,
"s": 25847,
"text": "1. -Xmx to set maximum heap size (max memory)"
},
{
"code": null,
"e": 25934,
"s": 25893,
"text": " java -Xmx512m heapMemory"
},
{
"code": null,
"e": 25984,
"s": 25934,
"text": "This command sets the maximum heap size as 512Mb."
},
{
"code": null,
"e": 25989,
"s": 25984,
"text": "Java"
},
{
"code": "// import required packagesimport java.io.*;import java.lang.*;import java.util.*; // driver classclass heapMemory { // main method public static void main(String[] args) { double mb = 1000000; // creating runtime time object Runtime r = Runtime.getRuntime(); // displaying max memory of heap in Mb System.out.println(\"Max memory\" + \" \" + r.maxMemory() / mb); // displaying initial memory in Mb System.out.println(\"Initial memory\" + \" \" + r.totalMemory() / mb); // displaying free memory in Mb System.out.println(\"Free memory\" + \" \" + r.freeMemory() / mb); // displaying consume memory in Mb System.out.println( \"Consume memory\" + \" \" + (r.totalMemory() - r.freeMemory()) / mb); }}",
"e": 26877,
"s": 25989,
"text": null
},
{
"code": null,
"e": 26972,
"s": 26877,
"text": "Max memory 134.217728\nInitial memory 134.217728\nFree memory 132.285184\nConsume memory 1.932544"
},
{
"code": null,
"e": 27044,
"s": 26972,
"text": "2. -Xms: we can use this command to set a minimum or initial heap size."
},
{
"code": null,
"e": 27070,
"s": 27044,
"text": " java -Xms64m heapMemory"
},
{
"code": null,
"e": 27131,
"s": 27070,
"text": "This command set the minimum size as 64Mb i.e totalMemory()."
},
{
"code": null,
"e": 27136,
"s": 27131,
"text": "Java"
},
{
"code": "// import required packagesimport java.io.*;import java.lang.*;import java.util.*; // driver classclass heapMemory { // main method public static void main(String[] args) { double mb = 1000000; // creating runtime time object Runtime r = Runtime.getRuntime(); // displaying max memory of heap in Mb System.out.println(\"Max memory\" + \" \" + r.maxMemory() / mb); // displaying initial memory in Mb System.out.println(\"Initial memory\" + \" \" + r.totalMemory() / mb); // displaying free memory in Mb System.out.println(\"Free memory\" + \" \" + r.freeMemory() / mb); // displaying consume memory in Mb System.out.println( \"Consume memory\" + \" \" + (r.totalMemory() - r.freeMemory()) / mb); }}",
"e": 28024,
"s": 27136,
"text": null
},
{
"code": null,
"e": 28119,
"s": 28024,
"text": "Max memory 134.217728\nInitial memory 134.217728\nFree memory 132.285192\nConsume memory 1.932536"
},
{
"code": null,
"e": 28137,
"s": 28121,
"text": "saurabh1990aror"
},
{
"code": null,
"e": 28142,
"s": 28137,
"text": "Java"
},
{
"code": null,
"e": 28156,
"s": 28142,
"text": "Java Programs"
},
{
"code": null,
"e": 28161,
"s": 28156,
"text": "Java"
},
{
"code": null,
"e": 28259,
"s": 28161,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28268,
"s": 28259,
"text": "Comments"
},
{
"code": null,
"e": 28281,
"s": 28268,
"text": "Old Comments"
},
{
"code": null,
"e": 28299,
"s": 28281,
"text": "Hashtable in Java"
},
{
"code": null,
"e": 28320,
"s": 28299,
"text": "Constructors in Java"
},
{
"code": null,
"e": 28366,
"s": 28320,
"text": "Different ways of Reading a text file in Java"
},
{
"code": null,
"e": 28409,
"s": 28366,
"text": "Comparator Interface in Java with Examples"
},
{
"code": null,
"e": 28446,
"s": 28409,
"text": "HashMap containsKey() Method in Java"
},
{
"code": null,
"e": 28490,
"s": 28446,
"text": "Convert a String to Character array in Java"
},
{
"code": null,
"e": 28516,
"s": 28490,
"text": "Java Programming Examples"
},
{
"code": null,
"e": 28550,
"s": 28516,
"text": "Convert Double to Integer in Java"
},
{
"code": null,
"e": 28597,
"s": 28550,
"text": "Implementing a Linked List in Java using Class"
}
] |
Powershell - If Else Statement
|
An if statement can be followed by an optional else statement, which executes when the Boolean expression is false.
Following is the syntax of an if...else statement −
if(Boolean_expression) {
// Executes when the Boolean expression is true
}else {
// Executes when the Boolean expression is false
}
If the boolean expression evaluates to true, then the if block of code will be executed, otherwise else block of code will be executed.
$x = 30
if($x -le 20){
write-host("This is if statement")
}else {
write-host("This is else statement")
}
This will produce the following result −
This is else statement
An if statement can be followed by an optional else if...else statement, which is very useful to test various conditions using single if...elseif statement.
When using if, elseif, else statements there are a few points to keep in mind.
An if can have zero or one else's and it must come after any elseif's.
An if can have zero or one else's and it must come after any elseif's.
An if can have zero to many elseif's and they must come before the else.
An if can have zero to many elseif's and they must come before the else.
Once an else if succeeds, none of the remaining elseif's or else's will be tested.
Once an else if succeeds, none of the remaining elseif's or else's will be tested.
Following is the syntax of an if...else statement −
if(Boolean_expression 1) {
// Executes when the Boolean expression 1 is true
}elseif(Boolean_expression 2) {
// Executes when the Boolean expression 2 is true
}elseif(Boolean_expression 3) {
// Executes when the Boolean expression 3 is true
}else {
// Executes when the none of the above condition is true.
}
$x = 30
if($x -eq 10){
write-host("Value of X is 10")
} elseif($x -eq 20){
write-host("Value of X is 20")
} elseif($x -eq 30){
write-host("Value of X is 30")
} else {
write-host("This is else statement")
}
This will produce the following result −
Value of X is 30
15 Lectures
3.5 hours
Fabrice Chrzanowski
35 Lectures
2.5 hours
Vijay Saini
145 Lectures
12.5 hours
Fettah Ben
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2150,
"s": 2034,
"text": "An if statement can be followed by an optional else statement, which executes when the Boolean expression is false."
},
{
"code": null,
"e": 2202,
"s": 2150,
"text": "Following is the syntax of an if...else statement −"
},
{
"code": null,
"e": 2341,
"s": 2202,
"text": "if(Boolean_expression) {\n // Executes when the Boolean expression is true\n}else {\n // Executes when the Boolean expression is false\n}\n"
},
{
"code": null,
"e": 2477,
"s": 2341,
"text": "If the boolean expression evaluates to true, then the if block of code will be executed, otherwise else block of code will be executed."
},
{
"code": null,
"e": 2589,
"s": 2477,
"text": "$x = 30\n\nif($x -le 20){\n write-host(\"This is if statement\")\n}else {\n write-host(\"This is else statement\")\n}"
},
{
"code": null,
"e": 2630,
"s": 2589,
"text": "This will produce the following result −"
},
{
"code": null,
"e": 2654,
"s": 2630,
"text": "This is else statement\n"
},
{
"code": null,
"e": 2811,
"s": 2654,
"text": "An if statement can be followed by an optional else if...else statement, which is very useful to test various conditions using single if...elseif statement."
},
{
"code": null,
"e": 2890,
"s": 2811,
"text": "When using if, elseif, else statements there are a few points to keep in mind."
},
{
"code": null,
"e": 2961,
"s": 2890,
"text": "An if can have zero or one else's and it must come after any elseif's."
},
{
"code": null,
"e": 3032,
"s": 2961,
"text": "An if can have zero or one else's and it must come after any elseif's."
},
{
"code": null,
"e": 3105,
"s": 3032,
"text": "An if can have zero to many elseif's and they must come before the else."
},
{
"code": null,
"e": 3178,
"s": 3105,
"text": "An if can have zero to many elseif's and they must come before the else."
},
{
"code": null,
"e": 3261,
"s": 3178,
"text": "Once an else if succeeds, none of the remaining elseif's or else's will be tested."
},
{
"code": null,
"e": 3344,
"s": 3261,
"text": "Once an else if succeeds, none of the remaining elseif's or else's will be tested."
},
{
"code": null,
"e": 3396,
"s": 3344,
"text": "Following is the syntax of an if...else statement −"
},
{
"code": null,
"e": 3718,
"s": 3396,
"text": "if(Boolean_expression 1) {\n // Executes when the Boolean expression 1 is true\n}elseif(Boolean_expression 2) {\n // Executes when the Boolean expression 2 is true\n}elseif(Boolean_expression 3) {\n // Executes when the Boolean expression 3 is true\n}else {\n // Executes when the none of the above condition is true.\n}\n"
},
{
"code": null,
"e": 3937,
"s": 3718,
"text": "$x = 30\n\nif($x -eq 10){\n write-host(\"Value of X is 10\")\n} elseif($x -eq 20){\n write-host(\"Value of X is 20\")\n} elseif($x -eq 30){\n write-host(\"Value of X is 30\")\n} else {\n write-host(\"This is else statement\")\n}"
},
{
"code": null,
"e": 3978,
"s": 3937,
"text": "This will produce the following result −"
},
{
"code": null,
"e": 3996,
"s": 3978,
"text": "Value of X is 30\n"
},
{
"code": null,
"e": 4031,
"s": 3996,
"text": "\n 15 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 4052,
"s": 4031,
"text": " Fabrice Chrzanowski"
},
{
"code": null,
"e": 4087,
"s": 4052,
"text": "\n 35 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 4100,
"s": 4087,
"text": " Vijay Saini"
},
{
"code": null,
"e": 4137,
"s": 4100,
"text": "\n 145 Lectures \n 12.5 hours \n"
},
{
"code": null,
"e": 4149,
"s": 4137,
"text": " Fettah Ben"
},
{
"code": null,
"e": 4156,
"s": 4149,
"text": " Print"
},
{
"code": null,
"e": 4167,
"s": 4156,
"text": " Add Notes"
}
] |
Write a program in Python to filter armstrong numbers in a given series
|
Assume you have a series and the result for filtering armstrong numbers,
original series is
0 153
1 323
2 371
3 420
4 500
dtype: int64
Armstrong numbers are:-
0 153
2 371
dtype: int64
To solve this, we will follow the steps given below −
Define a series.
Define a series.
Create an empty list and set for loop to access all the series data.
Create an empty list and set for loop to access all the series data.
Set armstrong intial value is 0 and create temp variable to store series elements one by one. It is defined below,
Set armstrong intial value is 0 and create temp variable to store series elements one by one. It is defined below,
l = []
for val in data:
armstrong = 0
temp = val
Create while loop and check temp>0 and calculate remainder by temp%10. Add armstrong value by taking cube of remainder and divide the temp value by 10 until it reaches 0 to terminate the loop. It is defined below,
Create while loop and check temp>0 and calculate remainder by temp%10. Add armstrong value by taking cube of remainder and divide the temp value by 10 until it reaches 0 to terminate the loop. It is defined below,
while(temp>0):
rem = temp % 10
armstrong = armstrong + (rem**3)
temp = temp // 10
Set if condition to compare an original value against temp value. If it is matched, then append the values to the list.
Set if condition to compare an original value against temp value. If it is matched, then append the values to the list.
if(armstrong==val):
l.append(val)
Finally, check the list values present in the series using isin(). It is defined below,
Finally, check the list values present in the series using isin(). It is defined below,
data[data.isin(l)]
Let’s see the below code to get a better implementation −
import pandas as pd
data = pd.Series([153,323,371,420,500])
print("original series is\n", data)
l = []
for val in data:
armstrong = 0
temp = val
while(temp>0):
rem = temp % 10
armstrong = armstrong + (rem**3)
temp = temp // 10
if(armstrong==val):
l.append(val)
print("Armstrong numbers are:-")
print(data[data.isin(l)])
original series is
0 153
1 323
2 371
3 420
4 500
dtype: int64
Armstrong numbers are:-
0 153
2 371
dtype: int64
|
[
{
"code": null,
"e": 1135,
"s": 1062,
"text": "Assume you have a series and the result for filtering armstrong numbers,"
},
{
"code": null,
"e": 1267,
"s": 1135,
"text": "original series is\n0 153\n1 323\n2 371\n3 420\n4 500\ndtype: int64\nArmstrong numbers are:-\n0 153\n2 371\ndtype: int64"
},
{
"code": null,
"e": 1321,
"s": 1267,
"text": "To solve this, we will follow the steps given below −"
},
{
"code": null,
"e": 1338,
"s": 1321,
"text": "Define a series."
},
{
"code": null,
"e": 1355,
"s": 1338,
"text": "Define a series."
},
{
"code": null,
"e": 1424,
"s": 1355,
"text": "Create an empty list and set for loop to access all the series data."
},
{
"code": null,
"e": 1493,
"s": 1424,
"text": "Create an empty list and set for loop to access all the series data."
},
{
"code": null,
"e": 1608,
"s": 1493,
"text": "Set armstrong intial value is 0 and create temp variable to store series elements one by one. It is defined below,"
},
{
"code": null,
"e": 1723,
"s": 1608,
"text": "Set armstrong intial value is 0 and create temp variable to store series elements one by one. It is defined below,"
},
{
"code": null,
"e": 1778,
"s": 1723,
"text": "l = []\nfor val in data:\n armstrong = 0\n temp = val"
},
{
"code": null,
"e": 1992,
"s": 1778,
"text": "Create while loop and check temp>0 and calculate remainder by temp%10. Add armstrong value by taking cube of remainder and divide the temp value by 10 until it reaches 0 to terminate the loop. It is defined below,"
},
{
"code": null,
"e": 2206,
"s": 1992,
"text": "Create while loop and check temp>0 and calculate remainder by temp%10. Add armstrong value by taking cube of remainder and divide the temp value by 10 until it reaches 0 to terminate the loop. It is defined below,"
},
{
"code": null,
"e": 2297,
"s": 2206,
"text": "while(temp>0):\n rem = temp % 10\n armstrong = armstrong + (rem**3)\n temp = temp // 10"
},
{
"code": null,
"e": 2417,
"s": 2297,
"text": "Set if condition to compare an original value against temp value. If it is matched, then append the values to the list."
},
{
"code": null,
"e": 2537,
"s": 2417,
"text": "Set if condition to compare an original value against temp value. If it is matched, then append the values to the list."
},
{
"code": null,
"e": 2574,
"s": 2537,
"text": "if(armstrong==val):\n l.append(val)"
},
{
"code": null,
"e": 2662,
"s": 2574,
"text": "Finally, check the list values present in the series using isin(). It is defined below,"
},
{
"code": null,
"e": 2750,
"s": 2662,
"text": "Finally, check the list values present in the series using isin(). It is defined below,"
},
{
"code": null,
"e": 2769,
"s": 2750,
"text": "data[data.isin(l)]"
},
{
"code": null,
"e": 2827,
"s": 2769,
"text": "Let’s see the below code to get a better implementation −"
},
{
"code": null,
"e": 3183,
"s": 2827,
"text": "import pandas as pd\ndata = pd.Series([153,323,371,420,500])\nprint(\"original series is\\n\", data)\nl = []\nfor val in data:\n armstrong = 0\n temp = val\n while(temp>0):\n rem = temp % 10\n armstrong = armstrong + (rem**3)\n temp = temp // 10\n if(armstrong==val):\n l.append(val)\nprint(\"Armstrong numbers are:-\")\nprint(data[data.isin(l)])"
},
{
"code": null,
"e": 3315,
"s": 3183,
"text": "original series is\n0 153\n1 323\n2 371\n3 420\n4 500\ndtype: int64\nArmstrong numbers are:-\n0 153\n2 371\ndtype: int64"
}
] |
Matplotlib – Date manipulation to show the year tick every 12 months
|
To make matplotlib date manipulation so that the year tick shows up every 12 months, we can take the following steps −
Set the figure size and adjust the padding between and around the subplots.
Create d, y, s, years, months, monthsFmt and yearsFmt using Pandas, Numpy and matplotlib dates.
Use "%B" in DateFormatter to show full month names.
Ue "%Y" in DateFormatter to show years.
Create a new figure or activate an existing figure.
Add an 'ax' to the figure as part of a subplot arrangement.
Plot "dts" and "s" data points using plot() method.
Set minor or major axes locator and formatter. Set minor_locator as months so that the year tick will be displayed every 12 months.
To display the figure, use show() method.
import numpy as np
from matplotlib import pyplot as plt, dates as mdates
import pandas as pd
plt.rcParams["figure.figsize"] = [7.00, 3.50]
plt.rcParams["figure.autolayout"] = True
d = pd.date_range("2020-01-01", "2021-06-01", freq="7D")
y = np.cumsum(np.random.normal(size=len(d)))
s = pd.Series(y, index=d)
years = mdates.YearLocator()
months = mdates.MonthLocator()
monthsFmt = mdates.DateFormatter('%B')
yearsFmt = mdates.DateFormatter('\n%Y')
dts = s.index.to_pydatetime()
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(dts, s)
ax.xaxis.set_minor_locator(months)
ax.xaxis.set_minor_formatter(monthsFmt)
plt.setp(ax.xaxis.get_minorticklabels(), rotation=90)
ax.xaxis.set_major_locator(years)
ax.xaxis.set_major_formatter(yearsFmt)
plt.show()
It will produce the following output
|
[
{
"code": null,
"e": 1181,
"s": 1062,
"text": "To make matplotlib date manipulation so that the year tick shows up every 12 months, we can take the following steps −"
},
{
"code": null,
"e": 1257,
"s": 1181,
"text": "Set the figure size and adjust the padding between and around the subplots."
},
{
"code": null,
"e": 1353,
"s": 1257,
"text": "Create d, y, s, years, months, monthsFmt and yearsFmt using Pandas, Numpy and matplotlib dates."
},
{
"code": null,
"e": 1405,
"s": 1353,
"text": "Use \"%B\" in DateFormatter to show full month names."
},
{
"code": null,
"e": 1445,
"s": 1405,
"text": "Ue \"%Y\" in DateFormatter to show years."
},
{
"code": null,
"e": 1497,
"s": 1445,
"text": "Create a new figure or activate an existing figure."
},
{
"code": null,
"e": 1557,
"s": 1497,
"text": "Add an 'ax' to the figure as part of a subplot arrangement."
},
{
"code": null,
"e": 1609,
"s": 1557,
"text": "Plot \"dts\" and \"s\" data points using plot() method."
},
{
"code": null,
"e": 1741,
"s": 1609,
"text": "Set minor or major axes locator and formatter. Set minor_locator as months so that the year tick will be displayed every 12 months."
},
{
"code": null,
"e": 1783,
"s": 1741,
"text": "To display the figure, use show() method."
},
{
"code": null,
"e": 2540,
"s": 1783,
"text": "import numpy as np\nfrom matplotlib import pyplot as plt, dates as mdates\nimport pandas as pd\n\nplt.rcParams[\"figure.figsize\"] = [7.00, 3.50]\nplt.rcParams[\"figure.autolayout\"] = True\n\nd = pd.date_range(\"2020-01-01\", \"2021-06-01\", freq=\"7D\")\ny = np.cumsum(np.random.normal(size=len(d)))\ns = pd.Series(y, index=d)\nyears = mdates.YearLocator()\nmonths = mdates.MonthLocator()\nmonthsFmt = mdates.DateFormatter('%B')\nyearsFmt = mdates.DateFormatter('\\n%Y')\n\ndts = s.index.to_pydatetime()\nfig = plt.figure()\n\nax = fig.add_subplot(111)\nax.plot(dts, s)\nax.xaxis.set_minor_locator(months)\nax.xaxis.set_minor_formatter(monthsFmt)\nplt.setp(ax.xaxis.get_minorticklabels(), rotation=90)\n\nax.xaxis.set_major_locator(years)\nax.xaxis.set_major_formatter(yearsFmt)\n\nplt.show()"
},
{
"code": null,
"e": 2577,
"s": 2540,
"text": "It will produce the following output"
}
] |
HTML DOM NodeList.forEach() Method - GeeksforGeeks
|
24 Jul, 2020
The forEach() method of the NodeList interface calls the callback given in parameter once for each value pair in the list, in insertion order.
Syntax:
NodeList.forEach(callback, currentValue);
Parameters:
Callback: A function to execute on each element of NodeList. It accepts 3 parameters:
currentValue: The current element to be processed in NodeList.
currentIndex (Optional): The index of the currentValue being processed in NodeList.
listobj (Optional): The NodeList on which forEach() is being applied.
thisArg (Optional): Value to use as this when executing callback.
Return value: This method returns undefined.
Example: In this example, we will create a NodeList and hence will get all values from NodeList using this method.
<!DOCTYPE HTML> <html> <head> <meta charset="UTF-8"> <title>HTML | DOM NodeList.forEach() Method</title></head> <body style="text-align:center;"> <h1 style="color:green;"> GeeksforGeeks </h1> <p> HTML | DOM NodeList.forEach() Method </p> <button onclick = "Geeks()"> Click Here </button> <p id="a"></p> <script> var a = document.getElementById("a"); a.innerHTML = "elements are : " function Geeks(){ var parentNode = document.createElement("div"); var c1 = document.createElement("p"); var c2 = document.createElement("span"); var c3 = document.createElement("h1"); parentNode.appendChild(c1); parentNode.appendChild(c2); parentNode.appendChild(c3); var nodelist = parentNode.childNodes; nodelist.forEach( function(currentValue, currentIndex, listObj) { a.innerHTML += "<li>"+currentValue.localName + `</li>`; console.log(currentValue, currentIndex); }, );}</script></body> </html>
Output:
Before Clicking Button:
After Clicking Button: Elements are called using forEach().
In the console: Element Values can be seen.
Supported Browsers:
Google Chrome
Edge
Firefox
Safari
Opera
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course.
HTML-DOM
HTML
JavaScript
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Insert Form Data into Database using PHP ?
REST API (Introduction)
Types of CSS (Cascading Style Sheet)
Form validation using HTML and JavaScript
How to position a div at the bottom of its container using CSS?
Convert a string to an integer in JavaScript
Difference between var, let and const keywords in JavaScript
How to calculate the number of days between two dates in javascript?
Differences between Functional Components and Class Components in React
How to append HTML code to a div using JavaScript ?
|
[
{
"code": null,
"e": 24622,
"s": 24594,
"text": "\n24 Jul, 2020"
},
{
"code": null,
"e": 24765,
"s": 24622,
"text": "The forEach() method of the NodeList interface calls the callback given in parameter once for each value pair in the list, in insertion order."
},
{
"code": null,
"e": 24773,
"s": 24765,
"text": "Syntax:"
},
{
"code": null,
"e": 24815,
"s": 24773,
"text": "NodeList.forEach(callback, currentValue);"
},
{
"code": null,
"e": 24827,
"s": 24815,
"text": "Parameters:"
},
{
"code": null,
"e": 24913,
"s": 24827,
"text": "Callback: A function to execute on each element of NodeList. It accepts 3 parameters:"
},
{
"code": null,
"e": 24976,
"s": 24913,
"text": "currentValue: The current element to be processed in NodeList."
},
{
"code": null,
"e": 25060,
"s": 24976,
"text": "currentIndex (Optional): The index of the currentValue being processed in NodeList."
},
{
"code": null,
"e": 25130,
"s": 25060,
"text": "listobj (Optional): The NodeList on which forEach() is being applied."
},
{
"code": null,
"e": 25196,
"s": 25130,
"text": "thisArg (Optional): Value to use as this when executing callback."
},
{
"code": null,
"e": 25241,
"s": 25196,
"text": "Return value: This method returns undefined."
},
{
"code": null,
"e": 25356,
"s": 25241,
"text": "Example: In this example, we will create a NodeList and hence will get all values from NodeList using this method."
},
{
"code": "<!DOCTYPE HTML> <html> <head> <meta charset=\"UTF-8\"> <title>HTML | DOM NodeList.forEach() Method</title></head> <body style=\"text-align:center;\"> <h1 style=\"color:green;\"> GeeksforGeeks </h1> <p> HTML | DOM NodeList.forEach() Method </p> <button onclick = \"Geeks()\"> Click Here </button> <p id=\"a\"></p> <script> var a = document.getElementById(\"a\"); a.innerHTML = \"elements are : \" function Geeks(){ var parentNode = document.createElement(\"div\"); var c1 = document.createElement(\"p\"); var c2 = document.createElement(\"span\"); var c3 = document.createElement(\"h1\"); parentNode.appendChild(c1); parentNode.appendChild(c2); parentNode.appendChild(c3); var nodelist = parentNode.childNodes; nodelist.forEach( function(currentValue, currentIndex, listObj) { a.innerHTML += \"<li>\"+currentValue.localName + `</li>`; console.log(currentValue, currentIndex); }, );}</script></body> </html>",
"e": 26478,
"s": 25356,
"text": null
},
{
"code": null,
"e": 26486,
"s": 26478,
"text": "Output:"
},
{
"code": null,
"e": 26510,
"s": 26486,
"text": "Before Clicking Button:"
},
{
"code": null,
"e": 26570,
"s": 26510,
"text": "After Clicking Button: Elements are called using forEach()."
},
{
"code": null,
"e": 26614,
"s": 26570,
"text": "In the console: Element Values can be seen."
},
{
"code": null,
"e": 26634,
"s": 26614,
"text": "Supported Browsers:"
},
{
"code": null,
"e": 26648,
"s": 26634,
"text": "Google Chrome"
},
{
"code": null,
"e": 26653,
"s": 26648,
"text": "Edge"
},
{
"code": null,
"e": 26661,
"s": 26653,
"text": "Firefox"
},
{
"code": null,
"e": 26668,
"s": 26661,
"text": "Safari"
},
{
"code": null,
"e": 26674,
"s": 26668,
"text": "Opera"
},
{
"code": null,
"e": 26811,
"s": 26674,
"text": "Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course."
},
{
"code": null,
"e": 26820,
"s": 26811,
"text": "HTML-DOM"
},
{
"code": null,
"e": 26825,
"s": 26820,
"text": "HTML"
},
{
"code": null,
"e": 26836,
"s": 26825,
"text": "JavaScript"
},
{
"code": null,
"e": 26853,
"s": 26836,
"text": "Web Technologies"
},
{
"code": null,
"e": 26858,
"s": 26853,
"text": "HTML"
},
{
"code": null,
"e": 26956,
"s": 26858,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27006,
"s": 26956,
"text": "How to Insert Form Data into Database using PHP ?"
},
{
"code": null,
"e": 27030,
"s": 27006,
"text": "REST API (Introduction)"
},
{
"code": null,
"e": 27067,
"s": 27030,
"text": "Types of CSS (Cascading Style Sheet)"
},
{
"code": null,
"e": 27109,
"s": 27067,
"text": "Form validation using HTML and JavaScript"
},
{
"code": null,
"e": 27173,
"s": 27109,
"text": "How to position a div at the bottom of its container using CSS?"
},
{
"code": null,
"e": 27218,
"s": 27173,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 27279,
"s": 27218,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 27348,
"s": 27279,
"text": "How to calculate the number of days between two dates in javascript?"
},
{
"code": null,
"e": 27420,
"s": 27348,
"text": "Differences between Functional Components and Class Components in React"
}
] |
Create bar plot of one column in an R data frame using ggplot2.
|
To create bar plot of one column in an R data frame using ggplot2, we can use
rownames of the data frame as x variable in aes.
For Example, if we have a data frame called df that contains two columns say X and Y
and we want to create the bar plot of values in Y then we can use the below mentioned
command −
ggplot(df,aes(rownames(df),Y))+geom_bar(stat="identity")
Following snippet creates a sample data frame −
x1<-rpois(5,10)
x2<-rpois(5,2)
x3<-rpois(5,5)
df<-data.frame(x1,x2,x3)
df
The following dataframe is created
x1 x2 x3
1 9 2 7
2 9 2 3
3 13 1 3
4 13 3 8
5 11 1 1
To load ggplot2 package and create bar plot for data in column x2 of df on the above
created data frame, add the following code to the above snippet −
x1<-rpois(5,10)
x2<-rpois(5,2)
x3<-rpois(5,5)
df<-data.frame(x1,x2,x3)
library(ggplot2)
ggplot(df,aes(rownames(df),x2))+geom_bar(stat="identity")
If you execute the above given snippet, it generates the following Output −
|
[
{
"code": null,
"e": 1189,
"s": 1062,
"text": "To create bar plot of one column in an R data frame using ggplot2, we can use\nrownames of the data frame as x variable in aes."
},
{
"code": null,
"e": 1370,
"s": 1189,
"text": "For Example, if we have a data frame called df that contains two columns say X and Y\nand we want to create the bar plot of values in Y then we can use the below mentioned\ncommand −"
},
{
"code": null,
"e": 1427,
"s": 1370,
"text": "ggplot(df,aes(rownames(df),Y))+geom_bar(stat=\"identity\")"
},
{
"code": null,
"e": 1475,
"s": 1427,
"text": "Following snippet creates a sample data frame −"
},
{
"code": null,
"e": 1549,
"s": 1475,
"text": "x1<-rpois(5,10)\nx2<-rpois(5,2)\nx3<-rpois(5,5)\ndf<-data.frame(x1,x2,x3)\ndf"
},
{
"code": null,
"e": 1584,
"s": 1549,
"text": "The following dataframe is created"
},
{
"code": null,
"e": 1636,
"s": 1584,
"text": "x1 x2 x3\n1 9 2 7\n2 9 2 3\n3 13 1 3\n4 13 3 8\n5 11 1 1"
},
{
"code": null,
"e": 1787,
"s": 1636,
"text": "To load ggplot2 package and create bar plot for data in column x2 of df on the above\ncreated data frame, add the following code to the above snippet −"
},
{
"code": null,
"e": 1934,
"s": 1787,
"text": "x1<-rpois(5,10)\nx2<-rpois(5,2)\nx3<-rpois(5,5)\ndf<-data.frame(x1,x2,x3)\nlibrary(ggplot2)\nggplot(df,aes(rownames(df),x2))+geom_bar(stat=\"identity\")\n"
},
{
"code": null,
"e": 2010,
"s": 1934,
"text": "If you execute the above given snippet, it generates the following Output −"
}
] |
MySQLi - Insert Query
|
To insert data into a MySQL table, you would need to use the SQL INSERT INTO command. You can insert data into the MySQL table by using the mysql> prompt or by using any script like PHP.
Here is a generic SQL syntax of INSERT INTO command to insert data into the MySQL table −
INSERT INTO table_name ( field1, field2,...fieldN )
VALUES
( value1, value2,...valueN );
To insert string data types, it is required to keep all the values into double or single quotes. For example "value".
To insert data from the command prompt, we will use SQL INSERT INTO command to insert data into MySQL table tutorials_tbl.
The following example will create 3 records into tutorials_tbl table −
root@host# mysql -u root -p password;
Enter password:*******
mysql> use TUTORIALS;
Database changed
mysql> INSERT INTO tutorials_tbl
→(tutorial_title, tutorial_author, submission_date)
→VALUES
→("Learn PHP", "John Poul", NOW());
Query OK, 1 row affected (0.01 sec)
mysql> INSERT INTO tutorials_tbl
→(tutorial_title, tutorial_author, submission_date)
→VALUES
→("Learn MySQL", "Abdul S", NOW());
Query OK, 1 row affected (0.01 sec)
mysql> INSERT INTO tutorials_tbl
→(tutorial_title, tutorial_author, submission_date)
→VALUES
→("JAVA Tutorial", "Sanjay", '2007-05-06');
Query OK, 1 row affected (0.01 sec)
mysql>
NOTE − Please note that all the arrow signs (→) are not a part of the SQL command. They are indicating a new line and they are created automatically by the MySQL prompt while pressing the enter key without giving a semicolon at the end of each line of the command.
In the above example, we have not provided a tutorial_id because at the time of table creation, we had given AUTO_INCREMENT option for this field. So MySQL takes care of inserting these IDs automatically. Here, NOW() is a MySQL function, which returns the current date and time.
PHP uses mysqli query() or mysql_query() function to insert a record into a MySQL table. This function takes two parameters and returns TRUE on success or FALSE on failure.
$mysqli→query($sql,$resultmode)
$sql
Required - SQL query to insert record into a table.
$resultmode
Optional - Either the constant MYSQLI_USE_RESULT or MYSQLI_STORE_RESULT depending on the desired behavior. By default, MYSQLI_STORE_RESULT is used.
This example will take three parameters from the user and will insert them into the MySQL table − −
Copy and paste the following example as mysql_example.php −
<html>
<head>
<title>Add New Record in MySQL Database</title>
</head>
<body>
<?php
if(isset($_POST['add'])) {
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = 'root@123';
$dbname = 'TUTORIALS';
$mysqli = new mysqli($dbhost, $dbuser, $dbpass, $dbname);
if($mysqli→connect_errno ) {
printf("Connect failed: %s<br />", $mysqli→connect_error);
exit();
}
printf('Connected successfully.<br />');
if(! get_magic_quotes_gpc() ) {
$tutorial_title = addslashes ($_POST['tutorial_title']);
$tutorial_author = addslashes ($_POST['tutorial_author']);
} else {
$tutorial_title = $_POST['tutorial_title'];
$tutorial_author = $_POST['tutorial_author'];
}
$submission_date = $_POST['submission_date'];
$sql = "INSERT INTO tutorials_tbl ".
"(tutorial_title,tutorial_author, submission_date) "."VALUES ".
"('$tutorial_title','$tutorial_author','$submission_date')";
if ($mysqli→query($sql)) {
printf("Record inserted successfully.<br />");
}
if ($mysqli→errno) {
printf("Could not insert record into table: %s<br />", $mysqli→error);
}
$mysqli→close();
} else {
?>
<form method = "post" action = "<?php $_PHP_SELF ?>">
<table width = "600" border = "0" cellspacing = "1" cellpadding = "2">
<tr>
<td width = "250">Tutorial Title</td>
<td><input name = "tutorial_title" type = "text" id = "tutorial_title"></td>
</tr>
<tr>
<td width = "250">Tutorial Author</td>
<td><input name = "tutorial_author" type = "text" id = "tutorial_author"></td>
</tr>
<tr>
<td width = "250">Submission Date [ yyyy-mm-dd ]</td>
<td><input name = "submission_date" type = "text" id = "submission_date"></td>
</tr>
<tr>
<td width = "250"> </td>
<td></td>
</tr>
<tr>
<td width = "250"> </td>
<td><input name = "add" type = "submit" id = "add" value = "Add Tutorial"></td>
</tr>
</table>
</form>
<?php
}
?>
</body>
</html>
Access the mysql_example.php deployed on apache web server, enter details and verify the output on submitting the form.
Record inserted successfully.
While doing a data insert, it is best to use the function get_magic_quotes_gpc() to check if the current configuration for magic quote is set or not. If this function returns false, then use the function addslashes() to add slashes before the quotes.
You can put many validations around to check if the entered data is correct or not and can take the appropriate action.
14 Lectures
1.5 hours
Stone River ELearning
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2450,
"s": 2263,
"text": "To insert data into a MySQL table, you would need to use the SQL INSERT INTO command. You can insert data into the MySQL table by using the mysql> prompt or by using any script like PHP."
},
{
"code": null,
"e": 2541,
"s": 2450,
"text": "Here is a generic SQL syntax of INSERT INTO command to insert data into the MySQL table −"
},
{
"code": null,
"e": 2637,
"s": 2541,
"text": "INSERT INTO table_name ( field1, field2,...fieldN )\n VALUES\n ( value1, value2,...valueN );\n"
},
{
"code": null,
"e": 2755,
"s": 2637,
"text": "To insert string data types, it is required to keep all the values into double or single quotes. For example \"value\"."
},
{
"code": null,
"e": 2878,
"s": 2755,
"text": "To insert data from the command prompt, we will use SQL INSERT INTO command to insert data into MySQL table tutorials_tbl."
},
{
"code": null,
"e": 2949,
"s": 2878,
"text": "The following example will create 3 records into tutorials_tbl table −"
},
{
"code": null,
"e": 3590,
"s": 2949,
"text": "root@host# mysql -u root -p password;\nEnter password:*******\nmysql> use TUTORIALS;\nDatabase changed\n\nmysql> INSERT INTO tutorials_tbl \n →(tutorial_title, tutorial_author, submission_date)\n →VALUES\n →(\"Learn PHP\", \"John Poul\", NOW());\nQuery OK, 1 row affected (0.01 sec)\n\nmysql> INSERT INTO tutorials_tbl\n →(tutorial_title, tutorial_author, submission_date)\n →VALUES\n →(\"Learn MySQL\", \"Abdul S\", NOW());\nQuery OK, 1 row affected (0.01 sec)\n\nmysql> INSERT INTO tutorials_tbl\n →(tutorial_title, tutorial_author, submission_date)\n →VALUES\n →(\"JAVA Tutorial\", \"Sanjay\", '2007-05-06');\nQuery OK, 1 row affected (0.01 sec)\nmysql>"
},
{
"code": null,
"e": 3855,
"s": 3590,
"text": "NOTE − Please note that all the arrow signs (→) are not a part of the SQL command. They are indicating a new line and they are created automatically by the MySQL prompt while pressing the enter key without giving a semicolon at the end of each line of the command."
},
{
"code": null,
"e": 4134,
"s": 3855,
"text": "In the above example, we have not provided a tutorial_id because at the time of table creation, we had given AUTO_INCREMENT option for this field. So MySQL takes care of inserting these IDs automatically. Here, NOW() is a MySQL function, which returns the current date and time."
},
{
"code": null,
"e": 4307,
"s": 4134,
"text": "PHP uses mysqli query() or mysql_query() function to insert a record into a MySQL table. This function takes two parameters and returns TRUE on success or FALSE on failure."
},
{
"code": null,
"e": 4340,
"s": 4307,
"text": "$mysqli→query($sql,$resultmode)\n"
},
{
"code": null,
"e": 4345,
"s": 4340,
"text": "$sql"
},
{
"code": null,
"e": 4397,
"s": 4345,
"text": "Required - SQL query to insert record into a table."
},
{
"code": null,
"e": 4409,
"s": 4397,
"text": "$resultmode"
},
{
"code": null,
"e": 4557,
"s": 4409,
"text": "Optional - Either the constant MYSQLI_USE_RESULT or MYSQLI_STORE_RESULT depending on the desired behavior. By default, MYSQLI_STORE_RESULT is used."
},
{
"code": null,
"e": 4657,
"s": 4557,
"text": "This example will take three parameters from the user and will insert them into the MySQL table − −"
},
{
"code": null,
"e": 4717,
"s": 4657,
"text": "Copy and paste the following example as mysql_example.php −"
},
{
"code": null,
"e": 7283,
"s": 4717,
"text": "<html>\n <head>\n <title>Add New Record in MySQL Database</title>\n </head>\n <body>\n <?php\n if(isset($_POST['add'])) {\n $dbhost = 'localhost';\n $dbuser = 'root';\n $dbpass = 'root@123';\n $dbname = 'TUTORIALS';\n $mysqli = new mysqli($dbhost, $dbuser, $dbpass, $dbname);\n \n if($mysqli→connect_errno ) {\n printf(\"Connect failed: %s<br />\", $mysqli→connect_error);\n exit();\n }\n printf('Connected successfully.<br />');\n\n if(! get_magic_quotes_gpc() ) {\n $tutorial_title = addslashes ($_POST['tutorial_title']);\n $tutorial_author = addslashes ($_POST['tutorial_author']);\n } else {\n $tutorial_title = $_POST['tutorial_title'];\n $tutorial_author = $_POST['tutorial_author'];\n }\n $submission_date = $_POST['submission_date'];\n $sql = \"INSERT INTO tutorials_tbl \".\n \"(tutorial_title,tutorial_author, submission_date) \".\"VALUES \".\n \"('$tutorial_title','$tutorial_author','$submission_date')\";\n \n if ($mysqli→query($sql)) {\n printf(\"Record inserted successfully.<br />\");\n }\n if ($mysqli→errno) {\n printf(\"Could not insert record into table: %s<br />\", $mysqli→error);\n }\n $mysqli→close();\n } else {\n ?> \n <form method = \"post\" action = \"<?php $_PHP_SELF ?>\">\n <table width = \"600\" border = \"0\" cellspacing = \"1\" cellpadding = \"2\">\n <tr>\n <td width = \"250\">Tutorial Title</td>\n <td><input name = \"tutorial_title\" type = \"text\" id = \"tutorial_title\"></td>\n </tr> \n <tr>\n <td width = \"250\">Tutorial Author</td>\n <td><input name = \"tutorial_author\" type = \"text\" id = \"tutorial_author\"></td>\n </tr> \n <tr>\n <td width = \"250\">Submission Date [ yyyy-mm-dd ]</td>\n <td><input name = \"submission_date\" type = \"text\" id = \"submission_date\"></td>\n </tr> \n <tr>\n <td width = \"250\"> </td>\n <td></td>\n </tr> \n <tr>\n <td width = \"250\"> </td>\n <td><input name = \"add\" type = \"submit\" id = \"add\" value = \"Add Tutorial\"></td>\n </tr>\n </table>\n </form>\n <?php\n }\n ?>\n </body>\n</html>"
},
{
"code": null,
"e": 7403,
"s": 7283,
"text": "Access the mysql_example.php deployed on apache web server, enter details and verify the output on submitting the form."
},
{
"code": null,
"e": 7434,
"s": 7403,
"text": "Record inserted successfully.\n"
},
{
"code": null,
"e": 7685,
"s": 7434,
"text": "While doing a data insert, it is best to use the function get_magic_quotes_gpc() to check if the current configuration for magic quote is set or not. If this function returns false, then use the function addslashes() to add slashes before the quotes."
},
{
"code": null,
"e": 7805,
"s": 7685,
"text": "You can put many validations around to check if the entered data is correct or not and can take the appropriate action."
},
{
"code": null,
"e": 7840,
"s": 7805,
"text": "\n 14 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 7863,
"s": 7840,
"text": " Stone River ELearning"
},
{
"code": null,
"e": 7870,
"s": 7863,
"text": " Print"
},
{
"code": null,
"e": 7881,
"s": 7870,
"text": " Add Notes"
}
] |
What is abstraction in C#?
|
Abstraction and encapsulation are related features in object-oriented programming. Abstraction allows making relevant information visible and encapsulation enables a programmer to implement the desired level of abstraction.
Abstraction can be achieved using abstract classes in C#. C# allows you to create abstract classes that are used to provide a partial class implementation of an interface. Implementation is completed when a derived class inherits from it. Abstract classes contain abstract methods, which are implemented by the derived class. The derived classes have more specialized functionality.
The following are some of the key points −
You cannot create an instance of an abstract class
You cannot create an instance of an abstract class
You cannot declare an abstract method outside an abstract class
You cannot declare an abstract method outside an abstract class
When a class is declared sealed, it cannot be inherited, abstract classes cannot be declared sealed.
When a class is declared sealed, it cannot be inherited, abstract classes cannot be declared sealed.
Live Demo
using System;
namespace Demo {
abstract class Shape {
public abstract int area();
}
class Rectangle: Shape {
private int length;
private int width;
public Rectangle( int a = 0, int b = 0) {
length = a;
width = b;
}
public override int area () {
Console.WriteLine("Rectangle class area :");
return (width * length);
}
}
class RectangleTester {
static void Main(string[] args) {
Rectangle r = new Rectangle(20, 15);
double a = r.area();
Console.WriteLine("Area: {0}",a);
Console.ReadKey();
}
}
}
Rectangle class area :
Area: 300
|
[
{
"code": null,
"e": 1286,
"s": 1062,
"text": "Abstraction and encapsulation are related features in object-oriented programming. Abstraction allows making relevant information visible and encapsulation enables a programmer to implement the desired level of abstraction."
},
{
"code": null,
"e": 1669,
"s": 1286,
"text": "Abstraction can be achieved using abstract classes in C#. C# allows you to create abstract classes that are used to provide a partial class implementation of an interface. Implementation is completed when a derived class inherits from it. Abstract classes contain abstract methods, which are implemented by the derived class. The derived classes have more specialized functionality."
},
{
"code": null,
"e": 1712,
"s": 1669,
"text": "The following are some of the key points −"
},
{
"code": null,
"e": 1763,
"s": 1712,
"text": "You cannot create an instance of an abstract class"
},
{
"code": null,
"e": 1814,
"s": 1763,
"text": "You cannot create an instance of an abstract class"
},
{
"code": null,
"e": 1878,
"s": 1814,
"text": "You cannot declare an abstract method outside an abstract class"
},
{
"code": null,
"e": 1942,
"s": 1878,
"text": "You cannot declare an abstract method outside an abstract class"
},
{
"code": null,
"e": 2043,
"s": 1942,
"text": "When a class is declared sealed, it cannot be inherited, abstract classes cannot be declared sealed."
},
{
"code": null,
"e": 2144,
"s": 2043,
"text": "When a class is declared sealed, it cannot be inherited, abstract classes cannot be declared sealed."
},
{
"code": null,
"e": 2155,
"s": 2144,
"text": " Live Demo"
},
{
"code": null,
"e": 2795,
"s": 2155,
"text": "using System;\nnamespace Demo {\n abstract class Shape {\n public abstract int area();\n }\n\n class Rectangle: Shape {\n private int length;\n private int width;\n\n public Rectangle( int a = 0, int b = 0) {\n length = a;\n width = b;\n }\n public override int area () {\n Console.WriteLine(\"Rectangle class area :\");\n return (width * length);\n }\n }\n class RectangleTester {\n static void Main(string[] args) {\n Rectangle r = new Rectangle(20, 15);\n double a = r.area();\n Console.WriteLine(\"Area: {0}\",a);\n Console.ReadKey();\n }\n }\n}"
},
{
"code": null,
"e": 2828,
"s": 2795,
"text": "Rectangle class area :\nArea: 300"
}
] |
Erlang - Atoms
|
An atom is a literal, a constant with name. An atom is to be enclosed in single quotes (') if it does not begin with a lower-case letter or if it contains other characters than alphanumeric characters, underscore (_), or @.
The following program is an example of how atoms can be used in Erlang. This program declares 3 atoms, atom1, atom_1 and ‘atom 1’ respectively. So you can see the different ways an atom can be declared.
-module(helloworld).
-export([start/0]).
start() ->
io:fwrite(atom1),
io:fwrite("~n"),
io:fwrite(atom_1),
io:fwrite("~n"),
io:fwrite('atom 1'),
io:fwrite("~n").
The output of the above program would be follows −
atom1
atom_1
atom 1
Let’s see some of the methods available in Erlang to work with atoms.
is_atom
This method is used to determine if a term is indeed an atom.
atom_to_list
This method is used to convert an atom to a list.
list_to_atom
This method is used to convert a list item to an atom.
atom_to_binary
This method is used to convert an atom to a binary value.
binary_to_atom
This method is used to convert a binary value to an atom value.
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2525,
"s": 2301,
"text": "An atom is a literal, a constant with name. An atom is to be enclosed in single quotes (') if it does not begin with a lower-case letter or if it contains other characters than alphanumeric characters, underscore (_), or @."
},
{
"code": null,
"e": 2728,
"s": 2525,
"text": "The following program is an example of how atoms can be used in Erlang. This program declares 3 atoms, atom1, atom_1 and ‘atom 1’ respectively. So you can see the different ways an atom can be declared."
},
{
"code": null,
"e": 2916,
"s": 2728,
"text": "-module(helloworld). \n-export([start/0]). \n\nstart() -> \n io:fwrite(atom1), \n io:fwrite(\"~n\"), \n io:fwrite(atom_1), \n io:fwrite(\"~n\"), \n io:fwrite('atom 1'), \n io:fwrite(\"~n\")."
},
{
"code": null,
"e": 2967,
"s": 2916,
"text": "The output of the above program would be follows −"
},
{
"code": null,
"e": 2988,
"s": 2967,
"text": "atom1\natom_1\natom 1\n"
},
{
"code": null,
"e": 3058,
"s": 2988,
"text": "Let’s see some of the methods available in Erlang to work with atoms."
},
{
"code": null,
"e": 3066,
"s": 3058,
"text": "is_atom"
},
{
"code": null,
"e": 3128,
"s": 3066,
"text": "This method is used to determine if a term is indeed an atom."
},
{
"code": null,
"e": 3141,
"s": 3128,
"text": "atom_to_list"
},
{
"code": null,
"e": 3191,
"s": 3141,
"text": "This method is used to convert an atom to a list."
},
{
"code": null,
"e": 3204,
"s": 3191,
"text": "list_to_atom"
},
{
"code": null,
"e": 3259,
"s": 3204,
"text": "This method is used to convert a list item to an atom."
},
{
"code": null,
"e": 3274,
"s": 3259,
"text": "atom_to_binary"
},
{
"code": null,
"e": 3332,
"s": 3274,
"text": "This method is used to convert an atom to a binary value."
},
{
"code": null,
"e": 3347,
"s": 3332,
"text": "binary_to_atom"
},
{
"code": null,
"e": 3411,
"s": 3347,
"text": "This method is used to convert a binary value to an atom value."
},
{
"code": null,
"e": 3418,
"s": 3411,
"text": " Print"
},
{
"code": null,
"e": 3429,
"s": 3418,
"text": " Add Notes"
}
] |
C# | Get an ICollection containing values in OrderedDictionary - GeeksforGeeks
|
01 Feb, 2019
OrderedDictionary.Values property is used to get an ICollection object containing the values in the OrderedDictionary collection.
Syntax:
public System.Collections.ICollection Values { get; }
Return Value: It returns an ICollection object containing the values in the OrderedDictionary collection.
Below given are some examples to understand the implementation in a better way:
Example 1:
// C# code to get an ICollection// containing the values in OrderedDictionaryusing System;using System.Collections;using System.Collections.Specialized; class GFG { // Driver method public static void Main() { // Creating a orderedDictionary named myDict OrderedDictionary myDict = new OrderedDictionary(); // Adding key and value in myDict myDict.Add("key1", "value1"); myDict.Add("key2", "value2"); myDict.Add("key3", "value3"); myDict.Add("key4", "value4"); myDict.Add("key5", "value5"); // Getting an ICollection containing // the values in OrderedDictionary ICollection valueCollection = myDict.Values; // Creating a String array String[] myValues = new String[myDict.Count]; // Copying the OrderedDictionary elements to // a one-dimensional Array object at the // specified index. valueCollection.CopyTo(myValues, 0); for (int i = 0; i < myDict.Count; i++) { Console.WriteLine(myValues[i]); } }}
Output:
value1
value2
value3
value4
value5
Example 2:
// C# code to get an ICollection// containing the values in OrderedDictionaryusing System;using System.Collections;using System.Collections.Specialized; class GFG { // Driver method public static void Main() { // Creating a orderedDictionary named myDict OrderedDictionary myDict = new OrderedDictionary(); // Adding key and value in myDict myDict.Add("A", "Apple"); myDict.Add("B", "Banana"); myDict.Add("C", "Cat"); myDict.Add("D", "Dog"); // Getting an ICollection containing // the values in OrderedDictionary ICollection valueCollection = myDict.Values; // Creating a String array String[] myValues = new String[myDict.Count]; // Copying the OrderedDictionary elements to // a one-dimensional Array object at the // specified index. valueCollection.CopyTo(myValues, 0); for (int i = 0; i < myDict.Count; i++) { Console.WriteLine(myValues[i]); } }}
Output:
Apple
Banana
Cat
Dog
Reference:
https://docs.microsoft.com/en-us/dotnet/api/system.collections.specialized.ordereddictionary.values?view=netframework-4.7.2
CSharp-Specialized-Namespace
CSharp-Specialized-OrderedDictionary
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Extension Method in C#
HashSet in C# with Examples
Top 50 C# Interview Questions & Answers
C# | How to insert an element in an Array?
C# | Inheritance
C# | List Class
Partial Classes in C#
Convert String to Character Array in C#
Lambda Expressions in C#
Linked List Implementation in C#
|
[
{
"code": null,
"e": 24302,
"s": 24274,
"text": "\n01 Feb, 2019"
},
{
"code": null,
"e": 24432,
"s": 24302,
"text": "OrderedDictionary.Values property is used to get an ICollection object containing the values in the OrderedDictionary collection."
},
{
"code": null,
"e": 24440,
"s": 24432,
"text": "Syntax:"
},
{
"code": null,
"e": 24495,
"s": 24440,
"text": "public System.Collections.ICollection Values { get; }\n"
},
{
"code": null,
"e": 24601,
"s": 24495,
"text": "Return Value: It returns an ICollection object containing the values in the OrderedDictionary collection."
},
{
"code": null,
"e": 24681,
"s": 24601,
"text": "Below given are some examples to understand the implementation in a better way:"
},
{
"code": null,
"e": 24692,
"s": 24681,
"text": "Example 1:"
},
{
"code": "// C# code to get an ICollection// containing the values in OrderedDictionaryusing System;using System.Collections;using System.Collections.Specialized; class GFG { // Driver method public static void Main() { // Creating a orderedDictionary named myDict OrderedDictionary myDict = new OrderedDictionary(); // Adding key and value in myDict myDict.Add(\"key1\", \"value1\"); myDict.Add(\"key2\", \"value2\"); myDict.Add(\"key3\", \"value3\"); myDict.Add(\"key4\", \"value4\"); myDict.Add(\"key5\", \"value5\"); // Getting an ICollection containing // the values in OrderedDictionary ICollection valueCollection = myDict.Values; // Creating a String array String[] myValues = new String[myDict.Count]; // Copying the OrderedDictionary elements to // a one-dimensional Array object at the // specified index. valueCollection.CopyTo(myValues, 0); for (int i = 0; i < myDict.Count; i++) { Console.WriteLine(myValues[i]); } }}",
"e": 25765,
"s": 24692,
"text": null
},
{
"code": null,
"e": 25773,
"s": 25765,
"text": "Output:"
},
{
"code": null,
"e": 25809,
"s": 25773,
"text": "value1\nvalue2\nvalue3\nvalue4\nvalue5\n"
},
{
"code": null,
"e": 25820,
"s": 25809,
"text": "Example 2:"
},
{
"code": "// C# code to get an ICollection// containing the values in OrderedDictionaryusing System;using System.Collections;using System.Collections.Specialized; class GFG { // Driver method public static void Main() { // Creating a orderedDictionary named myDict OrderedDictionary myDict = new OrderedDictionary(); // Adding key and value in myDict myDict.Add(\"A\", \"Apple\"); myDict.Add(\"B\", \"Banana\"); myDict.Add(\"C\", \"Cat\"); myDict.Add(\"D\", \"Dog\"); // Getting an ICollection containing // the values in OrderedDictionary ICollection valueCollection = myDict.Values; // Creating a String array String[] myValues = new String[myDict.Count]; // Copying the OrderedDictionary elements to // a one-dimensional Array object at the // specified index. valueCollection.CopyTo(myValues, 0); for (int i = 0; i < myDict.Count; i++) { Console.WriteLine(myValues[i]); } }}",
"e": 26837,
"s": 25820,
"text": null
},
{
"code": null,
"e": 26845,
"s": 26837,
"text": "Output:"
},
{
"code": null,
"e": 26867,
"s": 26845,
"text": "Apple\nBanana\nCat\nDog\n"
},
{
"code": null,
"e": 26878,
"s": 26867,
"text": "Reference:"
},
{
"code": null,
"e": 27002,
"s": 26878,
"text": "https://docs.microsoft.com/en-us/dotnet/api/system.collections.specialized.ordereddictionary.values?view=netframework-4.7.2"
},
{
"code": null,
"e": 27031,
"s": 27002,
"text": "CSharp-Specialized-Namespace"
},
{
"code": null,
"e": 27068,
"s": 27031,
"text": "CSharp-Specialized-OrderedDictionary"
},
{
"code": null,
"e": 27071,
"s": 27068,
"text": "C#"
},
{
"code": null,
"e": 27169,
"s": 27071,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27178,
"s": 27169,
"text": "Comments"
},
{
"code": null,
"e": 27191,
"s": 27178,
"text": "Old Comments"
},
{
"code": null,
"e": 27214,
"s": 27191,
"text": "Extension Method in C#"
},
{
"code": null,
"e": 27242,
"s": 27214,
"text": "HashSet in C# with Examples"
},
{
"code": null,
"e": 27282,
"s": 27242,
"text": "Top 50 C# Interview Questions & Answers"
},
{
"code": null,
"e": 27325,
"s": 27282,
"text": "C# | How to insert an element in an Array?"
},
{
"code": null,
"e": 27342,
"s": 27325,
"text": "C# | Inheritance"
},
{
"code": null,
"e": 27358,
"s": 27342,
"text": "C# | List Class"
},
{
"code": null,
"e": 27380,
"s": 27358,
"text": "Partial Classes in C#"
},
{
"code": null,
"e": 27420,
"s": 27380,
"text": "Convert String to Character Array in C#"
},
{
"code": null,
"e": 27445,
"s": 27420,
"text": "Lambda Expressions in C#"
}
] |
numpy.ravel_multi_index() function | Python - GeeksforGeeks
|
22 Apr, 2020
numpy.ravel_multi_index() function converts a tuple of index arrays into an array of flat indices, applying boundary modes to the multi-index.
Syntax : numpy.ravel_multi_index(multi_index, dims, mode = ‘raise’, order = ‘C)Parameters :multi_index : [tuple of array_like] A tuple of integer arrays, one array for each dimension.dims : [tuple of ints] The shape of array into which the indices from multi_index apply.mode : [{‘raise’, ‘wrap’, ‘clip’}, optional] Specifies how out-of-bounds indices are handled. Can specify either one mode or a tuple of modes, one mode per index.‘raise’ – raise an error (default)‘wrap’ – wrap around‘clip’ – clip to the rangeIn ‘clip’ mode, a negative index that would normally wrap will clip to 0 instead.order : [{‘C’, ‘F’}, optional] Determines whether the multi-index should be viewed as indexing in row-major (C-style) or column-major (Fortran-style) order.
Return : [ndarray] An array of indices into the flattened version of an array of dimensions dims.
Code #1 :
# Python program explaining# numpy.ravel_multi_index() function # importing numpy as geek import numpy as geek arr = geek.array([[3, 6, 6], [4, 5, 1]]) gfg = geek.ravel_multi_index(arr, (7, 6)) print(gfg)
Output :
[22 41 37]
Code #2 :
# Python program explaining# numpy.ravel_multi_index() function # importing numpy as geek import numpy as geek arr = geek.array([[3, 6, 6], [4, 5, 1]]) gfg = geek.ravel_multi_index(arr, (7, 6), order = 'F') print(gfg)
Output :
[31 41 13]
Code #3 :
# Python program explaining# numpy.ravel_multi_index() function # importing numpy as geek import numpy as geek arr = geek.array([[3, 6, 6], [4, 5, 1]]) gfg = geek.ravel_multi_index(arr, (7, 6), mode = 'clip') print(gfg)
Output :
[22 41 37]
Python numpy-arrayManipulation
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
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
Defaultdict in Python
Python | Get unique values from a list
Python | os.path.join() method
Selecting rows in pandas DataFrame based on conditions
Create a directory in Python
Python | Pandas dataframe.groupby()
|
[
{
"code": null,
"e": 24292,
"s": 24264,
"text": "\n22 Apr, 2020"
},
{
"code": null,
"e": 24435,
"s": 24292,
"text": "numpy.ravel_multi_index() function converts a tuple of index arrays into an array of flat indices, applying boundary modes to the multi-index."
},
{
"code": null,
"e": 25186,
"s": 24435,
"text": "Syntax : numpy.ravel_multi_index(multi_index, dims, mode = ‘raise’, order = ‘C)Parameters :multi_index : [tuple of array_like] A tuple of integer arrays, one array for each dimension.dims : [tuple of ints] The shape of array into which the indices from multi_index apply.mode : [{‘raise’, ‘wrap’, ‘clip’}, optional] Specifies how out-of-bounds indices are handled. Can specify either one mode or a tuple of modes, one mode per index.‘raise’ – raise an error (default)‘wrap’ – wrap around‘clip’ – clip to the rangeIn ‘clip’ mode, a negative index that would normally wrap will clip to 0 instead.order : [{‘C’, ‘F’}, optional] Determines whether the multi-index should be viewed as indexing in row-major (C-style) or column-major (Fortran-style) order."
},
{
"code": null,
"e": 25284,
"s": 25186,
"text": "Return : [ndarray] An array of indices into the flattened version of an array of dimensions dims."
},
{
"code": null,
"e": 25294,
"s": 25284,
"text": "Code #1 :"
},
{
"code": "# Python program explaining# numpy.ravel_multi_index() function # importing numpy as geek import numpy as geek arr = geek.array([[3, 6, 6], [4, 5, 1]]) gfg = geek.ravel_multi_index(arr, (7, 6)) print(gfg) ",
"e": 25504,
"s": 25294,
"text": null
},
{
"code": null,
"e": 25513,
"s": 25504,
"text": "Output :"
},
{
"code": null,
"e": 25525,
"s": 25513,
"text": "[22 41 37]\n"
},
{
"code": null,
"e": 25536,
"s": 25525,
"text": " Code #2 :"
},
{
"code": "# Python program explaining# numpy.ravel_multi_index() function # importing numpy as geek import numpy as geek arr = geek.array([[3, 6, 6], [4, 5, 1]]) gfg = geek.ravel_multi_index(arr, (7, 6), order = 'F') print(gfg) ",
"e": 25759,
"s": 25536,
"text": null
},
{
"code": null,
"e": 25768,
"s": 25759,
"text": "Output :"
},
{
"code": null,
"e": 25780,
"s": 25768,
"text": "[31 41 13]\n"
},
{
"code": null,
"e": 25791,
"s": 25780,
"text": " Code #3 :"
},
{
"code": "# Python program explaining# numpy.ravel_multi_index() function # importing numpy as geek import numpy as geek arr = geek.array([[3, 6, 6], [4, 5, 1]]) gfg = geek.ravel_multi_index(arr, (7, 6), mode = 'clip') print(gfg) ",
"e": 26016,
"s": 25791,
"text": null
},
{
"code": null,
"e": 26025,
"s": 26016,
"text": "Output :"
},
{
"code": null,
"e": 26037,
"s": 26025,
"text": "[22 41 37]\n"
},
{
"code": null,
"e": 26068,
"s": 26037,
"text": "Python numpy-arrayManipulation"
},
{
"code": null,
"e": 26081,
"s": 26068,
"text": "Python-numpy"
},
{
"code": null,
"e": 26088,
"s": 26081,
"text": "Python"
},
{
"code": null,
"e": 26186,
"s": 26088,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26218,
"s": 26186,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 26274,
"s": 26218,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 26316,
"s": 26274,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 26358,
"s": 26316,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 26380,
"s": 26358,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 26419,
"s": 26380,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 26450,
"s": 26419,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 26505,
"s": 26450,
"text": "Selecting rows in pandas DataFrame based on conditions"
},
{
"code": null,
"e": 26534,
"s": 26505,
"text": "Create a directory in Python"
}
] |
Program to list of candidates who have got majority vote in python
|
Suppose we have a list of numbers called nums where each number represents a vote to a candidate. We have to find the ids of the candidates that have greater than floor(n/3) votes, in non-decreasing order.
So, if the input is like nums = [3, 2, 6, 6, 6, 6, 7, 7, 7, 7, 7], then the output will be [6, 7], as 6 and 7 have 40% of the votes.
To solve this, we will follow these steps −
ans := a new empty set
sort the list nums
i := 0
n := size of nums
while i < size of nums, doif occurrences of nums[i] in nums > (n / 3), theninsert nums[i] into ansi := i + (n / 3)
if occurrences of nums[i] in nums > (n / 3), theninsert nums[i] into ans
insert nums[i] into ans
i := i + (n / 3)
return ans in sorted order
Let us see the following implementation to get better understanding −
Live Demo
class Solution:
def solve(self, nums):
ans = set([])
nums.sort()
i = 0
n = len(nums)
while i < len(nums):
if nums.count(nums[i]) > n // 3:
ans.add(nums[i])
i += n // 3
return sorted(list(ans))
ob = Solution()
nums = [3, 2, 6, 6, 6, 6, 7, 7, 7, 7, 7]
print(ob.solve(nums))
[3, 2, 6, 6, 6, 6, 7, 7, 7, 7, 7]
[6, 7]
|
[
{
"code": null,
"e": 1268,
"s": 1062,
"text": "Suppose we have a list of numbers called nums where each number represents a vote to a candidate. We have to find the ids of the candidates that have greater than floor(n/3) votes, in non-decreasing order."
},
{
"code": null,
"e": 1401,
"s": 1268,
"text": "So, if the input is like nums = [3, 2, 6, 6, 6, 6, 7, 7, 7, 7, 7], then the output will be [6, 7], as 6 and 7 have 40% of the votes."
},
{
"code": null,
"e": 1445,
"s": 1401,
"text": "To solve this, we will follow these steps −"
},
{
"code": null,
"e": 1468,
"s": 1445,
"text": "ans := a new empty set"
},
{
"code": null,
"e": 1487,
"s": 1468,
"text": "sort the list nums"
},
{
"code": null,
"e": 1494,
"s": 1487,
"text": "i := 0"
},
{
"code": null,
"e": 1512,
"s": 1494,
"text": "n := size of nums"
},
{
"code": null,
"e": 1627,
"s": 1512,
"text": "while i < size of nums, doif occurrences of nums[i] in nums > (n / 3), theninsert nums[i] into ansi := i + (n / 3)"
},
{
"code": null,
"e": 1700,
"s": 1627,
"text": "if occurrences of nums[i] in nums > (n / 3), theninsert nums[i] into ans"
},
{
"code": null,
"e": 1724,
"s": 1700,
"text": "insert nums[i] into ans"
},
{
"code": null,
"e": 1741,
"s": 1724,
"text": "i := i + (n / 3)"
},
{
"code": null,
"e": 1768,
"s": 1741,
"text": "return ans in sorted order"
},
{
"code": null,
"e": 1838,
"s": 1768,
"text": "Let us see the following implementation to get better understanding −"
},
{
"code": null,
"e": 1848,
"s": 1838,
"text": "Live Demo"
},
{
"code": null,
"e": 2189,
"s": 1848,
"text": "class Solution:\n def solve(self, nums):\n ans = set([])\n nums.sort()\n i = 0\n n = len(nums)\n while i < len(nums):\n if nums.count(nums[i]) > n // 3:\n ans.add(nums[i])\n i += n // 3\n return sorted(list(ans))\nob = Solution()\nnums = [3, 2, 6, 6, 6, 6, 7, 7, 7, 7, 7]\nprint(ob.solve(nums))"
},
{
"code": null,
"e": 2223,
"s": 2189,
"text": "[3, 2, 6, 6, 6, 6, 7, 7, 7, 7, 7]"
},
{
"code": null,
"e": 2230,
"s": 2223,
"text": "[6, 7]"
}
] |
A Simple Guide To Command Line Arguments With ArgParse | by Sam Starkman | Towards Data Science
|
The standard Python library argparse used to incorporate the parsing of command line arguments. Instead of having to manually set variables inside of the code, argparse can be used to add flexibility and reusability to your code by allowing user input values to be parsed and utilized.
Since argparse is part of the standard Python library, it should already be installed. However, if it’s not, you can install it using the follwing command:
pip install argparse
If you do not have pip installed, follow the installation docs here.
Here is a file called hello.py to demonstrate a very basic example of the structure and usage of the argparse library:
# Import the libraryimport argparse# Create the parserparser = argparse.ArgumentParser()# Add an argumentparser.add_argument('--name', type=str, required=True)# Parse the argumentargs = parser.parse_args()# Print "Hello" + the user input argumentprint('Hello,', args.name)
The code above is the most straightforward way to implement argparse. After importing the library, argparse.ArgumentParser() initializes the parser so that you can start to add custom arguments. To add your arguments, use parser.add_argument(). Some important parameters to note for this method are name, type, and required. The name is exactly what it sounds like — the name of the command line field. The type is the variable type that is expected as an input, and the required parameter is a boolean for whether or not this command line field is mandatory or not. The actual arguments can be accessed with args.name, where name is the name of the argument identified in add_argument().
Below is an example of the output when this code is run:
C:/> python hello.pyusage: hello.py [-h] --name NAMEhello.py: error: the following arguments are required: --name
As you can see, this will throw an error because the required name argument is missing. This is the result when you include --name:
C:/> python hello.py --name SamHello, Sam
Sometimes, you don’t want to use the flag’s name in the argument. You can use a positional argument to eliminate the need to specify the --name flag before inputting the actual value. Below are two versions — the first without positional arguments (multiply.py), and the second using positional arguments (multiply_with_positional.py).
import argparseparser = argparse.ArgumentParser()parser.add_argument('--x', type=int, required=True)parser.add_argument('--y', type=int, required=True)args = parser.parse_args()product = args.x * args.yprint('Product:', product)
C:/> python multiply.py --x 4 --y 5Product: 20
import argparseparser = argparse.ArgumentParser()parser.add_argument('x', type=int)parser.add_argument('y', type=int)args = parser.parse_args()product = args.x * args.yprint('Product:', product)
C:/> python multiply_with_positional.py 4 5Product: 20
While positional arguments make the command line cleaner, it can sometimes be difficult to tell what the actual field is since there is no visible name associated with it. To aid with this, you can use the help parameter in add_argument() to specify more details about the argument.
parser.add_argument('x', type=int, help='The first value to multiply')parser.add_argument('y', type=int, help='The second value to multiply')
Now, when you run your program with the help flag -h, you can see these details.
C:/> python multiply.py -husage: multiply.py [-h] x ypositional arguments:x The first value to multiplyy The second value to multiply
Optional arguments are useful if you want to give the user a choice to enable certain features. To add an optional argument, simply omit the required parameter in add_argument().
import argparseparser = argparse.ArgumentParser()parser.add_argument('--name', type=str, required=True)parser.add_argument('--age', type=int)args = parser.parse_args()if args.age: print(args.name, 'is', args.age, 'years old.')else: print('Hello,', args.name + '!')
Here we see two arguments: a name, which is required, and an optional age. (Notice the required=True is missing from the --age argument.)
The two outputs below show the execution when --age is included and when it is not.
C:/> python optional.py --name Sam --age 23Sam is 23 years old.
C:/> python optional.py --name SamHello, Sam!
We can check to see if the args.age argument exists and implement different logic based on whether or not the value was included.
Let’s say that instead of specifying x and y arguments for the user to input, you want the user to input a list of numbers and the script will return the sum of them all. There is no need to create a new argument for each new value (you also can’t possibly know how many values a user will input!) Using the nargs parameter in add_argument(), you can specify the number (or arbitrary number) of inputs the argument should expect.
In this example named sum.py, the --valueargument takes in 3 integers and will print the sum.
import argparseparser = argparse.ArgumentParser()parser.add_argument('--values', type=int, nargs=3)args = parser.parse_args()sum = sum(args.values)print('Sum:', sum)
C:/> python sum.py --values 1 2 3Sum: 6
What if you don’t want just 3 values, but any number of inputs? You can set nargs='+', which will allow the argument to take in any number of values. Using the same example above, with the only change being nargs=3 to nargs='+', you can run the script with however many input values you want.
C:/> python sum.py --values 1 2 3Sum: 6C:/> python sum.py --values 2 4 6 8 10Sum: 30C:/> python sum.py --values 1 2 3 4 5 6 7 8 9 10Sum: 55
Another important argparse feature is mutally exclusive arguments. There are times that, depending on one argument, you want to restrict the use of another. This could be because the user should only need to use one of the arguments, or that the arguments conflict with each other. The method add_mutually_exclusive_group() let’s us do exactly that — add a group of arguments that are mutually exclusive.
This next example, mutually_exclusive.py, demonstrates how both arguments in a mutually exclusive group cannot be used at the same time.
import argparseparser = argparse.ArgumentParser()group = parser.add_mutually_exclusive_group()group.add_argument('--add', action='store_true')group.add_argument('--subtract', action='store_true')parser.add_argument('x', type=int)parser.add_argument('y', type=int)args = parser.parse_args()if args.add: sum = args.x + args.y print('Sum:', sum)elif args.subtract: difference = args.x - args.y print('Difference:', difference)
By creating a group with group = parser.add_mutually_exclusive_group(), the user is only allowed to select one of the arguments to use. In the add_argument() method, there is a new parameter called action. This is simply storing the default method if the argument is blank.
The output example below shows what happens when you try to call --add and --subtract in the same command.
C:/> python mutually_exclusive.py --add 1 2Sum: 3C:/> python mutually_exclusive.py --subtract 4 3Difference: 1C:/> python mutually_exclusive.py --add --subtract 4 3usage: mutually_exclusive.py [-h] [--add | --subtract] x ymutually_exclusive.py: error: argument --subtract: not allowed with argument --add
As you can see from the error message, the script does not allow for --add and --subtract to be called at the same time!
The last argparse feature I am going to discuss is subparsers. Subparsers are powerful in that they allow for different arguments to be permitted based on the command being run. For example, when using the git command, some options are git checkout, git commit, and git add. Each one of these commands requires a unique set of arguments, and subparsers allow you to distinguish between them.
This last example describes how to create a subparser to establish completely different sets of arguments, depending on the command run. This user.py script will be used to demonstrate a login or a register, contingent on the first positional argument provided.
import argparseparser = argparse.ArgumentParser()subparser = parser.add_subparsers(dest='command')login = subparser.add_parser('login')register = subparser.add_parser('register')login.add_argument('--username', type=str, required=True)login.add_argument('--password', type=str, required=True)register.add_argument('--firstname', type=str, required=True)register.add_argument('--lastname', type=str, required=True)register.add_argument('--username', type=str, required=True)register.add_argument('--email', type=str, required=True)register.add_argument('--password', type=str, required=True)args = parser.parse_args()if args.command == 'login': print('Logging in with username:', args.username, 'and password:', args.password)elif args.command == 'register': print('Creating username', args.username, 'for new member', args.firstname, args.lastname, 'with email:', args.email, 'and password:', args.password)
Here, we added subparser = parser.add_subparsers(dest='command'). This is used to create the subparser, and the dest='command' is used to differentiate between which argument is actually used. You can see in the if statement that we distinguish between “login” and “register” with args.command.
We create two separate subparsers — one for “login” and one for “register”. This allows us to add individual arguments to each. Here, the “login” subparser requires a username and a password. The “register” subparser takes in a first and last name, a username, an email, and a password. Depending on whether “login” or “register” is specified in the script, the user must input the correct arguments, and the conditional statement will confirm the results.
C:/> python user.py login --username D0loresh4ze --password whoismrrobotLogging in with username: D0loresh4ze and password: whoismrrobot
C:/> python user.py register --firstname Dolores --lastname Haze --username Doloresh4ze --email dhaze@ecorp.com --password whoismrrobotCreating username Doloresh4ze for new member Dolores Haze with email: dhaze@ecorp.com and password: whoismrrobot
As expected, the print statement for logging in is called when login is specified as the command argument, and the register print statement is called when register is specified with its respective arguments.
The goal of this post was to give a brief and relevant overview of the Python library argparse. Code cleanliness and reusability is extremely valuable these days, and argparse can help developers write more modular scripts when requiring user input and interaction.
Thank you all for reading — I hope that I was able to improve your understanding of argparse, and that you can utilize it in your next project!
|
[
{
"code": null,
"e": 457,
"s": 171,
"text": "The standard Python library argparse used to incorporate the parsing of command line arguments. Instead of having to manually set variables inside of the code, argparse can be used to add flexibility and reusability to your code by allowing user input values to be parsed and utilized."
},
{
"code": null,
"e": 613,
"s": 457,
"text": "Since argparse is part of the standard Python library, it should already be installed. However, if it’s not, you can install it using the follwing command:"
},
{
"code": null,
"e": 634,
"s": 613,
"text": "pip install argparse"
},
{
"code": null,
"e": 703,
"s": 634,
"text": "If you do not have pip installed, follow the installation docs here."
},
{
"code": null,
"e": 822,
"s": 703,
"text": "Here is a file called hello.py to demonstrate a very basic example of the structure and usage of the argparse library:"
},
{
"code": null,
"e": 1095,
"s": 822,
"text": "# Import the libraryimport argparse# Create the parserparser = argparse.ArgumentParser()# Add an argumentparser.add_argument('--name', type=str, required=True)# Parse the argumentargs = parser.parse_args()# Print \"Hello\" + the user input argumentprint('Hello,', args.name)"
},
{
"code": null,
"e": 1784,
"s": 1095,
"text": "The code above is the most straightforward way to implement argparse. After importing the library, argparse.ArgumentParser() initializes the parser so that you can start to add custom arguments. To add your arguments, use parser.add_argument(). Some important parameters to note for this method are name, type, and required. The name is exactly what it sounds like — the name of the command line field. The type is the variable type that is expected as an input, and the required parameter is a boolean for whether or not this command line field is mandatory or not. The actual arguments can be accessed with args.name, where name is the name of the argument identified in add_argument()."
},
{
"code": null,
"e": 1841,
"s": 1784,
"text": "Below is an example of the output when this code is run:"
},
{
"code": null,
"e": 1955,
"s": 1841,
"text": "C:/> python hello.pyusage: hello.py [-h] --name NAMEhello.py: error: the following arguments are required: --name"
},
{
"code": null,
"e": 2087,
"s": 1955,
"text": "As you can see, this will throw an error because the required name argument is missing. This is the result when you include --name:"
},
{
"code": null,
"e": 2129,
"s": 2087,
"text": "C:/> python hello.py --name SamHello, Sam"
},
{
"code": null,
"e": 2465,
"s": 2129,
"text": "Sometimes, you don’t want to use the flag’s name in the argument. You can use a positional argument to eliminate the need to specify the --name flag before inputting the actual value. Below are two versions — the first without positional arguments (multiply.py), and the second using positional arguments (multiply_with_positional.py)."
},
{
"code": null,
"e": 2694,
"s": 2465,
"text": "import argparseparser = argparse.ArgumentParser()parser.add_argument('--x', type=int, required=True)parser.add_argument('--y', type=int, required=True)args = parser.parse_args()product = args.x * args.yprint('Product:', product)"
},
{
"code": null,
"e": 2741,
"s": 2694,
"text": "C:/> python multiply.py --x 4 --y 5Product: 20"
},
{
"code": null,
"e": 2936,
"s": 2741,
"text": "import argparseparser = argparse.ArgumentParser()parser.add_argument('x', type=int)parser.add_argument('y', type=int)args = parser.parse_args()product = args.x * args.yprint('Product:', product)"
},
{
"code": null,
"e": 2991,
"s": 2936,
"text": "C:/> python multiply_with_positional.py 4 5Product: 20"
},
{
"code": null,
"e": 3274,
"s": 2991,
"text": "While positional arguments make the command line cleaner, it can sometimes be difficult to tell what the actual field is since there is no visible name associated with it. To aid with this, you can use the help parameter in add_argument() to specify more details about the argument."
},
{
"code": null,
"e": 3416,
"s": 3274,
"text": "parser.add_argument('x', type=int, help='The first value to multiply')parser.add_argument('y', type=int, help='The second value to multiply')"
},
{
"code": null,
"e": 3497,
"s": 3416,
"text": "Now, when you run your program with the help flag -h, you can see these details."
},
{
"code": null,
"e": 3651,
"s": 3497,
"text": "C:/> python multiply.py -husage: multiply.py [-h] x ypositional arguments:x The first value to multiplyy The second value to multiply"
},
{
"code": null,
"e": 3830,
"s": 3651,
"text": "Optional arguments are useful if you want to give the user a choice to enable certain features. To add an optional argument, simply omit the required parameter in add_argument()."
},
{
"code": null,
"e": 4097,
"s": 3830,
"text": "import argparseparser = argparse.ArgumentParser()parser.add_argument('--name', type=str, required=True)parser.add_argument('--age', type=int)args = parser.parse_args()if args.age: print(args.name, 'is', args.age, 'years old.')else: print('Hello,', args.name + '!')"
},
{
"code": null,
"e": 4235,
"s": 4097,
"text": "Here we see two arguments: a name, which is required, and an optional age. (Notice the required=True is missing from the --age argument.)"
},
{
"code": null,
"e": 4319,
"s": 4235,
"text": "The two outputs below show the execution when --age is included and when it is not."
},
{
"code": null,
"e": 4383,
"s": 4319,
"text": "C:/> python optional.py --name Sam --age 23Sam is 23 years old."
},
{
"code": null,
"e": 4429,
"s": 4383,
"text": "C:/> python optional.py --name SamHello, Sam!"
},
{
"code": null,
"e": 4559,
"s": 4429,
"text": "We can check to see if the args.age argument exists and implement different logic based on whether or not the value was included."
},
{
"code": null,
"e": 4989,
"s": 4559,
"text": "Let’s say that instead of specifying x and y arguments for the user to input, you want the user to input a list of numbers and the script will return the sum of them all. There is no need to create a new argument for each new value (you also can’t possibly know how many values a user will input!) Using the nargs parameter in add_argument(), you can specify the number (or arbitrary number) of inputs the argument should expect."
},
{
"code": null,
"e": 5083,
"s": 4989,
"text": "In this example named sum.py, the --valueargument takes in 3 integers and will print the sum."
},
{
"code": null,
"e": 5249,
"s": 5083,
"text": "import argparseparser = argparse.ArgumentParser()parser.add_argument('--values', type=int, nargs=3)args = parser.parse_args()sum = sum(args.values)print('Sum:', sum)"
},
{
"code": null,
"e": 5289,
"s": 5249,
"text": "C:/> python sum.py --values 1 2 3Sum: 6"
},
{
"code": null,
"e": 5582,
"s": 5289,
"text": "What if you don’t want just 3 values, but any number of inputs? You can set nargs='+', which will allow the argument to take in any number of values. Using the same example above, with the only change being nargs=3 to nargs='+', you can run the script with however many input values you want."
},
{
"code": null,
"e": 5722,
"s": 5582,
"text": "C:/> python sum.py --values 1 2 3Sum: 6C:/> python sum.py --values 2 4 6 8 10Sum: 30C:/> python sum.py --values 1 2 3 4 5 6 7 8 9 10Sum: 55"
},
{
"code": null,
"e": 6127,
"s": 5722,
"text": "Another important argparse feature is mutally exclusive arguments. There are times that, depending on one argument, you want to restrict the use of another. This could be because the user should only need to use one of the arguments, or that the arguments conflict with each other. The method add_mutually_exclusive_group() let’s us do exactly that — add a group of arguments that are mutually exclusive."
},
{
"code": null,
"e": 6264,
"s": 6127,
"text": "This next example, mutually_exclusive.py, demonstrates how both arguments in a mutually exclusive group cannot be used at the same time."
},
{
"code": null,
"e": 6692,
"s": 6264,
"text": "import argparseparser = argparse.ArgumentParser()group = parser.add_mutually_exclusive_group()group.add_argument('--add', action='store_true')group.add_argument('--subtract', action='store_true')parser.add_argument('x', type=int)parser.add_argument('y', type=int)args = parser.parse_args()if args.add: sum = args.x + args.y print('Sum:', sum)elif args.subtract: difference = args.x - args.y print('Difference:', difference)"
},
{
"code": null,
"e": 6966,
"s": 6692,
"text": "By creating a group with group = parser.add_mutually_exclusive_group(), the user is only allowed to select one of the arguments to use. In the add_argument() method, there is a new parameter called action. This is simply storing the default method if the argument is blank."
},
{
"code": null,
"e": 7073,
"s": 6966,
"text": "The output example below shows what happens when you try to call --add and --subtract in the same command."
},
{
"code": null,
"e": 7378,
"s": 7073,
"text": "C:/> python mutually_exclusive.py --add 1 2Sum: 3C:/> python mutually_exclusive.py --subtract 4 3Difference: 1C:/> python mutually_exclusive.py --add --subtract 4 3usage: mutually_exclusive.py [-h] [--add | --subtract] x ymutually_exclusive.py: error: argument --subtract: not allowed with argument --add"
},
{
"code": null,
"e": 7499,
"s": 7378,
"text": "As you can see from the error message, the script does not allow for --add and --subtract to be called at the same time!"
},
{
"code": null,
"e": 7891,
"s": 7499,
"text": "The last argparse feature I am going to discuss is subparsers. Subparsers are powerful in that they allow for different arguments to be permitted based on the command being run. For example, when using the git command, some options are git checkout, git commit, and git add. Each one of these commands requires a unique set of arguments, and subparsers allow you to distinguish between them."
},
{
"code": null,
"e": 8153,
"s": 7891,
"text": "This last example describes how to create a subparser to establish completely different sets of arguments, depending on the command run. This user.py script will be used to demonstrate a login or a register, contingent on the first positional argument provided."
},
{
"code": null,
"e": 9067,
"s": 8153,
"text": "import argparseparser = argparse.ArgumentParser()subparser = parser.add_subparsers(dest='command')login = subparser.add_parser('login')register = subparser.add_parser('register')login.add_argument('--username', type=str, required=True)login.add_argument('--password', type=str, required=True)register.add_argument('--firstname', type=str, required=True)register.add_argument('--lastname', type=str, required=True)register.add_argument('--username', type=str, required=True)register.add_argument('--email', type=str, required=True)register.add_argument('--password', type=str, required=True)args = parser.parse_args()if args.command == 'login': print('Logging in with username:', args.username, 'and password:', args.password)elif args.command == 'register': print('Creating username', args.username, 'for new member', args.firstname, args.lastname, 'with email:', args.email, 'and password:', args.password)"
},
{
"code": null,
"e": 9362,
"s": 9067,
"text": "Here, we added subparser = parser.add_subparsers(dest='command'). This is used to create the subparser, and the dest='command' is used to differentiate between which argument is actually used. You can see in the if statement that we distinguish between “login” and “register” with args.command."
},
{
"code": null,
"e": 9819,
"s": 9362,
"text": "We create two separate subparsers — one for “login” and one for “register”. This allows us to add individual arguments to each. Here, the “login” subparser requires a username and a password. The “register” subparser takes in a first and last name, a username, an email, and a password. Depending on whether “login” or “register” is specified in the script, the user must input the correct arguments, and the conditional statement will confirm the results."
},
{
"code": null,
"e": 9956,
"s": 9819,
"text": "C:/> python user.py login --username D0loresh4ze --password whoismrrobotLogging in with username: D0loresh4ze and password: whoismrrobot"
},
{
"code": null,
"e": 10204,
"s": 9956,
"text": "C:/> python user.py register --firstname Dolores --lastname Haze --username Doloresh4ze --email dhaze@ecorp.com --password whoismrrobotCreating username Doloresh4ze for new member Dolores Haze with email: dhaze@ecorp.com and password: whoismrrobot"
},
{
"code": null,
"e": 10412,
"s": 10204,
"text": "As expected, the print statement for logging in is called when login is specified as the command argument, and the register print statement is called when register is specified with its respective arguments."
},
{
"code": null,
"e": 10678,
"s": 10412,
"text": "The goal of this post was to give a brief and relevant overview of the Python library argparse. Code cleanliness and reusability is extremely valuable these days, and argparse can help developers write more modular scripts when requiring user input and interaction."
}
] |
Bulma | Pagination - GeeksforGeeks
|
29 Jun, 2020
Bulma is a FLexbox based open-source CSS framework and its completely free. It is component rich, compatible, and well documented. It is highly responsive in nature. It uses classes to implement its design.The ‘pagination’ is a component used to indicate the existence of a series of related content across multiple pages. Pagination is used to enable navigation between pages on a website. The pagination component includes several other components that we have to add exclusively to design our content well. These components are listed below.
pagination-previous: It is used to navigate to the previous page.
pagination-next: It is used to navigate to the next page.
pagination-list: It is used to display different pages of the website.pagination-link: It is to indicate the page number in the anchor tag.pagination-ellipsis: It creates the range separators between the page numbers.
pagination-link: It is to indicate the page number in the anchor tag.
pagination-ellipsis: It creates the range separators between the page numbers.
Example 1: This example shows simple Bulma pagination component.
<!DOCTYPE html><html> <head> <title>Bulma Pagination</title> <link rel='stylesheet' href='https://cdnjs.cloudflare.com/ajax/libs/bulma/0.7.5/css/bulma.css'> <!-- custom css --> <style> div.columns { margin-top: 80px; } </style></head> <body> <div class='container'> <div class='columns is-mobile is-centered'> <div class='column is-10'> <nav class="pagination" role="navigation" aria-label="pagination"> <a class="pagination-previous">Previous</a> <a class="pagination-next">Next page</a> <ul class="pagination-list"> <li> <a href="#" class="pagination-link" aria-label="Page 1">1</a> </li> <li> <a href="#" class="pagination-link is-current" aria-label="Goto page 2" aria-current="page">2</a> </li> <li> <a href="#" class="pagination-link" aria-label="Goto page 3">3</a> </li> <li> <a href="#" class="pagination-link" aria-label="Goto page 4">4</a> </li> <li> <a href="#" class="pagination-link" aria-label="Goto page 5">5</a> </li> <li> <a class="pagination-link" aria-label="Goto page 6">6</a> </li> </ul> </nav> </div> </div> </div></body> </html>
Output:
Example 2: This example shows pagination of large number of pages.
<!DOCTYPE html><html> <head> <title>Bulma Pagination</title> <link rel='stylesheet' href='https://cdnjs.cloudflare.com/ajax/libs/bulma/0.7.5/css/bulma.css'> <!-- custom css --> <style> div.columns { margin-top: 80px; } </style></head> <body> <div class='container'> <div class='columns is-mobile is-centered'> <div class='column is-10'> <nav class="pagination" role="navigation" aria-label="pagination"> <a class="pagination-previous">Previous</a> <a class="pagination-next">Next page</a> <ul class="pagination-list"> <li> <a class="pagination-link" aria-label="Goto page 1">1</a> </li> <li> <a class="pagination-link" aria-label="Goto page 2">2</a> </li> <li> <a class="pagination-link" aria-label="Goto page 3">3</a> </li> <li> <span class="pagination-ellipsis"> ... </span> </li> <li> <a class="pagination-link" aria-label="Goto page 26">26</a> </li> <li> <a class="pagination-link is-current" aria-label="Page 27" aria-current="page">27</a> </li> <li> <a class="pagination-link" aria-label="Goto page 28">28</a> </li> <li> <a class="pagination-link" aria-label="Goto page 29">29</a> </li> <li> <a class="pagination-link" aria-label="Goto page 30">30</a> </li> </ul> </nav> </div> </div> </div></body> </html>
Output:
Example 3: This example shows pagination with different alignment.
<!DOCTYPE html><html> <head> <title>Bulma Pagination</title> <link rel='stylesheet' href='https://cdnjs.cloudflare.com/ajax/libs/bulma/0.7.5/css/bulma.css'> <!-- custom css --> <style> div.columns { margin-top: 80px; } .pagination { margin-bottom: 20px; } </style></head> <body> <div class='container'> <div class='columns is-mobile is-centered'> <div class='column is-10'> <nav class="pagination has-background-primary" role="navigation" aria-label="pagination"> <a class="pagination-previous">Previous</a> <a class="pagination-next">Next page</a> <ul class="pagination-list"> <li> <a class="pagination-link" aria-label="Goto page 1">1</a> </li> <li> <a class="pagination-link" aria-label="Goto page 2">2</a> </li> <li> <a class="pagination-link" aria-label="Goto page 3">3</a> </li> <li> <span class="pagination-ellipsis"> ... </span> </li> <li> <a class="pagination-link" aria-label="Goto page 26">26</a> </li> <li> <a class="pagination-link is-current" aria-label="Page 27" aria-current="page">27</a> </li> <li> <a class="pagination-link" aria-label="Goto page 28">28</a> </li> <li> <a class="pagination-link" aria-label="Goto page 29">29</a> </li> <li> <a class="pagination-link" aria-label="Goto page 30">30</a> </li> </ul> </nav> <nav class="pagination is-centered has-background-success" role="navigation" aria-label="pagination"> <a class="pagination-previous">Previous</a> <a class="pagination-next">Next page</a> <ul class="pagination-list"> <li> <a class="pagination-link" aria-label="Goto page 1">1</a> </li> <li> <a class="pagination-link" aria-label="Goto page 2">2</a> </li> <li> <a class="pagination-link" aria-label="Goto page 3">3</a> </li> <li> <span class="pagination-ellipsis"> ... </span> </li> <li> <a class="pagination-link" aria-label="Goto page 26">26</a> </li> <li> <a class="pagination-link is-current" aria-label="Page 27" aria-current="page">27</a> </li> <li> <a class="pagination-link" aria-label="Goto page 28">28</a> </li> <li> <a class="pagination-link" aria-label="Goto page 29">29</a> </li> <li> <a class="pagination-link" aria-label="Goto page 30">30</a> </li> </ul> </nav> <nav class="pagination is-right has-background-info" role="navigation" aria-label="pagination"> <a class="pagination-previous">Previous</a> <a class="pagination-next">Next page</a> <ul class="pagination-list"> <li> <a class="pagination-link" aria-label="Goto page 1">1</a> </li> <li> <a class="pagination-link" aria-label="Goto page 2">2</a> </li> <li> <a class="pagination-link" aria-label="Goto page 3">3</a> </li> <li> <span class="pagination-ellipsis"> ... </span> </li> <li> <a class="pagination-link" aria-label="Goto page 26">26</a> </li> <li> <a class="pagination-link is-current" aria-label="Page 27" aria-current="page">27</a> </li> <li> <a class="pagination-link" aria-label="Goto page 28">28</a> </li> <li> <a class="pagination-link" aria-label="Goto page 29">29</a> </li> <li> <a class="pagination-link" aria-label="Goto page 30">30</a> </li> </ul> </nav> </div> </div> </div></body> </html>
Output:
Example 4: This example shows pagination with different sizes.
<!DOCTYPE html><html> <head> <title>Bulma Pagination</title> <link rel='stylesheet' href='https://cdnjs.cloudflare.com/ajax/libs/bulma/0.7.5/css/bulma.css'> <!-- custom css --> <style> div.columns { margin-top: 80px; } .pagination { margin-bottom: 20px; } </style></head> <body> <div class='container'> <div class='columns is-mobile is-centered'> <div class='column is-10'> <nav class="pagination is-small has-background-primary" role="navigation" aria-label="pagination"> <a class="pagination-previous">Previous</a> <a class="pagination-next">Next page</a> <ul class="pagination-list"> <li> <a class="pagination-link" aria-label="Goto page 1">1</a> </li> <li> <a class="pagination-link" aria-label="Goto page 2">2</a> </li> <li> <a class="pagination-link" aria-label="Goto page 3">3</a> </li> <li> <span class="pagination-ellipsis"> ... </span> </li> <li> <a class="pagination-link" aria-label="Goto page 26">26</a> </li> <li> <a class="pagination-link is-current" aria-label="Page 27" aria-current="page">27</a> </li> <li> <a class="pagination-link" aria-label="Goto page 28">28</a> </li> <li> <a class="pagination-link" aria-label="Goto page 29">29</a> </li> <li> <a class="pagination-link" aria-label="Goto page 30">30</a> </li> </ul> </nav> <nav class="pagination is-medium has-background-success" role="navigation" aria-label="pagination"> <a class="pagination-previous">Previous</a> <a class="pagination-next">Next page</a> <ul class="pagination-list"> <li> <a class="pagination-link" aria-label="Goto page 1">1</a> </li> <li> <a class="pagination-link" aria-label="Goto page 2">2</a> </li> <li> <a class="pagination-link" aria-label="Goto page 3">3</a> </li> <li> <span class="pagination-ellipsis"> ... </span> </li> <li> <a class="pagination-link" aria-label="Goto page 26">26</a> </li> <li> <a class="pagination-link is-current" aria-label="Page 27" aria-current="page">27</a> </li> <li> <a class="pagination-link" aria-label="Goto page 28">28</a> </li> <li> <a class="pagination-link" aria-label="Goto page 29">29</a> </li> <li> <a class="pagination-link" aria-label="Goto page 30">30</a> </li> </ul> </nav> <nav class="pagination is-large has-background-info" role="navigation" aria-label="pagination"> <a class="pagination-previous">Previous</a> <a class="pagination-next">Next page</a> <ul class="pagination-list"> <li> <a class="pagination-link" aria-label="Goto page 1">1</a> </li> <li> <a class="pagination-link" aria-label="Goto page 2">2</a> </li> <li> <a class="pagination-link" aria-label="Goto page 3">3</a> </li> <li> <span class="pagination-ellipsis"> ... </span> </li> <li> <a class="pagination-link" aria-label="Goto page 26">26</a> </li> <li> <a class="pagination-link is-current" aria-label="Page 27" aria-current="page">27</a> </li> <li> <a class="pagination-link" aria-label="Goto page 28">28</a> </li> <li> <a class="pagination-link" aria-label="Goto page 29">29</a> </li> <li> <a class="pagination-link" aria-label="Goto page 30">30</a> </li> </ul> </nav> </div> </div> </div></body> </html>
Output:
Example 5: This example shows rounded pagination feature.
<!DOCTYPE html><html> <head> <title>Bulma Pagination</title> <link rel='stylesheet' href='https://cdnjs.cloudflare.com/ajax/libs/bulma/0.7.5/css/bulma.css'> <!-- custom css --> <style> div.columns { margin-top: 80px; } .pagination { margin-bottom: 20px; } </style></head> <body> <div class='container'> <div class='columns is-mobile is-centered'> <div class='column is-10'> <nav class="pagination is-rounded" role="navigation" aria-label="pagination"> <a class="pagination-previous">Previous</a> <a class="pagination-next">Next page</a> <ul class="pagination-list"> <li> <a class="pagination-link" aria-label="Goto page 1">1</a> </li> <li> <a class="pagination-link" aria-label="Goto page 2">2</a> </li> <li> <a class="pagination-link" aria-label="Goto page 3">3</a> </li> <li> <span class="pagination-ellipsis"> ... </span> </li> <li> <a class="pagination-link" aria-label="Goto page 26">26</a> </li> <li> <a class="pagination-link is-current" aria-label="Page 27" aria-current="page">27</a> </li> <li> <a class="pagination-link" aria-label="Goto page 28">28</a> </li> <li> <a class="pagination-link" aria-label="Goto page 29">29</a> </li> <li> <a class="pagination-link" aria-label="Goto page 30">30</a> </li> </ul> </nav> </div> </div> </div></body> </html>
Output:
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course.
Bulma
CSS
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
How to create footer to stay at the bottom of a Web page?
How to update Node.js and NPM to next version ?
CSS to put icon inside an input element in a form
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
How to set the default value for an HTML <select> element ?
How to update Node.js and NPM to next version ?
How to set input type date in dd-mm-yyyy format using HTML ?
|
[
{
"code": null,
"e": 26108,
"s": 26080,
"text": "\n29 Jun, 2020"
},
{
"code": null,
"e": 26653,
"s": 26108,
"text": "Bulma is a FLexbox based open-source CSS framework and its completely free. It is component rich, compatible, and well documented. It is highly responsive in nature. It uses classes to implement its design.The ‘pagination’ is a component used to indicate the existence of a series of related content across multiple pages. Pagination is used to enable navigation between pages on a website. The pagination component includes several other components that we have to add exclusively to design our content well. These components are listed below."
},
{
"code": null,
"e": 26719,
"s": 26653,
"text": "pagination-previous: It is used to navigate to the previous page."
},
{
"code": null,
"e": 26777,
"s": 26719,
"text": "pagination-next: It is used to navigate to the next page."
},
{
"code": null,
"e": 26995,
"s": 26777,
"text": "pagination-list: It is used to display different pages of the website.pagination-link: It is to indicate the page number in the anchor tag.pagination-ellipsis: It creates the range separators between the page numbers."
},
{
"code": null,
"e": 27065,
"s": 26995,
"text": "pagination-link: It is to indicate the page number in the anchor tag."
},
{
"code": null,
"e": 27144,
"s": 27065,
"text": "pagination-ellipsis: It creates the range separators between the page numbers."
},
{
"code": null,
"e": 27209,
"s": 27144,
"text": "Example 1: This example shows simple Bulma pagination component."
},
{
"code": "<!DOCTYPE html><html> <head> <title>Bulma Pagination</title> <link rel='stylesheet' href='https://cdnjs.cloudflare.com/ajax/libs/bulma/0.7.5/css/bulma.css'> <!-- custom css --> <style> div.columns { margin-top: 80px; } </style></head> <body> <div class='container'> <div class='columns is-mobile is-centered'> <div class='column is-10'> <nav class=\"pagination\" role=\"navigation\" aria-label=\"pagination\"> <a class=\"pagination-previous\">Previous</a> <a class=\"pagination-next\">Next page</a> <ul class=\"pagination-list\"> <li> <a href=\"#\" class=\"pagination-link\" aria-label=\"Page 1\">1</a> </li> <li> <a href=\"#\" class=\"pagination-link is-current\" aria-label=\"Goto page 2\" aria-current=\"page\">2</a> </li> <li> <a href=\"#\" class=\"pagination-link\" aria-label=\"Goto page 3\">3</a> </li> <li> <a href=\"#\" class=\"pagination-link\" aria-label=\"Goto page 4\">4</a> </li> <li> <a href=\"#\" class=\"pagination-link\" aria-label=\"Goto page 5\">5</a> </li> <li> <a class=\"pagination-link\" aria-label=\"Goto page 6\">6</a> </li> </ul> </nav> </div> </div> </div></body> </html>",
"e": 28688,
"s": 27209,
"text": null
},
{
"code": null,
"e": 28696,
"s": 28688,
"text": "Output:"
},
{
"code": null,
"e": 28763,
"s": 28696,
"text": "Example 2: This example shows pagination of large number of pages."
},
{
"code": "<!DOCTYPE html><html> <head> <title>Bulma Pagination</title> <link rel='stylesheet' href='https://cdnjs.cloudflare.com/ajax/libs/bulma/0.7.5/css/bulma.css'> <!-- custom css --> <style> div.columns { margin-top: 80px; } </style></head> <body> <div class='container'> <div class='columns is-mobile is-centered'> <div class='column is-10'> <nav class=\"pagination\" role=\"navigation\" aria-label=\"pagination\"> <a class=\"pagination-previous\">Previous</a> <a class=\"pagination-next\">Next page</a> <ul class=\"pagination-list\"> <li> <a class=\"pagination-link\" aria-label=\"Goto page 1\">1</a> </li> <li> <a class=\"pagination-link\" aria-label=\"Goto page 2\">2</a> </li> <li> <a class=\"pagination-link\" aria-label=\"Goto page 3\">3</a> </li> <li> <span class=\"pagination-ellipsis\"> ... </span> </li> <li> <a class=\"pagination-link\" aria-label=\"Goto page 26\">26</a> </li> <li> <a class=\"pagination-link is-current\" aria-label=\"Page 27\" aria-current=\"page\">27</a> </li> <li> <a class=\"pagination-link\" aria-label=\"Goto page 28\">28</a> </li> <li> <a class=\"pagination-link\" aria-label=\"Goto page 29\">29</a> </li> <li> <a class=\"pagination-link\" aria-label=\"Goto page 30\">30</a> </li> </ul> </nav> </div> </div> </div></body> </html>",
"e": 30568,
"s": 28763,
"text": null
},
{
"code": null,
"e": 30576,
"s": 30568,
"text": "Output:"
},
{
"code": null,
"e": 30643,
"s": 30576,
"text": "Example 3: This example shows pagination with different alignment."
},
{
"code": "<!DOCTYPE html><html> <head> <title>Bulma Pagination</title> <link rel='stylesheet' href='https://cdnjs.cloudflare.com/ajax/libs/bulma/0.7.5/css/bulma.css'> <!-- custom css --> <style> div.columns { margin-top: 80px; } .pagination { margin-bottom: 20px; } </style></head> <body> <div class='container'> <div class='columns is-mobile is-centered'> <div class='column is-10'> <nav class=\"pagination has-background-primary\" role=\"navigation\" aria-label=\"pagination\"> <a class=\"pagination-previous\">Previous</a> <a class=\"pagination-next\">Next page</a> <ul class=\"pagination-list\"> <li> <a class=\"pagination-link\" aria-label=\"Goto page 1\">1</a> </li> <li> <a class=\"pagination-link\" aria-label=\"Goto page 2\">2</a> </li> <li> <a class=\"pagination-link\" aria-label=\"Goto page 3\">3</a> </li> <li> <span class=\"pagination-ellipsis\"> ... </span> </li> <li> <a class=\"pagination-link\" aria-label=\"Goto page 26\">26</a> </li> <li> <a class=\"pagination-link is-current\" aria-label=\"Page 27\" aria-current=\"page\">27</a> </li> <li> <a class=\"pagination-link\" aria-label=\"Goto page 28\">28</a> </li> <li> <a class=\"pagination-link\" aria-label=\"Goto page 29\">29</a> </li> <li> <a class=\"pagination-link\" aria-label=\"Goto page 30\">30</a> </li> </ul> </nav> <nav class=\"pagination is-centered has-background-success\" role=\"navigation\" aria-label=\"pagination\"> <a class=\"pagination-previous\">Previous</a> <a class=\"pagination-next\">Next page</a> <ul class=\"pagination-list\"> <li> <a class=\"pagination-link\" aria-label=\"Goto page 1\">1</a> </li> <li> <a class=\"pagination-link\" aria-label=\"Goto page 2\">2</a> </li> <li> <a class=\"pagination-link\" aria-label=\"Goto page 3\">3</a> </li> <li> <span class=\"pagination-ellipsis\"> ... </span> </li> <li> <a class=\"pagination-link\" aria-label=\"Goto page 26\">26</a> </li> <li> <a class=\"pagination-link is-current\" aria-label=\"Page 27\" aria-current=\"page\">27</a> </li> <li> <a class=\"pagination-link\" aria-label=\"Goto page 28\">28</a> </li> <li> <a class=\"pagination-link\" aria-label=\"Goto page 29\">29</a> </li> <li> <a class=\"pagination-link\" aria-label=\"Goto page 30\">30</a> </li> </ul> </nav> <nav class=\"pagination is-right has-background-info\" role=\"navigation\" aria-label=\"pagination\"> <a class=\"pagination-previous\">Previous</a> <a class=\"pagination-next\">Next page</a> <ul class=\"pagination-list\"> <li> <a class=\"pagination-link\" aria-label=\"Goto page 1\">1</a> </li> <li> <a class=\"pagination-link\" aria-label=\"Goto page 2\">2</a> </li> <li> <a class=\"pagination-link\" aria-label=\"Goto page 3\">3</a> </li> <li> <span class=\"pagination-ellipsis\"> ... </span> </li> <li> <a class=\"pagination-link\" aria-label=\"Goto page 26\">26</a> </li> <li> <a class=\"pagination-link is-current\" aria-label=\"Page 27\" aria-current=\"page\">27</a> </li> <li> <a class=\"pagination-link\" aria-label=\"Goto page 28\">28</a> </li> <li> <a class=\"pagination-link\" aria-label=\"Goto page 29\">29</a> </li> <li> <a class=\"pagination-link\" aria-label=\"Goto page 30\">30</a> </li> </ul> </nav> </div> </div> </div></body> </html>",
"e": 35423,
"s": 30643,
"text": null
},
{
"code": null,
"e": 35431,
"s": 35423,
"text": "Output:"
},
{
"code": null,
"e": 35494,
"s": 35431,
"text": "Example 4: This example shows pagination with different sizes."
},
{
"code": "<!DOCTYPE html><html> <head> <title>Bulma Pagination</title> <link rel='stylesheet' href='https://cdnjs.cloudflare.com/ajax/libs/bulma/0.7.5/css/bulma.css'> <!-- custom css --> <style> div.columns { margin-top: 80px; } .pagination { margin-bottom: 20px; } </style></head> <body> <div class='container'> <div class='columns is-mobile is-centered'> <div class='column is-10'> <nav class=\"pagination is-small has-background-primary\" role=\"navigation\" aria-label=\"pagination\"> <a class=\"pagination-previous\">Previous</a> <a class=\"pagination-next\">Next page</a> <ul class=\"pagination-list\"> <li> <a class=\"pagination-link\" aria-label=\"Goto page 1\">1</a> </li> <li> <a class=\"pagination-link\" aria-label=\"Goto page 2\">2</a> </li> <li> <a class=\"pagination-link\" aria-label=\"Goto page 3\">3</a> </li> <li> <span class=\"pagination-ellipsis\"> ... </span> </li> <li> <a class=\"pagination-link\" aria-label=\"Goto page 26\">26</a> </li> <li> <a class=\"pagination-link is-current\" aria-label=\"Page 27\" aria-current=\"page\">27</a> </li> <li> <a class=\"pagination-link\" aria-label=\"Goto page 28\">28</a> </li> <li> <a class=\"pagination-link\" aria-label=\"Goto page 29\">29</a> </li> <li> <a class=\"pagination-link\" aria-label=\"Goto page 30\">30</a> </li> </ul> </nav> <nav class=\"pagination is-medium has-background-success\" role=\"navigation\" aria-label=\"pagination\"> <a class=\"pagination-previous\">Previous</a> <a class=\"pagination-next\">Next page</a> <ul class=\"pagination-list\"> <li> <a class=\"pagination-link\" aria-label=\"Goto page 1\">1</a> </li> <li> <a class=\"pagination-link\" aria-label=\"Goto page 2\">2</a> </li> <li> <a class=\"pagination-link\" aria-label=\"Goto page 3\">3</a> </li> <li> <span class=\"pagination-ellipsis\"> ... </span> </li> <li> <a class=\"pagination-link\" aria-label=\"Goto page 26\">26</a> </li> <li> <a class=\"pagination-link is-current\" aria-label=\"Page 27\" aria-current=\"page\">27</a> </li> <li> <a class=\"pagination-link\" aria-label=\"Goto page 28\">28</a> </li> <li> <a class=\"pagination-link\" aria-label=\"Goto page 29\">29</a> </li> <li> <a class=\"pagination-link\" aria-label=\"Goto page 30\">30</a> </li> </ul> </nav> <nav class=\"pagination is-large has-background-info\" role=\"navigation\" aria-label=\"pagination\"> <a class=\"pagination-previous\">Previous</a> <a class=\"pagination-next\">Next page</a> <ul class=\"pagination-list\"> <li> <a class=\"pagination-link\" aria-label=\"Goto page 1\">1</a> </li> <li> <a class=\"pagination-link\" aria-label=\"Goto page 2\">2</a> </li> <li> <a class=\"pagination-link\" aria-label=\"Goto page 3\">3</a> </li> <li> <span class=\"pagination-ellipsis\"> ... </span> </li> <li> <a class=\"pagination-link\" aria-label=\"Goto page 26\">26</a> </li> <li> <a class=\"pagination-link is-current\" aria-label=\"Page 27\" aria-current=\"page\">27</a> </li> <li> <a class=\"pagination-link\" aria-label=\"Goto page 28\">28</a> </li> <li> <a class=\"pagination-link\" aria-label=\"Goto page 29\">29</a> </li> <li> <a class=\"pagination-link\" aria-label=\"Goto page 30\">30</a> </li> </ul> </nav> </div> </div> </div></body> </html>",
"e": 40312,
"s": 35494,
"text": null
},
{
"code": null,
"e": 40320,
"s": 40312,
"text": "Output:"
},
{
"code": null,
"e": 40378,
"s": 40320,
"text": "Example 5: This example shows rounded pagination feature."
},
{
"code": "<!DOCTYPE html><html> <head> <title>Bulma Pagination</title> <link rel='stylesheet' href='https://cdnjs.cloudflare.com/ajax/libs/bulma/0.7.5/css/bulma.css'> <!-- custom css --> <style> div.columns { margin-top: 80px; } .pagination { margin-bottom: 20px; } </style></head> <body> <div class='container'> <div class='columns is-mobile is-centered'> <div class='column is-10'> <nav class=\"pagination is-rounded\" role=\"navigation\" aria-label=\"pagination\"> <a class=\"pagination-previous\">Previous</a> <a class=\"pagination-next\">Next page</a> <ul class=\"pagination-list\"> <li> <a class=\"pagination-link\" aria-label=\"Goto page 1\">1</a> </li> <li> <a class=\"pagination-link\" aria-label=\"Goto page 2\">2</a> </li> <li> <a class=\"pagination-link\" aria-label=\"Goto page 3\">3</a> </li> <li> <span class=\"pagination-ellipsis\"> ... </span> </li> <li> <a class=\"pagination-link\" aria-label=\"Goto page 26\">26</a> </li> <li> <a class=\"pagination-link is-current\" aria-label=\"Page 27\" aria-current=\"page\">27</a> </li> <li> <a class=\"pagination-link\" aria-label=\"Goto page 28\">28</a> </li> <li> <a class=\"pagination-link\" aria-label=\"Goto page 29\">29</a> </li> <li> <a class=\"pagination-link\" aria-label=\"Goto page 30\">30</a> </li> </ul> </nav> </div> </div> </div></body> </html>",
"e": 42244,
"s": 40378,
"text": null
},
{
"code": null,
"e": 42252,
"s": 42244,
"text": "Output:"
},
{
"code": null,
"e": 42389,
"s": 42252,
"text": "Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course."
},
{
"code": null,
"e": 42395,
"s": 42389,
"text": "Bulma"
},
{
"code": null,
"e": 42399,
"s": 42395,
"text": "CSS"
},
{
"code": null,
"e": 42404,
"s": 42399,
"text": "HTML"
},
{
"code": null,
"e": 42421,
"s": 42404,
"text": "Web Technologies"
},
{
"code": null,
"e": 42426,
"s": 42421,
"text": "HTML"
},
{
"code": null,
"e": 42524,
"s": 42426,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 42586,
"s": 42524,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 42636,
"s": 42586,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
},
{
"code": null,
"e": 42694,
"s": 42636,
"text": "How to create footer to stay at the bottom of a Web page?"
},
{
"code": null,
"e": 42742,
"s": 42694,
"text": "How to update Node.js and NPM to next version ?"
},
{
"code": null,
"e": 42792,
"s": 42742,
"text": "CSS to put icon inside an input element in a form"
},
{
"code": null,
"e": 42854,
"s": 42792,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 42904,
"s": 42854,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
},
{
"code": null,
"e": 42964,
"s": 42904,
"text": "How to set the default value for an HTML <select> element ?"
},
{
"code": null,
"e": 43012,
"s": 42964,
"text": "How to update Node.js and NPM to next version ?"
}
] |
Python and Oracle Cloud: loading data | by Luigi Saetta | Towards Data Science
|
Using OCI Python SDK and Autonomous DWH API you can easily load data for your Data Science and ML work
In a previous article, I have explored how we can use Python and popular Open Source frameworks, like Pandas and scikit-learn, to analyze data stored with Oracle Autonomous Data Warehouse (ADWC). In this shorter story, I want to show you how you can easily load even big data files using OCI Python SDK.
One of the big features of the Cloud is Automation. In the Cloud World, it is easier to dynamically provision resources (like VM, or even Databases) and manage them using an API.
Oracle Cloud Infrastructure (OCI) has many tools, within which you can choose your preferred, to automate a large set of tasks (I would say: everything I need):
REST API
OCI CLI
SDK
OCI Command Line Interface (CLI) is really good. But, if you want to develop your highly customized tools, perfectly tailored on your shoulders, I would recommend using SDK.
As you can see in the documentation, we have:
Python SDK
Java SDK
Ruby SDK
Go SDK
Since we’re talking about Data Science and ML Engineering, I would without any doubt choose Python.
With OCI Python SDK you have a complete and easy-to-use set of classes, well-documented, enabling you to build Python scripts to automate a large part of the pipeline for your daily work with data. And, moreover, you can even use it inside a Jupyter Notebook (or Jupyter Lab).
So, some days ago, I started with the evening task to build, for one of my customers, some examples to show how to load data inside Oracle ADWC, starting from flat files. Then, as a nice side-effect, I decided to explore the subject a little more and created a script to start/stop VM and even start/stop my ADWC instance.
You can find the set of examples inside my Github repo
In this story, I want to explain, with more details, how to load data, starting from flat files.
Well, obviously there is the documentation, but, if you’re using PyPi, installation is only one line of code:
pip install oci
It works also with Anaconda.
If you want to be one of the first to try the new features added, simply check out the OCI Python Github repository.
Then, you need to do some configuration tasks, needed to ensure secure communication between your working environment and your OCI Cloud. I’ll spend some time to clarify here since I don’t want you to lose precious time on this part.
First, you need to create an API signing key-pair, in PEM format. You must keep the private safe on your environment (the computer running the Python program) and store the public key in your Cloud profile. When you store it, you can read from Cloud UI the fingerprint.
Some more details can be found here:
docs.cloud.oracle.com
Then, with every type of clients (ObjectStorageClient, ComputeClient, ....) you need to supply a set of (key, value) pair, packed as a Dictionary, in order to specify:
your OCI userid
a key (API signing key) used to secure communication
the fingerprint of this key
your Cloud tenant identifier
OCI Region
This is an example of what you need to prepare (anonymized):
config = {“user”: “ocid1.user.oc1..XXXXX”,“key_file”: “/Users/lsaetta/Progetti/xxxx/oci_api_key.pem”,“fingerprint”: “YYYYY”,“tenancy”: “ocid1.tenancy.oc1..ZZZZZZ”,“region”: “eu-frankfurt-1”}
For user and your Cloud tenant, you need to use not the name, but the identifier OCID, that you can copy from the OCI Cloud Console.
At this point, you’re ready to load a set of files as Objects in the ObjectStore.
This is the code to load a single file, I’ll comment sooner:
As you can see, you need:
to create a client, in this case an ObjectStorageClient, and pass to the constructor the configuration Dictionary
call the method put_object with bucket_name, file_name, file_path as parameters
That’s all.
In the Github repository, you’ll find an enhanced version, handling a set of files.
Now, it is time to copy data from ObjectStore to ADWC tables.
First of all: we need to create a set of credentials and store them inside the DB, in order to enable PL/SQL code to access the ObjectStorage Bucket.
Go to the OCI UI and create, inside your profile (top right icon and UserSetting), an AuthToken:
Copy from the UI the Authentication Token. Remember to do that right after created, otherwise, you will not able to re-read it.
Second, store the Cloud Credentials inside the DB using this code; This step needs to be done only once:
import cx_Oracleconnection = cx_Oracle.connect(USER, PWD, 'adwc5_medium')# need to create a cursorcur = connection.cursor()statement = """BEGIN DBMS_CLOUD.CREATE_CREDENTIAL( credential_name => 'DEF_CRED_NAME', username => 'adwc_user@oracle.com', password => '<AUTH Token>' );END;"""cur.execute(statement)
Take care: if your user is a federated one, the name is the fully qualified name. It has a prefix like:
oracleidentitycloudservice/
and you must specify, in the CREATE_CREDENTIAL call, the fully qualified name.
Since we have now the flat files in the ObjectStore, we can employ the PL/SQL package DBMS_CLOUD to load the data inside ADWC tables.
Ok, it is PL/SQL code, but not very complicated, and you can easily cut&paste. We’ll wrap this code inside Python code.
We’re imaging the simpler scenario: one Oracle table for flat file and the format of the file is the same as the table (one-to-one correspondence between file and table fields)
We have to create the table inside the DB. For example:
CREATE TABLE CHANNELS (channel_id char(1), channel_desc varchar2(20), channel_class varchar2(20) );/
Then we can load the data contained in one file in this table, with this code:
import cx_Oracleconnection = cx_Oracle.connect(USER, PWD, 'adwc5_medium')# need to create a cursorcur = connection.cursor()statement = """BEGIN DBMS_CLOUD.COPY_DATA( table_name =>'CHANNELS1', credential_name =>'DEF_CRED_NAME', file_uri_list =>'https://swiftobjectstorage.eu-frankfurt-1.oraclecloud.com/v1/tenant-name/BUCKET_NAME/channels1.txt', format => json_object('delimiter' value ',') );END;"""cur.execute(statement)
One detail: to reference the Object you need to use the SWIFT-type URL. What you need to change in the above example is:
the Region Name (here it is eu-frankurt-1)
the name of your tenant
the name of the bucket in Object Store
the name of the Object (here: channels1.txt)
As we can see, the DBMS_CLOUD package has all the required API to:
store credentials inside the DB
COPY from ObjectStore to DB
It provides also some other nice features. For example, you can use Apache Parquet format for the files, instead of CSV.
If you want to check that data has really been loaded, you can use this snippet of code:
import pandas as pdimport cx_Oracleconnection = cx_Oracle.connect(USER, PWD, 'adwc5_medium')channel1 = pd.read_sql("select * from CHANNELS1", con=connection)# if it is a Notebookchannel1.head()
Another option for Data Loading is to create in the DB an External Table, referring to the file. A soon as you have the external table working, you can use DML instructions to load data inside the DB. For example, you can use CTAS: CREATE TABLE AS SELECT.
The procedure to create the external table is:
DBMS_CLOUD.CREATE_EXTERNAL_TABLE
more details here.
As a Data Scientist, you need to work with data. Sometimes you’ll need to load by yourself. Sometimes, you’ll have a DBA to load for you.
In this article, I have shown how to use OCI Python SDK to:
load files in the ObjectStore
copy data from ObjectStore to ADWC tables
In addition, I have given a close look at the power of OCI Python SDK. With it, you can create your highly customized set of tools to automate your daily work. You can even create your ADWC instance or scale it up&down (adding cores and storage space).
In a future article, I’ll return to Machine Learning. It is almost time to explore OML4Py.
If you want to find more examples using OCI Python SDK, you can have a look here
|
[
{
"code": null,
"e": 275,
"s": 172,
"text": "Using OCI Python SDK and Autonomous DWH API you can easily load data for your Data Science and ML work"
},
{
"code": null,
"e": 579,
"s": 275,
"text": "In a previous article, I have explored how we can use Python and popular Open Source frameworks, like Pandas and scikit-learn, to analyze data stored with Oracle Autonomous Data Warehouse (ADWC). In this shorter story, I want to show you how you can easily load even big data files using OCI Python SDK."
},
{
"code": null,
"e": 758,
"s": 579,
"text": "One of the big features of the Cloud is Automation. In the Cloud World, it is easier to dynamically provision resources (like VM, or even Databases) and manage them using an API."
},
{
"code": null,
"e": 919,
"s": 758,
"text": "Oracle Cloud Infrastructure (OCI) has many tools, within which you can choose your preferred, to automate a large set of tasks (I would say: everything I need):"
},
{
"code": null,
"e": 928,
"s": 919,
"text": "REST API"
},
{
"code": null,
"e": 936,
"s": 928,
"text": "OCI CLI"
},
{
"code": null,
"e": 940,
"s": 936,
"text": "SDK"
},
{
"code": null,
"e": 1114,
"s": 940,
"text": "OCI Command Line Interface (CLI) is really good. But, if you want to develop your highly customized tools, perfectly tailored on your shoulders, I would recommend using SDK."
},
{
"code": null,
"e": 1160,
"s": 1114,
"text": "As you can see in the documentation, we have:"
},
{
"code": null,
"e": 1171,
"s": 1160,
"text": "Python SDK"
},
{
"code": null,
"e": 1180,
"s": 1171,
"text": "Java SDK"
},
{
"code": null,
"e": 1189,
"s": 1180,
"text": "Ruby SDK"
},
{
"code": null,
"e": 1196,
"s": 1189,
"text": "Go SDK"
},
{
"code": null,
"e": 1296,
"s": 1196,
"text": "Since we’re talking about Data Science and ML Engineering, I would without any doubt choose Python."
},
{
"code": null,
"e": 1573,
"s": 1296,
"text": "With OCI Python SDK you have a complete and easy-to-use set of classes, well-documented, enabling you to build Python scripts to automate a large part of the pipeline for your daily work with data. And, moreover, you can even use it inside a Jupyter Notebook (or Jupyter Lab)."
},
{
"code": null,
"e": 1896,
"s": 1573,
"text": "So, some days ago, I started with the evening task to build, for one of my customers, some examples to show how to load data inside Oracle ADWC, starting from flat files. Then, as a nice side-effect, I decided to explore the subject a little more and created a script to start/stop VM and even start/stop my ADWC instance."
},
{
"code": null,
"e": 1951,
"s": 1896,
"text": "You can find the set of examples inside my Github repo"
},
{
"code": null,
"e": 2048,
"s": 1951,
"text": "In this story, I want to explain, with more details, how to load data, starting from flat files."
},
{
"code": null,
"e": 2158,
"s": 2048,
"text": "Well, obviously there is the documentation, but, if you’re using PyPi, installation is only one line of code:"
},
{
"code": null,
"e": 2174,
"s": 2158,
"text": "pip install oci"
},
{
"code": null,
"e": 2203,
"s": 2174,
"text": "It works also with Anaconda."
},
{
"code": null,
"e": 2320,
"s": 2203,
"text": "If you want to be one of the first to try the new features added, simply check out the OCI Python Github repository."
},
{
"code": null,
"e": 2554,
"s": 2320,
"text": "Then, you need to do some configuration tasks, needed to ensure secure communication between your working environment and your OCI Cloud. I’ll spend some time to clarify here since I don’t want you to lose precious time on this part."
},
{
"code": null,
"e": 2824,
"s": 2554,
"text": "First, you need to create an API signing key-pair, in PEM format. You must keep the private safe on your environment (the computer running the Python program) and store the public key in your Cloud profile. When you store it, you can read from Cloud UI the fingerprint."
},
{
"code": null,
"e": 2861,
"s": 2824,
"text": "Some more details can be found here:"
},
{
"code": null,
"e": 2883,
"s": 2861,
"text": "docs.cloud.oracle.com"
},
{
"code": null,
"e": 3051,
"s": 2883,
"text": "Then, with every type of clients (ObjectStorageClient, ComputeClient, ....) you need to supply a set of (key, value) pair, packed as a Dictionary, in order to specify:"
},
{
"code": null,
"e": 3067,
"s": 3051,
"text": "your OCI userid"
},
{
"code": null,
"e": 3120,
"s": 3067,
"text": "a key (API signing key) used to secure communication"
},
{
"code": null,
"e": 3148,
"s": 3120,
"text": "the fingerprint of this key"
},
{
"code": null,
"e": 3177,
"s": 3148,
"text": "your Cloud tenant identifier"
},
{
"code": null,
"e": 3188,
"s": 3177,
"text": "OCI Region"
},
{
"code": null,
"e": 3249,
"s": 3188,
"text": "This is an example of what you need to prepare (anonymized):"
},
{
"code": null,
"e": 3440,
"s": 3249,
"text": "config = {“user”: “ocid1.user.oc1..XXXXX”,“key_file”: “/Users/lsaetta/Progetti/xxxx/oci_api_key.pem”,“fingerprint”: “YYYYY”,“tenancy”: “ocid1.tenancy.oc1..ZZZZZZ”,“region”: “eu-frankfurt-1”}"
},
{
"code": null,
"e": 3573,
"s": 3440,
"text": "For user and your Cloud tenant, you need to use not the name, but the identifier OCID, that you can copy from the OCI Cloud Console."
},
{
"code": null,
"e": 3655,
"s": 3573,
"text": "At this point, you’re ready to load a set of files as Objects in the ObjectStore."
},
{
"code": null,
"e": 3716,
"s": 3655,
"text": "This is the code to load a single file, I’ll comment sooner:"
},
{
"code": null,
"e": 3742,
"s": 3716,
"text": "As you can see, you need:"
},
{
"code": null,
"e": 3856,
"s": 3742,
"text": "to create a client, in this case an ObjectStorageClient, and pass to the constructor the configuration Dictionary"
},
{
"code": null,
"e": 3936,
"s": 3856,
"text": "call the method put_object with bucket_name, file_name, file_path as parameters"
},
{
"code": null,
"e": 3948,
"s": 3936,
"text": "That’s all."
},
{
"code": null,
"e": 4032,
"s": 3948,
"text": "In the Github repository, you’ll find an enhanced version, handling a set of files."
},
{
"code": null,
"e": 4094,
"s": 4032,
"text": "Now, it is time to copy data from ObjectStore to ADWC tables."
},
{
"code": null,
"e": 4244,
"s": 4094,
"text": "First of all: we need to create a set of credentials and store them inside the DB, in order to enable PL/SQL code to access the ObjectStorage Bucket."
},
{
"code": null,
"e": 4341,
"s": 4244,
"text": "Go to the OCI UI and create, inside your profile (top right icon and UserSetting), an AuthToken:"
},
{
"code": null,
"e": 4469,
"s": 4341,
"text": "Copy from the UI the Authentication Token. Remember to do that right after created, otherwise, you will not able to re-read it."
},
{
"code": null,
"e": 4574,
"s": 4469,
"text": "Second, store the Cloud Credentials inside the DB using this code; This step needs to be done only once:"
},
{
"code": null,
"e": 4890,
"s": 4574,
"text": "import cx_Oracleconnection = cx_Oracle.connect(USER, PWD, 'adwc5_medium')# need to create a cursorcur = connection.cursor()statement = \"\"\"BEGIN DBMS_CLOUD.CREATE_CREDENTIAL( credential_name => 'DEF_CRED_NAME', username => 'adwc_user@oracle.com', password => '<AUTH Token>' );END;\"\"\"cur.execute(statement)"
},
{
"code": null,
"e": 4994,
"s": 4890,
"text": "Take care: if your user is a federated one, the name is the fully qualified name. It has a prefix like:"
},
{
"code": null,
"e": 5022,
"s": 4994,
"text": "oracleidentitycloudservice/"
},
{
"code": null,
"e": 5101,
"s": 5022,
"text": "and you must specify, in the CREATE_CREDENTIAL call, the fully qualified name."
},
{
"code": null,
"e": 5235,
"s": 5101,
"text": "Since we have now the flat files in the ObjectStore, we can employ the PL/SQL package DBMS_CLOUD to load the data inside ADWC tables."
},
{
"code": null,
"e": 5355,
"s": 5235,
"text": "Ok, it is PL/SQL code, but not very complicated, and you can easily cut&paste. We’ll wrap this code inside Python code."
},
{
"code": null,
"e": 5532,
"s": 5355,
"text": "We’re imaging the simpler scenario: one Oracle table for flat file and the format of the file is the same as the table (one-to-one correspondence between file and table fields)"
},
{
"code": null,
"e": 5588,
"s": 5532,
"text": "We have to create the table inside the DB. For example:"
},
{
"code": null,
"e": 5699,
"s": 5588,
"text": "CREATE TABLE CHANNELS (channel_id char(1), channel_desc varchar2(20), channel_class varchar2(20) );/"
},
{
"code": null,
"e": 5778,
"s": 5699,
"text": "Then we can load the data contained in one file in this table, with this code:"
},
{
"code": null,
"e": 6212,
"s": 5778,
"text": "import cx_Oracleconnection = cx_Oracle.connect(USER, PWD, 'adwc5_medium')# need to create a cursorcur = connection.cursor()statement = \"\"\"BEGIN DBMS_CLOUD.COPY_DATA( table_name =>'CHANNELS1', credential_name =>'DEF_CRED_NAME', file_uri_list =>'https://swiftobjectstorage.eu-frankfurt-1.oraclecloud.com/v1/tenant-name/BUCKET_NAME/channels1.txt', format => json_object('delimiter' value ',') );END;\"\"\"cur.execute(statement)"
},
{
"code": null,
"e": 6333,
"s": 6212,
"text": "One detail: to reference the Object you need to use the SWIFT-type URL. What you need to change in the above example is:"
},
{
"code": null,
"e": 6376,
"s": 6333,
"text": "the Region Name (here it is eu-frankurt-1)"
},
{
"code": null,
"e": 6400,
"s": 6376,
"text": "the name of your tenant"
},
{
"code": null,
"e": 6439,
"s": 6400,
"text": "the name of the bucket in Object Store"
},
{
"code": null,
"e": 6484,
"s": 6439,
"text": "the name of the Object (here: channels1.txt)"
},
{
"code": null,
"e": 6551,
"s": 6484,
"text": "As we can see, the DBMS_CLOUD package has all the required API to:"
},
{
"code": null,
"e": 6583,
"s": 6551,
"text": "store credentials inside the DB"
},
{
"code": null,
"e": 6611,
"s": 6583,
"text": "COPY from ObjectStore to DB"
},
{
"code": null,
"e": 6732,
"s": 6611,
"text": "It provides also some other nice features. For example, you can use Apache Parquet format for the files, instead of CSV."
},
{
"code": null,
"e": 6821,
"s": 6732,
"text": "If you want to check that data has really been loaded, you can use this snippet of code:"
},
{
"code": null,
"e": 7034,
"s": 6821,
"text": "import pandas as pdimport cx_Oracleconnection = cx_Oracle.connect(USER, PWD, 'adwc5_medium')channel1 = pd.read_sql(\"select * from CHANNELS1\", con=connection)# if it is a Notebookchannel1.head()"
},
{
"code": null,
"e": 7290,
"s": 7034,
"text": "Another option for Data Loading is to create in the DB an External Table, referring to the file. A soon as you have the external table working, you can use DML instructions to load data inside the DB. For example, you can use CTAS: CREATE TABLE AS SELECT."
},
{
"code": null,
"e": 7337,
"s": 7290,
"text": "The procedure to create the external table is:"
},
{
"code": null,
"e": 7370,
"s": 7337,
"text": "DBMS_CLOUD.CREATE_EXTERNAL_TABLE"
},
{
"code": null,
"e": 7389,
"s": 7370,
"text": "more details here."
},
{
"code": null,
"e": 7527,
"s": 7389,
"text": "As a Data Scientist, you need to work with data. Sometimes you’ll need to load by yourself. Sometimes, you’ll have a DBA to load for you."
},
{
"code": null,
"e": 7587,
"s": 7527,
"text": "In this article, I have shown how to use OCI Python SDK to:"
},
{
"code": null,
"e": 7617,
"s": 7587,
"text": "load files in the ObjectStore"
},
{
"code": null,
"e": 7659,
"s": 7617,
"text": "copy data from ObjectStore to ADWC tables"
},
{
"code": null,
"e": 7912,
"s": 7659,
"text": "In addition, I have given a close look at the power of OCI Python SDK. With it, you can create your highly customized set of tools to automate your daily work. You can even create your ADWC instance or scale it up&down (adding cores and storage space)."
},
{
"code": null,
"e": 8003,
"s": 7912,
"text": "In a future article, I’ll return to Machine Learning. It is almost time to explore OML4Py."
}
] |
Remove all values from HashMap in Java
|
To remove all values from HashMap, use the clear() method.
First, let us create a HashMap.
HashMap hm = new HashMap();
Add some elements to the HashMap
hm.put("Wallet", new Integer(700));
hm.put("Belt", new Integer(600));
hm.put("Backpack", new Integer(1200));
Now, remove all the elements
hm.clear();
The following is an example to remove all values from HashMap.
Live Demo
import java.util.*;
public class Demo {
public static void main(String args[]) {
// Create hash map
HashMap hm = new HashMap();
hm.put("Wallet", new Integer(700));
hm.put("Belt", new Integer(600));
hm.put("Backpack", new Integer(1200));
System.out.println("Map = "+hm);
hm.clear();
System.out.println("Map after removing all the elements (blank)= "+hm);
}
}
The following is the output
Map = {Backpack=1200, Belt=600, Wallet=700}
Map after removing all the elements (blank)= {}
|
[
{
"code": null,
"e": 1121,
"s": 1062,
"text": "To remove all values from HashMap, use the clear() method."
},
{
"code": null,
"e": 1153,
"s": 1121,
"text": "First, let us create a HashMap."
},
{
"code": null,
"e": 1181,
"s": 1153,
"text": "HashMap hm = new HashMap();"
},
{
"code": null,
"e": 1214,
"s": 1181,
"text": "Add some elements to the HashMap"
},
{
"code": null,
"e": 1323,
"s": 1214,
"text": "hm.put(\"Wallet\", new Integer(700));\nhm.put(\"Belt\", new Integer(600));\nhm.put(\"Backpack\", new Integer(1200));"
},
{
"code": null,
"e": 1352,
"s": 1323,
"text": "Now, remove all the elements"
},
{
"code": null,
"e": 1364,
"s": 1352,
"text": "hm.clear();"
},
{
"code": null,
"e": 1427,
"s": 1364,
"text": "The following is an example to remove all values from HashMap."
},
{
"code": null,
"e": 1438,
"s": 1427,
"text": " Live Demo"
},
{
"code": null,
"e": 1850,
"s": 1438,
"text": "import java.util.*;\npublic class Demo {\n public static void main(String args[]) {\n // Create hash map\n HashMap hm = new HashMap();\n hm.put(\"Wallet\", new Integer(700));\n hm.put(\"Belt\", new Integer(600));\n hm.put(\"Backpack\", new Integer(1200));\n System.out.println(\"Map = \"+hm);\n hm.clear();\n System.out.println(\"Map after removing all the elements (blank)= \"+hm);\n }\n}"
},
{
"code": null,
"e": 1878,
"s": 1850,
"text": "The following is the output"
},
{
"code": null,
"e": 1970,
"s": 1878,
"text": "Map = {Backpack=1200, Belt=600, Wallet=700}\nMap after removing all the elements (blank)= {}"
}
] |
Ways to Evaluate Regression Models | by Shravankumar Hiregoudar | Towards Data Science
|
Evaluation metrics;
Mean/Median of predictionStandard Deviation of predictionRange of predictionCoefficient of Determination (R2)Relative Standard Deviation/Coefficient of Variation (RSD)Relative Squared Error (RSE)Mean Absolute Error (MAE)Relative Absolute Error (RAE)Mean Squared Error (MSE)Root Mean Squared Error on Prediction (RMSE/RMSEP)Normalized Root Mean Squared Error (Norm RMSEP)Relative Root Mean Squared Error (RRMSEP)
Mean/Median of prediction
Standard Deviation of prediction
Range of prediction
Coefficient of Determination (R2)
Relative Standard Deviation/Coefficient of Variation (RSD)
Relative Squared Error (RSE)
Mean Absolute Error (MAE)
Relative Absolute Error (RAE)
Mean Squared Error (MSE)
Root Mean Squared Error on Prediction (RMSE/RMSEP)
Normalized Root Mean Squared Error (Norm RMSEP)
Relative Root Mean Squared Error (RRMSEP)
Let us consider an example of predicting Active Pharmaceutical Ingredients (API) concentration in a tablet. Using absorbance units from NIR spectroscopy we predict the API level in the tablet. The API concentration in a tablet can be 0.0, 0.1, 0.3, 0.5, 1.0, 1.5, 2.0, 2.5, 3.0. We apply PLS (Partial Least Square) and SVR (Support Vector Regressor) for the prediction of API level.
NOTE: The metrics can be used to compare multiple models or one model with different models
We can understand the bias in prediction between two models using the arithmetic mean of the predicted values.
For example, The mean of predicted values of 0.5 API is calculated by taking the sum of the predicted values for 0.5 API divided by the total number of samples having 0.5 API.
np.mean(predictedArray)
In Fig.1, We can understand how PLS and SVR have performed wrt mean. SVR predicted 0.0 API much better than PLS, whereas, PLS predicted 3.0 API better than SVR. We can choose the models based on the interest of the API level.
Disadvantage: Mean is affected by outliers. Use Median when you have outliers in your predicted values
The standard deviation (SD) is a measure of the amount of variation or dispersion of a set of values. A low standard deviation indicates that the values tend to be close to the mean (also called the expected value) of the set,. In contrast, a high standard deviation indicates that the values are spread out over a broader range. The SD of predicted values helps in understanding the dispersion of values in different models.
np.std(predictedArray)
In Fig.2, The dispersion of predicted values is less in SVR compared to PLS. So, SVR performs better when we consider the SD metrics.
The range of the prediction is the maximum and minimum value in the predicted values. Even range helps us to understand the dispersion between models.
R-squared (R2) is a statistical measure that represents the proportion of the variance for a dependent variable that’s explained by an independent variable or variables in a regression model. Whereas correlation explains the strength of the relationship between an independent and dependent variable, R-squared explains to what extent the variance of one variable explains the variance of the second variable. So, if the R2 of a model is 0.50, then approximately half of the observed variation can be explained by the model’s inputs.
from sklearn.metrics import r2_scorer2_score(Actual, Predicted)
Disadvantage: R2 doesn’t consider overfitting. For more details.
There is a saying that apples shouldn’t be compared with oranges or in other words, don’t compare two items or group of items that are practically incomparable. But the lack of comparability can be overcome if the two items or groups are somehow standardized or brought on the same scale. For instance, when comparing the variances of two groups that are overall very different, such as the variance in the size of bluefin tuna and blue whales, the coefficient of variation (CV) is the method of choice: the CV simply represents the variance of each group standardized by its group mean
The coefficient of variation (CV), also known as relative standard deviation (RSD), is a standardized measure of the dispersion of a probability distribution or frequency distribution. It helps us in understanding how the spread is the data in two different tests
Standard deviation is the most common measure of variability for a single data set. But why do we need yet another measure, such as the coefficient of variation? Well, comparing the standard deviations of two different data sets is meaningless, but comparing coefficients of variation is not.
from scipy.stats import variationvariation(data)
For example, If we consider two different data;
Data 1: Mean1 = 120000 : SD1 = 2000
Data 2: Mean2 = 900000 : SD2 = 10000
Let us calculate CV for both datasets
CV1 = SD1/Mean1 = 1.6%
CV2 = SD2/Mean2 = 1.1%
We can conclude Data 1 is more spread out than Data 2
The relative squared error (RSE) is relative to what it would have been if a simple predictor had been used. More specifically, this simple predictor is just the average of the actual values. Thus, the relative squared error takes the total squared error and normalizes it by dividing by the total squared error of the simple predictor. It can be compared between models whose errors are measured in the different units.
Mathematically, the relative squared error, Ei of an individual model i is evaluated by the equation:
where P(ij) is the value predicted by the individual model i for record j (out of n records); Tj is the target value for record j, and Tbar is given by the formula:
For a perfect fit, the numerator is equal to 0 and Ei = 0. So, the Ei index ranges from 0 to infinity, with 0 correspondings to the ideal.
In statistics, mean absolute error (MAE) is a measure of errors between paired observations expressing the same phenomenon. Examples of Y versus X include comparisons of predicted versus observed, subsequent time versus initial time, and one technique of measurement versus an alternative technique of measurement. It has the same unit as the original data, and it can only be compared between models whose errors are measured in the same units. It is usually similar in magnitude to RMSE, but slightly smaller. MAE is calculated as:
from sklearn.metrics import mean_absolute_errormean_absolute_error(actual, predicted)
It is thus an arithmetic average of the absolute errors, where yi is the prediction and xi the actual value. Note that alternative formulations may include relative frequencies as weight factors. The mean absolute error uses the same scale as the data being measured. This is known as a scale-dependent accuracy measure and, therefore cannot be used to make comparisons between series using different scales.
Note: As you see, all the statistics compare true values to their estimates, but do it in a slightly different way. They all tell you “how far away” are your estimated values from the true value. Sometimes square roots are used and occasionally absolute values — this is because when using square roots, the extreme values have more influence on the result (see Why to square the difference instead of taking the absolute value in standard deviation? or on Mathoverflow).
In MAE and RMSE, you simply look at the “average difference” between those two values. So you interpret them comparing to the scale of your variable (i.e., MSE of 1 point is a difference of 1 point of actual between predicted and actual).
In RAE and Relative RSE, you divide those differences by the variation of actual, so they have a scale from 0 to 1, and if you multiply this value by 100, you get similarity in 0–100 scale (i.e. percentage).
The values of ∑(MeanofActual — actual)2 or ∑|MeanofActual — actual| tell you how much actual differs from its mean value — so you could tell what it is about how much actual differs from itself (compare to variance). Because of that, the measures are named “relative” — they give you results related to the scale of actual.
Relative Absolute Error (RAE) is a way to measure the performance of a predictive model. RAE is not to be confused with relative error, which is a general measure of precision or accuracy for instruments like clocks, rulers, or scales. It is expressed as a ratio, comparing a mean error (residual) to errors produced by a trivial or naive model. A good forecasting model will produce a ratio close to zero; A poor model (one that’s worse than the naive model) will produce a ratio greater than one.
It is very similar to the relative squared error in the sense that it is also relative to a simple predictor, which is just the average of the actual values. In this case, though, the error is just the total absolute error instead of the total squared error. Thus, the relative absolute error takes the total absolute error and normalizes it by dividing by the total absolute error of the simple predictor.
Mathematically, the relative absolute error, Ei of an individual model i is evaluated by the equation:
where P(ij) is the value predicted by the individual model i for record j (out of n records); Tj is the target value for record j, and Tbar is given by the formula:
For a perfect fit, the numerator is equal to 0 and Ei = 0. So, the Ei index ranges from 0 to infinity, with 0 correspondings to the ideal.
Mean Squared Error (MSE) or Mean Squared Deviation (MSD) of an estimator (of a procedure for estimating an unobserved quantity) measures the average of the squares of the errors — that is, the average squared difference between the estimated values and the actual value. MSE is a risk function, corresponding to the expected value of the squared error loss. The fact that MSE is almost always strictly positive (and not zero) is because of randomness or because the estimator does not account for information that could produce a more accurate estimate.
The MSE assesses the quality of a predictor (i.e., a function mapping arbitrary inputs to a sample of values of some random variable), or an estimator (i.e., a mathematical function mapping a sample of data to an estimate of a parameter of the population from which the data is sampled). The definition of an MSE differs according to whether one is describing a predictor or an estimator.
The MSE is a measure of the quality of an estimator — it is always non-negative, and values closer to zero are better.
from sklearn.metrics import mean_squared_errormean_squared_error(actual, predicted)
Let’s analyze what this equation actually means.
In mathematics, the character that looks like weird E is called summation (Greek sigma). It is the sum of a sequence of numbers, from i=1 to n. Let’s imagine this like an array of points, where we go through all the points, from the first (i=1) to the last (i=n).
For each point, we take the y-coordinate of the point, and the y’-coordinate. We subtract the y-coordinate value from the y’-coordinate value and calculate the square of the result.
The third part is to take the sum of all the (y-y’)2 values and divide it by n, which will give the mean.
Our goal is to minimize this mean, which will provide us with the best line that goes through all the points. For more information.
In statistical modeling and particularly regression analyses, a common way of measuring the quality of the fit of the model is the RMSE (also called Root Mean Square Deviation), given by
from sklearn.metrics import mean_squared_errormse = mean_squared_error(actual, predicted)rmse = sqrt(mse)
where yi is the ith observation of y and ŷ the predicted y value given the model. If the predicted responses are very close to the true responses the RMSE will be small. If the predicted and true responses differ substantially — at least for some observations — the RMSE will be large. A value of zero would indicate a perfect fit to the data. Since the RMSE is measured on the same scale, with the same units as y, one can expect 68% of the y values to be within 1 RMSE — given the data is normally distributed.
NOTE: RMSE is concerned with deviations from the true value whereas S is concerned with deviations from the mean.
So calculating the MSE helps to compare different models that are based on the same y observations. But what if
one wants to compare model fits of different response variables?the response variable y is modified in some models, e.g. standardized or sqrt- or log-transformed?And does the splitting of data into a training and test dataset (after the modification) and the RMSE calculation based on the test data an effect on point 1. and 2.?
one wants to compare model fits of different response variables?
the response variable y is modified in some models, e.g. standardized or sqrt- or log-transformed?
And does the splitting of data into a training and test dataset (after the modification) and the RMSE calculation based on the test data an effect on point 1. and 2.?
The first two points are typical issues when comparing ecological indicator performances and the latter, so-called validation set approach, is pretty common in statistical and machine learning. One solution to overcome these barriers is to calculate the Normalized RMSE.
Normalizing the RMSE facilitates the comparison between datasets or models with different scales. You will find, however, various different methods of RMSE normalizations in the literature:
You can normalize by
If the response variables have few extreme values, choosing the interquartile range is a good option as it is less sensitive to outliers.
RMSEP/standard deviation is called Relative Root Mean Squared Error (RRMSEP)
1/RRMSEP is also a metric. A value greater than 2 is considered to be a good.
There are also terms like, Standard Error of Prediction(SEP) and Ratio of the Standard Error of Prediction to Standard Deviation (RPD) which are mainly used in chemometrics.
I hope this blog helped you to understand different metrics to evaluate your regression model. I have used multiple sources to understand and write this article. Thank you for your time.
|
[
{
"code": null,
"e": 191,
"s": 171,
"text": "Evaluation metrics;"
},
{
"code": null,
"e": 603,
"s": 191,
"text": "Mean/Median of predictionStandard Deviation of predictionRange of predictionCoefficient of Determination (R2)Relative Standard Deviation/Coefficient of Variation (RSD)Relative Squared Error (RSE)Mean Absolute Error (MAE)Relative Absolute Error (RAE)Mean Squared Error (MSE)Root Mean Squared Error on Prediction (RMSE/RMSEP)Normalized Root Mean Squared Error (Norm RMSEP)Relative Root Mean Squared Error (RRMSEP)"
},
{
"code": null,
"e": 629,
"s": 603,
"text": "Mean/Median of prediction"
},
{
"code": null,
"e": 662,
"s": 629,
"text": "Standard Deviation of prediction"
},
{
"code": null,
"e": 682,
"s": 662,
"text": "Range of prediction"
},
{
"code": null,
"e": 716,
"s": 682,
"text": "Coefficient of Determination (R2)"
},
{
"code": null,
"e": 775,
"s": 716,
"text": "Relative Standard Deviation/Coefficient of Variation (RSD)"
},
{
"code": null,
"e": 804,
"s": 775,
"text": "Relative Squared Error (RSE)"
},
{
"code": null,
"e": 830,
"s": 804,
"text": "Mean Absolute Error (MAE)"
},
{
"code": null,
"e": 860,
"s": 830,
"text": "Relative Absolute Error (RAE)"
},
{
"code": null,
"e": 885,
"s": 860,
"text": "Mean Squared Error (MSE)"
},
{
"code": null,
"e": 936,
"s": 885,
"text": "Root Mean Squared Error on Prediction (RMSE/RMSEP)"
},
{
"code": null,
"e": 984,
"s": 936,
"text": "Normalized Root Mean Squared Error (Norm RMSEP)"
},
{
"code": null,
"e": 1026,
"s": 984,
"text": "Relative Root Mean Squared Error (RRMSEP)"
},
{
"code": null,
"e": 1409,
"s": 1026,
"text": "Let us consider an example of predicting Active Pharmaceutical Ingredients (API) concentration in a tablet. Using absorbance units from NIR spectroscopy we predict the API level in the tablet. The API concentration in a tablet can be 0.0, 0.1, 0.3, 0.5, 1.0, 1.5, 2.0, 2.5, 3.0. We apply PLS (Partial Least Square) and SVR (Support Vector Regressor) for the prediction of API level."
},
{
"code": null,
"e": 1501,
"s": 1409,
"text": "NOTE: The metrics can be used to compare multiple models or one model with different models"
},
{
"code": null,
"e": 1612,
"s": 1501,
"text": "We can understand the bias in prediction between two models using the arithmetic mean of the predicted values."
},
{
"code": null,
"e": 1788,
"s": 1612,
"text": "For example, The mean of predicted values of 0.5 API is calculated by taking the sum of the predicted values for 0.5 API divided by the total number of samples having 0.5 API."
},
{
"code": null,
"e": 1812,
"s": 1788,
"text": "np.mean(predictedArray)"
},
{
"code": null,
"e": 2038,
"s": 1812,
"text": "In Fig.1, We can understand how PLS and SVR have performed wrt mean. SVR predicted 0.0 API much better than PLS, whereas, PLS predicted 3.0 API better than SVR. We can choose the models based on the interest of the API level."
},
{
"code": null,
"e": 2141,
"s": 2038,
"text": "Disadvantage: Mean is affected by outliers. Use Median when you have outliers in your predicted values"
},
{
"code": null,
"e": 2567,
"s": 2141,
"text": "The standard deviation (SD) is a measure of the amount of variation or dispersion of a set of values. A low standard deviation indicates that the values tend to be close to the mean (also called the expected value) of the set,. In contrast, a high standard deviation indicates that the values are spread out over a broader range. The SD of predicted values helps in understanding the dispersion of values in different models."
},
{
"code": null,
"e": 2590,
"s": 2567,
"text": "np.std(predictedArray)"
},
{
"code": null,
"e": 2724,
"s": 2590,
"text": "In Fig.2, The dispersion of predicted values is less in SVR compared to PLS. So, SVR performs better when we consider the SD metrics."
},
{
"code": null,
"e": 2875,
"s": 2724,
"text": "The range of the prediction is the maximum and minimum value in the predicted values. Even range helps us to understand the dispersion between models."
},
{
"code": null,
"e": 3409,
"s": 2875,
"text": "R-squared (R2) is a statistical measure that represents the proportion of the variance for a dependent variable that’s explained by an independent variable or variables in a regression model. Whereas correlation explains the strength of the relationship between an independent and dependent variable, R-squared explains to what extent the variance of one variable explains the variance of the second variable. So, if the R2 of a model is 0.50, then approximately half of the observed variation can be explained by the model’s inputs."
},
{
"code": null,
"e": 3473,
"s": 3409,
"text": "from sklearn.metrics import r2_scorer2_score(Actual, Predicted)"
},
{
"code": null,
"e": 3538,
"s": 3473,
"text": "Disadvantage: R2 doesn’t consider overfitting. For more details."
},
{
"code": null,
"e": 4125,
"s": 3538,
"text": "There is a saying that apples shouldn’t be compared with oranges or in other words, don’t compare two items or group of items that are practically incomparable. But the lack of comparability can be overcome if the two items or groups are somehow standardized or brought on the same scale. For instance, when comparing the variances of two groups that are overall very different, such as the variance in the size of bluefin tuna and blue whales, the coefficient of variation (CV) is the method of choice: the CV simply represents the variance of each group standardized by its group mean"
},
{
"code": null,
"e": 4389,
"s": 4125,
"text": "The coefficient of variation (CV), also known as relative standard deviation (RSD), is a standardized measure of the dispersion of a probability distribution or frequency distribution. It helps us in understanding how the spread is the data in two different tests"
},
{
"code": null,
"e": 4682,
"s": 4389,
"text": "Standard deviation is the most common measure of variability for a single data set. But why do we need yet another measure, such as the coefficient of variation? Well, comparing the standard deviations of two different data sets is meaningless, but comparing coefficients of variation is not."
},
{
"code": null,
"e": 4731,
"s": 4682,
"text": "from scipy.stats import variationvariation(data)"
},
{
"code": null,
"e": 4779,
"s": 4731,
"text": "For example, If we consider two different data;"
},
{
"code": null,
"e": 4815,
"s": 4779,
"text": "Data 1: Mean1 = 120000 : SD1 = 2000"
},
{
"code": null,
"e": 4852,
"s": 4815,
"text": "Data 2: Mean2 = 900000 : SD2 = 10000"
},
{
"code": null,
"e": 4890,
"s": 4852,
"text": "Let us calculate CV for both datasets"
},
{
"code": null,
"e": 4913,
"s": 4890,
"text": "CV1 = SD1/Mean1 = 1.6%"
},
{
"code": null,
"e": 4936,
"s": 4913,
"text": "CV2 = SD2/Mean2 = 1.1%"
},
{
"code": null,
"e": 4990,
"s": 4936,
"text": "We can conclude Data 1 is more spread out than Data 2"
},
{
"code": null,
"e": 5411,
"s": 4990,
"text": "The relative squared error (RSE) is relative to what it would have been if a simple predictor had been used. More specifically, this simple predictor is just the average of the actual values. Thus, the relative squared error takes the total squared error and normalizes it by dividing by the total squared error of the simple predictor. It can be compared between models whose errors are measured in the different units."
},
{
"code": null,
"e": 5513,
"s": 5411,
"text": "Mathematically, the relative squared error, Ei of an individual model i is evaluated by the equation:"
},
{
"code": null,
"e": 5678,
"s": 5513,
"text": "where P(ij) is the value predicted by the individual model i for record j (out of n records); Tj is the target value for record j, and Tbar is given by the formula:"
},
{
"code": null,
"e": 5817,
"s": 5678,
"text": "For a perfect fit, the numerator is equal to 0 and Ei = 0. So, the Ei index ranges from 0 to infinity, with 0 correspondings to the ideal."
},
{
"code": null,
"e": 6351,
"s": 5817,
"text": "In statistics, mean absolute error (MAE) is a measure of errors between paired observations expressing the same phenomenon. Examples of Y versus X include comparisons of predicted versus observed, subsequent time versus initial time, and one technique of measurement versus an alternative technique of measurement. It has the same unit as the original data, and it can only be compared between models whose errors are measured in the same units. It is usually similar in magnitude to RMSE, but slightly smaller. MAE is calculated as:"
},
{
"code": null,
"e": 6437,
"s": 6351,
"text": "from sklearn.metrics import mean_absolute_errormean_absolute_error(actual, predicted)"
},
{
"code": null,
"e": 6846,
"s": 6437,
"text": "It is thus an arithmetic average of the absolute errors, where yi is the prediction and xi the actual value. Note that alternative formulations may include relative frequencies as weight factors. The mean absolute error uses the same scale as the data being measured. This is known as a scale-dependent accuracy measure and, therefore cannot be used to make comparisons between series using different scales."
},
{
"code": null,
"e": 7318,
"s": 6846,
"text": "Note: As you see, all the statistics compare true values to their estimates, but do it in a slightly different way. They all tell you “how far away” are your estimated values from the true value. Sometimes square roots are used and occasionally absolute values — this is because when using square roots, the extreme values have more influence on the result (see Why to square the difference instead of taking the absolute value in standard deviation? or on Mathoverflow)."
},
{
"code": null,
"e": 7557,
"s": 7318,
"text": "In MAE and RMSE, you simply look at the “average difference” between those two values. So you interpret them comparing to the scale of your variable (i.e., MSE of 1 point is a difference of 1 point of actual between predicted and actual)."
},
{
"code": null,
"e": 7765,
"s": 7557,
"text": "In RAE and Relative RSE, you divide those differences by the variation of actual, so they have a scale from 0 to 1, and if you multiply this value by 100, you get similarity in 0–100 scale (i.e. percentage)."
},
{
"code": null,
"e": 8089,
"s": 7765,
"text": "The values of ∑(MeanofActual — actual)2 or ∑|MeanofActual — actual| tell you how much actual differs from its mean value — so you could tell what it is about how much actual differs from itself (compare to variance). Because of that, the measures are named “relative” — they give you results related to the scale of actual."
},
{
"code": null,
"e": 8588,
"s": 8089,
"text": "Relative Absolute Error (RAE) is a way to measure the performance of a predictive model. RAE is not to be confused with relative error, which is a general measure of precision or accuracy for instruments like clocks, rulers, or scales. It is expressed as a ratio, comparing a mean error (residual) to errors produced by a trivial or naive model. A good forecasting model will produce a ratio close to zero; A poor model (one that’s worse than the naive model) will produce a ratio greater than one."
},
{
"code": null,
"e": 8995,
"s": 8588,
"text": "It is very similar to the relative squared error in the sense that it is also relative to a simple predictor, which is just the average of the actual values. In this case, though, the error is just the total absolute error instead of the total squared error. Thus, the relative absolute error takes the total absolute error and normalizes it by dividing by the total absolute error of the simple predictor."
},
{
"code": null,
"e": 9098,
"s": 8995,
"text": "Mathematically, the relative absolute error, Ei of an individual model i is evaluated by the equation:"
},
{
"code": null,
"e": 9263,
"s": 9098,
"text": "where P(ij) is the value predicted by the individual model i for record j (out of n records); Tj is the target value for record j, and Tbar is given by the formula:"
},
{
"code": null,
"e": 9402,
"s": 9263,
"text": "For a perfect fit, the numerator is equal to 0 and Ei = 0. So, the Ei index ranges from 0 to infinity, with 0 correspondings to the ideal."
},
{
"code": null,
"e": 9956,
"s": 9402,
"text": "Mean Squared Error (MSE) or Mean Squared Deviation (MSD) of an estimator (of a procedure for estimating an unobserved quantity) measures the average of the squares of the errors — that is, the average squared difference between the estimated values and the actual value. MSE is a risk function, corresponding to the expected value of the squared error loss. The fact that MSE is almost always strictly positive (and not zero) is because of randomness or because the estimator does not account for information that could produce a more accurate estimate."
},
{
"code": null,
"e": 10345,
"s": 9956,
"text": "The MSE assesses the quality of a predictor (i.e., a function mapping arbitrary inputs to a sample of values of some random variable), or an estimator (i.e., a mathematical function mapping a sample of data to an estimate of a parameter of the population from which the data is sampled). The definition of an MSE differs according to whether one is describing a predictor or an estimator."
},
{
"code": null,
"e": 10464,
"s": 10345,
"text": "The MSE is a measure of the quality of an estimator — it is always non-negative, and values closer to zero are better."
},
{
"code": null,
"e": 10548,
"s": 10464,
"text": "from sklearn.metrics import mean_squared_errormean_squared_error(actual, predicted)"
},
{
"code": null,
"e": 10597,
"s": 10548,
"text": "Let’s analyze what this equation actually means."
},
{
"code": null,
"e": 10861,
"s": 10597,
"text": "In mathematics, the character that looks like weird E is called summation (Greek sigma). It is the sum of a sequence of numbers, from i=1 to n. Let’s imagine this like an array of points, where we go through all the points, from the first (i=1) to the last (i=n)."
},
{
"code": null,
"e": 11043,
"s": 10861,
"text": "For each point, we take the y-coordinate of the point, and the y’-coordinate. We subtract the y-coordinate value from the y’-coordinate value and calculate the square of the result."
},
{
"code": null,
"e": 11149,
"s": 11043,
"text": "The third part is to take the sum of all the (y-y’)2 values and divide it by n, which will give the mean."
},
{
"code": null,
"e": 11281,
"s": 11149,
"text": "Our goal is to minimize this mean, which will provide us with the best line that goes through all the points. For more information."
},
{
"code": null,
"e": 11468,
"s": 11281,
"text": "In statistical modeling and particularly regression analyses, a common way of measuring the quality of the fit of the model is the RMSE (also called Root Mean Square Deviation), given by"
},
{
"code": null,
"e": 11574,
"s": 11468,
"text": "from sklearn.metrics import mean_squared_errormse = mean_squared_error(actual, predicted)rmse = sqrt(mse)"
},
{
"code": null,
"e": 12088,
"s": 11574,
"text": "where yi is the ith observation of y and ŷ the predicted y value given the model. If the predicted responses are very close to the true responses the RMSE will be small. If the predicted and true responses differ substantially — at least for some observations — the RMSE will be large. A value of zero would indicate a perfect fit to the data. Since the RMSE is measured on the same scale, with the same units as y, one can expect 68% of the y values to be within 1 RMSE — given the data is normally distributed."
},
{
"code": null,
"e": 12202,
"s": 12088,
"text": "NOTE: RMSE is concerned with deviations from the true value whereas S is concerned with deviations from the mean."
},
{
"code": null,
"e": 12314,
"s": 12202,
"text": "So calculating the MSE helps to compare different models that are based on the same y observations. But what if"
},
{
"code": null,
"e": 12643,
"s": 12314,
"text": "one wants to compare model fits of different response variables?the response variable y is modified in some models, e.g. standardized or sqrt- or log-transformed?And does the splitting of data into a training and test dataset (after the modification) and the RMSE calculation based on the test data an effect on point 1. and 2.?"
},
{
"code": null,
"e": 12708,
"s": 12643,
"text": "one wants to compare model fits of different response variables?"
},
{
"code": null,
"e": 12807,
"s": 12708,
"text": "the response variable y is modified in some models, e.g. standardized or sqrt- or log-transformed?"
},
{
"code": null,
"e": 12974,
"s": 12807,
"text": "And does the splitting of data into a training and test dataset (after the modification) and the RMSE calculation based on the test data an effect on point 1. and 2.?"
},
{
"code": null,
"e": 13245,
"s": 12974,
"text": "The first two points are typical issues when comparing ecological indicator performances and the latter, so-called validation set approach, is pretty common in statistical and machine learning. One solution to overcome these barriers is to calculate the Normalized RMSE."
},
{
"code": null,
"e": 13435,
"s": 13245,
"text": "Normalizing the RMSE facilitates the comparison between datasets or models with different scales. You will find, however, various different methods of RMSE normalizations in the literature:"
},
{
"code": null,
"e": 13456,
"s": 13435,
"text": "You can normalize by"
},
{
"code": null,
"e": 13594,
"s": 13456,
"text": "If the response variables have few extreme values, choosing the interquartile range is a good option as it is less sensitive to outliers."
},
{
"code": null,
"e": 13671,
"s": 13594,
"text": "RMSEP/standard deviation is called Relative Root Mean Squared Error (RRMSEP)"
},
{
"code": null,
"e": 13749,
"s": 13671,
"text": "1/RRMSEP is also a metric. A value greater than 2 is considered to be a good."
},
{
"code": null,
"e": 13923,
"s": 13749,
"text": "There are also terms like, Standard Error of Prediction(SEP) and Ratio of the Standard Error of Prediction to Standard Deviation (RPD) which are mainly used in chemometrics."
}
] |
How to dynamically add/remove/update labels in a Tkinter window?
|
We can use the Tkinter Label widget to display text and images. By configuring the label widget, we can dynamically change the text, images, and other properties of the widget.
To dynamically update the Label widget, we can use either config(**options) or an inline configuration method such as for updating the text, we can use Label["text"]=text; for removing the label widget, we can use pack_forget() method.
# Import the required libraries
from tkinter import *
from tkinter import ttk
from PIL import ImageTk, Image
# Create an instance of tkinter frame or window
win=Tk()
# Set the size of the window
win.geometry("700x350")
def add_label():
global label
label=Label(win, text="1. A Newly created Label", font=('Aerial 18'))
label.pack()
def remove_label():
global label
label.pack_forget()
def update_label():
global label
label["text"]="2. Yay!! I am updated"
# Create buttons for add/remove/update the label widget
add=ttk.Button(win, text="Add a new Label", command=add_label)
add.pack(anchor=W, pady=10)
remove=ttk.Button(win, text="Remove the Label", command=remove_label)
remove.pack(anchor=W, pady=10)
update=ttk.Button(win, text="Update the Label", command=update_label)
update.pack(anchor=W, pady=10)
win.mainloop()
Running the above code will display a window with some buttons in it. Each button can be used to update/remove or add a label in the application.
Upon clicking the "Update the Label" button, the label will get updated as follows −
|
[
{
"code": null,
"e": 1239,
"s": 1062,
"text": "We can use the Tkinter Label widget to display text and images. By configuring the label widget, we can dynamically change the text, images, and other properties of the widget."
},
{
"code": null,
"e": 1475,
"s": 1239,
"text": "To dynamically update the Label widget, we can use either config(**options) or an inline configuration method such as for updating the text, we can use Label[\"text\"]=text; for removing the label widget, we can use pack_forget() method."
},
{
"code": null,
"e": 2325,
"s": 1475,
"text": "# Import the required libraries\nfrom tkinter import *\nfrom tkinter import ttk\nfrom PIL import ImageTk, Image\n\n# Create an instance of tkinter frame or window\nwin=Tk()\n\n# Set the size of the window\nwin.geometry(\"700x350\")\n\ndef add_label():\n global label\n label=Label(win, text=\"1. A Newly created Label\", font=('Aerial 18'))\n label.pack()\n\ndef remove_label():\n global label\n label.pack_forget()\n\ndef update_label():\n global label\n label[\"text\"]=\"2. Yay!! I am updated\"\n\n# Create buttons for add/remove/update the label widget\nadd=ttk.Button(win, text=\"Add a new Label\", command=add_label)\nadd.pack(anchor=W, pady=10)\n\nremove=ttk.Button(win, text=\"Remove the Label\", command=remove_label)\nremove.pack(anchor=W, pady=10)\n\nupdate=ttk.Button(win, text=\"Update the Label\", command=update_label)\nupdate.pack(anchor=W, pady=10)\n\nwin.mainloop()"
},
{
"code": null,
"e": 2471,
"s": 2325,
"text": "Running the above code will display a window with some buttons in it. Each button can be used to update/remove or add a label in the application."
},
{
"code": null,
"e": 2556,
"s": 2471,
"text": "Upon clicking the \"Update the Label\" button, the label will get updated as follows −"
}
] |
How to create a Vertical menu bar in Java?
|
Let us create a MenuBar −
JMenuBar menuBar = new JMenuBar();
Now, set its layout to create a Vertical Menu Bar with GridLayout −
menuBar.setLayout(new GridLayout(0,1));
The following is an example to create a Vertical menu bar in Java −
package my;
import java.awt.GridLayout;
import java.awt.event.KeyEvent;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
public class SwingDemo {
public static void main(final String args[]) {
JFrame frame = new JFrame("MenuBar Demo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JMenuBar menuBar = new JMenuBar();
menuBar.setLayout(new GridLayout(0,1));
JMenu fileMenu = new JMenu("File");
fileMenu.setMnemonic(KeyEvent.VK_F);
menuBar.add(fileMenu);
JMenuItem menuItem1 = new JMenuItem("New", KeyEvent.VK_N);
fileMenu.add(menuItem1);
JMenuItem menuItem2 = new JMenuItem("Open File", KeyEvent.VK_O);
fileMenu.add(menuItem2);
JMenu editMenu = new JMenu("Edit");
editMenu.setMnemonic(KeyEvent.VK_E);
menuBar.add(editMenu);
JMenuItem menuItem3 = new JMenuItem("Cut", KeyEvent.VK_C);
editMenu.add(menuItem3);
JMenu sourceMenu = new JMenu("Source");
sourceMenu.setMnemonic(KeyEvent.VK_S);
menuBar.add(sourceMenu);
JMenu refactorMenu = new JMenu("Refactor");
refactorMenu.setMnemonic(KeyEvent.VK_R);
menuBar.add(refactorMenu);
JMenu navigateMenu = new JMenu("Navigate");
navigateMenu.setMnemonic(KeyEvent.VK_A);
menuBar.add(navigateMenu);
menuBar.revalidate();
frame.setJMenuBar(menuBar);
frame.setSize(550, 350);
frame.setVisible(true);
}
}
This will produce the following output −
|
[
{
"code": null,
"e": 1088,
"s": 1062,
"text": "Let us create a MenuBar −"
},
{
"code": null,
"e": 1123,
"s": 1088,
"text": "JMenuBar menuBar = new JMenuBar();"
},
{
"code": null,
"e": 1191,
"s": 1123,
"text": "Now, set its layout to create a Vertical Menu Bar with GridLayout −"
},
{
"code": null,
"e": 1231,
"s": 1191,
"text": "menuBar.setLayout(new GridLayout(0,1));"
},
{
"code": null,
"e": 1299,
"s": 1231,
"text": "The following is an example to create a Vertical menu bar in Java −"
},
{
"code": null,
"e": 2788,
"s": 1299,
"text": "package my;\nimport java.awt.GridLayout;\nimport java.awt.event.KeyEvent;\nimport javax.swing.JFrame;\nimport javax.swing.JMenu;\nimport javax.swing.JMenuBar;\nimport javax.swing.JMenuItem;\npublic class SwingDemo {\n public static void main(final String args[]) {\n JFrame frame = new JFrame(\"MenuBar Demo\");\n frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n JMenuBar menuBar = new JMenuBar();\n menuBar.setLayout(new GridLayout(0,1));\n JMenu fileMenu = new JMenu(\"File\");\n fileMenu.setMnemonic(KeyEvent.VK_F);\n menuBar.add(fileMenu);\n JMenuItem menuItem1 = new JMenuItem(\"New\", KeyEvent.VK_N);\n fileMenu.add(menuItem1);\n JMenuItem menuItem2 = new JMenuItem(\"Open File\", KeyEvent.VK_O);\n fileMenu.add(menuItem2);\n JMenu editMenu = new JMenu(\"Edit\");\n editMenu.setMnemonic(KeyEvent.VK_E);\n menuBar.add(editMenu);\n JMenuItem menuItem3 = new JMenuItem(\"Cut\", KeyEvent.VK_C);\n editMenu.add(menuItem3);\n JMenu sourceMenu = new JMenu(\"Source\");\n sourceMenu.setMnemonic(KeyEvent.VK_S);\n menuBar.add(sourceMenu);\n JMenu refactorMenu = new JMenu(\"Refactor\");\n refactorMenu.setMnemonic(KeyEvent.VK_R);\n menuBar.add(refactorMenu);\n JMenu navigateMenu = new JMenu(\"Navigate\");\n navigateMenu.setMnemonic(KeyEvent.VK_A);\n menuBar.add(navigateMenu);\n menuBar.revalidate();\n frame.setJMenuBar(menuBar);\n frame.setSize(550, 350);\n frame.setVisible(true);\n }\n}"
},
{
"code": null,
"e": 2829,
"s": 2788,
"text": "This will produce the following output −"
}
] |
HTML - keygen Tag
|
The HTML <keygen> tag is used to process Web forms with certificate management systems. The element generates a secure key and submits the public key.
<!DOCTYPE html>
<html>
<head>
<title>HTML keygen Tag</title>
</head>
<body>
<form>
<keygen name = "random_key" challenge = "0987654321">
<input name = "firstname" value = "first name">
</form>
</body>
</html>
This will produce the following result −
This tag supports all the global attributes described in HTML Attribute Reference
The HTML <keygen> tag also supports the following additional attributes −
This tag supports all the event attributes described in − HTML Events Reference
19 Lectures
2 hours
Anadi Sharma
16 Lectures
1.5 hours
Anadi Sharma
18 Lectures
1.5 hours
Frahaan Hussain
57 Lectures
5.5 hours
DigiFisk (Programming Is Fun)
54 Lectures
6 hours
DigiFisk (Programming Is Fun)
45 Lectures
5.5 hours
DigiFisk (Programming Is Fun)
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2525,
"s": 2374,
"text": "The HTML <keygen> tag is used to process Web forms with certificate management systems. The element generates a secure key and submits the public key."
},
{
"code": null,
"e": 2785,
"s": 2525,
"text": "<!DOCTYPE html>\n<html>\n\n <head>\n <title>HTML keygen Tag</title>\n </head>\n\n <body>\n <form>\n <keygen name = \"random_key\" challenge = \"0987654321\">\n <input name = \"firstname\" value = \"first name\">\n </form>\n </body>\n\n</html>"
},
{
"code": null,
"e": 2826,
"s": 2785,
"text": "This will produce the following result −"
},
{
"code": null,
"e": 2908,
"s": 2826,
"text": "This tag supports all the global attributes described in HTML Attribute Reference"
},
{
"code": null,
"e": 2982,
"s": 2908,
"text": "The HTML <keygen> tag also supports the following additional attributes −"
},
{
"code": null,
"e": 3062,
"s": 2982,
"text": "This tag supports all the event attributes described in − HTML Events Reference"
},
{
"code": null,
"e": 3095,
"s": 3062,
"text": "\n 19 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 3109,
"s": 3095,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 3144,
"s": 3109,
"text": "\n 16 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 3158,
"s": 3144,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 3193,
"s": 3158,
"text": "\n 18 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 3210,
"s": 3193,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 3245,
"s": 3210,
"text": "\n 57 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 3276,
"s": 3245,
"text": " DigiFisk (Programming Is Fun)"
},
{
"code": null,
"e": 3309,
"s": 3276,
"text": "\n 54 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 3340,
"s": 3309,
"text": " DigiFisk (Programming Is Fun)"
},
{
"code": null,
"e": 3375,
"s": 3340,
"text": "\n 45 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 3406,
"s": 3375,
"text": " DigiFisk (Programming Is Fun)"
},
{
"code": null,
"e": 3413,
"s": 3406,
"text": " Print"
},
{
"code": null,
"e": 3424,
"s": 3413,
"text": " Add Notes"
}
] |
Match the elements of an array in a MySQL query
|
Let us first create a table table −
mysql> create table DemoTable1523
-> (
-> Id int,
-> Value int
-> );
Query OK, 0 rows affected (0.76 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable1523 values(1,56);
Query OK, 1 row affected (0.15 sec)
mysql> insert into DemoTable1523 values(2,78);
Query OK, 1 row affected (0.15 sec)
mysql> insert into DemoTable1523 values(1,34);
Query OK, 1 row affected (0.10 sec)
mysql> insert into DemoTable1523 values(2,45);
Query OK, 1 row affected (0.17 sec)
mysql> insert into DemoTable1523 values(1,99);
Query OK, 1 row affected (0.10 sec)
Display all records from the table using select statement −
mysql> select * from DemoTable1523;
This will produce the following output −
+------+-------+
| Id | Value |
+------+-------+
| 1 | 56 |
| 2 | 78 |
| 1 | 34 |
| 2 | 45 |
| 1 | 99 |
+------+-------+
5 rows in set (0.00 sec)
Following is the query to match the elements of array. Here, we are selecting id with matching values 34, 99, and 56 −
mysql> select Id from DemoTable1523
-> where Value IN ('34','99','56')
-> group by Id
-> having count(*)=3;
This will produce the following output −
+------+
| Id |
+------+
| 1 |
+------+
1 row in set (0.00 sec)
|
[
{
"code": null,
"e": 1098,
"s": 1062,
"text": "Let us first create a table table −"
},
{
"code": null,
"e": 1216,
"s": 1098,
"text": "mysql> create table DemoTable1523\n -> (\n -> Id int,\n -> Value int\n -> );\nQuery OK, 0 rows affected (0.76 sec)"
},
{
"code": null,
"e": 1272,
"s": 1216,
"text": "Insert some records in the table using insert command −"
},
{
"code": null,
"e": 1687,
"s": 1272,
"text": "mysql> insert into DemoTable1523 values(1,56);\nQuery OK, 1 row affected (0.15 sec)\nmysql> insert into DemoTable1523 values(2,78);\nQuery OK, 1 row affected (0.15 sec)\nmysql> insert into DemoTable1523 values(1,34);\nQuery OK, 1 row affected (0.10 sec)\nmysql> insert into DemoTable1523 values(2,45);\nQuery OK, 1 row affected (0.17 sec)\nmysql> insert into DemoTable1523 values(1,99);\nQuery OK, 1 row affected (0.10 sec)"
},
{
"code": null,
"e": 1747,
"s": 1687,
"text": "Display all records from the table using select statement −"
},
{
"code": null,
"e": 1783,
"s": 1747,
"text": "mysql> select * from DemoTable1523;"
},
{
"code": null,
"e": 1824,
"s": 1783,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2002,
"s": 1824,
"text": "+------+-------+\n| Id | Value |\n+------+-------+\n| 1 | 56 |\n| 2 | 78 |\n| 1 | 34 |\n| 2 | 45 |\n| 1 | 99 |\n+------+-------+\n5 rows in set (0.00 sec)"
},
{
"code": null,
"e": 2121,
"s": 2002,
"text": "Following is the query to match the elements of array. Here, we are selecting id with matching values 34, 99, and 56 −"
},
{
"code": null,
"e": 2238,
"s": 2121,
"text": "mysql> select Id from DemoTable1523\n -> where Value IN ('34','99','56')\n -> group by Id\n -> having count(*)=3;"
},
{
"code": null,
"e": 2279,
"s": 2238,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2348,
"s": 2279,
"text": "+------+\n| Id |\n+------+\n| 1 |\n+------+\n1 row in set (0.00 sec)"
}
] |
Jython - Servlets
|
A Java servlet is the most widely used web development technique. We can use Jython to write servlets and this adds many more advantages beyond what Java has to offer because now we can make use of the Python language features as well.
We shall use the NetBeans IDE to develop a Java web application with a Jython servlet. Ensure that the nbPython plugin is installed in the NetBeans installation. Start a new project to build a web application by choosing the following path - File → New Project → Java web → New Web Application.
Provide the Project name and location. The IDE will create the project folder structure. Add a Java servlet file (ServletTest.java) under the source packages node in the Projects window. This will add servlet-api.jar in the lib folder of the project. Also, let the IDE create the web.xml descriptor file. Add the following code in ServletTest.java.
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class ServletTest extends HttpServlet {
public void doGet (HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
}
public void doPost (HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType ("text/html");
PrintWriter toClient = response.getWriter();
toClient.println (
"<html>
<head>
<title>Servlet Test</title>" + "
</head>
<body>
<h1>Servlet Test</h1>
</body>
</html>"
);
}
}
The web.xml file created by NetBeans will be as shown below −
<web-app>
<servlet>
<servlet-name>ServletTest</servlet-name>
<servlet-class>ServletTest</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ServletTest</servlet-name>
<url-pattern>/ServletTest</url-pattern>
</servlet-mapping>
</web-app>
Build and run the project to obtain the text Servlet Test appearing in <h1> tag in the browser window. Thus, we have added a regular Java servlet in the application.
Now, we shall add the Jython Servlet. Jython servlets work by means of an intermediate Java servlet is also known as PyServlet. The PyServlet.class is present in the jython standalone.jar. Add it in the WEB-INF/lib folder.
The next step is to configure the web.xml to invoke the PyServlet, whenever a request for any *.py file is raised. This should be done by adding the following xml code in it.
<servlet>
<servlet-name>PyServlet</servlet-name>
<servlet-class>org.python.util.PyServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>PyServlet</servlet-name>
<url-pattern>*.py</url-pattern>
</servlet-mapping>
The full web.xml code will look as shown below.
<web-app>
<servlet>
<servlet-name>ServletTest</servlet-name>
<servlet-class>ServletTest</servlet-class>
</servlet>
<servlet>
<servlet-name>PyServlet</servlet-name>
<servlet-class>org.python.util.PyServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>ServletTest</servlet-name>
<url-pattern>/ServletTest</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>PyServlet</servlet-name>
<url-pattern>*.py</url-pattern>
</servlet-mapping>
</web-app>
Place the following Jython code in the WEB-INF folder inside the project folder as JythonServlet.py, which is equivalent to the previous ServletTest.java.
from javax.servlet.http import HttpServlet
class JythonServlet1 (HttpServlet):
def doGet(self,request,response):
self.doPost (request,response)
def doPost(self,request,response):
toClient = response.getWriter()
response.setContentType ("text/html")
toClient.println (
"<html>
<head>
<title>Servlet Test</title>" + "
</head>
<body>
<h1>Servlet Test</h1>
</body>
</html>"
)
Build the project and in the browser open the following URL −
http://localhost:8080/jythonwebapp/jythonservlet.py
The browser will show the Servlet Test in <h1> tag as in case of Java Servlet output.
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2317,
"s": 2081,
"text": "A Java servlet is the most widely used web development technique. We can use Jython to write servlets and this adds many more advantages beyond what Java has to offer because now we can make use of the Python language features as well."
},
{
"code": null,
"e": 2612,
"s": 2317,
"text": "We shall use the NetBeans IDE to develop a Java web application with a Jython servlet. Ensure that the nbPython plugin is installed in the NetBeans installation. Start a new project to build a web application by choosing the following path - File → New Project → Java web → New Web Application."
},
{
"code": null,
"e": 2961,
"s": 2612,
"text": "Provide the Project name and location. The IDE will create the project folder structure. Add a Java servlet file (ServletTest.java) under the source packages node in the Projects window. This will add servlet-api.jar in the lib folder of the project. Also, let the IDE create the web.xml descriptor file. Add the following code in ServletTest.java."
},
{
"code": null,
"e": 3719,
"s": 2961,
"text": "import java.io.*;\nimport javax.servlet.*;\nimport javax.servlet.http.*;\n\npublic class ServletTest extends HttpServlet {\n \n public void doGet (HttpServletRequest request, HttpServletResponse response)\n throws ServletException, IOException {\n doPost(request, response);\n }\n \n public void doPost (HttpServletRequest request, HttpServletResponse response)\n throws ServletException, IOException {\n response.setContentType (\"text/html\");\n PrintWriter toClient = response.getWriter();\n \n toClient.println (\n \"<html>\n <head>\n <title>Servlet Test</title>\" + \"\n </head>\n <body>\n <h1>Servlet Test</h1>\n </body>\n </html>\"\n );\n }\n}"
},
{
"code": null,
"e": 3781,
"s": 3719,
"text": "The web.xml file created by NetBeans will be as shown below −"
},
{
"code": null,
"e": 4065,
"s": 3781,
"text": "<web-app>\n <servlet>\n <servlet-name>ServletTest</servlet-name>\n <servlet-class>ServletTest</servlet-class>\n </servlet>\n \n <servlet-mapping>\n <servlet-name>ServletTest</servlet-name>\n <url-pattern>/ServletTest</url-pattern>\n </servlet-mapping>\n</web-app>"
},
{
"code": null,
"e": 4231,
"s": 4065,
"text": "Build and run the project to obtain the text Servlet Test appearing in <h1> tag in the browser window. Thus, we have added a regular Java servlet in the application."
},
{
"code": null,
"e": 4454,
"s": 4231,
"text": "Now, we shall add the Jython Servlet. Jython servlets work by means of an intermediate Java servlet is also known as PyServlet. The PyServlet.class is present in the jython standalone.jar. Add it in the WEB-INF/lib folder."
},
{
"code": null,
"e": 4629,
"s": 4454,
"text": "The next step is to configure the web.xml to invoke the PyServlet, whenever a request for any *.py file is raised. This should be done by adding the following xml code in it."
},
{
"code": null,
"e": 4907,
"s": 4629,
"text": "<servlet>\n <servlet-name>PyServlet</servlet-name>\n <servlet-class>org.python.util.PyServlet</servlet-class>\n <load-on-startup>1</load-on-startup>\n</servlet>\n\n<servlet-mapping>\n <servlet-name>PyServlet</servlet-name>\n <url-pattern>*.py</url-pattern>\n</servlet-mapping>"
},
{
"code": null,
"e": 4955,
"s": 4907,
"text": "The full web.xml code will look as shown below."
},
{
"code": null,
"e": 5551,
"s": 4955,
"text": "<web-app>\n <servlet>\n <servlet-name>ServletTest</servlet-name>\n <servlet-class>ServletTest</servlet-class>\n </servlet>\n \n <servlet>\n <servlet-name>PyServlet</servlet-name>\n <servlet-class>org.python.util.PyServlet</servlet-class>\n <load-on-startup>1</load-on-startup>\n </servlet>\n \n <servlet-mapping>\n <servlet-name>ServletTest</servlet-name>\n <url-pattern>/ServletTest</url-pattern>\n </servlet-mapping>\n \n <servlet-mapping>\n <servlet-name>PyServlet</servlet-name>\n <url-pattern>*.py</url-pattern>\n </servlet-mapping>\n</web-app>"
},
{
"code": null,
"e": 5706,
"s": 5551,
"text": "Place the following Jython code in the WEB-INF folder inside the project folder as JythonServlet.py, which is equivalent to the previous ServletTest.java."
},
{
"code": null,
"e": 6217,
"s": 5706,
"text": "from javax.servlet.http import HttpServlet\nclass JythonServlet1 (HttpServlet):\n def doGet(self,request,response):\n self.doPost (request,response)\n def doPost(self,request,response):\n toClient = response.getWriter()\n response.setContentType (\"text/html\")\n \n toClient.println (\n \"<html>\n <head>\n <title>Servlet Test</title>\" + \"\n </head>\n <body>\n <h1>Servlet Test</h1>\n </body>\n </html>\"\n )"
},
{
"code": null,
"e": 6279,
"s": 6217,
"text": "Build the project and in the browser open the following URL −"
},
{
"code": null,
"e": 6331,
"s": 6279,
"text": "http://localhost:8080/jythonwebapp/jythonservlet.py"
},
{
"code": null,
"e": 6417,
"s": 6331,
"text": "The browser will show the Servlet Test in <h1> tag as in case of Java Servlet output."
},
{
"code": null,
"e": 6424,
"s": 6417,
"text": " Print"
},
{
"code": null,
"e": 6435,
"s": 6424,
"text": " Add Notes"
}
] |
Boosting Python Scripts With Cython (Applied on Raspberry Pi) | by Ahmed Gad | Towards Data Science
|
Python might be one of today’s most popular programming languages, but it’s definitely not the most efficient. In the machine learning world in particular, practitioners sacrifice efficiency for the ease-of-use that Python offers.
That doesn’t mean that you can’t speed things up in other ways. Cython is an easy way to significantly lessen computation time of Python scripts, without sacrificing the functionality easily achieved using Python.
This tutorial will introduce you to using Cython to speed up Python scripts. We’ll look at a simple yet computationally expensive task: creating a for loop that iterates through a Python list of 1 billion numbers, and sums them. Since time is particularly important when running code on resource-limited devices, we’ll put this issue into context by considering how to implement Python code in Cython on Raspberry Pi (RPi). Cython makes a significant change in the speed of calculation. Think of it like a sloth compared to a cheetah.
This article was originally published on the Paperspace blog. You can run the code for my tutorials for free on Gradient.
The sections covered in this tutorial are as follows:
Python, CPython, and Cython
Cythonizing Simple Python Code
Cythonizing a for Loop
Assigning C Data Types to the Variables
Using Cython in Raspberry Pi
Let’s get started.
Many people are unaware of the fact that languages like Python are actually implemented in other languages. For example, the C implementation of Python is called CPython. Note that it is not Cython. For more information about the different implementations of Python, you can read this post.
The default and most popular implementation of Python is CPython. There is an important advantage of using it. C is a compiled language and its code is converted into machine code, which is executed directly by the central processing unit (CPU). Now you may wonder, if C is a compiled language, does that mean Python is too?
Python implementation in C (CPython) is not 100% complied, and also not 100% interpreted. There is both compilation and interpretation in the process of running a Python script. To make this clear, let’s see the steps of running a Python script:
Compiling source code using CPython to generate bytecodeInterpreting the bytecode in a CPython interpreterRunning the output of the CPython interpreter in a CPython virtual machine
Compiling source code using CPython to generate bytecode
Interpreting the bytecode in a CPython interpreter
Running the output of the CPython interpreter in a CPython virtual machine
Compilation takes place when CPython compiles the source code (.py file) to generate the CPython bytecode (.pyc file). The CPython bytecode (.pyc file) is then interpreted using a CPython interpreter, and the output runs in a CPython virtual machine. According to the above steps, the process of running a Python script involves both compilation and interpretation.
The CPython compiler generates the bytecode just once, but the interpreter is called each time the code runs. Usually the interpretation of the bytecode takes a lot of time. If using an interpreter slows down the execution, why use it at all? The big reason is that it helps make Python cross-platform. Since the bytecode runs in a CPython virtual machine on top of the CPU, it is independent of the machine it’s running on. As a result, the bytecode can run in different machines unchanged.
If there is no interpreter used, then the CPython compiler will generate machine code that directly runs in the CPU. Because different platforms have different instructions, the code will not be cross-platform.
In summary, using a compiler speeds up the process but an interpreter makes the code cross-platform. So, a reason why Python is slower than C is that an interpreter is used. Remember that the compiler just runs once but the interpreter runs each time the code is executed.
Python is much slower than C, but many programmers still prefer it since it’s so much easier to use. Python hides many details from the programmer, which can help prevent frustrating debugging. For instance, since Python is a dynamically-typed language you do not have to explicitly specify the type of each variable in your code — Python will deduce it automatically. In contrast, with statically-typed languages (like C, C++ or Java) you must specify the types of the variables, as seen below.
int x = 10 string s = "Hello"
Compare this to the implementation below in Python. Dynamic typing makes it easier to code, but adds much more burden on the machine to find the suitable datatype. This makes the process slower.
x = 10s = "Hello"
Generally speaking, “higher level” languages like Python are much easier to use for developers. However, when the code is run it will need to be converted into low-level instructions. This conversion takes more time, which is sacrificed for ease-of-use.
If time is an important factor, then you need to use the lower-level instructions. So rather than typing the code using Python, which is the interface, you can write it using CPython which is the backend of Python implemented in C. However, if you do so you will feel that you are programming in C, not Python.
CPython is much more complex. In CPython, everything is implemented in C. There is no way to escape the C complexity in coding. This is why many developers opt for Cython instead. But how is Cython different from CPython?
According to the Cython documentation, Cython is Python with C data types. Another definition from the Cython tutorial 2009 paper clarifies:
Cython is a programming language based on Python with extra syntax to provide static type declarations. This takes advantage of the benefits of Python while allowing one to achieve the speed of C.
According to the above definitions, Cython is a language which lets you have the best of both worlds — speed and ease-of-use. You can still write regular code in Python, but to speed things up at run time Cython allows you to replace some pieces of the Python code with C. So, you end up mixing both languages together in a single file. Note that you can imagine that everything in Python is valid in Cython, but with some limitations. For more info about the limitations, you can visit this page.
The regular Python file has a .py extension, but the Cython file has the .pyx extension instead. The same Python code can be written inside the .pyx files, but these allow you to also use Cython code. Note that just placing the Python code into a .pyx file may speed up the process compared to running the Python code directly, but not as much as when also declaring the variable types. Thus, the focus of this tutorial is not only on writing the Python code within the .pyx file but also on making edits which will make it run faster. By doing so we add a bit of difficulty to the programming, but much time is saved from doing so. If you have any experience with C programming, then it will be even easier for you.
To make your Python into Cython, first you need to create a file with the .pyx extension rather than the .py extension. Inside this file, you can start by writing regular Python code (note that there are some limitations in the Python code accepted by Cython, as clarified in the Cython docs).
Before going forward, make sure Cython is installed. You can do so with the following command.
pip install cython
To generate the .pyd/.so file we need to first build the Cython file. The .pyd/.so file represents the module to be imported later. To build the Cython file, a setup.py file will be used. Create this file and place the code below within it. We’ll use the distutils.core.setup() function to call the Cython.Build.cythonize() function, which will cythonize the .pyx file. This function accepts the path of the file you want to cythonize. Here I’m assuming that the setup.py file is placed in the same location as the test_cython.pyx file.
import distutils.core import Cython.Build distutils.core.setup(ext_modules = Cython.Build.cythonize("test_cython.pyx"))
In order to build the Cython file, issue the command below in the command prompt. The current directory of the command prompt is expected to be the same as the directory of the setup.py file.
python setup.py build_ext --inplace
After this command completes, two files will be placed beside the .pyx file. The first one has the .c extension and the other file will have the extension .pyd (or similar, based on the operating system used). In order to use the generated file, just import the test_cython module and the “Hello Cython” message will appear directly, as you see below.
We have now successfully cythonized the Python code. The next section discusses cythonizing a .pyx file in which loop is created.
Now let’s optimize our aforementioned task: a for loop that iterates through 1 million numbers and sums them. Let’s start by looking at the efficiency of just the iterations of the loop. The time module is imported for estimating how long it takes to execute.
import timecdef unsigned long long int maxvalcdef unsigned long long int totalcdef int kcdef double t1, t2, tmaxval = 1000000000t1=time.time()for k in range(maxval): total = total + kprint "Total =", totalt2=time.time()t = t2-t1print("%.10f" % t)
In a .pyx file, the mean time for 3 runs is 0.0281 seconds. The code is running on a machine with Core i7–6500U CPU @ 2.5 GHz and 16 GB DDR3 RAM.
Compare this with the time it takes to run in a normal Python file, the mean of which is 0.0411 seconds. This means Cython is 1.46 times faster than Python for the iterations alone, even though we don’t need to modify the for loop to get it to execute at C-speed.
Now let’s add the summing task. We’ll use the range() function for this.
import timet1 = time.time()total = 0for k in range(1000000): total = total + kprint "Total =", totalt2 = time.time()t = t2-t1print("%.100f" % t)
Note that both of the scripts return the same value, which is 499999500000. In Python this takes an average of 0.1183 seconds to run (between three trials). In Cython it is 1.35 times faster, at an average of 0.0875 seconds.
Let’s see another example in which the loop iterates through 1 billion number starting from 0.
import timet1 = time.time()total = 0for k in range(1000000000): total = total + kprint "Total =", totalt2 = time.time()t = t2-t1print("%.20f" % t)
The Cython script completed in nearly 85 seconds (1.4 minutes) while the Python script completed in nearly 115 seconds (1.9 minutes). In both cases it’s simply too much time. What is the benefit of using Cython if it lasts for more than a minute on such a trivial task? Note that this is our fault, not Cython’s.
As discussed previously, writing the Python code within the Cython .pyx script is an improvement, but it does not make a very large cut in the execution time. We have to make edits to the Python code within the Cython script. The first thing to focus on is to explicitly define the data types of the variables used.
According to the previous code, there are 5 variables used: total, k, t1, t2, and t. All of these variables have their data types deduced implicitly by the code, thus taking more time. To save the time used for deducing their data types, let’s assign their data types from the C language instead.
The type of the total variable is unsigned long long int. It is an integer because the sum of all numbers is an integer, and it is unsigned because the sum will be positive. But why it is long long? Because the sum of all numbers is very large, long long is added to increase the variable size to the maximum possible size.
The type defined for the variable k is int, and the double type is assigned for the remaining three variables t1, t2, and t.
import timecdef unsigned long long int totalcdef int kcdef double t1, t2, tt1 = time.time()for k in range(1000000000): total = total + kprint "Total =", totalt2 = time.time()t = t2-t1print("%.20f" % t)
While Python takes more than 1.9 minutes, Cython takes only 0.00009346 seconds .
Now that we’ve seen how to speed up the performance of the Python scripts by using Cython, let’s apply this to Raspberry Pi (RPi).
If this is the first time you’re using your Raspberry Pi, then both your PC and the RPi need to get connected over a network. You can do this by connecting both of them to a switch in which the DHCP (Dynamic Host Configuration Protocol) is active to assign them IP addresses automatically. After successful network creation, you can access the RPi based on the IPv4 address assigned to it. How do you know what the IPv4 address assigned to your RPi is? Don’t worry, you can simply use an IP scanner tool. In this tutorial, I will use a free application called Advanced IP Scanner.
The interface of the application is as seen below. It accepts a range of IPv4 addresses to search for, and returns the information for active devices.
You need to enter the range of IPv4 addresses in your local network. If you do not know the range, just issue the ipconfig command in Windows (or ifconfig in Linux) to know your PC IPv4 address (as shown in the figure below). In my case, the IPv4 address assigned to the Wi-Fi adapter of my PC is 192.168.43.177 and the subnet mask is 255.255.255.0. This means that the range of IPv4 addresses in the network is from 192.168.43.1 to 192.168.43.255. According to the figure, the IPv4 address 192.168.43.1 is assigned to the gateway. Note that the last IPv4 address in the range, 192.168.43.255, is reserved for broadcast messages. Thus, the range to search should start from 192.168.43.2 and end at 192.168.43.254.
According to the result of the scan shown in the next figure, the IPv4 address assigned to the RPi is 192.168.43.63. This IPv4 address can be used to create a secure shell (SSH) session.
For establishing the SSH session, I will use a free software called MobaXterm. The interface of the application is as follows.
In order to create an SSH session, just click on the Session button at the top-left corner. A new window appears as shown below.
From this window, click on the SSH button at the top-left corner to open the window shown below. Just enter the IPv4 address of the RPi and the username (which is by default pi), then click OK to start the session.
After clicking the OK button, a new window appears asking for the password. The default password is raspberrypi. After logging in, the next window appears. The pane to the left helps to navigate the directories of the RPi easily. There is also a command-line for entering commands.
Create a new file and set its extension to .pyx for writing the code of the last example. There are options in the bar at the left pane for creating new files and directories. You can use the new file icon to make things even simpler, as shown in the following figure. I created a file named test_cython.pyx in the root directory of the RPi.
Just double-click the file to open it, paste the code, and save it. After that we can create the setup.py file, which is exactly the same as we discussed previously. Next we must issue the following command for building the Cython script.
python3 setup.py build_ext --inplace
After this command completes successfully, you can find the output files listed in the left pane according to the next figure. Note that the extension of the module to be imported is now .so, as we are no longer using Windows.
Now let’s activate Python and import the module, as shown below and run the Cython code.
This article was originally published on the Paperspace blog. You can run the code for my tutorials for free on Gradient.
This tutorial discussed how to use Cython to reduce the computation time of executing Python scripts. We looked at the example of using a for loop to sum all elements in a Python list of 1 billion numbers, and compared its time for execution with and without declaring the variable types. While this takes nearly two minutes to run in pure Python, it takes essentially no time to run with static variables declared using Cython.
In the next tutorial we’ll replace this Python list with a NumPy array, and see how we can optimize NumPy array processing using Cython. Then we’ll look at how to cythonize more advanced Python scripts, such as genetic algorithms. This are great ways to easily enhance the efficiency of your machine learning projects.
|
[
{
"code": null,
"e": 403,
"s": 172,
"text": "Python might be one of today’s most popular programming languages, but it’s definitely not the most efficient. In the machine learning world in particular, practitioners sacrifice efficiency for the ease-of-use that Python offers."
},
{
"code": null,
"e": 617,
"s": 403,
"text": "That doesn’t mean that you can’t speed things up in other ways. Cython is an easy way to significantly lessen computation time of Python scripts, without sacrificing the functionality easily achieved using Python."
},
{
"code": null,
"e": 1152,
"s": 617,
"text": "This tutorial will introduce you to using Cython to speed up Python scripts. We’ll look at a simple yet computationally expensive task: creating a for loop that iterates through a Python list of 1 billion numbers, and sums them. Since time is particularly important when running code on resource-limited devices, we’ll put this issue into context by considering how to implement Python code in Cython on Raspberry Pi (RPi). Cython makes a significant change in the speed of calculation. Think of it like a sloth compared to a cheetah."
},
{
"code": null,
"e": 1274,
"s": 1152,
"text": "This article was originally published on the Paperspace blog. You can run the code for my tutorials for free on Gradient."
},
{
"code": null,
"e": 1328,
"s": 1274,
"text": "The sections covered in this tutorial are as follows:"
},
{
"code": null,
"e": 1356,
"s": 1328,
"text": "Python, CPython, and Cython"
},
{
"code": null,
"e": 1387,
"s": 1356,
"text": "Cythonizing Simple Python Code"
},
{
"code": null,
"e": 1410,
"s": 1387,
"text": "Cythonizing a for Loop"
},
{
"code": null,
"e": 1450,
"s": 1410,
"text": "Assigning C Data Types to the Variables"
},
{
"code": null,
"e": 1479,
"s": 1450,
"text": "Using Cython in Raspberry Pi"
},
{
"code": null,
"e": 1498,
"s": 1479,
"text": "Let’s get started."
},
{
"code": null,
"e": 1789,
"s": 1498,
"text": "Many people are unaware of the fact that languages like Python are actually implemented in other languages. For example, the C implementation of Python is called CPython. Note that it is not Cython. For more information about the different implementations of Python, you can read this post."
},
{
"code": null,
"e": 2114,
"s": 1789,
"text": "The default and most popular implementation of Python is CPython. There is an important advantage of using it. C is a compiled language and its code is converted into machine code, which is executed directly by the central processing unit (CPU). Now you may wonder, if C is a compiled language, does that mean Python is too?"
},
{
"code": null,
"e": 2360,
"s": 2114,
"text": "Python implementation in C (CPython) is not 100% complied, and also not 100% interpreted. There is both compilation and interpretation in the process of running a Python script. To make this clear, let’s see the steps of running a Python script:"
},
{
"code": null,
"e": 2541,
"s": 2360,
"text": "Compiling source code using CPython to generate bytecodeInterpreting the bytecode in a CPython interpreterRunning the output of the CPython interpreter in a CPython virtual machine"
},
{
"code": null,
"e": 2598,
"s": 2541,
"text": "Compiling source code using CPython to generate bytecode"
},
{
"code": null,
"e": 2649,
"s": 2598,
"text": "Interpreting the bytecode in a CPython interpreter"
},
{
"code": null,
"e": 2724,
"s": 2649,
"text": "Running the output of the CPython interpreter in a CPython virtual machine"
},
{
"code": null,
"e": 3090,
"s": 2724,
"text": "Compilation takes place when CPython compiles the source code (.py file) to generate the CPython bytecode (.pyc file). The CPython bytecode (.pyc file) is then interpreted using a CPython interpreter, and the output runs in a CPython virtual machine. According to the above steps, the process of running a Python script involves both compilation and interpretation."
},
{
"code": null,
"e": 3582,
"s": 3090,
"text": "The CPython compiler generates the bytecode just once, but the interpreter is called each time the code runs. Usually the interpretation of the bytecode takes a lot of time. If using an interpreter slows down the execution, why use it at all? The big reason is that it helps make Python cross-platform. Since the bytecode runs in a CPython virtual machine on top of the CPU, it is independent of the machine it’s running on. As a result, the bytecode can run in different machines unchanged."
},
{
"code": null,
"e": 3793,
"s": 3582,
"text": "If there is no interpreter used, then the CPython compiler will generate machine code that directly runs in the CPU. Because different platforms have different instructions, the code will not be cross-platform."
},
{
"code": null,
"e": 4066,
"s": 3793,
"text": "In summary, using a compiler speeds up the process but an interpreter makes the code cross-platform. So, a reason why Python is slower than C is that an interpreter is used. Remember that the compiler just runs once but the interpreter runs each time the code is executed."
},
{
"code": null,
"e": 4562,
"s": 4066,
"text": "Python is much slower than C, but many programmers still prefer it since it’s so much easier to use. Python hides many details from the programmer, which can help prevent frustrating debugging. For instance, since Python is a dynamically-typed language you do not have to explicitly specify the type of each variable in your code — Python will deduce it automatically. In contrast, with statically-typed languages (like C, C++ or Java) you must specify the types of the variables, as seen below."
},
{
"code": null,
"e": 4592,
"s": 4562,
"text": "int x = 10 string s = \"Hello\""
},
{
"code": null,
"e": 4787,
"s": 4592,
"text": "Compare this to the implementation below in Python. Dynamic typing makes it easier to code, but adds much more burden on the machine to find the suitable datatype. This makes the process slower."
},
{
"code": null,
"e": 4805,
"s": 4787,
"text": "x = 10s = \"Hello\""
},
{
"code": null,
"e": 5059,
"s": 4805,
"text": "Generally speaking, “higher level” languages like Python are much easier to use for developers. However, when the code is run it will need to be converted into low-level instructions. This conversion takes more time, which is sacrificed for ease-of-use."
},
{
"code": null,
"e": 5370,
"s": 5059,
"text": "If time is an important factor, then you need to use the lower-level instructions. So rather than typing the code using Python, which is the interface, you can write it using CPython which is the backend of Python implemented in C. However, if you do so you will feel that you are programming in C, not Python."
},
{
"code": null,
"e": 5592,
"s": 5370,
"text": "CPython is much more complex. In CPython, everything is implemented in C. There is no way to escape the C complexity in coding. This is why many developers opt for Cython instead. But how is Cython different from CPython?"
},
{
"code": null,
"e": 5733,
"s": 5592,
"text": "According to the Cython documentation, Cython is Python with C data types. Another definition from the Cython tutorial 2009 paper clarifies:"
},
{
"code": null,
"e": 5930,
"s": 5733,
"text": "Cython is a programming language based on Python with extra syntax to provide static type declarations. This takes advantage of the benefits of Python while allowing one to achieve the speed of C."
},
{
"code": null,
"e": 6428,
"s": 5930,
"text": "According to the above definitions, Cython is a language which lets you have the best of both worlds — speed and ease-of-use. You can still write regular code in Python, but to speed things up at run time Cython allows you to replace some pieces of the Python code with C. So, you end up mixing both languages together in a single file. Note that you can imagine that everything in Python is valid in Cython, but with some limitations. For more info about the limitations, you can visit this page."
},
{
"code": null,
"e": 7145,
"s": 6428,
"text": "The regular Python file has a .py extension, but the Cython file has the .pyx extension instead. The same Python code can be written inside the .pyx files, but these allow you to also use Cython code. Note that just placing the Python code into a .pyx file may speed up the process compared to running the Python code directly, but not as much as when also declaring the variable types. Thus, the focus of this tutorial is not only on writing the Python code within the .pyx file but also on making edits which will make it run faster. By doing so we add a bit of difficulty to the programming, but much time is saved from doing so. If you have any experience with C programming, then it will be even easier for you."
},
{
"code": null,
"e": 7439,
"s": 7145,
"text": "To make your Python into Cython, first you need to create a file with the .pyx extension rather than the .py extension. Inside this file, you can start by writing regular Python code (note that there are some limitations in the Python code accepted by Cython, as clarified in the Cython docs)."
},
{
"code": null,
"e": 7534,
"s": 7439,
"text": "Before going forward, make sure Cython is installed. You can do so with the following command."
},
{
"code": null,
"e": 7553,
"s": 7534,
"text": "pip install cython"
},
{
"code": null,
"e": 8090,
"s": 7553,
"text": "To generate the .pyd/.so file we need to first build the Cython file. The .pyd/.so file represents the module to be imported later. To build the Cython file, a setup.py file will be used. Create this file and place the code below within it. We’ll use the distutils.core.setup() function to call the Cython.Build.cythonize() function, which will cythonize the .pyx file. This function accepts the path of the file you want to cythonize. Here I’m assuming that the setup.py file is placed in the same location as the test_cython.pyx file."
},
{
"code": null,
"e": 8210,
"s": 8090,
"text": "import distutils.core import Cython.Build distutils.core.setup(ext_modules = Cython.Build.cythonize(\"test_cython.pyx\"))"
},
{
"code": null,
"e": 8402,
"s": 8210,
"text": "In order to build the Cython file, issue the command below in the command prompt. The current directory of the command prompt is expected to be the same as the directory of the setup.py file."
},
{
"code": null,
"e": 8438,
"s": 8402,
"text": "python setup.py build_ext --inplace"
},
{
"code": null,
"e": 8790,
"s": 8438,
"text": "After this command completes, two files will be placed beside the .pyx file. The first one has the .c extension and the other file will have the extension .pyd (or similar, based on the operating system used). In order to use the generated file, just import the test_cython module and the “Hello Cython” message will appear directly, as you see below."
},
{
"code": null,
"e": 8920,
"s": 8790,
"text": "We have now successfully cythonized the Python code. The next section discusses cythonizing a .pyx file in which loop is created."
},
{
"code": null,
"e": 9180,
"s": 8920,
"text": "Now let’s optimize our aforementioned task: a for loop that iterates through 1 million numbers and sums them. Let’s start by looking at the efficiency of just the iterations of the loop. The time module is imported for estimating how long it takes to execute."
},
{
"code": null,
"e": 9430,
"s": 9180,
"text": "import timecdef unsigned long long int maxvalcdef unsigned long long int totalcdef int kcdef double t1, t2, tmaxval = 1000000000t1=time.time()for k in range(maxval): total = total + kprint \"Total =\", totalt2=time.time()t = t2-t1print(\"%.10f\" % t)"
},
{
"code": null,
"e": 9576,
"s": 9430,
"text": "In a .pyx file, the mean time for 3 runs is 0.0281 seconds. The code is running on a machine with Core i7–6500U CPU @ 2.5 GHz and 16 GB DDR3 RAM."
},
{
"code": null,
"e": 9840,
"s": 9576,
"text": "Compare this with the time it takes to run in a normal Python file, the mean of which is 0.0411 seconds. This means Cython is 1.46 times faster than Python for the iterations alone, even though we don’t need to modify the for loop to get it to execute at C-speed."
},
{
"code": null,
"e": 9913,
"s": 9840,
"text": "Now let’s add the summing task. We’ll use the range() function for this."
},
{
"code": null,
"e": 10061,
"s": 9913,
"text": "import timet1 = time.time()total = 0for k in range(1000000): total = total + kprint \"Total =\", totalt2 = time.time()t = t2-t1print(\"%.100f\" % t)"
},
{
"code": null,
"e": 10286,
"s": 10061,
"text": "Note that both of the scripts return the same value, which is 499999500000. In Python this takes an average of 0.1183 seconds to run (between three trials). In Cython it is 1.35 times faster, at an average of 0.0875 seconds."
},
{
"code": null,
"e": 10381,
"s": 10286,
"text": "Let’s see another example in which the loop iterates through 1 billion number starting from 0."
},
{
"code": null,
"e": 10531,
"s": 10381,
"text": "import timet1 = time.time()total = 0for k in range(1000000000): total = total + kprint \"Total =\", totalt2 = time.time()t = t2-t1print(\"%.20f\" % t)"
},
{
"code": null,
"e": 10844,
"s": 10531,
"text": "The Cython script completed in nearly 85 seconds (1.4 minutes) while the Python script completed in nearly 115 seconds (1.9 minutes). In both cases it’s simply too much time. What is the benefit of using Cython if it lasts for more than a minute on such a trivial task? Note that this is our fault, not Cython’s."
},
{
"code": null,
"e": 11160,
"s": 10844,
"text": "As discussed previously, writing the Python code within the Cython .pyx script is an improvement, but it does not make a very large cut in the execution time. We have to make edits to the Python code within the Cython script. The first thing to focus on is to explicitly define the data types of the variables used."
},
{
"code": null,
"e": 11457,
"s": 11160,
"text": "According to the previous code, there are 5 variables used: total, k, t1, t2, and t. All of these variables have their data types deduced implicitly by the code, thus taking more time. To save the time used for deducing their data types, let’s assign their data types from the C language instead."
},
{
"code": null,
"e": 11781,
"s": 11457,
"text": "The type of the total variable is unsigned long long int. It is an integer because the sum of all numbers is an integer, and it is unsigned because the sum will be positive. But why it is long long? Because the sum of all numbers is very large, long long is added to increase the variable size to the maximum possible size."
},
{
"code": null,
"e": 11906,
"s": 11781,
"text": "The type defined for the variable k is int, and the double type is assigned for the remaining three variables t1, t2, and t."
},
{
"code": null,
"e": 12111,
"s": 11906,
"text": "import timecdef unsigned long long int totalcdef int kcdef double t1, t2, tt1 = time.time()for k in range(1000000000): total = total + kprint \"Total =\", totalt2 = time.time()t = t2-t1print(\"%.20f\" % t)"
},
{
"code": null,
"e": 12192,
"s": 12111,
"text": "While Python takes more than 1.9 minutes, Cython takes only 0.00009346 seconds ."
},
{
"code": null,
"e": 12323,
"s": 12192,
"text": "Now that we’ve seen how to speed up the performance of the Python scripts by using Cython, let’s apply this to Raspberry Pi (RPi)."
},
{
"code": null,
"e": 12904,
"s": 12323,
"text": "If this is the first time you’re using your Raspberry Pi, then both your PC and the RPi need to get connected over a network. You can do this by connecting both of them to a switch in which the DHCP (Dynamic Host Configuration Protocol) is active to assign them IP addresses automatically. After successful network creation, you can access the RPi based on the IPv4 address assigned to it. How do you know what the IPv4 address assigned to your RPi is? Don’t worry, you can simply use an IP scanner tool. In this tutorial, I will use a free application called Advanced IP Scanner."
},
{
"code": null,
"e": 13055,
"s": 12904,
"text": "The interface of the application is as seen below. It accepts a range of IPv4 addresses to search for, and returns the information for active devices."
},
{
"code": null,
"e": 13769,
"s": 13055,
"text": "You need to enter the range of IPv4 addresses in your local network. If you do not know the range, just issue the ipconfig command in Windows (or ifconfig in Linux) to know your PC IPv4 address (as shown in the figure below). In my case, the IPv4 address assigned to the Wi-Fi adapter of my PC is 192.168.43.177 and the subnet mask is 255.255.255.0. This means that the range of IPv4 addresses in the network is from 192.168.43.1 to 192.168.43.255. According to the figure, the IPv4 address 192.168.43.1 is assigned to the gateway. Note that the last IPv4 address in the range, 192.168.43.255, is reserved for broadcast messages. Thus, the range to search should start from 192.168.43.2 and end at 192.168.43.254."
},
{
"code": null,
"e": 13956,
"s": 13769,
"text": "According to the result of the scan shown in the next figure, the IPv4 address assigned to the RPi is 192.168.43.63. This IPv4 address can be used to create a secure shell (SSH) session."
},
{
"code": null,
"e": 14083,
"s": 13956,
"text": "For establishing the SSH session, I will use a free software called MobaXterm. The interface of the application is as follows."
},
{
"code": null,
"e": 14212,
"s": 14083,
"text": "In order to create an SSH session, just click on the Session button at the top-left corner. A new window appears as shown below."
},
{
"code": null,
"e": 14427,
"s": 14212,
"text": "From this window, click on the SSH button at the top-left corner to open the window shown below. Just enter the IPv4 address of the RPi and the username (which is by default pi), then click OK to start the session."
},
{
"code": null,
"e": 14709,
"s": 14427,
"text": "After clicking the OK button, a new window appears asking for the password. The default password is raspberrypi. After logging in, the next window appears. The pane to the left helps to navigate the directories of the RPi easily. There is also a command-line for entering commands."
},
{
"code": null,
"e": 15051,
"s": 14709,
"text": "Create a new file and set its extension to .pyx for writing the code of the last example. There are options in the bar at the left pane for creating new files and directories. You can use the new file icon to make things even simpler, as shown in the following figure. I created a file named test_cython.pyx in the root directory of the RPi."
},
{
"code": null,
"e": 15290,
"s": 15051,
"text": "Just double-click the file to open it, paste the code, and save it. After that we can create the setup.py file, which is exactly the same as we discussed previously. Next we must issue the following command for building the Cython script."
},
{
"code": null,
"e": 15327,
"s": 15290,
"text": "python3 setup.py build_ext --inplace"
},
{
"code": null,
"e": 15554,
"s": 15327,
"text": "After this command completes successfully, you can find the output files listed in the left pane according to the next figure. Note that the extension of the module to be imported is now .so, as we are no longer using Windows."
},
{
"code": null,
"e": 15643,
"s": 15554,
"text": "Now let’s activate Python and import the module, as shown below and run the Cython code."
},
{
"code": null,
"e": 15765,
"s": 15643,
"text": "This article was originally published on the Paperspace blog. You can run the code for my tutorials for free on Gradient."
},
{
"code": null,
"e": 16194,
"s": 15765,
"text": "This tutorial discussed how to use Cython to reduce the computation time of executing Python scripts. We looked at the example of using a for loop to sum all elements in a Python list of 1 billion numbers, and compared its time for execution with and without declaring the variable types. While this takes nearly two minutes to run in pure Python, it takes essentially no time to run with static variables declared using Cython."
}
] |
W3.CSS - Modal Dialog
|
W3.CSS can be used to display a customizable modal dialog box instead of the standard JavaScript alert.
It uses w3-row and w3-col style classes to define rows and columns respectively.
modal-dialog
Represents the main parent window to define a dialog box.
w3-modal-dialog
Represents the dialog content container.
w3-modal-content
Represents dialog contents.
<html>
<head>
<title>The W3.CSS Modal dialog</title>
<meta name = "viewport" content = "width = device-width, initial-scale = 1">
<link rel = "stylesheet" href = "https://www.w3schools.com/lib/w3.css">
</head>
<body class = "w3-container">
<h2>Modal dialog Demo</h2>
<a class = "w3-btn w3-teal" href = "#model-dialog">Open a Modal dialog</a>
<div id = "model-dialog" class = "w3-modal">
<div class = "w3-modal-dialog">
<div class = "w3-modal-content w3-card-8">
<header class = "w3-container w3-teal">
<a href = "#" class = "w3-closebtn">×</a>
<h2>TutorialsPoint</h2>
</header>
<div class = "w3-container">
<p>Hello World!</p>
</div>
<footer class = "w3-container w3-teal">
<p>@TutorialsPoint.COM</p>
</footer>
</div>
</div>
</div>
</body>
</html>
Verify the result.
|
[
{
"code": null,
"e": 2013,
"s": 1909,
"text": "W3.CSS can be used to display a customizable modal dialog box instead of the standard JavaScript alert."
},
{
"code": null,
"e": 2094,
"s": 2013,
"text": "It uses w3-row and w3-col style classes to define rows and columns respectively."
},
{
"code": null,
"e": 2107,
"s": 2094,
"text": "modal-dialog"
},
{
"code": null,
"e": 2165,
"s": 2107,
"text": "Represents the main parent window to define a dialog box."
},
{
"code": null,
"e": 2181,
"s": 2165,
"text": "w3-modal-dialog"
},
{
"code": null,
"e": 2222,
"s": 2181,
"text": "Represents the dialog content container."
},
{
"code": null,
"e": 2239,
"s": 2222,
"text": "w3-modal-content"
},
{
"code": null,
"e": 2267,
"s": 2239,
"text": "Represents dialog contents."
},
{
"code": null,
"e": 3277,
"s": 2267,
"text": "<html>\n <head>\n <title>The W3.CSS Modal dialog</title>\n <meta name = \"viewport\" content = \"width = device-width, initial-scale = 1\">\n <link rel = \"stylesheet\" href = \"https://www.w3schools.com/lib/w3.css\">\n </head>\n \n <body class = \"w3-container\">\n <h2>Modal dialog Demo</h2>\n <a class = \"w3-btn w3-teal\" href = \"#model-dialog\">Open a Modal dialog</a>\n <div id = \"model-dialog\" class = \"w3-modal\">\n <div class = \"w3-modal-dialog\">\n <div class = \"w3-modal-content w3-card-8\">\n <header class = \"w3-container w3-teal\">\n <a href = \"#\" class = \"w3-closebtn\">×</a>\n <h2>TutorialsPoint</h2>\n </header>\n <div class = \"w3-container\">\n <p>Hello World!</p>\n </div>\n <footer class = \"w3-container w3-teal\">\n <p>@TutorialsPoint.COM</p>\n </footer>\n </div>\n </div>\n </div>\n </body>\n</html>"
}
] |
Autowire byName in Spring | Spring Bean Autowire byName Example
|
PROGRAMMINGJava ExamplesC Examples
Java Examples
C Examples
C Tutorials
aws
JAVAEXCEPTIONSCOLLECTIONSSWINGJDBC
EXCEPTIONS
COLLECTIONS
SWING
JDBC
JAVA 8
SPRING
SPRING BOOT
HIBERNATE
PYTHON
PHP
JQUERY
PROGRAMMINGJava ExamplesC Examples
Java Examples
C Examples
C Tutorials
aws
In this tutorial, we are going to learn about Spring bean autowire byName. Wiring in spring is nothing but configuring the dependencies of a bean in the XML file.
Generally, if we want to inject the dependencies into a bean, we need to wire the dependencies explicitly by using the ref attribute. like below
<bean id="travelBean" class="Travel">
<property name="car" ref="carBean" />
</bean>
<bean id="carBean" class="Car">
<property name="carName" value="BMW"></property>
</bean>
By making use of the autowire mechanism in spring, we no need to wire the dependencies explicitly. Just by using the autowire strategies, spring will automatically inject the dependencies.
Spring has given an autowire property in the <bean> tag to wire the dependencies. We have 4 different types of values associated with the autowire attribute. Those are autowire byName, byType, constructor, and auto-detect.
Let’s understand the autowire byName.
In spring, autowire byName is one of the strategies in bean autowiring strategies. In this strategy, while injecting the properties spring container verifies whether a property name of bean class and bean id in XML are matched or not. If matched then that property will be injected.
Spring IOC always uses the setter injection in case of autowire byName.
Create a Car Bean :
public class Car {
private String carName;
private String carType;
public String getCarName() {
return carName;
}
public void setCarName(String carName) {
this.carName = carName;
}
public String getCarType() {
return carType;
}
public void setCarType(String carType) {
this.carType = carType;
}
}
Create a Travel Bean :
public class Travel {
String name;
String type;
private Car car;
public Car getCar() {
return car;
}
public void setCar(Car car) {
this.car = car;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
}
Spring XML configuration :
spring.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">
<bean id="travelBean" class="Travel" autowire="byName">
<property name="name" value="Agarwal Travels" />
<property name="type" value="International" />
</bean>
<bean id="car" class="Car">
<property name="carName" value="Audi"/>
<property name="carType" value="Suv"/>
</bean>
</beans>
On the above XML in line number 6, we declare a travel bean with autowire="byName" and we inject name and type property values. But we didn’t inject any property for car bean in travel <bean>.
But, since it is declared as autowire byName, the container checks whether the property name car is mating with any bean id in XML, if it matches, that bean will be injected automatically. In this case, the car is injected to Travel bean, since the property name in Travel class car is matched with bean id in the car <bean> in XML.
If we remove the autowire="byName" attribute from travel <bean>. We should get NullPointerException since it is not defined.
Run the Application :
Main.java
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;
public final class Main {
public static final void main(String[] args) {
BeanFactory factory = new XmlBeanFactory(new ClassPathResource("spring.xml"));
Travel travel = (Travel)factory.getBean("travelBean");
String carName = travel.getCar().getCarName();
System.out.println("Travel Name : "+travel.getName());
System.out.println("Travel Type : "+travel.getType());
System.out.println("Car Name : "+carName);
}
}
Output :
Travel Name : Agarwal Travels
Travel Type : International
Car Name : Audi
Complete Example is available for download : Spring Bean Autowire byName Example
Happy Learning 🙂
Spring Bean Autowire byName Example
File size: 9 KB
Downloads: 673
Spring Bean Autowire By Constructor Example
Spring Bean Autowire ByType Example
Types of Spring Bean Scopes Example
@Autowired,@Qualifier,@Value annotations in Spring
@Qualifier annotation example in Spring
Spring Collection Dependency List Example
Spring Java Configuration Example
Spring Collection Map Dependency Example
Spring AOP Around Advice Example XML
spring expression language example
Spring AOP Example Before and After Advice XML
Spring JdbcTemplate CRUD Application
Spring Hibernate Example
Spring AOP ThrowsAdvice Example XML
Dependency Injection (IoC) in spring with Example
Spring Bean Autowire By Constructor Example
Spring Bean Autowire ByType Example
Types of Spring Bean Scopes Example
@Autowired,@Qualifier,@Value annotations in Spring
@Qualifier annotation example in Spring
Spring Collection Dependency List Example
Spring Java Configuration Example
Spring Collection Map Dependency Example
Spring AOP Around Advice Example XML
spring expression language example
Spring AOP Example Before and After Advice XML
Spring JdbcTemplate CRUD Application
Spring Hibernate Example
Spring AOP ThrowsAdvice Example XML
Dependency Injection (IoC) in spring with Example
|
[
{
"code": null,
"e": 158,
"s": 123,
"text": "PROGRAMMINGJava ExamplesC Examples"
},
{
"code": null,
"e": 172,
"s": 158,
"text": "Java Examples"
},
{
"code": null,
"e": 183,
"s": 172,
"text": "C Examples"
},
{
"code": null,
"e": 195,
"s": 183,
"text": "C Tutorials"
},
{
"code": null,
"e": 199,
"s": 195,
"text": "aws"
},
{
"code": null,
"e": 234,
"s": 199,
"text": "JAVAEXCEPTIONSCOLLECTIONSSWINGJDBC"
},
{
"code": null,
"e": 245,
"s": 234,
"text": "EXCEPTIONS"
},
{
"code": null,
"e": 257,
"s": 245,
"text": "COLLECTIONS"
},
{
"code": null,
"e": 263,
"s": 257,
"text": "SWING"
},
{
"code": null,
"e": 268,
"s": 263,
"text": "JDBC"
},
{
"code": null,
"e": 275,
"s": 268,
"text": "JAVA 8"
},
{
"code": null,
"e": 282,
"s": 275,
"text": "SPRING"
},
{
"code": null,
"e": 294,
"s": 282,
"text": "SPRING BOOT"
},
{
"code": null,
"e": 304,
"s": 294,
"text": "HIBERNATE"
},
{
"code": null,
"e": 311,
"s": 304,
"text": "PYTHON"
},
{
"code": null,
"e": 315,
"s": 311,
"text": "PHP"
},
{
"code": null,
"e": 322,
"s": 315,
"text": "JQUERY"
},
{
"code": null,
"e": 357,
"s": 322,
"text": "PROGRAMMINGJava ExamplesC Examples"
},
{
"code": null,
"e": 371,
"s": 357,
"text": "Java Examples"
},
{
"code": null,
"e": 382,
"s": 371,
"text": "C Examples"
},
{
"code": null,
"e": 394,
"s": 382,
"text": "C Tutorials"
},
{
"code": null,
"e": 398,
"s": 394,
"text": "aws"
},
{
"code": null,
"e": 561,
"s": 398,
"text": "In this tutorial, we are going to learn about Spring bean autowire byName. Wiring in spring is nothing but configuring the dependencies of a bean in the XML file."
},
{
"code": null,
"e": 706,
"s": 561,
"text": "Generally, if we want to inject the dependencies into a bean, we need to wire the dependencies explicitly by using the ref attribute. like below"
},
{
"code": null,
"e": 883,
"s": 706,
"text": "<bean id=\"travelBean\" class=\"Travel\">\n <property name=\"car\" ref=\"carBean\" />\n</bean>\n<bean id=\"carBean\" class=\"Car\">\n <property name=\"carName\" value=\"BMW\"></property>\n</bean>"
},
{
"code": null,
"e": 1072,
"s": 883,
"text": "By making use of the autowire mechanism in spring, we no need to wire the dependencies explicitly. Just by using the autowire strategies, spring will automatically inject the dependencies."
},
{
"code": null,
"e": 1295,
"s": 1072,
"text": "Spring has given an autowire property in the <bean> tag to wire the dependencies. We have 4 different types of values associated with the autowire attribute. Those are autowire byName, byType, constructor, and auto-detect."
},
{
"code": null,
"e": 1333,
"s": 1295,
"text": "Let’s understand the autowire byName."
},
{
"code": null,
"e": 1616,
"s": 1333,
"text": "In spring, autowire byName is one of the strategies in bean autowiring strategies. In this strategy, while injecting the properties spring container verifies whether a property name of bean class and bean id in XML are matched or not. If matched then that property will be injected."
},
{
"code": null,
"e": 1688,
"s": 1616,
"text": "Spring IOC always uses the setter injection in case of autowire byName."
},
{
"code": null,
"e": 1708,
"s": 1688,
"text": "Create a Car Bean :"
},
{
"code": null,
"e": 2082,
"s": 1708,
"text": "public class Car {\n private String carName;\n private String carType;\n\n public String getCarName() {\n return carName;\n }\n\n public void setCarName(String carName) {\n this.carName = carName;\n }\n\n public String getCarType() {\n return carType;\n }\n\n public void setCarType(String carType) {\n this.carType = carType;\n }\n\n}"
},
{
"code": null,
"e": 2105,
"s": 2082,
"text": "Create a Travel Bean :"
},
{
"code": null,
"e": 2562,
"s": 2105,
"text": "public class Travel {\n String name;\n String type;\n private Car car;\n\n public Car getCar() {\n return car;\n }\n\n public void setCar(Car car) {\n this.car = car;\n }\n\n public String getName() {\n return name;\n }\n\n public void setName(String name) {\n this.name = name;\n }\n\n public String getType() {\n return type;\n }\n\n public void setType(String type) {\n this.type = type;\n }\n}"
},
{
"code": null,
"e": 2589,
"s": 2562,
"text": "Spring XML configuration :"
},
{
"code": null,
"e": 2600,
"s": 2589,
"text": "spring.xml"
},
{
"code": null,
"e": 3400,
"s": 2600,
"text": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<beans xmlns=\"http://www.springframework.org/schema/beans\"\n xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:context=\"http://www.springframework.org/schema/context\"\n xsi:schemaLocation=\"http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd\n http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd\">\n <bean id=\"travelBean\" class=\"Travel\" autowire=\"byName\">\n <property name=\"name\" value=\"Agarwal Travels\" />\n <property name=\"type\" value=\"International\" />\n </bean>\n <bean id=\"car\" class=\"Car\">\n <property name=\"carName\" value=\"Audi\"/>\n <property name=\"carType\" value=\"Suv\"/>\n </bean>\n</beans>"
},
{
"code": null,
"e": 3593,
"s": 3400,
"text": "On the above XML in line number 6, we declare a travel bean with autowire=\"byName\" and we inject name and type property values. But we didn’t inject any property for car bean in travel <bean>."
},
{
"code": null,
"e": 3926,
"s": 3593,
"text": "But, since it is declared as autowire byName, the container checks whether the property name car is mating with any bean id in XML, if it matches, that bean will be injected automatically. In this case, the car is injected to Travel bean, since the property name in Travel class car is matched with bean id in the car <bean> in XML."
},
{
"code": null,
"e": 4051,
"s": 3926,
"text": "If we remove the autowire=\"byName\" attribute from travel <bean>. We should get NullPointerException since it is not defined."
},
{
"code": null,
"e": 4073,
"s": 4051,
"text": "Run the Application :"
},
{
"code": null,
"e": 4083,
"s": 4073,
"text": "Main.java"
},
{
"code": null,
"e": 4722,
"s": 4083,
"text": "import org.springframework.beans.factory.BeanFactory;\nimport org.springframework.beans.factory.xml.XmlBeanFactory;\nimport org.springframework.core.io.ClassPathResource;\n\npublic final class Main {\n\n public static final void main(String[] args) {\n BeanFactory factory = new XmlBeanFactory(new ClassPathResource(\"spring.xml\"));\n Travel travel = (Travel)factory.getBean(\"travelBean\");\n String carName = travel.getCar().getCarName();\n\n System.out.println(\"Travel Name : \"+travel.getName());\n System.out.println(\"Travel Type : \"+travel.getType());\n System.out.println(\"Car Name : \"+carName);\n }\n}"
},
{
"code": null,
"e": 4731,
"s": 4722,
"text": "Output :"
},
{
"code": null,
"e": 4805,
"s": 4731,
"text": "Travel Name : Agarwal Travels\nTravel Type : International\nCar Name : Audi"
},
{
"code": null,
"e": 4886,
"s": 4805,
"text": "Complete Example is available for download : Spring Bean Autowire byName Example"
},
{
"code": null,
"e": 4903,
"s": 4886,
"text": "Happy Learning 🙂"
},
{
"code": null,
"e": 4974,
"s": 4903,
"text": "\n\nSpring Bean Autowire byName Example\n\nFile size: 9 KB\nDownloads: 673\n"
},
{
"code": null,
"e": 5567,
"s": 4974,
"text": "\nSpring Bean Autowire By Constructor Example\nSpring Bean Autowire ByType Example\nTypes of Spring Bean Scopes Example\n@Autowired,@Qualifier,@Value annotations in Spring\n@Qualifier annotation example in Spring\nSpring Collection Dependency List Example\nSpring Java Configuration Example\nSpring Collection Map Dependency Example\nSpring AOP Around Advice Example XML\nspring expression language example\nSpring AOP Example Before and After Advice XML\nSpring JdbcTemplate CRUD Application\nSpring Hibernate Example\nSpring AOP ThrowsAdvice Example XML\nDependency Injection (IoC) in spring with Example\n"
},
{
"code": null,
"e": 5611,
"s": 5567,
"text": "Spring Bean Autowire By Constructor Example"
},
{
"code": null,
"e": 5647,
"s": 5611,
"text": "Spring Bean Autowire ByType Example"
},
{
"code": null,
"e": 5683,
"s": 5647,
"text": "Types of Spring Bean Scopes Example"
},
{
"code": null,
"e": 5734,
"s": 5683,
"text": "@Autowired,@Qualifier,@Value annotations in Spring"
},
{
"code": null,
"e": 5774,
"s": 5734,
"text": "@Qualifier annotation example in Spring"
},
{
"code": null,
"e": 5816,
"s": 5774,
"text": "Spring Collection Dependency List Example"
},
{
"code": null,
"e": 5850,
"s": 5816,
"text": "Spring Java Configuration Example"
},
{
"code": null,
"e": 5891,
"s": 5850,
"text": "Spring Collection Map Dependency Example"
},
{
"code": null,
"e": 5928,
"s": 5891,
"text": "Spring AOP Around Advice Example XML"
},
{
"code": null,
"e": 5963,
"s": 5928,
"text": "spring expression language example"
},
{
"code": null,
"e": 6010,
"s": 5963,
"text": "Spring AOP Example Before and After Advice XML"
},
{
"code": null,
"e": 6047,
"s": 6010,
"text": "Spring JdbcTemplate CRUD Application"
},
{
"code": null,
"e": 6072,
"s": 6047,
"text": "Spring Hibernate Example"
},
{
"code": null,
"e": 6108,
"s": 6072,
"text": "Spring AOP ThrowsAdvice Example XML"
}
] |
Flask â Templates
|
It is possible to return the output of a function bound to a certain URL in the form of HTML. For instance, in the following script, hello() function will render ‘Hello World’ with <h1> tag attached to it.
from flask import Flask
app = Flask(__name__)
@app.route('/')
def index():
return '<html><body><h1>Hello World</h1></body></html>'
if __name__ == '__main__':
app.run(debug = True)
However, generating HTML content from Python code is cumbersome, especially when variable data and Python language elements like conditionals or loops need to be put. This would require frequent escaping from HTML.
This is where one can take advantage of Jinja2 template engine, on which Flask is based. Instead of returning hardcode HTML from the function, a HTML file can be rendered by the render_template() function.
from flask import Flask
app = Flask(__name__)
@app.route('/')
def index():
return render_template(‘hello.html’)
if __name__ == '__main__':
app.run(debug = True)
Flask will try to find the HTML file in the templates folder, in the same folder in which this script is present.
Application folder
Hello.py
templates
hello.html
Hello.py
templates
hello.html
hello.html
The term ‘web templating system’ refers to designing an HTML script in which the variable data can be inserted dynamically. A web template system comprises of a template engine, some kind of data source and a template processor.
Flask uses jinja2 template engine. A web template contains HTML syntax interspersed placeholders for variables and expressions (in these case Python expressions) which are replaced values when the template is rendered.
The following code is saved as hello.html in the templates folder.
<!doctype html>
<html>
<body>
<h1>Hello {{ name }}!</h1>
</body>
</html>
Next, run the following script from Python shell.
from flask import Flask, render_template
app = Flask(__name__)
@app.route('/hello/<user>')
def hello_name(user):
return render_template('hello.html', name = user)
if __name__ == '__main__':
app.run(debug = True)
As the development server starts running, open the browser and enter URL as − http://localhost:5000/hello/mvl
The variable part of URL is inserted at {{ name }} place holder.
The jinja2 template engine uses the following delimiters for escaping from HTML.
{% ... %} for Statements
{{ ... }} for Expressions to print to the template output
{# ... #} for Comments not included in the template output
# ... ## for Line Statements
In the following example, use of conditional statement in the template is demonstrated. The URL rule to the hello() function accepts the integer parameter. It is passed to the hello.html template. Inside it, the value of number received (marks) is compared (greater or less than 50) and accordingly HTML is conditionally rendered.
The Python Script is as follows −
from flask import Flask, render_template
app = Flask(__name__)
@app.route('/hello/<int:score>')
def hello_name(score):
return render_template('hello.html', marks = score)
if __name__ == '__main__':
app.run(debug = True)
HTML template script of hello.html is as follows −
<!doctype html>
<html>
<body>
{% if marks>50 %}
<h1> Your result is pass!</h1>
{% else %}
<h1>Your result is fail</h1>
{% endif %}
</body>
</html>
Note that the conditional statements if-else and endif are enclosed in delimiter {%..%}.
Run the Python script and visit URL http://localhost/hello/60 and then http://localhost/hello/30 to see the output of HTML changing conditionally.
The Python loop constructs can also be employed inside the template. In the following script, the result() function sends a dictionary object to template results.html when URL http://localhost:5000/result is opened in the browser.
The Template part of result.html employs a for loop to render key and value pairs of dictionary object result{} as cells of an HTML table.
Run the following code from Python shell.
from flask import Flask, render_template
app = Flask(__name__)
@app.route('/result')
def result():
dict = {'phy':50,'che':60,'maths':70}
return render_template('result.html', result = dict)
if __name__ == '__main__':
app.run(debug = True)
Save the following HTML script as result.html in the templates folder.
<!doctype html>
<html>
<body>
<table border = 1>
{% for key, value in result.items() %}
<tr>
<th> {{ key }} </th>
<td> {{ value }} </td>
</tr>
{% endfor %}
</table>
</body>
</html>
Here, again the Python statements corresponding to the For loop are enclosed in {%..%} whereas, the expressions key and value are put inside {{ }}.
After the development starts running, open http://localhost:5000/result in the browser to get the following output.
22 Lectures
6 hours
Malhar Lathkar
21 Lectures
1.5 hours
Jack Chan
16 Lectures
4 hours
Malhar Lathkar
54 Lectures
6 hours
Srikanth Guskra
88 Lectures
3.5 hours
Jorge Escobar
80 Lectures
12 hours
Stone River ELearning
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2239,
"s": 2033,
"text": "It is possible to return the output of a function bound to a certain URL in the form of HTML. For instance, in the following script, hello() function will render ‘Hello World’ with <h1> tag attached to it."
},
{
"code": null,
"e": 2427,
"s": 2239,
"text": "from flask import Flask\napp = Flask(__name__)\n\n@app.route('/')\ndef index():\n return '<html><body><h1>Hello World</h1></body></html>'\n\nif __name__ == '__main__':\n app.run(debug = True)"
},
{
"code": null,
"e": 2642,
"s": 2427,
"text": "However, generating HTML content from Python code is cumbersome, especially when variable data and Python language elements like conditionals or loops need to be put. This would require frequent escaping from HTML."
},
{
"code": null,
"e": 2848,
"s": 2642,
"text": "This is where one can take advantage of Jinja2 template engine, on which Flask is based. Instead of returning hardcode HTML from the function, a HTML file can be rendered by the render_template() function."
},
{
"code": null,
"e": 3017,
"s": 2848,
"text": "from flask import Flask\napp = Flask(__name__)\n\n@app.route('/')\ndef index():\n return render_template(‘hello.html’)\n\nif __name__ == '__main__':\n app.run(debug = True)"
},
{
"code": null,
"e": 3131,
"s": 3017,
"text": "Flask will try to find the HTML file in the templates folder, in the same folder in which this script is present."
},
{
"code": null,
"e": 3186,
"s": 3131,
"text": "Application folder\n\nHello.py\ntemplates\n\nhello.html\n\n\n\n"
},
{
"code": null,
"e": 3195,
"s": 3186,
"text": "Hello.py"
},
{
"code": null,
"e": 3219,
"s": 3195,
"text": "templates\n\nhello.html\n\n"
},
{
"code": null,
"e": 3230,
"s": 3219,
"text": "hello.html"
},
{
"code": null,
"e": 3459,
"s": 3230,
"text": "The term ‘web templating system’ refers to designing an HTML script in which the variable data can be inserted dynamically. A web template system comprises of a template engine, some kind of data source and a template processor."
},
{
"code": null,
"e": 3678,
"s": 3459,
"text": "Flask uses jinja2 template engine. A web template contains HTML syntax interspersed placeholders for variables and expressions (in these case Python expressions) which are replaced values when the template is rendered."
},
{
"code": null,
"e": 3745,
"s": 3678,
"text": "The following code is saved as hello.html in the templates folder."
},
{
"code": null,
"e": 3841,
"s": 3745,
"text": "<!doctype html>\n<html>\n <body>\n \n <h1>Hello {{ name }}!</h1>\n \n </body>\n</html>"
},
{
"code": null,
"e": 3891,
"s": 3841,
"text": "Next, run the following script from Python shell."
},
{
"code": null,
"e": 4111,
"s": 3891,
"text": "from flask import Flask, render_template\napp = Flask(__name__)\n\n@app.route('/hello/<user>')\ndef hello_name(user):\n return render_template('hello.html', name = user)\n\nif __name__ == '__main__':\n app.run(debug = True)"
},
{
"code": null,
"e": 4221,
"s": 4111,
"text": "As the development server starts running, open the browser and enter URL as − http://localhost:5000/hello/mvl"
},
{
"code": null,
"e": 4286,
"s": 4221,
"text": "The variable part of URL is inserted at {{ name }} place holder."
},
{
"code": null,
"e": 4367,
"s": 4286,
"text": "The jinja2 template engine uses the following delimiters for escaping from HTML."
},
{
"code": null,
"e": 4392,
"s": 4367,
"text": "{% ... %} for Statements"
},
{
"code": null,
"e": 4450,
"s": 4392,
"text": "{{ ... }} for Expressions to print to the template output"
},
{
"code": null,
"e": 4509,
"s": 4450,
"text": "{# ... #} for Comments not included in the template output"
},
{
"code": null,
"e": 4538,
"s": 4509,
"text": "# ... ## for Line Statements"
},
{
"code": null,
"e": 4869,
"s": 4538,
"text": "In the following example, use of conditional statement in the template is demonstrated. The URL rule to the hello() function accepts the integer parameter. It is passed to the hello.html template. Inside it, the value of number received (marks) is compared (greater or less than 50) and accordingly HTML is conditionally rendered."
},
{
"code": null,
"e": 4903,
"s": 4869,
"text": "The Python Script is as follows −"
},
{
"code": null,
"e": 5131,
"s": 4903,
"text": "from flask import Flask, render_template\napp = Flask(__name__)\n\n@app.route('/hello/<int:score>')\ndef hello_name(score):\n return render_template('hello.html', marks = score)\n\nif __name__ == '__main__':\n app.run(debug = True)"
},
{
"code": null,
"e": 5182,
"s": 5131,
"text": "HTML template script of hello.html is as follows −"
},
{
"code": null,
"e": 5371,
"s": 5182,
"text": "<!doctype html>\n<html>\n <body>\n {% if marks>50 %}\n <h1> Your result is pass!</h1>\n {% else %}\n <h1>Your result is fail</h1>\n {% endif %}\n </body>\n</html>"
},
{
"code": null,
"e": 5460,
"s": 5371,
"text": "Note that the conditional statements if-else and endif are enclosed in delimiter {%..%}."
},
{
"code": null,
"e": 5607,
"s": 5460,
"text": "Run the Python script and visit URL http://localhost/hello/60 and then http://localhost/hello/30 to see the output of HTML changing conditionally."
},
{
"code": null,
"e": 5838,
"s": 5607,
"text": "The Python loop constructs can also be employed inside the template. In the following script, the result() function sends a dictionary object to template results.html when URL http://localhost:5000/result is opened in the browser."
},
{
"code": null,
"e": 5977,
"s": 5838,
"text": "The Template part of result.html employs a for loop to render key and value pairs of dictionary object result{} as cells of an HTML table."
},
{
"code": null,
"e": 6019,
"s": 5977,
"text": "Run the following code from Python shell."
},
{
"code": null,
"e": 6269,
"s": 6019,
"text": "from flask import Flask, render_template\napp = Flask(__name__)\n\n@app.route('/result')\ndef result():\n dict = {'phy':50,'che':60,'maths':70}\n return render_template('result.html', result = dict)\n\nif __name__ == '__main__':\n app.run(debug = True)"
},
{
"code": null,
"e": 6340,
"s": 6269,
"text": "Save the following HTML script as result.html in the templates folder."
},
{
"code": null,
"e": 6611,
"s": 6340,
"text": "<!doctype html>\n<html>\n <body>\n <table border = 1>\n {% for key, value in result.items() %}\n <tr>\n <th> {{ key }} </th>\n <td> {{ value }} </td>\n </tr>\n {% endfor %}\n </table>\n </body>\n</html>"
},
{
"code": null,
"e": 6759,
"s": 6611,
"text": "Here, again the Python statements corresponding to the For loop are enclosed in {%..%} whereas, the expressions key and value are put inside {{ }}."
},
{
"code": null,
"e": 6875,
"s": 6759,
"text": "After the development starts running, open http://localhost:5000/result in the browser to get the following output."
},
{
"code": null,
"e": 6908,
"s": 6875,
"text": "\n 22 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 6924,
"s": 6908,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 6959,
"s": 6924,
"text": "\n 21 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 6970,
"s": 6959,
"text": " Jack Chan"
},
{
"code": null,
"e": 7003,
"s": 6970,
"text": "\n 16 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 7019,
"s": 7003,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 7052,
"s": 7019,
"text": "\n 54 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 7069,
"s": 7052,
"text": " Srikanth Guskra"
},
{
"code": null,
"e": 7104,
"s": 7069,
"text": "\n 88 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 7119,
"s": 7104,
"text": " Jorge Escobar"
},
{
"code": null,
"e": 7153,
"s": 7119,
"text": "\n 80 Lectures \n 12 hours \n"
},
{
"code": null,
"e": 7176,
"s": 7153,
"text": " Stone River ELearning"
},
{
"code": null,
"e": 7183,
"s": 7176,
"text": " Print"
},
{
"code": null,
"e": 7194,
"s": 7183,
"text": " Add Notes"
}
] |
MomentJS - Day of week
|
This method will get/set the day of the week. It takes input from 0-6, where 0 is for Sunday and 6 as Saturday. If the value is greater than the range, it will fall in the next week. You can set the day of week using number or string.
moment().day(Number|String);
moment().day();
moment().days(Number|String);
moment().days();
var m = moment().day(); // gives 4 for thursday
var d = moment().day(0); //shows sunday
var a = moment().day('Monday'); //set the day of week to monday
var k = moment().day(10); //since it greater than 0-6 it sets to the next week and outputs Wed.
var o = moment().day(-5); // since the value is -ve it will set for last week
This gets or sets the day of the week according to the locale.
moment().weekday(Number);
moment().weekday();
As per the locale, if Sunday is set as the first day of week, you will have to set moment.weekday(0) to Sunday. If Monday is the first day of week you will see moment.weekday(0) to set as Monday.
The working of it remains same as day of week where if greater than range it will set to next week , if -ve value it will go for last week.
var m = moment().weekday();
var d = moment().weekday(4);
var a = moment().weekday('Monday');
var k = moment().weekday(10);
var o = moment().weekday(-5);
This method will set / get the day of week as per ISO where 1 is Monday and 7 is Sunday. So the range is 1-7 and anything greater than the range will fall in the next week and less than the range will fall in the last week.
moment().isoWeekday(Number);
moment().isoWeekday();
var m = moment().isoWeekday();
var d = moment().isoWeekday(4);
var a = moment().isoWeekday('Monday');
var k = moment().isoWeekday(10);
var o = moment().isoWeekday(-5);
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2195,
"s": 1960,
"text": "This method will get/set the day of the week. It takes input from 0-6, where 0 is for Sunday and 6 as Saturday. If the value is greater than the range, it will fall in the next week. You can set the day of week using number or string."
},
{
"code": null,
"e": 2288,
"s": 2195,
"text": "moment().day(Number|String);\nmoment().day();\nmoment().days(Number|String);\nmoment().days();\n"
},
{
"code": null,
"e": 2614,
"s": 2288,
"text": "var m = moment().day(); // gives 4 for thursday\nvar d = moment().day(0); //shows sunday\nvar a = moment().day('Monday'); //set the day of week to monday\nvar k = moment().day(10); //since it greater than 0-6 it sets to the next week and outputs Wed.\nvar o = moment().day(-5); // since the value is -ve it will set for last week"
},
{
"code": null,
"e": 2677,
"s": 2614,
"text": "This gets or sets the day of the week according to the locale."
},
{
"code": null,
"e": 2724,
"s": 2677,
"text": "moment().weekday(Number);\nmoment().weekday();\n"
},
{
"code": null,
"e": 2920,
"s": 2724,
"text": "As per the locale, if Sunday is set as the first day of week, you will have to set moment.weekday(0) to Sunday. If Monday is the first day of week you will see moment.weekday(0) to set as Monday."
},
{
"code": null,
"e": 3060,
"s": 2920,
"text": "The working of it remains same as day of week where if greater than range it will set to next week , if -ve value it will go for last week."
},
{
"code": null,
"e": 3213,
"s": 3060,
"text": "var m = moment().weekday();\nvar d = moment().weekday(4);\nvar a = moment().weekday('Monday');\nvar k = moment().weekday(10);\nvar o = moment().weekday(-5);"
},
{
"code": null,
"e": 3437,
"s": 3213,
"text": "This method will set / get the day of week as per ISO where 1 is Monday and 7 is Sunday. So the range is 1-7 and anything greater than the range will fall in the next week and less than the range will fall in the last week."
},
{
"code": null,
"e": 3490,
"s": 3437,
"text": "moment().isoWeekday(Number);\nmoment().isoWeekday();\n"
},
{
"code": null,
"e": 3658,
"s": 3490,
"text": "var m = moment().isoWeekday();\nvar d = moment().isoWeekday(4);\nvar a = moment().isoWeekday('Monday');\nvar k = moment().isoWeekday(10);\nvar o = moment().isoWeekday(-5);"
},
{
"code": null,
"e": 3665,
"s": 3658,
"text": " Print"
},
{
"code": null,
"e": 3676,
"s": 3665,
"text": " Add Notes"
}
] |
Equation of ellipse from its focus, directrix, and eccentricity - GeeksforGeeks
|
09 Apr, 2021
Given focus(x, y), directrix(ax + by + c) and eccentricity e of an ellipse, the task is to find the equation of ellipse using its focus, directrix, and eccentricity.Examples:
Input: x1 = 1, y1 = 1, a = 1, b = -1, c = 3, e = 0.5
Output: 1.75 x^2 + 1.75 y^2 + -5.50 x + -2.50 y + 0.50 xy + 1.75 = 0
Input: x1 = -1, y1 = 1, a = 1, b = -1, c = 3, e = 0.5
Output: 1.75 x^2 + 1.75 y^2 + 2.50 x + -2.50 y + 0.50 xy + 1.75 = 0
Let P(x, y) be any point on the ellipse whose focus S(x1, y1), directrix is the straight line ax + by + c = 0 and eccentricity is e. Draw PM perpendicular from P on the directrix. Then by definition of ellipse distance SP = e * PM => SP^2 = (e * PM)^2
(x – x1)^2 + (y – y1)^2 = e * ( ( a*x + b*y + c ) / (sqrt( a*a + b*b )) ) ^ 2let ( a*a + b*b ) = tx^2 + x1^2 – 2*x1*x + y^2 + y1^2 – 2*y1*y = e * ( ( a*x + b*y + c ) ^ 2 )/ t
on cross multiplying above we get
t*x^2 + t*x1^2 – 2*t*x1*x + t*y^2 + t*y1^2 – 2*t*y1*y = e * ( ( a*x + b*y + c ) ^ 2 )t*x^2 + t*x1^2 – 2*t*x1*x + t*y^2 + t*y1^2 – 2*t*y1*y = e*a^2*x^2 + e*b^2*y^2 + 2*e*a*x*b*y + e*c^2 + 2*e*c*(a*x + b*y)t*x^2 + t*x1^2 – 2*t*x1*x + t*y^2 + t*y1^2 – 2*t*y1*y = e*a^2*x^2 + e*b^2*y^2 + 2*e*a*x*b*y + e*c^2 + 2*e*c*a*x + 2*e*c*b*yt*x^2 – e*a^2*x^2 + t*y^2 – e*b^2*y^2 – 2*t*x1*x – 2*e*c*a*x – 2*t*y1*y – 2*e*c*b*y – 2*e*a*x*b*y – e*c^2 + t*x1^2 + t*y1^2 =0
This can be compared with a general form that is:
a*x^2 + 2*h*x*y + b*y^2 + 2*g*x + 2*f*y + c = 0
Below is the implementation of the above approach:
C++
Java
Python3
C#
PHP
Javascript
// C++ program to find equation of an ellipse// using focus and directrix.#include <bits/stdc++.h>#include <iomanip>#include <iostream>#include <math.h> using namespace std; // Function to find equation of ellipse.void equation_ellipse(float x1, float y1, float a, float b, float c, float e){ float t = a * a + b * b; float a1 = t - e * (a * a); float b1 = t - e * (b * b); float c1 = (-2 * t * x1) - (2 * e * c * a); float d1 = (-2 * t * y1) - (2 * e * c * b); float e1 = -2 * e * a * b; float f1 = (-e * c * c) + (t * x1 * x1) + (t * y1 * y1); cout << fixed; cout << setprecision(2); cout << "Equation of ellipse is \n" << a1 << " x^2 + " << b1 << " y^2 + " << c1 << " x + " << d1 << " y + " << e1 << " xy + " << f1 << " = 0";} // Driver Codeint main(){ float x1 = 1, y1 = 1, a = 1, b = -1, c = 3, e = 0.5 * 0.5; equation_ellipse(x1, y1, a, b, c, e); return 0;}
// Java program to find equation of an ellipse// using focus and directrix.import java.util.*; class solution{ // Function to find equation of ellipse.static void equation_ellipse(float x1, float y1, float a, float b, float c, float e){ float t = a * a + b * b; float a1 = t - e * (a * a); float b1 = t - e * (b * b); float c1 = (-2 * t * x1) - (2 * e * c * a); float d1 = (-2 * t * y1) - (2 * e * c * b); float e1 = -2 * e * a * b; float f1 = (-e * c * c) + (t * x1 * x1) + (t * y1 * y1); System.out.println("Equation of ellipse is "); System.out.print(a1+" x^2 + "+ b1 + " y^2 + "+ c1 + " x + " + d1 + " y + " + e1 + " xy + " + f1 + " = 0"); } // Driver Codepublic static void main(String arr[]){ float x1 = 1, y1 = 1, a = 1, b = -1, c = 3, e = (float)0.5 * (float)0.5; equation_ellipse(x1, y1, a, b, c, e); }} //This code is contributed by Surendra_Gaangwar
# Python3 program to find equation of an ellipse# using focus and directrix. # Function to find equation of ellipse.def equation_ellipse(x1, y1, a, b, c, e) : t = a * a + b * b a1 = t - e * (a * a) b1 = t - e * (b * b) c1 = (-2 * t * x1) - (2 * e * c * a) d1 = (-2 * t * y1) - (2 * e * c * b) e1 = -2 * e * a * b f1 = (-e * c * c) + (t * x1 * x1) + (t * y1 * y1) print("Equation of ellipse is",a1,"x^2 +", b1 ,"y^2 +", c1, "x +" ,d1 ,"y +", e1 ,"xy +" , f1 ,"= 0") # Driver Codeif __name__ == "__main__" : x1, y1, a, b, c, e = 1, 1, 1, -1, 3, 0.5 * 0.5 equation_ellipse(x1, y1, a, b, c, e) # This code is contributed by Ryuga
// C# program to find equation of an ellipse// using focus and directrix. class solution{ // Function to find equation of ellipse.static void equation_ellipse(float x1, float y1, float a, float b, float c, float e){ float t = a * a + b * b; float a1 = t - e * (a * a); float b1 = t - e * (b * b); float c1 = (-2 * t * x1) - (2 * e * c * a); float d1 = (-2 * t * y1) - (2 * e * c * b); float e1 = -2 * e * a * b; float f1 = (-e * c * c) + (t * x1 * x1) + (t * y1 * y1); System.Console.WriteLine("Equation of ellipse is "); System.Console.WriteLine(a1+" x^2 + "+ b1 + " y^2 + "+ c1 + " x + " + d1 + " y + " + e1 + " xy + " + f1 + " = 0"); } // Driver Codepublic static void Main(){ float x1 = 1, y1 = 1, a = 1, b = -1, c = 3, e = (float)0.5 * (float)0.5; equation_ellipse(x1, y1, a, b, c, e); }} //This code is contributed by mits
<?php// PHP program to find equation of// an ellipse using focus and directrix. // Function to find equation of ellipse.function equation_ellipse($x1, $y1, $a, $b, $c, $e){ $t = ($a * $a) + ($b * $b); $a1 = $t - $e * ($a * $a); $b1 = $t - $e * ($b * $b); $c1 = (-2 * $t * $x1) - (2 * $e * $c * $a); $d1 = (-2 * $t * $y1) - (2 * $e * $c * $b); $e1 = -2 * $e * $a * $b; $f1 = (-$e * $c * $c) + ($t * $x1 * $x1) + ($t * $y1 * $y1); $fixed; // echo setprecision(2); echo "Equation of ellipse is \n" , $a1, " x^2 + ", $b1 , " y^2 + ", $c1 , " x + " , $d1 , " y + ", $e1 , " xy + " , $f1 , " = 0";} // Driver Code$x1 = 1; $y1 = 1;$a = 1;$b = -1;$c = 3;$e = 0.5 * 0.5;equation_ellipse($x1, $y1, $a, $b, $c, $e); // This code is contributed by jit_t?>
<script> // Javascript program to find equation// of an ellipse using focus and directrix. // Function to find equation of ellipse.function equation_ellipse(x1, y1, a, b, c, e){ var t = a * a + b * b; var a1 = t - e * (a * a); var b1 = t - e * (b * b); var c1 = (-2 * t * x1) - (2 * e * c * a); var d1 = (-2 * t * y1) - (2 * e * c * b); var e1 = -2 * e * a * b; var f1 = (-e * c * c) + (t * x1 * x1) + (t * y1 * y1); document.write("Equation of ellipse is " + "<br>"); document.write(a1+" x^2 + "+ b1 + " y^2 + "+ c1 + " x + " + d1 + " y + " + e1 + " xy + " + f1 + " = 0");} // Driver Codevar x1 = 1, y1 = 1, a = 1, b = -1, c = 3, e = 0.5 * 0.5;equation_ellipse(x1, y1, a, b, c, e); // This code is contributed by Khushboogoyal499 </script>
Equation of ellipse is
1.75 x^2 + 1.75 y^2 + -5.50 x + -2.50 y + 0.50 xy + 1.75 = 0
SURENDRA_GANGWAR
Mithun Kumar
jit_t
ankthon
khushboogoyal499
Geometric
Mathematical
Mathematical
Geometric
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Convex Hull | Set 2 (Graham Scan)
Given n line segments, find if any two segments intersect
Closest Pair of Points | O(nlogn) Implementation
Line Clipping | Set 1 (Cohen–Sutherland Algorithm)
Check whether a given point lies inside a triangle or not
Program for Fibonacci numbers
Write a program to print all permutations of a given string
C++ Data Types
Set in C++ Standard Template Library (STL)
Coin Change | DP-7
|
[
{
"code": null,
"e": 25204,
"s": 25176,
"text": "\n09 Apr, 2021"
},
{
"code": null,
"e": 25381,
"s": 25204,
"text": "Given focus(x, y), directrix(ax + by + c) and eccentricity e of an ellipse, the task is to find the equation of ellipse using its focus, directrix, and eccentricity.Examples: "
},
{
"code": null,
"e": 25627,
"s": 25381,
"text": "Input: x1 = 1, y1 = 1, a = 1, b = -1, c = 3, e = 0.5\nOutput: 1.75 x^2 + 1.75 y^2 + -5.50 x + -2.50 y + 0.50 xy + 1.75 = 0\n\nInput: x1 = -1, y1 = 1, a = 1, b = -1, c = 3, e = 0.5\nOutput: 1.75 x^2 + 1.75 y^2 + 2.50 x + -2.50 y + 0.50 xy + 1.75 = 0 "
},
{
"code": null,
"e": 25884,
"s": 25631,
"text": "Let P(x, y) be any point on the ellipse whose focus S(x1, y1), directrix is the straight line ax + by + c = 0 and eccentricity is e. Draw PM perpendicular from P on the directrix. Then by definition of ellipse distance SP = e * PM => SP^2 = (e * PM)^2 "
},
{
"code": null,
"e": 26059,
"s": 25884,
"text": "(x – x1)^2 + (y – y1)^2 = e * ( ( a*x + b*y + c ) / (sqrt( a*a + b*b )) ) ^ 2let ( a*a + b*b ) = tx^2 + x1^2 – 2*x1*x + y^2 + y1^2 – 2*y1*y = e * ( ( a*x + b*y + c ) ^ 2 )/ t"
},
{
"code": null,
"e": 26094,
"s": 26059,
"text": "on cross multiplying above we get "
},
{
"code": null,
"e": 26549,
"s": 26094,
"text": "t*x^2 + t*x1^2 – 2*t*x1*x + t*y^2 + t*y1^2 – 2*t*y1*y = e * ( ( a*x + b*y + c ) ^ 2 )t*x^2 + t*x1^2 – 2*t*x1*x + t*y^2 + t*y1^2 – 2*t*y1*y = e*a^2*x^2 + e*b^2*y^2 + 2*e*a*x*b*y + e*c^2 + 2*e*c*(a*x + b*y)t*x^2 + t*x1^2 – 2*t*x1*x + t*y^2 + t*y1^2 – 2*t*y1*y = e*a^2*x^2 + e*b^2*y^2 + 2*e*a*x*b*y + e*c^2 + 2*e*c*a*x + 2*e*c*b*yt*x^2 – e*a^2*x^2 + t*y^2 – e*b^2*y^2 – 2*t*x1*x – 2*e*c*a*x – 2*t*y1*y – 2*e*c*b*y – 2*e*a*x*b*y – e*c^2 + t*x1^2 + t*y1^2 =0 "
},
{
"code": null,
"e": 26601,
"s": 26549,
"text": "This can be compared with a general form that is: "
},
{
"code": null,
"e": 26649,
"s": 26601,
"text": "a*x^2 + 2*h*x*y + b*y^2 + 2*g*x + 2*f*y + c = 0"
},
{
"code": null,
"e": 26702,
"s": 26649,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 26706,
"s": 26702,
"text": "C++"
},
{
"code": null,
"e": 26711,
"s": 26706,
"text": "Java"
},
{
"code": null,
"e": 26719,
"s": 26711,
"text": "Python3"
},
{
"code": null,
"e": 26722,
"s": 26719,
"text": "C#"
},
{
"code": null,
"e": 26726,
"s": 26722,
"text": "PHP"
},
{
"code": null,
"e": 26737,
"s": 26726,
"text": "Javascript"
},
{
"code": "// C++ program to find equation of an ellipse// using focus and directrix.#include <bits/stdc++.h>#include <iomanip>#include <iostream>#include <math.h> using namespace std; // Function to find equation of ellipse.void equation_ellipse(float x1, float y1, float a, float b, float c, float e){ float t = a * a + b * b; float a1 = t - e * (a * a); float b1 = t - e * (b * b); float c1 = (-2 * t * x1) - (2 * e * c * a); float d1 = (-2 * t * y1) - (2 * e * c * b); float e1 = -2 * e * a * b; float f1 = (-e * c * c) + (t * x1 * x1) + (t * y1 * y1); cout << fixed; cout << setprecision(2); cout << \"Equation of ellipse is \\n\" << a1 << \" x^2 + \" << b1 << \" y^2 + \" << c1 << \" x + \" << d1 << \" y + \" << e1 << \" xy + \" << f1 << \" = 0\";} // Driver Codeint main(){ float x1 = 1, y1 = 1, a = 1, b = -1, c = 3, e = 0.5 * 0.5; equation_ellipse(x1, y1, a, b, c, e); return 0;}",
"e": 27716,
"s": 26737,
"text": null
},
{
"code": "// Java program to find equation of an ellipse// using focus and directrix.import java.util.*; class solution{ // Function to find equation of ellipse.static void equation_ellipse(float x1, float y1, float a, float b, float c, float e){ float t = a * a + b * b; float a1 = t - e * (a * a); float b1 = t - e * (b * b); float c1 = (-2 * t * x1) - (2 * e * c * a); float d1 = (-2 * t * y1) - (2 * e * c * b); float e1 = -2 * e * a * b; float f1 = (-e * c * c) + (t * x1 * x1) + (t * y1 * y1); System.out.println(\"Equation of ellipse is \"); System.out.print(a1+\" x^2 + \"+ b1 + \" y^2 + \"+ c1 + \" x + \" + d1 + \" y + \" + e1 + \" xy + \" + f1 + \" = 0\"); } // Driver Codepublic static void main(String arr[]){ float x1 = 1, y1 = 1, a = 1, b = -1, c = 3, e = (float)0.5 * (float)0.5; equation_ellipse(x1, y1, a, b, c, e); }} //This code is contributed by Surendra_Gaangwar",
"e": 28676,
"s": 27716,
"text": null
},
{
"code": "# Python3 program to find equation of an ellipse# using focus and directrix. # Function to find equation of ellipse.def equation_ellipse(x1, y1, a, b, c, e) : t = a * a + b * b a1 = t - e * (a * a) b1 = t - e * (b * b) c1 = (-2 * t * x1) - (2 * e * c * a) d1 = (-2 * t * y1) - (2 * e * c * b) e1 = -2 * e * a * b f1 = (-e * c * c) + (t * x1 * x1) + (t * y1 * y1) print(\"Equation of ellipse is\",a1,\"x^2 +\", b1 ,\"y^2 +\", c1, \"x +\" ,d1 ,\"y +\", e1 ,\"xy +\" , f1 ,\"= 0\") # Driver Codeif __name__ == \"__main__\" : x1, y1, a, b, c, e = 1, 1, 1, -1, 3, 0.5 * 0.5 equation_ellipse(x1, y1, a, b, c, e) # This code is contributed by Ryuga",
"e": 29350,
"s": 28676,
"text": null
},
{
"code": "// C# program to find equation of an ellipse// using focus and directrix. class solution{ // Function to find equation of ellipse.static void equation_ellipse(float x1, float y1, float a, float b, float c, float e){ float t = a * a + b * b; float a1 = t - e * (a * a); float b1 = t - e * (b * b); float c1 = (-2 * t * x1) - (2 * e * c * a); float d1 = (-2 * t * y1) - (2 * e * c * b); float e1 = -2 * e * a * b; float f1 = (-e * c * c) + (t * x1 * x1) + (t * y1 * y1); System.Console.WriteLine(\"Equation of ellipse is \"); System.Console.WriteLine(a1+\" x^2 + \"+ b1 + \" y^2 + \"+ c1 + \" x + \" + d1 + \" y + \" + e1 + \" xy + \" + f1 + \" = 0\"); } // Driver Codepublic static void Main(){ float x1 = 1, y1 = 1, a = 1, b = -1, c = 3, e = (float)0.5 * (float)0.5; equation_ellipse(x1, y1, a, b, c, e); }} //This code is contributed by mits",
"e": 30278,
"s": 29350,
"text": null
},
{
"code": "<?php// PHP program to find equation of// an ellipse using focus and directrix. // Function to find equation of ellipse.function equation_ellipse($x1, $y1, $a, $b, $c, $e){ $t = ($a * $a) + ($b * $b); $a1 = $t - $e * ($a * $a); $b1 = $t - $e * ($b * $b); $c1 = (-2 * $t * $x1) - (2 * $e * $c * $a); $d1 = (-2 * $t * $y1) - (2 * $e * $c * $b); $e1 = -2 * $e * $a * $b; $f1 = (-$e * $c * $c) + ($t * $x1 * $x1) + ($t * $y1 * $y1); $fixed; // echo setprecision(2); echo \"Equation of ellipse is \\n\" , $a1, \" x^2 + \", $b1 , \" y^2 + \", $c1 , \" x + \" , $d1 , \" y + \", $e1 , \" xy + \" , $f1 , \" = 0\";} // Driver Code$x1 = 1; $y1 = 1;$a = 1;$b = -1;$c = 3;$e = 0.5 * 0.5;equation_ellipse($x1, $y1, $a, $b, $c, $e); // This code is contributed by jit_t?>",
"e": 31157,
"s": 30278,
"text": null
},
{
"code": "<script> // Javascript program to find equation// of an ellipse using focus and directrix. // Function to find equation of ellipse.function equation_ellipse(x1, y1, a, b, c, e){ var t = a * a + b * b; var a1 = t - e * (a * a); var b1 = t - e * (b * b); var c1 = (-2 * t * x1) - (2 * e * c * a); var d1 = (-2 * t * y1) - (2 * e * c * b); var e1 = -2 * e * a * b; var f1 = (-e * c * c) + (t * x1 * x1) + (t * y1 * y1); document.write(\"Equation of ellipse is \" + \"<br>\"); document.write(a1+\" x^2 + \"+ b1 + \" y^2 + \"+ c1 + \" x + \" + d1 + \" y + \" + e1 + \" xy + \" + f1 + \" = 0\");} // Driver Codevar x1 = 1, y1 = 1, a = 1, b = -1, c = 3, e = 0.5 * 0.5;equation_ellipse(x1, y1, a, b, c, e); // This code is contributed by Khushboogoyal499 </script>",
"e": 31949,
"s": 31157,
"text": null
},
{
"code": null,
"e": 32034,
"s": 31949,
"text": "Equation of ellipse is \n1.75 x^2 + 1.75 y^2 + -5.50 x + -2.50 y + 0.50 xy + 1.75 = 0"
},
{
"code": null,
"e": 32053,
"s": 32036,
"text": "SURENDRA_GANGWAR"
},
{
"code": null,
"e": 32066,
"s": 32053,
"text": "Mithun Kumar"
},
{
"code": null,
"e": 32072,
"s": 32066,
"text": "jit_t"
},
{
"code": null,
"e": 32080,
"s": 32072,
"text": "ankthon"
},
{
"code": null,
"e": 32097,
"s": 32080,
"text": "khushboogoyal499"
},
{
"code": null,
"e": 32107,
"s": 32097,
"text": "Geometric"
},
{
"code": null,
"e": 32120,
"s": 32107,
"text": "Mathematical"
},
{
"code": null,
"e": 32133,
"s": 32120,
"text": "Mathematical"
},
{
"code": null,
"e": 32143,
"s": 32133,
"text": "Geometric"
},
{
"code": null,
"e": 32241,
"s": 32143,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 32275,
"s": 32241,
"text": "Convex Hull | Set 2 (Graham Scan)"
},
{
"code": null,
"e": 32333,
"s": 32275,
"text": "Given n line segments, find if any two segments intersect"
},
{
"code": null,
"e": 32382,
"s": 32333,
"text": "Closest Pair of Points | O(nlogn) Implementation"
},
{
"code": null,
"e": 32433,
"s": 32382,
"text": "Line Clipping | Set 1 (Cohen–Sutherland Algorithm)"
},
{
"code": null,
"e": 32491,
"s": 32433,
"text": "Check whether a given point lies inside a triangle or not"
},
{
"code": null,
"e": 32521,
"s": 32491,
"text": "Program for Fibonacci numbers"
},
{
"code": null,
"e": 32581,
"s": 32521,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 32596,
"s": 32581,
"text": "C++ Data Types"
},
{
"code": null,
"e": 32639,
"s": 32596,
"text": "Set in C++ Standard Template Library (STL)"
}
] |
Sort in C++ Standard Template Library (STL)
|
Here we will see how to use the sort() function of C++ STL to sort an array So if the array is like A = [52, 14, 85, 63, 99, 54, 21], then the output will be [14 21 52 54 63 85 99]. To sort we will use the sort() function, that is present in the header file <algorithm>. The code is like below −
Live Demo
#include <iostream>
#include <algorithm>
using namespace std;
int main() {
int arr[] = {52, 14, 85, 63, 99, 54, 21};
int n = sizeof(arr) / sizeof(arr[0]);
cout << "Array before sorting: ";
for (int i = 0; i < n; i++)
cout << arr[i] << " ";
sort(arr, arr + n);
cout << "\nArray after sorting: ";
for (int i = 0; i < n; i++)
cout << arr[i] << " ";
}
Array before sorting: 52 14 85 63 99 54 21
Array after sorting: 14 21 52 54 63 85 99
|
[
{
"code": null,
"e": 1358,
"s": 1062,
"text": "Here we will see how to use the sort() function of C++ STL to sort an array So if the array is like A = [52, 14, 85, 63, 99, 54, 21], then the output will be [14 21 52 54 63 85 99]. To sort we will use the sort() function, that is present in the header file <algorithm>. The code is like below −"
},
{
"code": null,
"e": 1369,
"s": 1358,
"text": " Live Demo"
},
{
"code": null,
"e": 1750,
"s": 1369,
"text": "#include <iostream>\n#include <algorithm>\nusing namespace std;\nint main() {\n int arr[] = {52, 14, 85, 63, 99, 54, 21};\n int n = sizeof(arr) / sizeof(arr[0]);\n cout << \"Array before sorting: \";\n for (int i = 0; i < n; i++)\n cout << arr[i] << \" \";\n sort(arr, arr + n);\n cout << \"\\nArray after sorting: \";\n for (int i = 0; i < n; i++)\n cout << arr[i] << \" \";\n}"
},
{
"code": null,
"e": 1835,
"s": 1750,
"text": "Array before sorting: 52 14 85 63 99 54 21\nArray after sorting: 14 21 52 54 63 85 99"
}
] |
Getting console.log output from Chrome with Selenium Python API bindings.
|
We can get console.log output from Chrome with Selenium Python API bindings. We will perform this with the DesiredCapabilities class. We shall enable the logging from the browser with DesiredCapabilities.Chrome setting.
We have to pass this browser capability to the driver object by passing it as a parameter to the Chrome class. To enable logging we shall set the property goog:loggingPrefs of the browser to 'browser':'ALL'.
Syntax:dc = DesiredCapabilities.CHROME
dc['goog:loggingPrefs'] = { 'browser':'ALL' }
driver = webdriver.Chrome(desired_capabilities=dc)
from selenium import webdriver
from selenium.webdriver.common.desired_capabilities import
DesiredCapabilities
#set browser log
dc = DesiredCapabilities.CHROME
dc['goog:loggingPrefs'] = { 'browser':'ALL' }
driver = webdriver.Chrome(executable_path="C:\\chromedriver.exe",
desired_capabilities=dc)
#launch browser
driver.get ("https://www.tutorialspoint.com/index.htm")
#obtain with get_log()
for e in driver.get_log('browser'):
print(e)
driver.quit()
|
[
{
"code": null,
"e": 1282,
"s": 1062,
"text": "We can get console.log output from Chrome with Selenium Python API bindings. We will perform this with the DesiredCapabilities class. We shall enable the logging from the browser with DesiredCapabilities.Chrome setting."
},
{
"code": null,
"e": 1490,
"s": 1282,
"text": "We have to pass this browser capability to the driver object by passing it as a parameter to the Chrome class. To enable logging we shall set the property goog:loggingPrefs of the browser to 'browser':'ALL'."
},
{
"code": null,
"e": 1626,
"s": 1490,
"text": "Syntax:dc = DesiredCapabilities.CHROME\ndc['goog:loggingPrefs'] = { 'browser':'ALL' }\ndriver = webdriver.Chrome(desired_capabilities=dc)"
},
{
"code": null,
"e": 2079,
"s": 1626,
"text": "from selenium import webdriver\nfrom selenium.webdriver.common.desired_capabilities import\nDesiredCapabilities\n#set browser log\ndc = DesiredCapabilities.CHROME\ndc['goog:loggingPrefs'] = { 'browser':'ALL' }\ndriver = webdriver.Chrome(executable_path=\"C:\\\\chromedriver.exe\",\ndesired_capabilities=dc)\n#launch browser\ndriver.get (\"https://www.tutorialspoint.com/index.htm\")\n#obtain with get_log()\nfor e in driver.get_log('browser'):\n print(e)\ndriver.quit()"
}
] |
Returning a value even if there is no result in a MySQL query?
|
You can use IFNULL() function from MySQL to return a value even if there is not result. Let us create a table. Te query to create a table.
mysql> create table IfNullDemo
−> (
−> Id int,
−> Name varchar(100)
−> );
Query OK, 0 rows affected (0.60 sec)
Insert some records in the table with the help of insert command. The query is as follows −
mysql> insert into IfNullDemo values(1,'John');
Query OK, 1 row affected (0.18 sec)
mysql> insert into IfNullDemo values(200,'Sam');
Query OK, 1 row affected (0.21 sec)
mysql> insert into IfNullDemo values(204,'Carol');
Query OK, 1 row affected (0.14 sec)
mysql> insert into IfNullDemo values(510,'Johnson');
Query OK, 1 row affected (0.18 sec)
Display all records from the table with the help of select statement. The query is as follows −
mysql> select *from IfNullDemo;
The following is the output −
+------+---------+
| Id | Name |
+------+---------+
| 1 | John |
| 200 | Sam |
| 204 | Carol |
| 510 | Johnson |
+------+---------+
4 rows in set (0.00 sec)
Let us first return a value for TRUE condition −
The query is as follows −
mysql> select ifnull((select Id from IfNullDemo where Id = 200),'No Result Found') As ResultFound;
The following is the output −
+-------------+
| ResultFound |
+-------------+
| 200 |
+-------------+
1 row in set (0.00 sec)
Now, let us return a value if there is no result using the IFNULL method. The query is as follows −
mysql> select ifnull((select Id from IfNullDemo where Id = 400),'No Result Found') As ResultFound;
The following is the output −
+-----------------+
| ResultFound |
+-----------------+
| No Result Found |
+-----------------+
1 row in set (0.00 sec)
|
[
{
"code": null,
"e": 1201,
"s": 1062,
"text": "You can use IFNULL() function from MySQL to return a value even if there is not result. Let us create a table. Te query to create a table."
},
{
"code": null,
"e": 1324,
"s": 1201,
"text": "mysql> create table IfNullDemo\n −> (\n −> Id int,\n −> Name varchar(100)\n −> );\nQuery OK, 0 rows affected (0.60 sec)"
},
{
"code": null,
"e": 1416,
"s": 1324,
"text": "Insert some records in the table with the help of insert command. The query is as follows −"
},
{
"code": null,
"e": 1764,
"s": 1416,
"text": "mysql> insert into IfNullDemo values(1,'John');\nQuery OK, 1 row affected (0.18 sec)\n\nmysql> insert into IfNullDemo values(200,'Sam');\nQuery OK, 1 row affected (0.21 sec)\n\nmysql> insert into IfNullDemo values(204,'Carol');\nQuery OK, 1 row affected (0.14 sec)\n\nmysql> insert into IfNullDemo values(510,'Johnson');\nQuery OK, 1 row affected (0.18 sec)"
},
{
"code": null,
"e": 1860,
"s": 1764,
"text": "Display all records from the table with the help of select statement. The query is as follows −"
},
{
"code": null,
"e": 1892,
"s": 1860,
"text": "mysql> select *from IfNullDemo;"
},
{
"code": null,
"e": 1922,
"s": 1892,
"text": "The following is the output −"
},
{
"code": null,
"e": 2099,
"s": 1922,
"text": "+------+---------+\n| Id | Name |\n+------+---------+\n| 1 | John |\n| 200 | Sam |\n| 204 | Carol |\n| 510 | Johnson |\n+------+---------+\n4 rows in set (0.00 sec)"
},
{
"code": null,
"e": 2148,
"s": 2099,
"text": "Let us first return a value for TRUE condition −"
},
{
"code": null,
"e": 2174,
"s": 2148,
"text": "The query is as follows −"
},
{
"code": null,
"e": 2273,
"s": 2174,
"text": "mysql> select ifnull((select Id from IfNullDemo where Id = 200),'No Result Found') As ResultFound;"
},
{
"code": null,
"e": 2303,
"s": 2273,
"text": "The following is the output −"
},
{
"code": null,
"e": 2407,
"s": 2303,
"text": "+-------------+\n| ResultFound |\n+-------------+\n| 200 |\n+-------------+\n1 row in set (0.00 sec)"
},
{
"code": null,
"e": 2507,
"s": 2407,
"text": "Now, let us return a value if there is no result using the IFNULL method. The query is as follows −"
},
{
"code": null,
"e": 2606,
"s": 2507,
"text": "mysql> select ifnull((select Id from IfNullDemo where Id = 400),'No Result Found') As ResultFound;"
},
{
"code": null,
"e": 2636,
"s": 2606,
"text": "The following is the output −"
},
{
"code": null,
"e": 2760,
"s": 2636,
"text": "+-----------------+\n| ResultFound |\n+-----------------+\n| No Result Found |\n+-----------------+\n1 row in set (0.00 sec)"
}
] |
Reverse Linked List II in C++
|
Suppose we have a linked list. We have to reverse the nodes from position m to n. We have to do it in one pass. So if the list is [1,2,3,4,5] and m = 2 and n = 4, then the result will be [1,4,,3,2,5]
Let us see the steps −
There will be two methods, the reverseN() and reverseBetween(). The reverseBetween() will work as main method.
define one link node pointer called successor as null
The reverseN will work as follows −
if n = 1, then successor := next of head, and return head
last = reverseN(next of head, n - 1)
next of (next of head) = head, and next of head := successor, return last
the reverseBetween() method will be like −
if m = 1, then return reverseN(head, n)
next of head := reverseBetween(next of head, m – 1, n – 1)
Let us see the following implementation to get better understanding −
Live Demo
#include <bits/stdc++.h>
using namespace std;
class ListNode{
public:
int val;
ListNode *next;
ListNode(int data){
val = data;
next = NULL;
}
};
ListNode *make_list(vector<int> v){
ListNode *head = new ListNode(v[0]);
for(int i = 1; i<v.size(); i++){
ListNode *ptr = head;
while(ptr->next != NULL){
ptr = ptr->next;
}
ptr->next = new ListNode(v[i]);
}
return head;
}
void print_list(ListNode *head){
ListNode *ptr = head;
cout << "[";
while(ptr){
cout << ptr->val << ", ";
ptr = ptr->next;
}
cout << "]" << endl;
}
class Solution {
public:
ListNode* successor = NULL;
ListNode* reverseN(ListNode* head, int n ){
if(n == 1){
successor = head->next;
return head;
}
ListNode* last = reverseN(head->next, n - 1);
head->next->next = head;
head->next = successor;
return last;
}
ListNode* reverseBetween(ListNode* head, int m, int n) {
if(m == 1){
return reverseN(head, n);
}
head->next = reverseBetween(head->next, m - 1, n - 1);
return head;
}
};
main(){
Solution ob;
vector<int> v = {1,2,3,4,5,6,7,8};
ListNode *head = make_list(v);
print_list(ob.reverseBetween(head, 2, 6));
}
[1,2,3,4,5,6,7,8]
2
6
[1, 6, 5, 4, 3, 2, 7, 8, ]
|
[
{
"code": null,
"e": 1262,
"s": 1062,
"text": "Suppose we have a linked list. We have to reverse the nodes from position m to n. We have to do it in one pass. So if the list is [1,2,3,4,5] and m = 2 and n = 4, then the result will be [1,4,,3,2,5]"
},
{
"code": null,
"e": 1285,
"s": 1262,
"text": "Let us see the steps −"
},
{
"code": null,
"e": 1396,
"s": 1285,
"text": "There will be two methods, the reverseN() and reverseBetween(). The reverseBetween() will work as main method."
},
{
"code": null,
"e": 1450,
"s": 1396,
"text": "define one link node pointer called successor as null"
},
{
"code": null,
"e": 1486,
"s": 1450,
"text": "The reverseN will work as follows −"
},
{
"code": null,
"e": 1544,
"s": 1486,
"text": "if n = 1, then successor := next of head, and return head"
},
{
"code": null,
"e": 1581,
"s": 1544,
"text": "last = reverseN(next of head, n - 1)"
},
{
"code": null,
"e": 1655,
"s": 1581,
"text": "next of (next of head) = head, and next of head := successor, return last"
},
{
"code": null,
"e": 1698,
"s": 1655,
"text": "the reverseBetween() method will be like −"
},
{
"code": null,
"e": 1738,
"s": 1698,
"text": "if m = 1, then return reverseN(head, n)"
},
{
"code": null,
"e": 1797,
"s": 1738,
"text": "next of head := reverseBetween(next of head, m – 1, n – 1)"
},
{
"code": null,
"e": 1867,
"s": 1797,
"text": "Let us see the following implementation to get better understanding −"
},
{
"code": null,
"e": 1878,
"s": 1867,
"text": " Live Demo"
},
{
"code": null,
"e": 3295,
"s": 1878,
"text": "#include <bits/stdc++.h>\nusing namespace std;\nclass ListNode{\n public:\n int val;\n ListNode *next;\n ListNode(int data){\n val = data;\n next = NULL;\n }\n };\n ListNode *make_list(vector<int> v){\n ListNode *head = new ListNode(v[0]);\n for(int i = 1; i<v.size(); i++){\n ListNode *ptr = head;\n while(ptr->next != NULL){\n ptr = ptr->next;\n }\n ptr->next = new ListNode(v[i]);\n }\n return head;\n }\n void print_list(ListNode *head){\n ListNode *ptr = head;\n cout << \"[\";\n while(ptr){\n cout << ptr->val << \", \";\n ptr = ptr->next;\n }\n cout << \"]\" << endl;\n }\n class Solution {\n public:\n ListNode* successor = NULL;\n ListNode* reverseN(ListNode* head, int n ){\n if(n == 1){\n successor = head->next;\n return head;\n }\n ListNode* last = reverseN(head->next, n - 1);\n head->next->next = head;\n head->next = successor;\n return last;\n }\n ListNode* reverseBetween(ListNode* head, int m, int n) {\n if(m == 1){\n return reverseN(head, n);\n }\n head->next = reverseBetween(head->next, m - 1, n - 1);\n return head;\n }\n };\nmain(){\n Solution ob;\n vector<int> v = {1,2,3,4,5,6,7,8};\n ListNode *head = make_list(v);\n print_list(ob.reverseBetween(head, 2, 6));\n}"
},
{
"code": null,
"e": 3317,
"s": 3295,
"text": "[1,2,3,4,5,6,7,8]\n2\n6"
},
{
"code": null,
"e": 3344,
"s": 3317,
"text": "[1, 6, 5, 4, 3, 2, 7, 8, ]"
}
] |
Add Interactive Slider to Bokeh Plots - GeeksforGeeks
|
28 Jul, 2021
Bokeh is an interactive Data visualization library of Python. It can be used to create interactive plots, dashboards, and data applications. Widgets are nothing but additional visual elements that you can add to your plots to interactively control your Bokeh document. There are various types of widgets such as button, div, spinner, slider, etc. In this article, we will learn about the slider widget in bokeh.
The Bokeh slider can be configured with start and end values, a step size, an initial value, and a title. Basically, you need to import the Slider widget from bokeh.models.
Syntax:
from bokeh.models import CustomJS, Slider
Slider() function can be used to create a slider.
Syntax:
Slider(start=0, end=10, value=1, step=.1, title=”Stuff”)
Parameter:
start: It represents the sliders starting value.
end:It represents the sliders ending value.
value: It represents the current value of the slider.
step: It represents the interval through which the slider moves.
title: It represents the title of the slider widget.
Now add callback functionality using CustomJS which is called when on_change event occurs.
Syntax:
js_on_change(“value”, CustomJS(code=”””.... “””))
js_on_change is a callback function that is called when slider on_change event occurs. and customJS(code=””” “””) represents the code that is to be executed once the event occurs. Now call the callback function using the slider object and create a layout of all the elements you want to display on the browser.
Example: Creating a slider using bokeh
Python
from bokeh.layouts import columnfrom bokeh.models import ColumnDataSource, Slider, CustomJSfrom bokeh.plotting import figure, output_file, showimport numpy as np x = np.linspace(0, 10, 500)y = np.sin(x) source = ColumnDataSource(data=dict(x=x, y=y)) # Create plots and widgetsplot = figure() plot.line('x', 'y', source=source, line_width=3, line_alpha=0.5) # Create Slider objectslider = Slider(start=0, end=6, value=2, step=0.2, title='Number of points') # Adding callback codecallback = CustomJS(args=dict(source=source, val=slider), code=""" const data = source.data; const freq = val.value; const x = data['x']; const y = data['y']; for (var i = 0; i < x.length; i++) { y[i] = Math.sin(freq*x[i]); } source.change.emit();""") slider.js_on_change('value', callback) # Arrange plots and widgets in layoutslayout = column(slider, plot) output_file('exam.html') show(layout)
Output:
Picked
Python-Bokeh
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Box Plot in Python using Matplotlib
Bar Plot in Matplotlib
Python | Get dictionary keys as a list
Python | Convert set into a list
Ways to filter Pandas DataFrame by column values
Python - Call function from another file
loops in python
Multithreading in Python | Set 2 (Synchronization)
Python Dictionary keys() method
Python Lambda Functions
|
[
{
"code": null,
"e": 23901,
"s": 23873,
"text": "\n28 Jul, 2021"
},
{
"code": null,
"e": 24313,
"s": 23901,
"text": "Bokeh is an interactive Data visualization library of Python. It can be used to create interactive plots, dashboards, and data applications. Widgets are nothing but additional visual elements that you can add to your plots to interactively control your Bokeh document. There are various types of widgets such as button, div, spinner, slider, etc. In this article, we will learn about the slider widget in bokeh."
},
{
"code": null,
"e": 24486,
"s": 24313,
"text": "The Bokeh slider can be configured with start and end values, a step size, an initial value, and a title. Basically, you need to import the Slider widget from bokeh.models."
},
{
"code": null,
"e": 24494,
"s": 24486,
"text": "Syntax:"
},
{
"code": null,
"e": 24536,
"s": 24494,
"text": "from bokeh.models import CustomJS, Slider"
},
{
"code": null,
"e": 24586,
"s": 24536,
"text": "Slider() function can be used to create a slider."
},
{
"code": null,
"e": 24594,
"s": 24586,
"text": "Syntax:"
},
{
"code": null,
"e": 24651,
"s": 24594,
"text": "Slider(start=0, end=10, value=1, step=.1, title=”Stuff”)"
},
{
"code": null,
"e": 24662,
"s": 24651,
"text": "Parameter:"
},
{
"code": null,
"e": 24711,
"s": 24662,
"text": "start: It represents the sliders starting value."
},
{
"code": null,
"e": 24755,
"s": 24711,
"text": "end:It represents the sliders ending value."
},
{
"code": null,
"e": 24809,
"s": 24755,
"text": "value: It represents the current value of the slider."
},
{
"code": null,
"e": 24874,
"s": 24809,
"text": "step: It represents the interval through which the slider moves."
},
{
"code": null,
"e": 24927,
"s": 24874,
"text": "title: It represents the title of the slider widget."
},
{
"code": null,
"e": 25018,
"s": 24927,
"text": "Now add callback functionality using CustomJS which is called when on_change event occurs."
},
{
"code": null,
"e": 25026,
"s": 25018,
"text": "Syntax:"
},
{
"code": null,
"e": 25076,
"s": 25026,
"text": "js_on_change(“value”, CustomJS(code=”””.... “””))"
},
{
"code": null,
"e": 25389,
"s": 25076,
"text": "js_on_change is a callback function that is called when slider on_change event occurs. and customJS(code=””” “””) represents the code that is to be executed once the event occurs. Now call the callback function using the slider object and create a layout of all the elements you want to display on the browser."
},
{
"code": null,
"e": 25428,
"s": 25389,
"text": "Example: Creating a slider using bokeh"
},
{
"code": null,
"e": 25435,
"s": 25428,
"text": "Python"
},
{
"code": "from bokeh.layouts import columnfrom bokeh.models import ColumnDataSource, Slider, CustomJSfrom bokeh.plotting import figure, output_file, showimport numpy as np x = np.linspace(0, 10, 500)y = np.sin(x) source = ColumnDataSource(data=dict(x=x, y=y)) # Create plots and widgetsplot = figure() plot.line('x', 'y', source=source, line_width=3, line_alpha=0.5) # Create Slider objectslider = Slider(start=0, end=6, value=2, step=0.2, title='Number of points') # Adding callback codecallback = CustomJS(args=dict(source=source, val=slider), code=\"\"\" const data = source.data; const freq = val.value; const x = data['x']; const y = data['y']; for (var i = 0; i < x.length; i++) { y[i] = Math.sin(freq*x[i]); } source.change.emit();\"\"\") slider.js_on_change('value', callback) # Arrange plots and widgets in layoutslayout = column(slider, plot) output_file('exam.html') show(layout)",
"e": 26387,
"s": 25435,
"text": null
},
{
"code": null,
"e": 26395,
"s": 26387,
"text": "Output:"
},
{
"code": null,
"e": 26402,
"s": 26395,
"text": "Picked"
},
{
"code": null,
"e": 26415,
"s": 26402,
"text": "Python-Bokeh"
},
{
"code": null,
"e": 26422,
"s": 26415,
"text": "Python"
},
{
"code": null,
"e": 26520,
"s": 26422,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26529,
"s": 26520,
"text": "Comments"
},
{
"code": null,
"e": 26542,
"s": 26529,
"text": "Old Comments"
},
{
"code": null,
"e": 26578,
"s": 26542,
"text": "Box Plot in Python using Matplotlib"
},
{
"code": null,
"e": 26601,
"s": 26578,
"text": "Bar Plot in Matplotlib"
},
{
"code": null,
"e": 26640,
"s": 26601,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 26673,
"s": 26640,
"text": "Python | Convert set into a list"
},
{
"code": null,
"e": 26722,
"s": 26673,
"text": "Ways to filter Pandas DataFrame by column values"
},
{
"code": null,
"e": 26763,
"s": 26722,
"text": "Python - Call function from another file"
},
{
"code": null,
"e": 26779,
"s": 26763,
"text": "loops in python"
},
{
"code": null,
"e": 26830,
"s": 26779,
"text": "Multithreading in Python | Set 2 (Synchronization)"
},
{
"code": null,
"e": 26862,
"s": 26830,
"text": "Python Dictionary keys() method"
}
] |
Ext.js - Quick Guide
|
Ext JS is a popular JavaScript framework which provides rich UI for building web applications with cross-browser functionality. Ext JS is basically used for creating desktop applications. It supports all the modern browsers such as IE6+, FF, Chrome, Safari 6+, Opera 12+, etc. Whereas another product of Sencha, Sencha Touch is used for mobile applications.
Ext JS is based on MVC/MVVM architecture. The latest version of Ext JS 6 is a single platform, which can be used for both desktop and mobile application without having different code for different platform.
The first version of Ext JS was developed by Jack Slocum in 2006. It was a set of utility classes, which is an extension of YUI. He named the library as YUI-ext.
Ext JS version 2.0 was released in 2007. This version had a new API documentation for desktop application with limited features. This version doesn’t have backward compatibility with previous version of Ext JS.
Ext JS version 3.0 was released in 2009. This version added new features as chart and list view but at the cost of speed. It had backward compatibility with version 2.0.
After the release of Ext JS 3, the developers of Ext JS had the major challenge of ramping up the speed. Ext JS version 4.0 was released in 2011. It had the complete revised structure, which was followed by MVC architecture and a speedy application.
Ext JS version 5.0 was released in 2014. The major change in this release was to change the MVC architecture to MVVM architecture. It includes the ability to build desktop apps on touch-enabled devices, two-way data binding, responsive layouts, and many more features.
Ext JS 6 merges the Ext JS (for desktop application) and Sencha Touch (for mobile application) framework.
Following are the highlighted features of Ext JS.
Customizable UI widgets with collection of rich UI such as grids, pivot grids, forms, charts, trees.
Customizable UI widgets with collection of rich UI such as grids, pivot grids, forms, charts, trees.
Code compatibility of new versions with the older one.
Code compatibility of new versions with the older one.
A flexible layout manager helps to organize the display of data and content across multiple browsers, devices, and screen sizes.
A flexible layout manager helps to organize the display of data and content across multiple browsers, devices, and screen sizes.
Advance data package decouples the UI widgets from the data layer. The data package allows client-side collection of data using highly functional models that enable features such as sorting and filtering.
Advance data package decouples the UI widgets from the data layer. The data package allows client-side collection of data using highly functional models that enable features such as sorting and filtering.
It is protocol agnostic, and can access data from any back-end source.
It is protocol agnostic, and can access data from any back-end source.
Customizable Themes Ext JS widgets are available in multiple out-of-the-box themes that are consistent across platforms.
Customizable Themes Ext JS widgets are available in multiple out-of-the-box themes that are consistent across platforms.
Sencha Ext JS is the leading standard for business-grade web application development. Ext JS provides the tools necessary to build robust applications for desktop and tablets.
Streamlines cross-platform development across desktops, tablets, and smartphones - for both modern and legacy browsers.
Streamlines cross-platform development across desktops, tablets, and smartphones - for both modern and legacy browsers.
Increases the productivity of development teams by integrating into enterprise development environments via IDE plugins.
Increases the productivity of development teams by integrating into enterprise development environments via IDE plugins.
Reduces the cost of web application development.
Reduces the cost of web application development.
Empowers the teams to create apps with a compelling user experience.
Empowers the teams to create apps with a compelling user experience.
Offers a set of widgets to easily make a powerful UI.
Offers a set of widgets to easily make a powerful UI.
Follows MVC architecture, hence the code is highly readable.
Follows MVC architecture, hence the code is highly readable.
The size of the library is large, around 500 KB, which makes initial loading time more and makes application slow.
The size of the library is large, around 500 KB, which makes initial loading time more and makes application slow.
HTML is full of tags that makes it complex and difficult to debug.
HTML is full of tags that makes it complex and difficult to debug.
According to general public license policy, it is free for open source applications but paid for commercial applications.
According to general public license policy, it is free for open source applications but paid for commercial applications.
Sometimes for loading even simple things require few lines of coding, which is simpler in plain html or JQuery.
Sometimes for loading even simple things require few lines of coding, which is simpler in plain html or JQuery.
Need quite experienced developer for developing Ext JS applications.
Need quite experienced developer for developing Ext JS applications.
Following are the tools provided by Sencha used for Ext JS application development mainly at the production level.
Sencha CMD is a tool which provides the features of Ext JS code minification, scaffolding, and production build generation.
Sencha IDE plugins integrates Sencha frameworks into IntelliJ, WebStorm IDEs, which helps in improving the developer’s productivity by providing features such as code completion, code inspection, code navigation, code generation, code refactoring, template creation, spell-checking, etc.
Sencha Inspector is a debugging tool which helps the debugger to debug any issue while development.
This section guides you on how to download and set up Ext JS on your machine. Please follow the steps to set up the environment.
Download the trial version of Ext JS library files from Sencha https://www.sencha.com. You will get the trial version from the site on your registered mail id, which will be a zipped folder named ext-6.0.1-trial.
Unzip the folder and you will find various JavaScript and CSS files, which you will include in our application. We will mostly include the following files −
JavaScript Files − JS file which you can find under the folder \ext-6.0.1-trial\ext6.0.1\build are −
ext.js
This is the core file which contains all the functionalities to run the application.
ext-all.js
This file contains all the code minified with no comments in the file.
ext-all-debug.js
This is the unminified version of ext-all.js for debugging purpose.
ext-all-dev.js
This file is also unminified and is used for development purpose as it contains all the comments and console logs to check any errors/issue.
ext-all.js
This file is used for production purpose mostly as it is much smaller than any other.
You can add these files to your projects JS folder or you can provide a direct path where the file resides in your system.
CSS Files − There are number of theme-based files, which you can find under folder \ext6.0.1-trial\ext-6.0.1\build\classic\theme-classic\resources\theme-classic-all.css
If you are going to use desktop application, then you can use classic themes under folder \ext-6.0.1-trial\ext-6.0.1\build\classic
If you are going to use desktop application, then you can use classic themes under folder \ext-6.0.1-trial\ext-6.0.1\build\classic
If we are going to use mobile application, then you can use modern themes which can be found under folder \ext-6.0.1-trial\ext-6.0.1\build\modern
If we are going to use mobile application, then you can use modern themes which can be found under folder \ext-6.0.1-trial\ext-6.0.1\build\modern
The following library files will be added in an Ext JS application.
<html>
<head>
<link rel = "stylesheet" type = "text/css"
href = "..\ext-6.0.1-trial\ext-6.0.1\build\classic\theme-classic\resources\theme-classic-all.css" />
<script type = "text/javascript"
src = "..\ext-6.0.1-trial\ext-6.0.1\build\ext-all.js" > </script>
<script type = "text/javascript" src = "app.js" > </script>
</head>
</html>
You will keep ExtJS application code in app.js file.
CDN is content delivery network with which you do not need to download the Ext JS library files, instead you can directly add CDN link for ExtJS to your program as follows −
<html>
<head>
<link rel = "stylesheet" type = "text/css"
href = "https://cdnjs.cloudflare.com/ajax/libs/extjs/6.0.0/classic/theme-crisp/resources/theme-crisp-all.css" / >
<script type = "text/javascript"
src = "https://cdnjs.cloudflare.com/ajax/libs/extjs/6.0.0/ext-all.js"> </script>
<script type = "text/javascript" src = "app.js" > </script>
</head>
</html>
As it is a JavaScript framework, which is used for developing web applications, in our project we will have HTML, JS files. To write our Ext JS programs, we will need a text editor. There are even multiple IDEs available in the market. But for now, we can consider one of the following −
Notepad − On Windows machine, you can use any simple text editor such as Notepad (Recommended for this tutorial), Notepad++, sublime.
Notepad − On Windows machine, you can use any simple text editor such as Notepad (Recommended for this tutorial), Notepad++, sublime.
Eclipse − It is an IDE developed by the eclipse open-source community and can be downloaded from https://www.eclipse.org/.
Eclipse − It is an IDE developed by the eclipse open-source community and can be downloaded from https://www.eclipse.org/.
Ext JS supports cross-browser compatibility, it supports all major browsers such as −
IE 6 and above
Firefox 3.6 and above
Chrome10 and above
Safari 4 and above
Opera 11 and above
You can use any browser for running Ext JS application.
Naming convention is a set of rule to be followed for identifiers. It makes the code more readable and understandable to other programmers as well.
Naming convention in Ext JS follows the standard JavaScript convention, which is not mandatory but a good practice to follow. It should follow the camel case syntax for naming the class, method, variable and properties.
If the name is combined with two words, the second word will start with an uppercase letter always. For example, doLayout(), StudentForm, firstName, etc.
Ext JS follows MVC/ MVVM architecture.
MVC – Model View Controller architecture (version 4)
MVVM – Model View Viewmodel (version 5)
This architecture is not mandatory for the program, however, it is a best practice to follow this structure to make your code highly maintainable and organized.
----------src
----------resources
-------------------CSS files
-------------------Images
----------JavaScript
--------------------App Folder
-------------------------------Controller
------------------------------------Contoller.js
-------------------------------Model
------------------------------------Model.js
-------------------------------Store
------------------------------------Store.js
-------------------------------View
------------------------------------View.js
-------------------------------Utils
------------------------------------Utils.js
--------------------------------app.js
-----------HTML files
Ext JS app folder will reside in JavaScript folder of your project.
The App will contain controller, view, model, store, and utility files with app.js.
app.js − The main file from where the flow of program will start, which should be included in the main HTML file using <script> tag. App calls the controller of application for the rest of the functionality.
Controller.js − It is the controller file of Ext JS MVC architecture. This contains all the control of the application, the events listeners, and most of the functionality of the code. It has the path defined for all the other files used in that application such as store, view, model, require, mixins.
View.js − It contains the interface part of the application, which shows up to the user. Ext JS uses various UI rich views, which can be extended and customized here according to the requirement.
Store.js − It contains the data locally cached which is to be rendered on the view with the help of model objects. Store fetches the data using proxies which has the path defined for services to fetch the backend data.
Model.js − It contains the objects which binds the store data to view. It has the mapping of backend data objects to the view dataIndex. The data is fetched with the help of store.
Utils.js − It is not included in MVC architecture but a best practice to use to make the code clean, less complex, and more readable. We can write methods in this file and call them in the controller or the view renderer wherever required. It is helpful for code reusability purpose as well.
In MVVM architecture, the controller is replaced by ViewModel.
ViewModel − It basically mediates the changes between view and model. It binds the data from the model to the view. At the same time, it does not have any direct interaction with the view. It has only knowledge of the model.
For example, if we are using one model object at two-three places in UI. If we change the value at one place of UI, we can see without even saving that change. The value of model changes and so gets reflected in all the places in the UI, wherever the model is used.
It makes the developers’ effort much lesser and easier as no extra coding is required for binding data.
This chapter lists down the steps to write the first Hello World program in Ext JS.
Create an index.htm page in the editor of our choice. Include the required library files in the head section of html page as follows.
<!DOCTYPE html>
<html>
<head>
<link href = "https://cdnjs.cloudflare.com/ajax/libs/extjs/6.0.0/classic/theme-classic/resources/theme-classic-all.css"
rel = "stylesheet" />
<script type = "text/javascript"
src = "https://cdnjs.cloudflare.com/ajax/libs/extjs/6.0.0/ext-all.js"></script>
<script type = "text/javascript">
Ext.onReady(function() {
Ext.create('Ext.Panel', {
renderTo: 'helloWorldPanel',
height: 200,
width: 600,
title: 'Hello world',
html: 'First Ext JS Hello World Program'
});
});
</script>
</head>
<body>
<div id = "helloWorldPanel" />
</body>
</html>
Ext.onReady() method will be called once the Ext JS is ready to render the Ext JS elements.
Ext.onReady() method will be called once the Ext JS is ready to render the Ext JS elements.
Ext.create() method is used to create an object in Ext JS. Here we are creating an object of simple panel class Ext.Panel.
Ext.create() method is used to create an object in Ext JS. Here we are creating an object of simple panel class Ext.Panel.
Ext.Panel is the predefined class in Ext JS for creating a panel.
Ext.Panel is the predefined class in Ext JS for creating a panel.
Every Ext JS class has different properties to perform some basic functionalities.
Every Ext JS class has different properties to perform some basic functionalities.
Ext.Panel class has various properties such as −
renderTo is the element where this panel has to render. 'helloWorldPanel' is the div id in Index.html file.
renderTo is the element where this panel has to render. 'helloWorldPanel' is the div id in Index.html file.
Height and width properties are for customizing the size of the panel.
Height and width properties are for customizing the size of the panel.
Title property is to provide the title to the panel.
Title property is to provide the title to the panel.
Html property is the html content to be shown in the panel.
Html property is the html content to be shown in the panel.
Open the index.htm file in a standard browser and you will get the following output on the browser.
Ext JS is a JavaScript framework having functionalities of object oriented programming. Ext is the namespace, which encapsulates all the classes in Ext JS.
Ext provides more than 300 classes, which we can use for various functionalities.
Ext.define() is used for defining the classes in Ext JS.
Ext.define(class name, class members/properties, callback function);
Class name is the name of the class according to app structure. For example, appName.folderName.ClassName studentApp.view.StudentView.
Class properties/members defines the behavior of class.
Callback function is optional. It is called when the class has loaded properly.
Ext.define(studentApp.view.StudentDeatilsGrid, {
extend : 'Ext.grid.GridPanel',
id : 'studentsDetailsGrid',
store : 'StudentsDetailsGridStore',
renderTo : 'studentsDetailsRenderDiv',
layout : 'fit',
columns : [{
text : 'Student Name',
dataIndex : 'studentName'
},{
text : 'ID',
dataIndex : 'studentId'
},{
text : 'Department',
dataIndex : 'department'
}]
});
As like other OOPS based languages, we can create objects in Ext JS as well.
Following are the different ways of creating objects in Ext JS.
var studentObject = new student();
studentObject.getStudentName();
Ext.create('Ext.Panel', {
renderTo : 'helloWorldPanel',
height : 100,
width : 100,
title : 'Hello world',
html : 'First Ext JS Hello World Program'
});
Inheritance is the principle of using functionality defined in class A into class B.
In Ext JS, inheritance can be done using two methods −
Ext.define(studentApp.view.StudentDetailsGrid, {
extend : 'Ext.grid.GridPanel',
...
});
Here, our custom class StudentDetailsGrid is using the basic features of Ext JS class GridPanel.
Mixins is a different way of using class A in class B without extend.
mixins : {
commons : 'DepartmentApp.utils.DepartmentUtils'
},
Mixins are added in the controller where we declare all the other classes such as store, view, etc. In this way, we can call DepartmentUtils class and use its functions in the controller or in this application.
Container in Ext JS is the component where we can add other container or child components. These containers can have multiple layout to arrange the components in the containers. We can add or remove the components from the container and from its child elements. Ext.container.Container is the base class for all the containers in Ext JS.
This example shows how to define the components inside a container
This example shows how to define a container inside a container with other components
There are various type of containers Ext.panel.Panel, Ext.form.Panel, Ext.tab.Panel and Ext.container.Viewport are frequently used containers in Ext JS. Below are the example which shows how to use these containers.
This example shows a Ext.panel.Panel container
This example shows a Ext.form.Panel container
This example shows a Ext.tab.Panel container
This example shows a Ext.container.Viewport container
Layout is the way the elements are arranged in a container. It can be horizontal, vertical, or any other. Ext JS has a different layout defined in its library but we can always write custom layouts as well.
This layout allows to position the items using XY coordinates in the container.
This layout allows to place all the items in stack fashion (one on top of the other) inside the container.
This layout gives the privilege to the user to specify the size of each element with respect to the container size.
In this layout various panels are nested and separated by borders.
This is the default layout that decides the layout of the elements based on the number of elements.
This layout arranges different components in tab fashion. Tabs will be displayed on top of the container. Every time only one tab is visible and each tab is considered as a different component.
In this layout, every time the elements come for full container space. There is a bottom tool bar in the wizard for navigation.
This layout is to show multiple columns in the container. We can define a fixed or percentage width to the columns. The percentage width will be calculated based on the full size of the container.
In this layout, the container is filled with a single panel. When there is no specific requirement related to the layout, then this layout is used.
As the name implies, this layout arranges the components in a container in the HTML table format.
This layout allows the element to be distributed in a vertical manner. This is one of the most used layout.
This layout allows the element to be distributed in a horizontal manner.
ExtJS UI is made up of one or many widgets called Components. Ext Js has various UI components defined that can be customised as per your requirements.
Grid component can be used to show the data in a tabular format.
Form widget is to get the data from the user.
Message box is basically used to show data in the form of alert box.
Charts are used to represent data in pictorial format.
Tool tip is used to show some basic information when any event occurs.
This UI widget is to create a window, which should pop up when any event occurs.
HTML Editor is one of the very useful UI component, which is used for styling the data that the user enters in terms of fonts, color, size, etc.
Shows the progress of the backend work.
Drag and drop feature is one of the powerful features added to make the developer’s task easy. A drag operation, essentially, is a click gesture on some UI element, while the mouse button is held down and the mouse is moved. A drop operation occurs when the mouse button is released after a drag operation.
Adding drag and drop class to the draggable targets.
var dd = Ext.create('Ext.dd.DD', el, 'imagesDDGroup', {
isTarget: false
});
Adding drag and drop target class to drappable target.
var mainTarget = Ext.create('Ext.dd.DDTarget', 'mainRoom', 'imagesDDGroup', {
ignoreSelf: false
});
Following is a simple example.
<!DOCTYPE html>
<html>
<head>
<link href = "https://cdnjs.cloudflare.com/ajax/libs/extjs/6.0.0/classic/theme-classic/resources/theme-classic-all.css"
rel = "stylesheet" />
<script type = "text/javascript"
src = "https://cdnjs.cloudflare.com/ajax/libs/extjs/6.0.0/ext-all.js"></script>
<script type = "text/javascript">
Ext.application ({
launch: function() {
var images = Ext.get('images').select('img');
Ext.each(images.elements, function(el) {
var dd = Ext.create('Ext.dd.DD', el, 'imagesDDGroup', {
isTarget: false
});
});
}
});
var mainTarget = Ext.create('Ext.dd.DDTarget', 'mainRoom', 'imagesDDGroup', {
ignoreSelf: false
});
</script>
<style>
#content {
width:600px;
height:400px;
padding:10px;
border:1px solid #000;
}
#images {
float:left;
width:40%;
height:100%;
border:1px solid Black;
background-color:rgba(222, 222, 222, 1.0);
}
#mainRoom {
float:left;
width:55%;
height:100%;
margin-left:15px;
border:1px solid Black;
background-color:rgba(222, 222, 222, 1.0);
}
.image {
width:64px;
height:64px;
margin:10px;
cursor:pointer;
border:1px solid Black;
display: inline-block;
}
</style>
</head>
<body>
<div id = "content">
<div id = "images">
<img src = "/extjs/images/1.jpg" class = "image" />
<img src = "/extjs/images/2.jpg" class = "image" />
<img src = "/extjs/images/3.jpg" class = "image" />
<img src = "/extjs/images/4.jpg" class = "image" />
<img src = "/extjs/images/5.jpg" class = "image" />
<img src = "/extjs/images/6.jpg" class = "image" />
<img src = "/extjs/images/7.jpg" class = "image" />
<img src = "/extjs/images/8.jpg" class = "image" />
</div>
<div id = "mainRoom"></div>
</div>
</body>
</html>
The above program will produce the following result −
With the help of drag and drop in Extjs, we can move data from grid to grid and grid to form. Following are the examples of moving data between grids and forms.
Drag and drop - Grid to Grid
drag and drop - Grid to Form
Ext.js provides a number of themes to be used in your applications. You can add a different theme in place of a classic theme and see the difference in the output. This is done simply by replacing the theme CSS file as explained ahead.
Consider your very first Hello World application. Remove the following CSS from the application.
https://cdnjs.cloudflare.com/ajax/libs/extjs/6.0.0/classic/theme-classic/resources/theme-classic-all.css
Add the following CSS to use the Neptune theme.
https://cdnjs.cloudflare.com/ajax/libs/extjs/6.0.0/classic/theme-neptune/resources/theme-neptune-all.css
To see the effect, try the following program.
<!DOCTYPE html>
<html>
<head>
<link href = "https://cdnjs.cloudflare.com/ajax/libs/extjs/6.0.0/classic/theme-neptune/resources/theme-neptune-all.css"
rel = "stylesheet" />
<script type = "text/javascript"
src = "https://cdnjs.cloudflare.com/ajax/libs/extjs/6.0.0/ext-all.js"></script>
<script type = "text/javascript">
Ext.onReady(function() {
Ext.create('Ext.Panel', {
renderTo: 'helloWorldPanel',
height: 200,
width: 600,
title: 'Hello world',
html: 'First Ext JS Hello World Program'
});
});
</script>
</head>
<body>
<div id = "helloWorldPanel" />
</body>
</html>
The above program will produce the following result −
Consider your very first Hello World application. Remove the following CSS from the application.
https://cdnjs.cloudflare.com/ajax/libs/extjs/6.0.0/classic/theme-classic/resources/theme-classic-all.css
Add the following CSS to use the Neptune theme.
https://cdnjs.cloudflare.com/ajax/libs/extjs/6.0.0/classic/theme-crisp/resources/theme-crisp-all.css
To see the effect, try the following program.
<!DOCTYPE html>
<html>
<head>
<link href = "https://cdnjs.cloudflare.com/ajax/libs/extjs/6.0.0/classic/theme-crisp/resources/theme-crisp-all.css"
rel = "stylesheet" />
<script type = "text/javascript"
src = "https://cdnjs.cloudflare.com/ajax/libs/extjs/6.0.0/ext-all.js"></script>
<script type = "text/javascript">
Ext.onReady(function() {
Ext.create('Ext.Panel', {
renderTo: 'helloWorldPanel',
height: 200,
width: 600,
title: 'Hello world',
html: 'First Ext JS Hello World Program'
});
});
</script>
</head>
<body>
<div id = "helloWorldPanel" />
</body>
</html>
The above program will produce the following result −
Consider your very first Hello World application. Remove the following CSS from the application.
https://cdnjs.cloudflare.com/ajax/libs/extjs/6.0.0/classic/theme-classic/resources/theme-classic-all.css
Add the following CSS to use the Triton theme.
https://cdnjs.cloudflare.com/ajax/libs/extjs/6.0.0/classic/theme-triton/resources/theme-triton-all.css
To see the effect, try the following program.
<!DOCTYPE html>
<html>
<head>
<link href = "https://cdnjs.cloudflare.com/ajax/libs/extjs/6.0.0/classic/theme-triton/resources/theme-triton-all.css"
rel = "stylesheet" />
<script type = "text/javascript"
src = "https://cdnjs.cloudflare.com/ajax/libs/extjs/6.0.0/ext-all.js"></script>
<script type = "text/javascript">
Ext.onReady(function() {
Ext.create('Ext.Panel', {
renderTo: 'helloWorldPanel',
height: 200,
width: 600,
title: 'Hello world',
html: 'First Ext JS Hello World Program'
});
});
</script>
</head>
<body>
<div id = "helloWorldPanel" />
</body>
</html>
The above program will produce the following result −
Consider your very first Hello World application. Remove the following CSS from the application.
https://cdnjs.cloudflare.com/ajax/libs/extjs/6.0.0/classic/theme-classic/resources/theme-classic-all.css
Add the following CSS to use the Gray theme.
https://cdnjs.cloudflare.com/ajax/libs/extjs/6.0.0/classic/theme-gray/resources/theme-gray-all.css
To see the effect, try the following program.
<!DOCTYPE html>
<html>
<head>
<link href = "https://cdnjs.cloudflare.com/ajax/libs/extjs/6.0.0/classic/theme-gray/resources/theme-gray-all.css"
rel = "stylesheet" />
<script type = "text/javascript"
src = "https://cdnjs.cloudflare.com/ajax/libs/extjs/6.0.0/ext-all.js"></script>
<script type = "text/javascript">
Ext.onReady(function() {
Ext.create('Ext.Panel', {
renderTo: 'helloWorldPanel',
height: 200,
width: 600,
title: 'Hello world',
html: 'First Ext JS Hello World Program'
});
});
</script>
</head>
<body>
<div id = "helloWorldPanel" />
</body>
</html>
The above program will produce the following result −
Events are something which get fired when something happens to the class. For example, when a button is getting clicked or before/after the element is rendered.
Built-in events using listeners
Attaching events later
Custom events
Ext JS provides listener property for writing events and custom events in Ext JS files.
Writing listener in Ext JS
We will add the listener in the previous program itself by adding a listen property to the panel.
<!DOCTYPE html>
<html>
<head>
<link href = "https://cdnjs.cloudflare.com/ajax/libs/extjs/6.0.0/classic/theme-neptune/resources/theme-neptune-all.css"
rel = "stylesheet" />
<script type = "text/javascript"
src = "https://cdnjs.cloudflare.com/ajax/libs/extjs/6.0.0/ext-all.js"></script>
<script type = "text/javascript">
Ext.onReady(function() {
Ext.create('Ext.Button', {
renderTo: Ext.getElementById('helloWorldPanel'),
text: 'My Button',
listeners: {
click: function() {
Ext.MessageBox.alert('Alert box', 'Button is clicked');
}
}
});
});
</script>
</head>
<body>
<p> Please click the button to see event listener </p>
<div id = 'helloWorldPanel' /> <!-- panel will be rendered here-- >
</body>
</html>
The above program will produce the following result −
Please click the button to see event listener:
This way we can also write multiple events in listeners property.
Multiple Events in the Same Listener
<!DOCTYPE html>
<html>
<head>
<link href = "https://cdnjs.cloudflare.com/ajax/libs/extjs/6.0.0/classic/theme-neptune/resources/theme-neptune-all.css"
rel = "stylesheet" />
<script type = "text/javascript"
src = "https://cdnjs.cloudflare.com/ajax/libs/extjs/6.0.0/ext-all.js"></script>
<script type = "text/javascript">
Ext.onReady(function() {
Ext.get('tag2').hide()
Ext.create('Ext.Button', {
renderTo: Ext.getElementById('helloWorldPanel'),
text: 'My Button',
listeners: {
click: function() {
this.hide();
},
hide: function() {
Ext.get('tag1').hide();
Ext.get('tag2').show();
}
}
});
});
</script>
</head>
<body>
<div id = "tag1">Please click the button to see event listener.</div>
<div id = "tag2">The button was clicked and now it is hidden.</div>
<div id = 'helloWorldPanel' /> <!-- panel will be rendered here-- >
</body>
</html>
In the previous method of writing events, we have written events in listeners at the time of creating elements. The other way is to attach events.
<!DOCTYPE html>
<html>
<head>
<link href = "https://cdnjs.cloudflare.com/ajax/libs/extjs/6.0.0/classic/theme-neptune/resources/theme-neptune-all.css"
rel = "stylesheet" />
<script type = "text/javascript"
src = "https://cdnjs.cloudflare.com/ajax/libs/extjs/6.0.0/ext-all.js"></script>
<script type = "text/javascript">
Ext.onReady(function() {
var button = Ext.create('Ext.Button', {
renderTo: Ext.getElementById('helloWorldPanel'),
text: 'My Button'
});
// This way we can attach event to the button after the button is created.
button.on('click', function() {
Ext.MessageBox.alert('Alert box', 'Button is clicked');
});
});
</script>
</head>
<body>
<p> Please click the button to see event listener </p>
<div id = 'helloWorldPanel' /> <!-- panel will be rendered here-- >
</body>
</html>
The above program will produce the following result −
Please click the button to see event listener:
We can write custom events in Ext JS and fire the events with fireEvent method. Following example explains how to write custom events.
<!DOCTYPE html>
<html>
<head>
<link href = "https://cdnjs.cloudflare.com/ajax/libs/extjs/6.0.0/classic/theme-neptune/resources/theme-neptune-all.css"
rel = "stylesheet" />
<script type = "text/javascript"
src = "https://cdnjs.cloudflare.com/ajax/libs/extjs/6.0.0/ext-all.js"></script>
<script type = "text/javascript">
Ext.onReady(function() {
var button = Ext.create('Ext.Button', {
renderTo: Ext.getElementById('helloWorldPanel'),
text: 'My Button',
listeners: {
myEvent: function(button) {
Ext.MessageBox.alert('Alert box', 'My custom event is called');
}
}
});
Ext.defer(function() {
button.fireEvent('myEvent');
}, 5000);
});
</script>
</head>
<body>
<p> The event will be called after 5 seconds when the page is loaded. </p>
<div id = 'helloWorldPanel' /> <!-- panel will be rendered here-- >
</body>
</html>
Once the page is loaded and the document is ready, the UI page with a button will appear and as we are firing an event after 5 secs, the document is ready. The alert box will appear after 5 seconds.
The event will be called after 5 seconds when the page is loaded.
Here, we have written the custom event 'myEvent' and we are firing events as button.fireEvent(eventName);
Data package is used for loading and saving all the data in the application.
Data package has numerous number of classes but the most important classes are −
Model
Store
Proxy
The base class for model is Ext.data.Model. It represents an entity in an application. It binds the store data to view. It has mapping of backend data objects to the view dataIndex. The data is fetched with the help of store.
For creating a model, we need to extend Ext.data.Model class and we need to define the fields, their name, and mapping.
Ext.define('StudentDataModel', {
extend: 'Ext.data.Model',
fields: [
{name: 'name', mapping : 'name'},
{name: 'age', mapping : 'age'},
{name: 'marks', mapping : 'marks'}
]
});
Here, the name should be the same as the dataIndex, which we declare in the view and the mapping should match the data, either static or dynamic from the database, which is to be fetched using store.
The base class for store is Ext.data.Store. It contains the data locally cached, which is to be rendered on view with the help of model objects. Store fetches the data using proxies, which has the path defined for services to fetch the backend data.
Store data can be fetched in two ways - static or dynamic.
For static store, we will have all the data present in the store as shown in the following code.
Ext.create('Ext.data.Store', {
model: 'StudentDataModel',
data: [
{ name : "Asha", age : "16", marks : "90" },
{ name : "Vinit", age : "18", marks : "95" },
{ name : "Anand", age : "20", marks : "68" },
{ name : "Niharika", age : "21", marks : "86" },
{ name : "Manali", age : "22", marks : "57" }
];
});
Dynamic data can be fetched using proxy. We can have proxy which can fetch data from Ajax, Rest, and Json.
The base class for proxy is Ext.data.proxy.Proxy. Proxy is used by Models and Stores to handle the loading and saving of Model data.
There are two types of proxies
Client Proxy
Server Proxy
Client proxies include Memory and Local Storage using HTML5 local storage.
Server proxies handle data from the remote server using Ajax, Json data, and Rest service.
Defining proxies in the server
Ext.create('Ext.data.Store', {
model: 'StudentDataModel',
proxy : {
type : 'rest',
actionMethods : {
read : 'POST' // Get or Post type based on requirement
},
url : 'restUrlPathOrJsonFilePath', // here we have to include the rest URL path
// which fetches data from database or Json file path where the data is stored
reader: {
type : 'json', // the type of data which is fetched is of JSON type
root : 'data'
},
}
});
Ext.js provides the facility to use different font packages. Font packages are used to add different classes for icons available in the package.
Font-Awesome
Font-Pictos
ExtJS new theme, Triton, has an inbuilt font family font-awesome included in the framework itself, hence we do not need any explicit requirement for the font-awesome stylesheet.
Following is an example of using Font-Awesome classes in the Triton theme.
Font-Awesome with Triton theme
When we are using any other theme apart from Triton, we need or require to add a stylesheet for font-awesome explicitly.
Following is an example of using Font-Awesome classes without the Triton theme.
Font-Awesome with normal theme(Any theme other then Triton theme)
Font-pictos is not included in the framework for ExtJS, hence we have to require the same. Only licenced users of Sencha will have the benefit to use font-pictos.
Step 1 − Require font-pictos class using the following command.
"requires": ["font-pictos"]
Step 2 − Now add pictos classes as −
iconCls: 'pictos pictos-home'
Application Styling refers to user adjustment of the look and feel of the components. These adjustments may include: color, color gradients, font, margins/padding, etc. Ext JS 6 has a new way of styling the application.
It uses SCSS for styling. SCSS is a more dynamic way of writing the CSS code. We can write the variables in our stylesheet with the help of this. However, a browser cannot understand SCSS. It can only understand CSS, hence all SCSS files should get compiled into CSS to a production-ready code.
Thus, SCSS file is called preprocessor files. In Ext.js, compilation is done through Sencha CMD tool. Sencha CMD compiles it manually only once using the following command.
sencha app build [development]
Global_CSS is the main CSS file, which has all SCSS variables associated with it in ExtJS that can be used in our application for customizing our theme by providing different value based on our need.
Following are some of the CSS variables available in the Global_CSS in Ext.js.
$base-color
$base-color: color (e.g. $base-color : #808080)
This base color is to be used throughout the theme.
$base-gradient
$base-gradient: string (e.g. $base-gradient : 'matte')
This base gradient is to be used throughout the theme.
$body-background-color
$body-background-color: color (e.g. $body-background-color : #808080)
Background color to apply to the body element. If set to transparent or 'none', no background-color style will be set on the body element.
$color
$color : color (e.g. $color : #808080)
This default text color is to be used throughout the theme.
$font-family
$font-family : string (e.g. $font-family : arial)
This default font-family is to be used throughout the theme.
$font-size
$font-size : number (e.g. $font-size : 9px )
This default font-size is to be used throughout the theme.
$font-weight
$font-weight : string/number (e.g. $font-weight : normal )
This default font-weight is to be used throughout the theme.
$font-weight-bold
$font-weight-bold : string/number (e.g. $font-weight-bold : bold )
This default font-weight for bold font is to be used throughout the theme.
$include-chrome
$include-chrome : boolean (e.g. $include-chrome : true)
True to include Chrome specific rules.
$include-ff
$include-ff : boolean (e.g. $include-ff : true)
True to include Firefox specific rules.
$include-ie
$include-ie : boolean (e.g. $include-ie : true)
True to include Internet Explorer specific rules for IE9 and lower.
$include-opera
$include-opera : boolean (e.g. $include-opera : true)
True to include Opera specific rules.
$include-safari
$include-safari : boolean (e.g. $include-safari : true)
True to include Opera specific rules.
$include-webkit
$include-webkit : boolean (e.g. $include-webkit : true)
True to include Webkit specific rules.
Drawing package in ExtJS enables you to draw general purpose graphics. This can be used for graphics that work on all browsers and mobile devices.
This graphics is used to create a circulare shape.
This graphics is used to create a rectanglar shape.
This graphics is used to create an arc shape.
This graphics is used to create an ellipse shape.
This graphics is used to create an elliptical arc shape.
This graphics is used to add an image to your application.
This graphics is used to create a free path.
This graphics is used to add any text to your application.
This property is used to move the starting point in your container, after the graphic is rendered. It can be used with any graphics.
This property is used to add a rotation to the drawing added. It can be used with any graphics.
This graphic is used to create a square.
It is always best to communicate with the users in the language they understand and prefer. Extjs localization package supports over 40 languages such as German, French, Korean, Chinese, etc. It is very simple to implement the locale in ExtJs. You’ll find all of the bundled locale files in the override folder of the ext-locale package. Locale files just overrides that tells Ext JS to replace the default English values of certain components.
The following program is to show the month in different locale to see the effect. Try the following program.
<!DOCTYPE html>
<html>
<head>
<link href = "https://cdnjs.cloudflare.com/ajax/libs/extjs/6.0.0/classic/theme-classic/resources/theme-classic-all.css"
rel = "stylesheet" />
<script type = "text/javascript"
src = "https://cdnjs.cloudflare.com/ajax/libs/extjs/6.0.0/ext-all.js"></script>
<script type = "text/javascript"
src = "https://cdnjs.cloudflare.com/ajax/libs/extjs/6.0.0/classic/locale/locale-fr.js"></script>
<script type = "text/javascript">
Ext.onReady(function() {
var monthArray = Ext.Array.map(Ext.Date.monthNames, function (e) { return [e]; });
var ds = Ext.create('Ext.data.Store', {
fields: ['month'],
remoteSort: true,
pageSize: 6,
proxy: {
type: 'memory',
enablePaging: true,
data: monthArray,
reader: {type: 'array'}
}
});
Ext.create('Ext.grid.Panel', {
renderTo: 'grid',
id : 'gridId',
width: 600,
height: 200,
title:'Month Browser',
columns:[{
text: 'Month of the year',
dataIndex: 'month',
width: 300
}],
store: ds,
bbar: Ext.create('Ext.toolbar.Paging', {
pageSize: 6,
store: ds,
displayInfo: true
})
});
Ext.getCmp('gridId').getStore().load();
});
</script>
</head>
<body>
<div id = "grid" />
</body>
</html>
The above program will produce the following result
For using different locale other than English, we would need to add the locale specific file in our program. Here we are using https://cdnjs.cloudflare.com/ajax/libs/extjs/6.0.0/classic/locale/localefr.js for French. You can use different locale for different languages such as https://cdnjs.cloudflare.com/ajax/libs/extjs/6.0.0/classic/locale/locale-ko.js for korean, etc.
The following program is to show the date picker in Korean locale to see the effect. Try the following program.
<!DOCTYPE html>
<html>
<head>
<link href = "https://cdnjs.cloudflare.com/ajax/libs/extjs/6.0.0/classic/theme-classic/resources/theme-classic-all.css"
rel = "stylesheet" />
<script type = "text/javascript"
src = "https://cdnjs.cloudflare.com/ajax/libs/extjs/6.0.0/ext-all.js"></script>
<script type = "text/javascript"
src = "https://cdnjs.cloudflare.com/ajax/libs/extjs/6.0.0/classic/locale/locale-ko.js"></script>
<script type = "text/javascript">
Ext.onReady(function() {
Ext.create('Ext.picker.Date', {
renderTo: 'datePicker'
});
});
</script>
</head>
<body>
<div id = "datePicker" />
</body>
</html>
The above program will produce the following result −
Following table lists the few locales available in ExtJS and the main file locale URL to be changed.
In general accessibility means availability, the content is accessible means the content is available.
In software terms, the application is accessible means the application is available for all. Here, all means the persons with disabilities, the visually impaired or those who use screen readers to use a computer or those who prefer to navigate using the keyboard instead of using a mouse. navigation with keyboard instead of using a mouse.
Applications which are accessible are called ARIA (Accessible Rich Internet Applications).
Ext JS is designed to keep this in mind that it should work with all keyboard navigations. It has built-in tab indexing and focus-ability, and it is always on by default so we do not need to add any property to enable this functionality.
This functionality allows all keyboard-enabled components to interact with the user when tabbed into. For example, we can use tab for moving on to the next component instead of a mouse. Same way, we can use shift+tab for moving backward and use enter on the keyboard to click, etc.
Focus is inbuilt in Extjs when using keystroke for tabbing.
Following example shows how to the style changes, when the focus changes with the tabs.
<!DOCTYPE html>
<html>
<head>
<link href = "https://cdnjs.cloudflare.com/ajax/libs/extjs/6.0.0/classic/theme-crisp/resources/theme-crisp-all.css"
rel = "stylesheet" />
<script type = "text/javascript"
src = "https://cdnjs.cloudflare.com/ajax/libs/extjs/6.0.0/ext-all.js"></script>
<script type = "text/javascript">
Ext.onReady(function(){
Ext.create('Ext.Button', {
renderTo: Ext.getElementById('button1'),
text: 'Button1',
listeners: {
click: function() {
Ext.MessageBox.alert('Alert box', 'Button 1 is clicked');
}
}
});
Ext.create('Ext.Button', {
renderTo: Ext.getElementById('button2'),
text: 'Button2',
listeners: {
click: function() {
Ext.MessageBox.alert('Alert box', 'Button 2 is clicked');
}
}
});
Ext.create('Ext.Button', {
renderTo: Ext.getElementById('button3'),
text: 'Button3',
listeners: {
click: function() {
Ext.MessageBox.alert('Alert box', 'Button 3 is clicked');
}
}
});
});
</script>
</head>
<body> <p>Please click the button to see event listener:</p>
<span id = "button3"/>
<span id = "button2"/>
<span id = "button1"/>
</body>
</html>
To see the effect, use tab for moving from the next button and shft+tab for focusing backward. Use enter and see how the focused button's related alert would pop up.
Please click the button to see event listener:
ExtJS provides the theme aria for the visually impaired.
Following example shows the aria theme which is easily accessible for the visually impaired.
<!DOCTYPE html>
<html>
<head>
<link href = "https://cdnjs.cloudflare.com/ajax/libs/extjs/6.0.0/classic/theme-aria/resources/theme-aria-all.css"
rel = "stylesheet" />
<script type = "text/javascript"
src = "https://cdnjs.cloudflare.com/ajax/libs/extjs/6.0.0/ext-all.js"></script>
<script type = "text/javascript">
Ext.require([
'Ext.grid.*',
'Ext.data.*'
]);
// Creation of data model
Ext.define('StudentDataModel', {
extend: 'Ext.data.Model',
fields: [
{name: 'name', mapping : 'name'},
{name: 'age', mapping : 'age'},
{name: 'marks', mapping : 'marks'}
]
});
Ext.onReady(function() {
// Store data
var myData = [
{ name : "Asha", age : "16", marks : "90" },
{ name : "Vinit", age : "18", marks : "95" },
{ name : "Anand", age : "20", marks : "68" },
{ name : "Niharika", age : "21", marks : "86" },
{ name : "Manali", age : "22", marks : "57" }
];
// Creation of first grid store
var firstGridStore = Ext.create('Ext.data.Store', {
model: 'StudentDataModel',
data: myData
});
// Creation of first grid
var firstGrid = Ext.create('Ext.grid.Panel', {
store : firstGridStore,
columns :
[{
header: "Student Name",
dataIndex: 'name',
id : 'name',
flex: 1,
sortable: true
},{
header: "Age",
dataIndex: 'age',
flex: .5,
sortable: true
},{
header: "Marks",
dataIndex: 'marks',
flex: .5,
sortable: true
}],
stripeRows : true,
title : 'First Grid',
margins : '0 2 0 0'
});
// Creation of a panel to show both the grids.
var displayPanel = Ext.create('Ext.Panel', {
width : 600,
height : 200,
layout : {
type: 'hbox',
align: 'stretch',
padding: 5
},
renderTo : 'panel',
defaults : { flex : 1 },
items : [
firstGrid
]
});
});
</script>
</head>
<body>
<div id = "panel" > </div>
</body>
</html>
The above program will produce the following result. You can use tab and mouse up and down keys for moving the focus across the grid and the theme is basically for the visually impaired people.
Any JavaScript code can be debugged using alert() box or console.log() or with the debug pointer in a debugger.
Place an alert box in the code where you want to check the flow or any variable value. For example, alert('message to show' + variable);
Debugger is the most important tool for any developer to check the issue and error in the code while developing.
Ext JS is a JavaScript framework, hence it can be easily debugged using developer tools provided by or specific to different browsers. All the major browsers have their developer tools available to test and debug JavaScript code.
Popular debuggers are IE development tool for IE, firebug for firefox, and chrome development tool for Chrome browser.
Chrome debugger comes with Chrome browser, however, firebug has to be installed specifically as it doesn’t come as a package with firefox.
Here is a link to install firebug for firefox browser http://getfirebug.com
The shortcut to open the development tool in Windows OS is F12 keyboard key.
There are two ways to debug JavaScript code.
The first way, is to place console.log() in the code and see the value of the log, which will be printed in the console of the development tool.
The first way, is to place console.log() in the code and see the value of the log, which will be printed in the console of the development tool.
The second way is by using breakpoints in the development tool. Following is the process.
Open the file in all the available scripts under script tag.
Now place a breakpoint to the line you want to debug.
Run the application in the browser.
Now, whenever the code flow will reach this line, it will break the code and stay there until the user runs the code by keys F6 (go to the next line of the code), F7 (go inside the function) or F8 (go to the next breakpoint or run the code if there is no more breakpoints) based on the flow you want to debug.
You can select the variable or the function you want to see the value of.
You can use the console to check the value or to check some changes in the browser itself.
The second way is by using breakpoints in the development tool. Following is the process.
Open the file in all the available scripts under script tag.
Open the file in all the available scripts under script tag.
Now place a breakpoint to the line you want to debug.
Now place a breakpoint to the line you want to debug.
Run the application in the browser.
Run the application in the browser.
Now, whenever the code flow will reach this line, it will break the code and stay there until the user runs the code by keys F6 (go to the next line of the code), F7 (go inside the function) or F8 (go to the next breakpoint or run the code if there is no more breakpoints) based on the flow you want to debug.
Now, whenever the code flow will reach this line, it will break the code and stay there until the user runs the code by keys F6 (go to the next line of the code), F7 (go inside the function) or F8 (go to the next breakpoint or run the code if there is no more breakpoints) based on the flow you want to debug.
You can select the variable or the function you want to see the value of.
You can select the variable or the function you want to see the value of.
You can use the console to check the value or to check some changes in the browser itself.
You can use the console to check the value or to check some changes in the browser itself.
Following are a few inbuilt functions, which are heavily used in Ext JS.
This class checks the platform you are using, whether it is a phone or a desktop, a mac or Windows operating system. These are the following methods related to Ext.is class.
Ext.is.Platforms
This function returns the platform available for this version.
For example, when you run the following function, it returns something like this −
[Object { property = "platform", regex = RegExp, identity = "iPhone"},
Object { property = "platform", regex = RegExp, identity = "iPod"},
Object { property = "userAgent", regex = RegExp, identity = "iPad"},
Object { property = "userAgent", regex = RegExp, identity = "Blackberry"},
Object { property = "userAgent", regex = RegExp, identity = "Android"},
Object { property = "platform", regex = RegExp, identity = "Mac"},
Object { property = "platform", regex = RegExp, identity = "Windows"},
Object { property = "platform", regex = RegExp, identity = "Linux"}]
Ext.is.Android
This function will return true, if you are using Android operating system, else it returns false.
Ext.is.Desktop
This function will return true, if you are using a desktop for the application, else it returns false.
Ext.is.Phone
This function will return true, if you are using a mobile, else it returns false.
Ext.is.iPhone
This function will return true if you are using iPhone, else it returns false.
Ext.is.iPod
This function will return true, if you are using iPod, else it returns false.
Ext.is.iPad
This function will return true, if you are using an iPad, else it returns false.
Ext.is.Windows
This function will return true, if you are using Windows operating system, else it returns false.
Ext.is.Linux
This function will return true, if you are using Linux operating system, else it returns false.
Ext.is.Blackberry
This function will return true, if you are using Blackberry, else it returns false.
Ext.is.Mac
This function will return true, if you are using Mac operating system, else it returns false.
As the name indicates, this class provides information if the feature is supported by the current environment of the browser/device or not.
Ext.supports.History
It checks if the device supports HTML 5 history as window.history or not. If the device supports history, then it returns true, else false.
Ext.supports.GeoLocation
It checks if the device supports geolocation method or not. Internally it checks for navigator.geolocation method.
Ext.supports.Svg
It checks if the device supports HTML 5 feature scalable vector graphics (svg) method or not. Internally it checks for doc.createElementNS && !!doc.createElementNS( "http:/" + "/www.w3.org/2000/svg", "svg").createSVGRect.
Ext.supports.Canvas
It checks if the device supports HTML 5 feature canvas to draw method or not. Internally it checks for doc.createElement('canvas').getContext and returns a value based on the output of this method.
Ext.supports.Range
It checks if the browser supports document.createRange method or not.
Ext.String class has various methods to work with string data. The most used methods are encoding decoding, trim, toggle, urlAppend, etc.
Encoding Decoding function − These are the functions available in Ext.String class to encode and decode HTML values.
Ext.String.htmlEncode
This function is used to encode html value to make it parsable.
Example −
Ext.String.htmlEncode("< p > Hello World < /p >");
Output - "< p > Hello World < /p >".
Ext.String.htmlDecode
This function is used to decode the encoded html value.
Example −
Ext.String.htmlDecode("< p > Hello World < /p >");
Output - "< p > Hello World < /p >"
Ext.String.trim
This function is to trim the unwanted space in the string.
Ext.String.trim(' hello ');
Output – "hello"
Ext.String.urlAppend
This method is used to append a value in the URL string.
Example −
Ext.String.urlAppend('https://www.google.com' , 'hello');
Output - "https://www.google.com?hello"
Ext.String.urlAppend('https://www.google.com?index=1' , 'hello');
Output – "https://www.google.com?index=1&hello"
Ext.String.toggle
This function is to toggle the values between two different values.
Example −
var toggleString = 'ASC'
toggleString = Ext.String.toggle(a, 'ASC', 'DESC');
Output – DESC as toggleString had value ASC. Now again, if we
print the same we will get toggleString = “ASC” this time, as
it had value 'DESC'.
It is similar to ternary operator
toggleString = ((toggleString =='ASC')? 'DESC' : 'ASC' );
Ext.userAgent()
This function gives information about browser userAgent. UserAgent is to identify the browser and the operating system to the web server.
Example − If you are working in Mozilla, it returns something like: "mozilla/5.0 (windows nt 6.1; wow64; rv:43.0) gecko/20100101 firefox/43.0"
Version related function
This function returns the version of the browser currently in use, if the function is called related to IE. In Firefox browser, it returns 0. These functions are Ext.firefoxVersion, Ext.ieVersion, etc.
Example − If you are using Firefox browser and you call the method Ext.ieVersion for fetching the version of IE, then it returns 0. If you are using the same method in IE browser, then it will return the version you are using such as 8, 9, etc.
Ext.getVersion()
This function returns the current Ext JS version in use.
Example − If you call Ext.getVersion(), it returns an array of values such as version, short version, etc.
Ext.getVersion().version returns the current version of Ext JS used in the program, such as “4.2.2".
Browser related functions
These functions return Boolean values based on the browser in use. These methods are Ext.isIE, Ext.isIE6, Ext.isFF06, and Ext.isChrome.
Example − If you are using Chrome browser, then the function Ext.isChrome will return true all, otherwise it will return false.
Ext.typeOf()
This function returns the datatype of the variable.
Example −
var a = 5;
var b = 'hello';
Ext.typeOf(a);
Output – Number
Ext.typeOf(b);
Output - String
DataType related methods − These functions return boolean value based on the datatype of the variable
Example −
var a = ['a', 'bc'];
var b = 'hello';
var c = 123;
var emptyVariable;
var definedVariable;
function extraFunction(){return true;}
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2381,
"s": 2023,
"text": "Ext JS is a popular JavaScript framework which provides rich UI for building web applications with cross-browser functionality. Ext JS is basically used for creating desktop applications. It supports all the modern browsers such as IE6+, FF, Chrome, Safari 6+, Opera 12+, etc. Whereas another product of Sencha, Sencha Touch is used for mobile applications."
},
{
"code": null,
"e": 2588,
"s": 2381,
"text": "Ext JS is based on MVC/MVVM architecture. The latest version of Ext JS 6 is a single platform, which can be used for both desktop and mobile application without having different code for different platform."
},
{
"code": null,
"e": 2750,
"s": 2588,
"text": "The first version of Ext JS was developed by Jack Slocum in 2006. It was a set of utility classes, which is an extension of YUI. He named the library as YUI-ext."
},
{
"code": null,
"e": 2961,
"s": 2750,
"text": "Ext JS version 2.0 was released in 2007. This version had a new API documentation for desktop application with limited features. This version doesn’t have backward compatibility with previous version of Ext JS."
},
{
"code": null,
"e": 3131,
"s": 2961,
"text": "Ext JS version 3.0 was released in 2009. This version added new features as chart and list view but at the cost of speed. It had backward compatibility with version 2.0."
},
{
"code": null,
"e": 3381,
"s": 3131,
"text": "After the release of Ext JS 3, the developers of Ext JS had the major challenge of ramping up the speed. Ext JS version 4.0 was released in 2011. It had the complete revised structure, which was followed by MVC architecture and a speedy application."
},
{
"code": null,
"e": 3650,
"s": 3381,
"text": "Ext JS version 5.0 was released in 2014. The major change in this release was to change the MVC architecture to MVVM architecture. It includes the ability to build desktop apps on touch-enabled devices, two-way data binding, responsive layouts, and many more features."
},
{
"code": null,
"e": 3756,
"s": 3650,
"text": "Ext JS 6 merges the Ext JS (for desktop application) and Sencha Touch (for mobile application) framework."
},
{
"code": null,
"e": 3806,
"s": 3756,
"text": "Following are the highlighted features of Ext JS."
},
{
"code": null,
"e": 3907,
"s": 3806,
"text": "Customizable UI widgets with collection of rich UI such as grids, pivot grids, forms, charts, trees."
},
{
"code": null,
"e": 4008,
"s": 3907,
"text": "Customizable UI widgets with collection of rich UI such as grids, pivot grids, forms, charts, trees."
},
{
"code": null,
"e": 4063,
"s": 4008,
"text": "Code compatibility of new versions with the older one."
},
{
"code": null,
"e": 4118,
"s": 4063,
"text": "Code compatibility of new versions with the older one."
},
{
"code": null,
"e": 4247,
"s": 4118,
"text": "A flexible layout manager helps to organize the display of data and content across multiple browsers, devices, and screen sizes."
},
{
"code": null,
"e": 4376,
"s": 4247,
"text": "A flexible layout manager helps to organize the display of data and content across multiple browsers, devices, and screen sizes."
},
{
"code": null,
"e": 4581,
"s": 4376,
"text": "Advance data package decouples the UI widgets from the data layer. The data package allows client-side collection of data using highly functional models that enable features such as sorting and filtering."
},
{
"code": null,
"e": 4786,
"s": 4581,
"text": "Advance data package decouples the UI widgets from the data layer. The data package allows client-side collection of data using highly functional models that enable features such as sorting and filtering."
},
{
"code": null,
"e": 4857,
"s": 4786,
"text": "It is protocol agnostic, and can access data from any back-end source."
},
{
"code": null,
"e": 4928,
"s": 4857,
"text": "It is protocol agnostic, and can access data from any back-end source."
},
{
"code": null,
"e": 5049,
"s": 4928,
"text": "Customizable Themes Ext JS widgets are available in multiple out-of-the-box themes that are consistent across platforms."
},
{
"code": null,
"e": 5170,
"s": 5049,
"text": "Customizable Themes Ext JS widgets are available in multiple out-of-the-box themes that are consistent across platforms."
},
{
"code": null,
"e": 5346,
"s": 5170,
"text": "Sencha Ext JS is the leading standard for business-grade web application development. Ext JS provides the tools necessary to build robust applications for desktop and tablets."
},
{
"code": null,
"e": 5466,
"s": 5346,
"text": "Streamlines cross-platform development across desktops, tablets, and smartphones - for both modern and legacy browsers."
},
{
"code": null,
"e": 5586,
"s": 5466,
"text": "Streamlines cross-platform development across desktops, tablets, and smartphones - for both modern and legacy browsers."
},
{
"code": null,
"e": 5707,
"s": 5586,
"text": "Increases the productivity of development teams by integrating into enterprise development environments via IDE plugins."
},
{
"code": null,
"e": 5828,
"s": 5707,
"text": "Increases the productivity of development teams by integrating into enterprise development environments via IDE plugins."
},
{
"code": null,
"e": 5877,
"s": 5828,
"text": "Reduces the cost of web application development."
},
{
"code": null,
"e": 5926,
"s": 5877,
"text": "Reduces the cost of web application development."
},
{
"code": null,
"e": 5995,
"s": 5926,
"text": "Empowers the teams to create apps with a compelling user experience."
},
{
"code": null,
"e": 6064,
"s": 5995,
"text": "Empowers the teams to create apps with a compelling user experience."
},
{
"code": null,
"e": 6118,
"s": 6064,
"text": "Offers a set of widgets to easily make a powerful UI."
},
{
"code": null,
"e": 6172,
"s": 6118,
"text": "Offers a set of widgets to easily make a powerful UI."
},
{
"code": null,
"e": 6233,
"s": 6172,
"text": "Follows MVC architecture, hence the code is highly readable."
},
{
"code": null,
"e": 6294,
"s": 6233,
"text": "Follows MVC architecture, hence the code is highly readable."
},
{
"code": null,
"e": 6409,
"s": 6294,
"text": "The size of the library is large, around 500 KB, which makes initial loading time more and makes application slow."
},
{
"code": null,
"e": 6524,
"s": 6409,
"text": "The size of the library is large, around 500 KB, which makes initial loading time more and makes application slow."
},
{
"code": null,
"e": 6591,
"s": 6524,
"text": "HTML is full of tags that makes it complex and difficult to debug."
},
{
"code": null,
"e": 6658,
"s": 6591,
"text": "HTML is full of tags that makes it complex and difficult to debug."
},
{
"code": null,
"e": 6780,
"s": 6658,
"text": "According to general public license policy, it is free for open source applications but paid for commercial applications."
},
{
"code": null,
"e": 6902,
"s": 6780,
"text": "According to general public license policy, it is free for open source applications but paid for commercial applications."
},
{
"code": null,
"e": 7014,
"s": 6902,
"text": "Sometimes for loading even simple things require few lines of coding, which is simpler in plain html or JQuery."
},
{
"code": null,
"e": 7126,
"s": 7014,
"text": "Sometimes for loading even simple things require few lines of coding, which is simpler in plain html or JQuery."
},
{
"code": null,
"e": 7195,
"s": 7126,
"text": "Need quite experienced developer for developing Ext JS applications."
},
{
"code": null,
"e": 7264,
"s": 7195,
"text": "Need quite experienced developer for developing Ext JS applications."
},
{
"code": null,
"e": 7379,
"s": 7264,
"text": "Following are the tools provided by Sencha used for Ext JS application development mainly at the production level."
},
{
"code": null,
"e": 7503,
"s": 7379,
"text": "Sencha CMD is a tool which provides the features of Ext JS code minification, scaffolding, and production build generation."
},
{
"code": null,
"e": 7791,
"s": 7503,
"text": "Sencha IDE plugins integrates Sencha frameworks into IntelliJ, WebStorm IDEs, which helps in improving the developer’s productivity by providing features such as code completion, code inspection, code navigation, code generation, code refactoring, template creation, spell-checking, etc."
},
{
"code": null,
"e": 7891,
"s": 7791,
"text": "Sencha Inspector is a debugging tool which helps the debugger to debug any issue while development."
},
{
"code": null,
"e": 8020,
"s": 7891,
"text": "This section guides you on how to download and set up Ext JS on your machine. Please follow the steps to set up the environment."
},
{
"code": null,
"e": 8233,
"s": 8020,
"text": "Download the trial version of Ext JS library files from Sencha https://www.sencha.com. You will get the trial version from the site on your registered mail id, which will be a zipped folder named ext-6.0.1-trial."
},
{
"code": null,
"e": 8390,
"s": 8233,
"text": "Unzip the folder and you will find various JavaScript and CSS files, which you will include in our application. We will mostly include the following files −"
},
{
"code": null,
"e": 8491,
"s": 8390,
"text": "JavaScript Files − JS file which you can find under the folder \\ext-6.0.1-trial\\ext6.0.1\\build are −"
},
{
"code": null,
"e": 8498,
"s": 8491,
"text": "ext.js"
},
{
"code": null,
"e": 8583,
"s": 8498,
"text": "This is the core file which contains all the functionalities to run the application."
},
{
"code": null,
"e": 8594,
"s": 8583,
"text": "ext-all.js"
},
{
"code": null,
"e": 8665,
"s": 8594,
"text": "This file contains all the code minified with no comments in the file."
},
{
"code": null,
"e": 8682,
"s": 8665,
"text": "ext-all-debug.js"
},
{
"code": null,
"e": 8750,
"s": 8682,
"text": "This is the unminified version of ext-all.js for debugging purpose."
},
{
"code": null,
"e": 8765,
"s": 8750,
"text": "ext-all-dev.js"
},
{
"code": null,
"e": 8906,
"s": 8765,
"text": "This file is also unminified and is used for development purpose as it contains all the comments and console logs to check any errors/issue."
},
{
"code": null,
"e": 8917,
"s": 8906,
"text": "ext-all.js"
},
{
"code": null,
"e": 9003,
"s": 8917,
"text": "This file is used for production purpose mostly as it is much smaller than any other."
},
{
"code": null,
"e": 9126,
"s": 9003,
"text": "You can add these files to your projects JS folder or you can provide a direct path where the file resides in your system."
},
{
"code": null,
"e": 9295,
"s": 9126,
"text": "CSS Files − There are number of theme-based files, which you can find under folder \\ext6.0.1-trial\\ext-6.0.1\\build\\classic\\theme-classic\\resources\\theme-classic-all.css"
},
{
"code": null,
"e": 9426,
"s": 9295,
"text": "If you are going to use desktop application, then you can use classic themes under folder \\ext-6.0.1-trial\\ext-6.0.1\\build\\classic"
},
{
"code": null,
"e": 9557,
"s": 9426,
"text": "If you are going to use desktop application, then you can use classic themes under folder \\ext-6.0.1-trial\\ext-6.0.1\\build\\classic"
},
{
"code": null,
"e": 9703,
"s": 9557,
"text": "If we are going to use mobile application, then you can use modern themes which can be found under folder \\ext-6.0.1-trial\\ext-6.0.1\\build\\modern"
},
{
"code": null,
"e": 9849,
"s": 9703,
"text": "If we are going to use mobile application, then you can use modern themes which can be found under folder \\ext-6.0.1-trial\\ext-6.0.1\\build\\modern"
},
{
"code": null,
"e": 9917,
"s": 9849,
"text": "The following library files will be added in an Ext JS application."
},
{
"code": null,
"e": 10294,
"s": 9917,
"text": "<html>\n <head>\n <link rel = \"stylesheet\" type = \"text/css\" \n href = \"..\\ext-6.0.1-trial\\ext-6.0.1\\build\\classic\\theme-classic\\resources\\theme-classic-all.css\" />\n <script type = \"text/javascript\" \n src = \"..\\ext-6.0.1-trial\\ext-6.0.1\\build\\ext-all.js\" > </script>\n <script type = \"text/javascript\" src = \"app.js\" > </script>\n </head>\n</html>"
},
{
"code": null,
"e": 10347,
"s": 10294,
"text": "You will keep ExtJS application code in app.js file."
},
{
"code": null,
"e": 10521,
"s": 10347,
"text": "CDN is content delivery network with which you do not need to download the Ext JS library files, instead you can directly add CDN link for ExtJS to your program as follows −"
},
{
"code": null,
"e": 10927,
"s": 10521,
"text": "<html>\n <head>\n <link rel = \"stylesheet\" type = \"text/css\" \n href = \"https://cdnjs.cloudflare.com/ajax/libs/extjs/6.0.0/classic/theme-crisp/resources/theme-crisp-all.css\" / >\n <script type = \"text/javascript\" \n src = \"https://cdnjs.cloudflare.com/ajax/libs/extjs/6.0.0/ext-all.js\"> </script>\n <script type = \"text/javascript\" src = \"app.js\" > </script> \n </head>\n</html>"
},
{
"code": null,
"e": 11215,
"s": 10927,
"text": "As it is a JavaScript framework, which is used for developing web applications, in our project we will have HTML, JS files. To write our Ext JS programs, we will need a text editor. There are even multiple IDEs available in the market. But for now, we can consider one of the following −"
},
{
"code": null,
"e": 11349,
"s": 11215,
"text": "Notepad − On Windows machine, you can use any simple text editor such as Notepad (Recommended for this tutorial), Notepad++, sublime."
},
{
"code": null,
"e": 11483,
"s": 11349,
"text": "Notepad − On Windows machine, you can use any simple text editor such as Notepad (Recommended for this tutorial), Notepad++, sublime."
},
{
"code": null,
"e": 11606,
"s": 11483,
"text": "Eclipse − It is an IDE developed by the eclipse open-source community and can be downloaded from https://www.eclipse.org/."
},
{
"code": null,
"e": 11729,
"s": 11606,
"text": "Eclipse − It is an IDE developed by the eclipse open-source community and can be downloaded from https://www.eclipse.org/."
},
{
"code": null,
"e": 11815,
"s": 11729,
"text": "Ext JS supports cross-browser compatibility, it supports all major browsers such as −"
},
{
"code": null,
"e": 11830,
"s": 11815,
"text": "IE 6 and above"
},
{
"code": null,
"e": 11852,
"s": 11830,
"text": "Firefox 3.6 and above"
},
{
"code": null,
"e": 11871,
"s": 11852,
"text": "Chrome10 and above"
},
{
"code": null,
"e": 11890,
"s": 11871,
"text": "Safari 4 and above"
},
{
"code": null,
"e": 11909,
"s": 11890,
"text": "Opera 11 and above"
},
{
"code": null,
"e": 11965,
"s": 11909,
"text": "You can use any browser for running Ext JS application."
},
{
"code": null,
"e": 12113,
"s": 11965,
"text": "Naming convention is a set of rule to be followed for identifiers. It makes the code more readable and understandable to other programmers as well."
},
{
"code": null,
"e": 12333,
"s": 12113,
"text": "Naming convention in Ext JS follows the standard JavaScript convention, which is not mandatory but a good practice to follow. It should follow the camel case syntax for naming the class, method, variable and properties."
},
{
"code": null,
"e": 12487,
"s": 12333,
"text": "If the name is combined with two words, the second word will start with an uppercase letter always. For example, doLayout(), StudentForm, firstName, etc."
},
{
"code": null,
"e": 12526,
"s": 12487,
"text": "Ext JS follows MVC/ MVVM architecture."
},
{
"code": null,
"e": 12579,
"s": 12526,
"text": "MVC – Model View Controller architecture (version 4)"
},
{
"code": null,
"e": 12619,
"s": 12579,
"text": "MVVM – Model View Viewmodel (version 5)"
},
{
"code": null,
"e": 12780,
"s": 12619,
"text": "This architecture is not mandatory for the program, however, it is a best practice to follow this structure to make your code highly maintainable and organized."
},
{
"code": null,
"e": 13400,
"s": 12780,
"text": "----------src\n----------resources\n-------------------CSS files\n-------------------Images\n----------JavaScript\n--------------------App Folder\n-------------------------------Controller\n------------------------------------Contoller.js\n-------------------------------Model\n------------------------------------Model.js\n-------------------------------Store\n------------------------------------Store.js\n-------------------------------View\n------------------------------------View.js\n-------------------------------Utils\n------------------------------------Utils.js\n--------------------------------app.js\n-----------HTML files\n"
},
{
"code": null,
"e": 13468,
"s": 13400,
"text": "Ext JS app folder will reside in JavaScript folder of your project."
},
{
"code": null,
"e": 13552,
"s": 13468,
"text": "The App will contain controller, view, model, store, and utility files with app.js."
},
{
"code": null,
"e": 13760,
"s": 13552,
"text": "app.js − The main file from where the flow of program will start, which should be included in the main HTML file using <script> tag. App calls the controller of application for the rest of the functionality."
},
{
"code": null,
"e": 14063,
"s": 13760,
"text": "Controller.js − It is the controller file of Ext JS MVC architecture. This contains all the control of the application, the events listeners, and most of the functionality of the code. It has the path defined for all the other files used in that application such as store, view, model, require, mixins."
},
{
"code": null,
"e": 14259,
"s": 14063,
"text": "View.js − It contains the interface part of the application, which shows up to the user. Ext JS uses various UI rich views, which can be extended and customized here according to the requirement."
},
{
"code": null,
"e": 14478,
"s": 14259,
"text": "Store.js − It contains the data locally cached which is to be rendered on the view with the help of model objects. Store fetches the data using proxies which has the path defined for services to fetch the backend data."
},
{
"code": null,
"e": 14659,
"s": 14478,
"text": "Model.js − It contains the objects which binds the store data to view. It has the mapping of backend data objects to the view dataIndex. The data is fetched with the help of store."
},
{
"code": null,
"e": 14951,
"s": 14659,
"text": "Utils.js − It is not included in MVC architecture but a best practice to use to make the code clean, less complex, and more readable. We can write methods in this file and call them in the controller or the view renderer wherever required. It is helpful for code reusability purpose as well."
},
{
"code": null,
"e": 15014,
"s": 14951,
"text": "In MVVM architecture, the controller is replaced by ViewModel."
},
{
"code": null,
"e": 15239,
"s": 15014,
"text": "ViewModel − It basically mediates the changes between view and model. It binds the data from the model to the view. At the same time, it does not have any direct interaction with the view. It has only knowledge of the model."
},
{
"code": null,
"e": 15505,
"s": 15239,
"text": "For example, if we are using one model object at two-three places in UI. If we change the value at one place of UI, we can see without even saving that change. The value of model changes and so gets reflected in all the places in the UI, wherever the model is used."
},
{
"code": null,
"e": 15609,
"s": 15505,
"text": "It makes the developers’ effort much lesser and easier as no extra coding is required for binding data."
},
{
"code": null,
"e": 15693,
"s": 15609,
"text": "This chapter lists down the steps to write the first Hello World program in Ext JS."
},
{
"code": null,
"e": 15827,
"s": 15693,
"text": "Create an index.htm page in the editor of our choice. Include the required library files in the head section of html page as follows."
},
{
"code": null,
"e": 16584,
"s": 15827,
"text": "<!DOCTYPE html>\n<html>\n <head>\n <link href = \"https://cdnjs.cloudflare.com/ajax/libs/extjs/6.0.0/classic/theme-classic/resources/theme-classic-all.css\" \n rel = \"stylesheet\" />\n <script type = \"text/javascript\" \n src = \"https://cdnjs.cloudflare.com/ajax/libs/extjs/6.0.0/ext-all.js\"></script>\n \n <script type = \"text/javascript\">\n Ext.onReady(function() {\n Ext.create('Ext.Panel', {\n renderTo: 'helloWorldPanel',\n height: 200,\n width: 600,\n title: 'Hello world',\n html: 'First Ext JS Hello World Program'\n });\n });\n </script>\n </head>\n \n <body>\n <div id = \"helloWorldPanel\" />\n </body>\n</html>"
},
{
"code": null,
"e": 16676,
"s": 16584,
"text": "Ext.onReady() method will be called once the Ext JS is ready to render the Ext JS elements."
},
{
"code": null,
"e": 16768,
"s": 16676,
"text": "Ext.onReady() method will be called once the Ext JS is ready to render the Ext JS elements."
},
{
"code": null,
"e": 16891,
"s": 16768,
"text": "Ext.create() method is used to create an object in Ext JS. Here we are creating an object of simple panel class Ext.Panel."
},
{
"code": null,
"e": 17014,
"s": 16891,
"text": "Ext.create() method is used to create an object in Ext JS. Here we are creating an object of simple panel class Ext.Panel."
},
{
"code": null,
"e": 17080,
"s": 17014,
"text": "Ext.Panel is the predefined class in Ext JS for creating a panel."
},
{
"code": null,
"e": 17146,
"s": 17080,
"text": "Ext.Panel is the predefined class in Ext JS for creating a panel."
},
{
"code": null,
"e": 17229,
"s": 17146,
"text": "Every Ext JS class has different properties to perform some basic functionalities."
},
{
"code": null,
"e": 17312,
"s": 17229,
"text": "Every Ext JS class has different properties to perform some basic functionalities."
},
{
"code": null,
"e": 17361,
"s": 17312,
"text": "Ext.Panel class has various properties such as −"
},
{
"code": null,
"e": 17469,
"s": 17361,
"text": "renderTo is the element where this panel has to render. 'helloWorldPanel' is the div id in Index.html file."
},
{
"code": null,
"e": 17577,
"s": 17469,
"text": "renderTo is the element where this panel has to render. 'helloWorldPanel' is the div id in Index.html file."
},
{
"code": null,
"e": 17648,
"s": 17577,
"text": "Height and width properties are for customizing the size of the panel."
},
{
"code": null,
"e": 17719,
"s": 17648,
"text": "Height and width properties are for customizing the size of the panel."
},
{
"code": null,
"e": 17772,
"s": 17719,
"text": "Title property is to provide the title to the panel."
},
{
"code": null,
"e": 17825,
"s": 17772,
"text": "Title property is to provide the title to the panel."
},
{
"code": null,
"e": 17885,
"s": 17825,
"text": "Html property is the html content to be shown in the panel."
},
{
"code": null,
"e": 17945,
"s": 17885,
"text": "Html property is the html content to be shown in the panel."
},
{
"code": null,
"e": 18045,
"s": 17945,
"text": "Open the index.htm file in a standard browser and you will get the following output on the browser."
},
{
"code": null,
"e": 18201,
"s": 18045,
"text": "Ext JS is a JavaScript framework having functionalities of object oriented programming. Ext is the namespace, which encapsulates all the classes in Ext JS."
},
{
"code": null,
"e": 18283,
"s": 18201,
"text": "Ext provides more than 300 classes, which we can use for various functionalities."
},
{
"code": null,
"e": 18340,
"s": 18283,
"text": "Ext.define() is used for defining the classes in Ext JS."
},
{
"code": null,
"e": 18410,
"s": 18340,
"text": "Ext.define(class name, class members/properties, callback function);\n"
},
{
"code": null,
"e": 18546,
"s": 18410,
"text": "Class name is the name of the class according to app structure. For example, appName.folderName.ClassName studentApp.view.StudentView."
},
{
"code": null,
"e": 18602,
"s": 18546,
"text": "Class properties/members defines the behavior of class."
},
{
"code": null,
"e": 18682,
"s": 18602,
"text": "Callback function is optional. It is called when the class has loaded properly."
},
{
"code": null,
"e": 19108,
"s": 18682,
"text": "Ext.define(studentApp.view.StudentDeatilsGrid, {\n extend : 'Ext.grid.GridPanel',\n id : 'studentsDetailsGrid',\n store : 'StudentsDetailsGridStore',\n renderTo : 'studentsDetailsRenderDiv',\n layout : 'fit',\n \n columns : [{\n text : 'Student Name',\n dataIndex : 'studentName'\n },{\n text : 'ID',\n dataIndex : 'studentId'\n },{\n text : 'Department',\n dataIndex : 'department'\n }]\n});"
},
{
"code": null,
"e": 19185,
"s": 19108,
"text": "As like other OOPS based languages, we can create objects in Ext JS as well."
},
{
"code": null,
"e": 19249,
"s": 19185,
"text": "Following are the different ways of creating objects in Ext JS."
},
{
"code": null,
"e": 19317,
"s": 19249,
"text": "var studentObject = new student();\nstudentObject.getStudentName();\n"
},
{
"code": null,
"e": 19487,
"s": 19317,
"text": "Ext.create('Ext.Panel', {\n renderTo : 'helloWorldPanel',\n height : 100,\n width : 100,\n title : 'Hello world',\n html : \t'First Ext JS Hello World Program'\t\t\n});"
},
{
"code": null,
"e": 19572,
"s": 19487,
"text": "Inheritance is the principle of using functionality defined in class A into class B."
},
{
"code": null,
"e": 19627,
"s": 19572,
"text": "In Ext JS, inheritance can be done using two methods −"
},
{
"code": null,
"e": 19721,
"s": 19627,
"text": "Ext.define(studentApp.view.StudentDetailsGrid, {\n extend : 'Ext.grid.GridPanel',\n ...\n});"
},
{
"code": null,
"e": 19818,
"s": 19721,
"text": "Here, our custom class StudentDetailsGrid is using the basic features of Ext JS class GridPanel."
},
{
"code": null,
"e": 19888,
"s": 19818,
"text": "Mixins is a different way of using class A in class B without extend."
},
{
"code": null,
"e": 19953,
"s": 19888,
"text": "mixins : {\n commons : 'DepartmentApp.utils.DepartmentUtils'\n},"
},
{
"code": null,
"e": 20164,
"s": 19953,
"text": "Mixins are added in the controller where we declare all the other classes such as store, view, etc. In this way, we can call DepartmentUtils class and use its functions in the controller or in this application."
},
{
"code": null,
"e": 20502,
"s": 20164,
"text": "Container in Ext JS is the component where we can add other container or child components. These containers can have multiple layout to arrange the components in the containers. We can add or remove the components from the container and from its child elements. Ext.container.Container is the base class for all the containers in Ext JS."
},
{
"code": null,
"e": 20569,
"s": 20502,
"text": "This example shows how to define the components inside a container"
},
{
"code": null,
"e": 20655,
"s": 20569,
"text": "This example shows how to define a container inside a container with other components"
},
{
"code": null,
"e": 20871,
"s": 20655,
"text": "There are various type of containers Ext.panel.Panel, Ext.form.Panel, Ext.tab.Panel and Ext.container.Viewport are frequently used containers in Ext JS. Below are the example which shows how to use these containers."
},
{
"code": null,
"e": 20918,
"s": 20871,
"text": "This example shows a Ext.panel.Panel container"
},
{
"code": null,
"e": 20964,
"s": 20918,
"text": "This example shows a Ext.form.Panel container"
},
{
"code": null,
"e": 21009,
"s": 20964,
"text": "This example shows a Ext.tab.Panel container"
},
{
"code": null,
"e": 21063,
"s": 21009,
"text": "This example shows a Ext.container.Viewport container"
},
{
"code": null,
"e": 21270,
"s": 21063,
"text": "Layout is the way the elements are arranged in a container. It can be horizontal, vertical, or any other. Ext JS has a different layout defined in its library but we can always write custom layouts as well."
},
{
"code": null,
"e": 21350,
"s": 21270,
"text": "This layout allows to position the items using XY coordinates in the container."
},
{
"code": null,
"e": 21457,
"s": 21350,
"text": "This layout allows to place all the items in stack fashion (one on top of the other) inside the container."
},
{
"code": null,
"e": 21573,
"s": 21457,
"text": "This layout gives the privilege to the user to specify the size of each element with respect to the container size."
},
{
"code": null,
"e": 21640,
"s": 21573,
"text": "In this layout various panels are nested and separated by borders."
},
{
"code": null,
"e": 21740,
"s": 21640,
"text": "This is the default layout that decides the layout of the elements based on the number of elements."
},
{
"code": null,
"e": 21934,
"s": 21740,
"text": "This layout arranges different components in tab fashion. Tabs will be displayed on top of the container. Every time only one tab is visible and each tab is considered as a different component."
},
{
"code": null,
"e": 22062,
"s": 21934,
"text": "In this layout, every time the elements come for full container space. There is a bottom tool bar in the wizard for navigation."
},
{
"code": null,
"e": 22259,
"s": 22062,
"text": "This layout is to show multiple columns in the container. We can define a fixed or percentage width to the columns. The percentage width will be calculated based on the full size of the container."
},
{
"code": null,
"e": 22407,
"s": 22259,
"text": "In this layout, the container is filled with a single panel. When there is no specific requirement related to the layout, then this layout is used."
},
{
"code": null,
"e": 22505,
"s": 22407,
"text": "As the name implies, this layout arranges the components in a container in the HTML table format."
},
{
"code": null,
"e": 22613,
"s": 22505,
"text": "This layout allows the element to be distributed in a vertical manner. This is one of the most used layout."
},
{
"code": null,
"e": 22686,
"s": 22613,
"text": "This layout allows the element to be distributed in a horizontal manner."
},
{
"code": null,
"e": 22838,
"s": 22686,
"text": "ExtJS UI is made up of one or many widgets called Components. Ext Js has various UI components defined that can be customised as per your requirements."
},
{
"code": null,
"e": 22903,
"s": 22838,
"text": "Grid component can be used to show the data in a tabular format."
},
{
"code": null,
"e": 22949,
"s": 22903,
"text": "Form widget is to get the data from the user."
},
{
"code": null,
"e": 23018,
"s": 22949,
"text": "Message box is basically used to show data in the form of alert box."
},
{
"code": null,
"e": 23073,
"s": 23018,
"text": "Charts are used to represent data in pictorial format."
},
{
"code": null,
"e": 23144,
"s": 23073,
"text": "Tool tip is used to show some basic information when any event occurs."
},
{
"code": null,
"e": 23225,
"s": 23144,
"text": "This UI widget is to create a window, which should pop up when any event occurs."
},
{
"code": null,
"e": 23370,
"s": 23225,
"text": "HTML Editor is one of the very useful UI component, which is used for styling the data that the user enters in terms of fonts, color, size, etc."
},
{
"code": null,
"e": 23410,
"s": 23370,
"text": "Shows the progress of the backend work."
},
{
"code": null,
"e": 23717,
"s": 23410,
"text": "Drag and drop feature is one of the powerful features added to make the developer’s task easy. A drag operation, essentially, is a click gesture on some UI element, while the mouse button is held down and the mouse is moved. A drop operation occurs when the mouse button is released after a drag operation."
},
{
"code": null,
"e": 23770,
"s": 23717,
"text": "Adding drag and drop class to the draggable targets."
},
{
"code": null,
"e": 23850,
"s": 23770,
"text": "var dd = Ext.create('Ext.dd.DD', el, 'imagesDDGroup', {\n isTarget: false\n});\n"
},
{
"code": null,
"e": 23905,
"s": 23850,
"text": "Adding drag and drop target class to drappable target."
},
{
"code": null,
"e": 24009,
"s": 23905,
"text": "var mainTarget = Ext.create('Ext.dd.DDTarget', 'mainRoom', 'imagesDDGroup', {\n ignoreSelf: false\n});\n"
},
{
"code": null,
"e": 24040,
"s": 24009,
"text": "Following is a simple example."
},
{
"code": null,
"e": 26395,
"s": 24040,
"text": "<!DOCTYPE html>\n<html>\n <head>\n <link href = \"https://cdnjs.cloudflare.com/ajax/libs/extjs/6.0.0/classic/theme-classic/resources/theme-classic-all.css\" \n rel = \"stylesheet\" />\n <script type = \"text/javascript\" \n src = \"https://cdnjs.cloudflare.com/ajax/libs/extjs/6.0.0/ext-all.js\"></script>\n \n <script type = \"text/javascript\">\n Ext.application ({\n launch: function() {\n var images = Ext.get('images').select('img');\n Ext.each(images.elements, function(el) {\n var dd = Ext.create('Ext.dd.DD', el, 'imagesDDGroup', {\n isTarget: false\n });\n });\n }\n }); \n var mainTarget = Ext.create('Ext.dd.DDTarget', 'mainRoom', 'imagesDDGroup', {\n ignoreSelf: false\n });\n </script>\n \n <style>\n #content {\n width:600px;\n height:400px;\n padding:10px;\n border:1px solid #000;\n }\n #images {\n float:left;\n width:40%;\n height:100%;\n border:1px solid Black;\n background-color:rgba(222, 222, 222, 1.0);\n }\n #mainRoom {\n float:left;\n width:55%;\n height:100%;\n margin-left:15px;\n border:1px solid Black;\n background-color:rgba(222, 222, 222, 1.0);\n }\n .image { \n width:64px;\n height:64px;\n margin:10px;\n cursor:pointer;\n border:1px solid Black;\n display: inline-block;\n }\n </style>\n </head>\n \n <body>\n <div id = \"content\"> \n <div id = \"images\"> \n <img src = \"/extjs/images/1.jpg\" class = \"image\" />\n <img src = \"/extjs/images/2.jpg\" class = \"image\" />\n <img src = \"/extjs/images/3.jpg\" class = \"image\" />\n <img src = \"/extjs/images/4.jpg\" class = \"image\" />\n <img src = \"/extjs/images/5.jpg\" class = \"image\" />\n <img src = \"/extjs/images/6.jpg\" class = \"image\" />\n <img src = \"/extjs/images/7.jpg\" class = \"image\" />\n <img src = \"/extjs/images/8.jpg\" class = \"image\" />\n </div>\n <div id = \"mainRoom\"></div>\n </div>\n </body>\n</html>"
},
{
"code": null,
"e": 26449,
"s": 26395,
"text": "The above program will produce the following result −"
},
{
"code": null,
"e": 26610,
"s": 26449,
"text": "With the help of drag and drop in Extjs, we can move data from grid to grid and grid to form. Following are the examples of moving data between grids and forms."
},
{
"code": null,
"e": 26639,
"s": 26610,
"text": "Drag and drop - Grid to Grid"
},
{
"code": null,
"e": 26668,
"s": 26639,
"text": "drag and drop - Grid to Form"
},
{
"code": null,
"e": 26904,
"s": 26668,
"text": "Ext.js provides a number of themes to be used in your applications. You can add a different theme in place of a classic theme and see the difference in the output. This is done simply by replacing the theme CSS file as explained ahead."
},
{
"code": null,
"e": 27001,
"s": 26904,
"text": "Consider your very first Hello World application. Remove the following CSS from the application."
},
{
"code": null,
"e": 27107,
"s": 27001,
"text": "https://cdnjs.cloudflare.com/ajax/libs/extjs/6.0.0/classic/theme-classic/resources/theme-classic-all.css\n"
},
{
"code": null,
"e": 27155,
"s": 27107,
"text": "Add the following CSS to use the Neptune theme."
},
{
"code": null,
"e": 27261,
"s": 27155,
"text": "https://cdnjs.cloudflare.com/ajax/libs/extjs/6.0.0/classic/theme-neptune/resources/theme-neptune-all.css\n"
},
{
"code": null,
"e": 27307,
"s": 27261,
"text": "To see the effect, try the following program."
},
{
"code": null,
"e": 28064,
"s": 27307,
"text": "<!DOCTYPE html>\n<html>\n <head>\n <link href = \"https://cdnjs.cloudflare.com/ajax/libs/extjs/6.0.0/classic/theme-neptune/resources/theme-neptune-all.css\" \n rel = \"stylesheet\" />\n <script type = \"text/javascript\" \n src = \"https://cdnjs.cloudflare.com/ajax/libs/extjs/6.0.0/ext-all.js\"></script>\n \n <script type = \"text/javascript\">\n Ext.onReady(function() {\n Ext.create('Ext.Panel', {\n renderTo: 'helloWorldPanel',\n height: 200,\n width: 600,\n title: 'Hello world',\n html: 'First Ext JS Hello World Program'\n });\n });\n </script>\n </head>\n \n <body>\n <div id = \"helloWorldPanel\" />\n </body>\n</html>"
},
{
"code": null,
"e": 28118,
"s": 28064,
"text": "The above program will produce the following result −"
},
{
"code": null,
"e": 28215,
"s": 28118,
"text": "Consider your very first Hello World application. Remove the following CSS from the application."
},
{
"code": null,
"e": 28321,
"s": 28215,
"text": "https://cdnjs.cloudflare.com/ajax/libs/extjs/6.0.0/classic/theme-classic/resources/theme-classic-all.css\n"
},
{
"code": null,
"e": 28369,
"s": 28321,
"text": "Add the following CSS to use the Neptune theme."
},
{
"code": null,
"e": 28471,
"s": 28369,
"text": "https://cdnjs.cloudflare.com/ajax/libs/extjs/6.0.0/classic/theme-crisp/resources/theme-crisp-all.css\n"
},
{
"code": null,
"e": 28517,
"s": 28471,
"text": "To see the effect, try the following program."
},
{
"code": null,
"e": 29263,
"s": 28517,
"text": "<!DOCTYPE html>\n<html>\n <head>\n <link href = \"https://cdnjs.cloudflare.com/ajax/libs/extjs/6.0.0/classic/theme-crisp/resources/theme-crisp-all.css\" \n rel = \"stylesheet\" />\n <script type = \"text/javascript\" \n src = \"https://cdnjs.cloudflare.com/ajax/libs/extjs/6.0.0/ext-all.js\"></script>\n <script type = \"text/javascript\">\n Ext.onReady(function() {\n Ext.create('Ext.Panel', {\n renderTo: 'helloWorldPanel',\n height: 200,\n width: 600,\n title: 'Hello world',\n html: 'First Ext JS Hello World Program'\n });\n });\n </script>\n </head>\n \n <body>\n <div id = \"helloWorldPanel\" />\n </body>\n</html>"
},
{
"code": null,
"e": 29317,
"s": 29263,
"text": "The above program will produce the following result −"
},
{
"code": null,
"e": 29414,
"s": 29317,
"text": "Consider your very first Hello World application. Remove the following CSS from the application."
},
{
"code": null,
"e": 29520,
"s": 29414,
"text": "https://cdnjs.cloudflare.com/ajax/libs/extjs/6.0.0/classic/theme-classic/resources/theme-classic-all.css\n"
},
{
"code": null,
"e": 29567,
"s": 29520,
"text": "Add the following CSS to use the Triton theme."
},
{
"code": null,
"e": 29671,
"s": 29567,
"text": "https://cdnjs.cloudflare.com/ajax/libs/extjs/6.0.0/classic/theme-triton/resources/theme-triton-all.css\n"
},
{
"code": null,
"e": 29717,
"s": 29671,
"text": "To see the effect, try the following program."
},
{
"code": null,
"e": 30472,
"s": 29717,
"text": "<!DOCTYPE html>\n<html>\n <head>\n <link href = \"https://cdnjs.cloudflare.com/ajax/libs/extjs/6.0.0/classic/theme-triton/resources/theme-triton-all.css\" \n rel = \"stylesheet\" />\n <script type = \"text/javascript\" \n src = \"https://cdnjs.cloudflare.com/ajax/libs/extjs/6.0.0/ext-all.js\"></script>\n \n <script type = \"text/javascript\">\n Ext.onReady(function() {\n Ext.create('Ext.Panel', {\n renderTo: 'helloWorldPanel',\n height: 200,\n width: 600,\n title: 'Hello world',\n html: 'First Ext JS Hello World Program'\n });\n });\n </script>\n </head>\n \n <body>\n <div id = \"helloWorldPanel\" />\n </body>\n</html>"
},
{
"code": null,
"e": 30526,
"s": 30472,
"text": "The above program will produce the following result −"
},
{
"code": null,
"e": 30623,
"s": 30526,
"text": "Consider your very first Hello World application. Remove the following CSS from the application."
},
{
"code": null,
"e": 30729,
"s": 30623,
"text": "https://cdnjs.cloudflare.com/ajax/libs/extjs/6.0.0/classic/theme-classic/resources/theme-classic-all.css\n"
},
{
"code": null,
"e": 30774,
"s": 30729,
"text": "Add the following CSS to use the Gray theme."
},
{
"code": null,
"e": 30874,
"s": 30774,
"text": "https://cdnjs.cloudflare.com/ajax/libs/extjs/6.0.0/classic/theme-gray/resources/theme-gray-all.css\n"
},
{
"code": null,
"e": 30920,
"s": 30874,
"text": "To see the effect, try the following program."
},
{
"code": null,
"e": 31671,
"s": 30920,
"text": "<!DOCTYPE html>\n<html>\n <head>\n <link href = \"https://cdnjs.cloudflare.com/ajax/libs/extjs/6.0.0/classic/theme-gray/resources/theme-gray-all.css\" \n rel = \"stylesheet\" />\n <script type = \"text/javascript\" \n src = \"https://cdnjs.cloudflare.com/ajax/libs/extjs/6.0.0/ext-all.js\"></script>\n \n <script type = \"text/javascript\">\n Ext.onReady(function() {\n Ext.create('Ext.Panel', {\n renderTo: 'helloWorldPanel',\n height: 200,\n width: 600,\n title: 'Hello world',\n html: 'First Ext JS Hello World Program'\n });\n });\n </script>\n </head>\n \n <body>\n <div id = \"helloWorldPanel\" />\n </body>\n</html>"
},
{
"code": null,
"e": 31725,
"s": 31671,
"text": "The above program will produce the following result −"
},
{
"code": null,
"e": 31886,
"s": 31725,
"text": "Events are something which get fired when something happens to the class. For example, when a button is getting clicked or before/after the element is rendered."
},
{
"code": null,
"e": 31918,
"s": 31886,
"text": "Built-in events using listeners"
},
{
"code": null,
"e": 31941,
"s": 31918,
"text": "Attaching events later"
},
{
"code": null,
"e": 31955,
"s": 31941,
"text": "Custom events"
},
{
"code": null,
"e": 32043,
"s": 31955,
"text": "Ext JS provides listener property for writing events and custom events in Ext JS files."
},
{
"code": null,
"e": 32070,
"s": 32043,
"text": "Writing listener in Ext JS"
},
{
"code": null,
"e": 32168,
"s": 32070,
"text": "We will add the listener in the previous program itself by adding a listen property to the panel."
},
{
"code": null,
"e": 33131,
"s": 32168,
"text": "<!DOCTYPE html>\n<html>\n <head>\n <link href = \"https://cdnjs.cloudflare.com/ajax/libs/extjs/6.0.0/classic/theme-neptune/resources/theme-neptune-all.css\" \n rel = \"stylesheet\" />\n <script type = \"text/javascript\" \n src = \"https://cdnjs.cloudflare.com/ajax/libs/extjs/6.0.0/ext-all.js\"></script>\n \n <script type = \"text/javascript\">\n Ext.onReady(function() {\n Ext.create('Ext.Button', {\n renderTo: Ext.getElementById('helloWorldPanel'),\n text: 'My Button',\n \n listeners: {\n click: function() {\n Ext.MessageBox.alert('Alert box', 'Button is clicked');\t\n }\n }\n });\n });\n </script> \n </head>\n \n <body>\n <p> Please click the button to see event listener </p>\n <div id = 'helloWorldPanel' /> <!-- panel will be rendered here-- >\n </body>\n</html>"
},
{
"code": null,
"e": 33185,
"s": 33131,
"text": "The above program will produce the following result −"
},
{
"code": null,
"e": 33232,
"s": 33185,
"text": "Please click the button to see event listener:"
},
{
"code": null,
"e": 33298,
"s": 33232,
"text": "This way we can also write multiple events in listeners property."
},
{
"code": null,
"e": 33335,
"s": 33298,
"text": "Multiple Events in the Same Listener"
},
{
"code": null,
"e": 34537,
"s": 33335,
"text": "<!DOCTYPE html>\n<html>\n <head>\n <link href = \"https://cdnjs.cloudflare.com/ajax/libs/extjs/6.0.0/classic/theme-neptune/resources/theme-neptune-all.css\" \n rel = \"stylesheet\" />\n <script type = \"text/javascript\" \n src = \"https://cdnjs.cloudflare.com/ajax/libs/extjs/6.0.0/ext-all.js\"></script>\n \n <script type = \"text/javascript\">\n Ext.onReady(function() {\n Ext.get('tag2').hide()\n Ext.create('Ext.Button', {\n renderTo: Ext.getElementById('helloWorldPanel'),\n text: 'My Button',\n \n listeners: {\n click: function() {\n this.hide();\n },\n hide: function() {\n Ext.get('tag1').hide();\n Ext.get('tag2').show();\n }\n }\n });\n }); \n </script> \n </head>\n \n <body>\n <div id = \"tag1\">Please click the button to see event listener.</div>\n <div id = \"tag2\">The button was clicked and now it is hidden.</div>\n <div id = 'helloWorldPanel' /> <!-- panel will be rendered here-- >\n </body>\n</html>"
},
{
"code": null,
"e": 34684,
"s": 34537,
"text": "In the previous method of writing events, we have written events in listeners at the time of creating elements. The other way is to attach events."
},
{
"code": null,
"e": 35681,
"s": 34684,
"text": "<!DOCTYPE html>\n<html>\n <head>\n <link href = \"https://cdnjs.cloudflare.com/ajax/libs/extjs/6.0.0/classic/theme-neptune/resources/theme-neptune-all.css\" \n rel = \"stylesheet\" />\n <script type = \"text/javascript\" \n src = \"https://cdnjs.cloudflare.com/ajax/libs/extjs/6.0.0/ext-all.js\"></script>\n \n <script type = \"text/javascript\">\n Ext.onReady(function() {\n var button = Ext.create('Ext.Button', {\n renderTo: Ext.getElementById('helloWorldPanel'),\n text: 'My Button'\n });\n\n // This way we can attach event to the button after the button is created.\n button.on('click', function() {\n Ext.MessageBox.alert('Alert box', 'Button is clicked');\n });\n });\n </script> \n </head>\n \n <body>\n <p> Please click the button to see event listener </p>\n <div id = 'helloWorldPanel' /> <!-- panel will be rendered here-- >\n </body>\n</html>"
},
{
"code": null,
"e": 35735,
"s": 35681,
"text": "The above program will produce the following result −"
},
{
"code": null,
"e": 35782,
"s": 35735,
"text": "Please click the button to see event listener:"
},
{
"code": null,
"e": 35917,
"s": 35782,
"text": "We can write custom events in Ext JS and fire the events with fireEvent method. Following example explains how to write custom events."
},
{
"code": null,
"e": 37030,
"s": 35917,
"text": "<!DOCTYPE html>\n<html>\n <head>\n <link href = \"https://cdnjs.cloudflare.com/ajax/libs/extjs/6.0.0/classic/theme-neptune/resources/theme-neptune-all.css\" \n rel = \"stylesheet\" />\n <script type = \"text/javascript\" \n src = \"https://cdnjs.cloudflare.com/ajax/libs/extjs/6.0.0/ext-all.js\"></script>\n \n <script type = \"text/javascript\">\n Ext.onReady(function() {\n var button = Ext.create('Ext.Button', {\n renderTo: Ext.getElementById('helloWorldPanel'),\n text: 'My Button',\n \n listeners: {\n myEvent: function(button) {\n Ext.MessageBox.alert('Alert box', 'My custom event is called');\n }\n }\n });\n Ext.defer(function() {\n button.fireEvent('myEvent');\n }, 5000);\n }); \n </script> \n </head>\n \n <body>\n <p> The event will be called after 5 seconds when the page is loaded. </p>\n <div id = 'helloWorldPanel' /> <!-- panel will be rendered here-- >\n </body>\n</html>"
},
{
"code": null,
"e": 37229,
"s": 37030,
"text": "Once the page is loaded and the document is ready, the UI page with a button will appear and as we are firing an event after 5 secs, the document is ready. The alert box will appear after 5 seconds."
},
{
"code": null,
"e": 37295,
"s": 37229,
"text": "The event will be called after 5 seconds when the page is loaded."
},
{
"code": null,
"e": 37401,
"s": 37295,
"text": "Here, we have written the custom event 'myEvent' and we are firing events as button.fireEvent(eventName);"
},
{
"code": null,
"e": 37478,
"s": 37401,
"text": "Data package is used for loading and saving all the data in the application."
},
{
"code": null,
"e": 37559,
"s": 37478,
"text": "Data package has numerous number of classes but the most important classes are −"
},
{
"code": null,
"e": 37565,
"s": 37559,
"text": "Model"
},
{
"code": null,
"e": 37571,
"s": 37565,
"text": "Store"
},
{
"code": null,
"e": 37577,
"s": 37571,
"text": "Proxy"
},
{
"code": null,
"e": 37803,
"s": 37577,
"text": "The base class for model is Ext.data.Model. It represents an entity in an application. It binds the store data to view. It has mapping of backend data objects to the view dataIndex. The data is fetched with the help of store."
},
{
"code": null,
"e": 37923,
"s": 37803,
"text": "For creating a model, we need to extend Ext.data.Model class and we need to define the fields, their name, and mapping."
},
{
"code": null,
"e": 38126,
"s": 37923,
"text": "Ext.define('StudentDataModel', {\n extend: 'Ext.data.Model',\n fields: [\n {name: 'name', mapping : 'name'},\n {name: 'age', mapping : 'age'},\n {name: 'marks', mapping : 'marks'}\n ]\n});"
},
{
"code": null,
"e": 38326,
"s": 38126,
"text": "Here, the name should be the same as the dataIndex, which we declare in the view and the mapping should match the data, either static or dynamic from the database, which is to be fetched using store."
},
{
"code": null,
"e": 38576,
"s": 38326,
"text": "The base class for store is Ext.data.Store. It contains the data locally cached, which is to be rendered on view with the help of model objects. Store fetches the data using proxies, which has the path defined for services to fetch the backend data."
},
{
"code": null,
"e": 38635,
"s": 38576,
"text": "Store data can be fetched in two ways - static or dynamic."
},
{
"code": null,
"e": 38732,
"s": 38635,
"text": "For static store, we will have all the data present in the store as shown in the following code."
},
{
"code": null,
"e": 39076,
"s": 38732,
"text": "Ext.create('Ext.data.Store', {\n model: 'StudentDataModel',\n data: [\n { name : \"Asha\", age : \"16\", marks : \"90\" },\n { name : \"Vinit\", age : \"18\", marks : \"95\" },\n { name : \"Anand\", age : \"20\", marks : \"68\" },\n { name : \"Niharika\", age : \"21\", marks : \"86\" },\n { name : \"Manali\", age : \"22\", marks : \"57\" }\n ];\n});"
},
{
"code": null,
"e": 39183,
"s": 39076,
"text": "Dynamic data can be fetched using proxy. We can have proxy which can fetch data from Ajax, Rest, and Json."
},
{
"code": null,
"e": 39316,
"s": 39183,
"text": "The base class for proxy is Ext.data.proxy.Proxy. Proxy is used by Models and Stores to handle the loading and saving of Model data."
},
{
"code": null,
"e": 39347,
"s": 39316,
"text": "There are two types of proxies"
},
{
"code": null,
"e": 39360,
"s": 39347,
"text": "Client Proxy"
},
{
"code": null,
"e": 39373,
"s": 39360,
"text": "Server Proxy"
},
{
"code": null,
"e": 39448,
"s": 39373,
"text": "Client proxies include Memory and Local Storage using HTML5 local storage."
},
{
"code": null,
"e": 39539,
"s": 39448,
"text": "Server proxies handle data from the remote server using Ajax, Json data, and Rest service."
},
{
"code": null,
"e": 39570,
"s": 39539,
"text": "Defining proxies in the server"
},
{
"code": null,
"e": 40070,
"s": 39570,
"text": "Ext.create('Ext.data.Store', {\n model: 'StudentDataModel',\n proxy : {\n type : 'rest',\n actionMethods : {\n read : 'POST' // Get or Post type based on requirement\n },\n url : 'restUrlPathOrJsonFilePath', // here we have to include the rest URL path \n // which fetches data from database or Json file path where the data is stored\n reader: {\n type : 'json', // the type of data which is fetched is of JSON type\n root : 'data'\n },\n }\n});"
},
{
"code": null,
"e": 40215,
"s": 40070,
"text": "Ext.js provides the facility to use different font packages. Font packages are used to add different classes for icons available in the package."
},
{
"code": null,
"e": 40228,
"s": 40215,
"text": "Font-Awesome"
},
{
"code": null,
"e": 40240,
"s": 40228,
"text": "Font-Pictos"
},
{
"code": null,
"e": 40418,
"s": 40240,
"text": "ExtJS new theme, Triton, has an inbuilt font family font-awesome included in the framework itself, hence we do not need any explicit requirement for the font-awesome stylesheet."
},
{
"code": null,
"e": 40493,
"s": 40418,
"text": "Following is an example of using Font-Awesome classes in the Triton theme."
},
{
"code": null,
"e": 40524,
"s": 40493,
"text": "Font-Awesome with Triton theme"
},
{
"code": null,
"e": 40645,
"s": 40524,
"text": "When we are using any other theme apart from Triton, we need or require to add a stylesheet for font-awesome explicitly."
},
{
"code": null,
"e": 40725,
"s": 40645,
"text": "Following is an example of using Font-Awesome classes without the Triton theme."
},
{
"code": null,
"e": 40791,
"s": 40725,
"text": "Font-Awesome with normal theme(Any theme other then Triton theme)"
},
{
"code": null,
"e": 40954,
"s": 40791,
"text": "Font-pictos is not included in the framework for ExtJS, hence we have to require the same. Only licenced users of Sencha will have the benefit to use font-pictos."
},
{
"code": null,
"e": 41018,
"s": 40954,
"text": "Step 1 − Require font-pictos class using the following command."
},
{
"code": null,
"e": 41047,
"s": 41018,
"text": "\"requires\": [\"font-pictos\"]\n"
},
{
"code": null,
"e": 41084,
"s": 41047,
"text": "Step 2 − Now add pictos classes as −"
},
{
"code": null,
"e": 41115,
"s": 41084,
"text": "iconCls: 'pictos pictos-home'\n"
},
{
"code": null,
"e": 41335,
"s": 41115,
"text": "Application Styling refers to user adjustment of the look and feel of the components. These adjustments may include: color, color gradients, font, margins/padding, etc. Ext JS 6 has a new way of styling the application."
},
{
"code": null,
"e": 41630,
"s": 41335,
"text": "It uses SCSS for styling. SCSS is a more dynamic way of writing the CSS code. We can write the variables in our stylesheet with the help of this. However, a browser cannot understand SCSS. It can only understand CSS, hence all SCSS files should get compiled into CSS to a production-ready code."
},
{
"code": null,
"e": 41803,
"s": 41630,
"text": "Thus, SCSS file is called preprocessor files. In Ext.js, compilation is done through Sencha CMD tool. Sencha CMD compiles it manually only once using the following command."
},
{
"code": null,
"e": 41835,
"s": 41803,
"text": "sencha app build [development]\n"
},
{
"code": null,
"e": 42035,
"s": 41835,
"text": "Global_CSS is the main CSS file, which has all SCSS variables associated with it in ExtJS that can be used in our application for customizing our theme by providing different value based on our need."
},
{
"code": null,
"e": 42114,
"s": 42035,
"text": "Following are some of the CSS variables available in the Global_CSS in Ext.js."
},
{
"code": null,
"e": 42126,
"s": 42114,
"text": "$base-color"
},
{
"code": null,
"e": 42174,
"s": 42126,
"text": "$base-color: color (e.g. $base-color : #808080)"
},
{
"code": null,
"e": 42226,
"s": 42174,
"text": "This base color is to be used throughout the theme."
},
{
"code": null,
"e": 42241,
"s": 42226,
"text": "$base-gradient"
},
{
"code": null,
"e": 42296,
"s": 42241,
"text": "$base-gradient: string (e.g. $base-gradient : 'matte')"
},
{
"code": null,
"e": 42351,
"s": 42296,
"text": "This base gradient is to be used throughout the theme."
},
{
"code": null,
"e": 42374,
"s": 42351,
"text": "$body-background-color"
},
{
"code": null,
"e": 42444,
"s": 42374,
"text": "$body-background-color: color (e.g. $body-background-color : #808080)"
},
{
"code": null,
"e": 42583,
"s": 42444,
"text": "Background color to apply to the body element. If set to transparent or 'none', no background-color style will be set on the body element."
},
{
"code": null,
"e": 42590,
"s": 42583,
"text": "$color"
},
{
"code": null,
"e": 42629,
"s": 42590,
"text": "$color : color (e.g. $color : #808080)"
},
{
"code": null,
"e": 42689,
"s": 42629,
"text": "This default text color is to be used throughout the theme."
},
{
"code": null,
"e": 42702,
"s": 42689,
"text": "$font-family"
},
{
"code": null,
"e": 42752,
"s": 42702,
"text": "$font-family : string (e.g. $font-family : arial)"
},
{
"code": null,
"e": 42813,
"s": 42752,
"text": "This default font-family is to be used throughout the theme."
},
{
"code": null,
"e": 42824,
"s": 42813,
"text": "$font-size"
},
{
"code": null,
"e": 42869,
"s": 42824,
"text": "$font-size : number (e.g. $font-size : 9px )"
},
{
"code": null,
"e": 42928,
"s": 42869,
"text": "This default font-size is to be used throughout the theme."
},
{
"code": null,
"e": 42941,
"s": 42928,
"text": "$font-weight"
},
{
"code": null,
"e": 43000,
"s": 42941,
"text": "$font-weight : string/number (e.g. $font-weight : normal )"
},
{
"code": null,
"e": 43061,
"s": 43000,
"text": "This default font-weight is to be used throughout the theme."
},
{
"code": null,
"e": 43079,
"s": 43061,
"text": "$font-weight-bold"
},
{
"code": null,
"e": 43146,
"s": 43079,
"text": "$font-weight-bold : string/number (e.g. $font-weight-bold : bold )"
},
{
"code": null,
"e": 43221,
"s": 43146,
"text": "This default font-weight for bold font is to be used throughout the theme."
},
{
"code": null,
"e": 43237,
"s": 43221,
"text": "$include-chrome"
},
{
"code": null,
"e": 43293,
"s": 43237,
"text": "$include-chrome : boolean (e.g. $include-chrome : true)"
},
{
"code": null,
"e": 43332,
"s": 43293,
"text": "True to include Chrome specific rules."
},
{
"code": null,
"e": 43344,
"s": 43332,
"text": "$include-ff"
},
{
"code": null,
"e": 43392,
"s": 43344,
"text": "$include-ff : boolean (e.g. $include-ff : true)"
},
{
"code": null,
"e": 43432,
"s": 43392,
"text": "True to include Firefox specific rules."
},
{
"code": null,
"e": 43444,
"s": 43432,
"text": "$include-ie"
},
{
"code": null,
"e": 43492,
"s": 43444,
"text": "$include-ie : boolean (e.g. $include-ie : true)"
},
{
"code": null,
"e": 43560,
"s": 43492,
"text": "True to include Internet Explorer specific rules for IE9 and lower."
},
{
"code": null,
"e": 43575,
"s": 43560,
"text": "$include-opera"
},
{
"code": null,
"e": 43629,
"s": 43575,
"text": "$include-opera : boolean (e.g. $include-opera : true)"
},
{
"code": null,
"e": 43667,
"s": 43629,
"text": "True to include Opera specific rules."
},
{
"code": null,
"e": 43683,
"s": 43667,
"text": "$include-safari"
},
{
"code": null,
"e": 43739,
"s": 43683,
"text": "$include-safari : boolean (e.g. $include-safari : true)"
},
{
"code": null,
"e": 43777,
"s": 43739,
"text": "True to include Opera specific rules."
},
{
"code": null,
"e": 43793,
"s": 43777,
"text": "$include-webkit"
},
{
"code": null,
"e": 43849,
"s": 43793,
"text": "$include-webkit : boolean (e.g. $include-webkit : true)"
},
{
"code": null,
"e": 43888,
"s": 43849,
"text": "True to include Webkit specific rules."
},
{
"code": null,
"e": 44035,
"s": 43888,
"text": "Drawing package in ExtJS enables you to draw general purpose graphics. This can be used for graphics that work on all browsers and mobile devices."
},
{
"code": null,
"e": 44086,
"s": 44035,
"text": "This graphics is used to create a circulare shape."
},
{
"code": null,
"e": 44138,
"s": 44086,
"text": "This graphics is used to create a rectanglar shape."
},
{
"code": null,
"e": 44184,
"s": 44138,
"text": "This graphics is used to create an arc shape."
},
{
"code": null,
"e": 44234,
"s": 44184,
"text": "This graphics is used to create an ellipse shape."
},
{
"code": null,
"e": 44291,
"s": 44234,
"text": "This graphics is used to create an elliptical arc shape."
},
{
"code": null,
"e": 44350,
"s": 44291,
"text": "This graphics is used to add an image to your application."
},
{
"code": null,
"e": 44395,
"s": 44350,
"text": "This graphics is used to create a free path."
},
{
"code": null,
"e": 44454,
"s": 44395,
"text": "This graphics is used to add any text to your application."
},
{
"code": null,
"e": 44587,
"s": 44454,
"text": "This property is used to move the starting point in your container, after the graphic is rendered. It can be used with any graphics."
},
{
"code": null,
"e": 44683,
"s": 44587,
"text": "This property is used to add a rotation to the drawing added. It can be used with any graphics."
},
{
"code": null,
"e": 44724,
"s": 44683,
"text": "This graphic is used to create a square."
},
{
"code": null,
"e": 45169,
"s": 44724,
"text": "It is always best to communicate with the users in the language they understand and prefer. Extjs localization package supports over 40 languages such as German, French, Korean, Chinese, etc. It is very simple to implement the locale in ExtJs. You’ll find all of the bundled locale files in the override folder of the ext-locale package. Locale files just overrides that tells Ext JS to replace the default English values of certain components."
},
{
"code": null,
"e": 45278,
"s": 45169,
"text": "The following program is to show the month in different locale to see the effect. Try the following program."
},
{
"code": null,
"e": 47026,
"s": 45278,
"text": "<!DOCTYPE html>\n<html>\n <head>\n <link href = \"https://cdnjs.cloudflare.com/ajax/libs/extjs/6.0.0/classic/theme-classic/resources/theme-classic-all.css\" \n rel = \"stylesheet\" />\n <script type = \"text/javascript\" \n src = \"https://cdnjs.cloudflare.com/ajax/libs/extjs/6.0.0/ext-all.js\"></script>\n <script type = \"text/javascript\" \n src = \"https://cdnjs.cloudflare.com/ajax/libs/extjs/6.0.0/classic/locale/locale-fr.js\"></script>\n \n <script type = \"text/javascript\">\n Ext.onReady(function() {\n var monthArray = Ext.Array.map(Ext.Date.monthNames, function (e) { return [e]; });\n var ds = Ext.create('Ext.data.Store', {\n fields: ['month'],\n remoteSort: true,\n pageSize: 6,\n \n proxy: {\n type: 'memory',\n enablePaging: true,\n data: monthArray,\n reader: {type: 'array'}\n }\n });\n Ext.create('Ext.grid.Panel', {\n renderTo: 'grid',\n id : 'gridId',\n width: 600,\n height: 200,\n title:'Month Browser',\n \n columns:[{\n text: 'Month of the year',\n dataIndex: 'month',\n width: 300\n }],\n store: ds,\n bbar: Ext.create('Ext.toolbar.Paging', {\n pageSize: 6,\n store: ds,\n displayInfo: true\n })\n }); \n Ext.getCmp('gridId').getStore().load();\n });\n </script>\n </head>\n \n <body>\n <div id = \"grid\" />\n </body>\n</html>"
},
{
"code": null,
"e": 47078,
"s": 47026,
"text": "The above program will produce the following result"
},
{
"code": null,
"e": 47452,
"s": 47078,
"text": "For using different locale other than English, we would need to add the locale specific file in our program. Here we are using https://cdnjs.cloudflare.com/ajax/libs/extjs/6.0.0/classic/locale/localefr.js for French. You can use different locale for different languages such as https://cdnjs.cloudflare.com/ajax/libs/extjs/6.0.0/classic/locale/locale-ko.js for korean, etc."
},
{
"code": null,
"e": 47564,
"s": 47452,
"text": "The following program is to show the date picker in Korean locale to see the effect. Try the following program."
},
{
"code": null,
"e": 48314,
"s": 47564,
"text": "<!DOCTYPE html>\n<html>\n <head>\n <link href = \"https://cdnjs.cloudflare.com/ajax/libs/extjs/6.0.0/classic/theme-classic/resources/theme-classic-all.css\" \n rel = \"stylesheet\" />\n <script type = \"text/javascript\" \n src = \"https://cdnjs.cloudflare.com/ajax/libs/extjs/6.0.0/ext-all.js\"></script>\n <script type = \"text/javascript\" \n src = \"https://cdnjs.cloudflare.com/ajax/libs/extjs/6.0.0/classic/locale/locale-ko.js\"></script>\n \n <script type = \"text/javascript\">\n Ext.onReady(function() {\n Ext.create('Ext.picker.Date', {\n renderTo: 'datePicker'\n });\n });\n </script>\n </head>\n \n <body>\n <div id = \"datePicker\" />\n </body>\n</html>"
},
{
"code": null,
"e": 48368,
"s": 48314,
"text": "The above program will produce the following result −"
},
{
"code": null,
"e": 48469,
"s": 48368,
"text": "Following table lists the few locales available in ExtJS and the main file locale URL to be changed."
},
{
"code": null,
"e": 48572,
"s": 48469,
"text": "In general accessibility means availability, the content is accessible means the content is available."
},
{
"code": null,
"e": 48912,
"s": 48572,
"text": "In software terms, the application is accessible means the application is available for all. Here, all means the persons with disabilities, the visually impaired or those who use screen readers to use a computer or those who prefer to navigate using the keyboard instead of using a mouse. navigation with keyboard instead of using a mouse."
},
{
"code": null,
"e": 49003,
"s": 48912,
"text": "Applications which are accessible are called ARIA (Accessible Rich Internet Applications)."
},
{
"code": null,
"e": 49241,
"s": 49003,
"text": "Ext JS is designed to keep this in mind that it should work with all keyboard navigations. It has built-in tab indexing and focus-ability, and it is always on by default so we do not need to add any property to enable this functionality."
},
{
"code": null,
"e": 49523,
"s": 49241,
"text": "This functionality allows all keyboard-enabled components to interact with the user when tabbed into. For example, we can use tab for moving on to the next component instead of a mouse. Same way, we can use shift+tab for moving backward and use enter on the keyboard to click, etc."
},
{
"code": null,
"e": 49583,
"s": 49523,
"text": "Focus is inbuilt in Extjs when using keystroke for tabbing."
},
{
"code": null,
"e": 49671,
"s": 49583,
"text": "Following example shows how to the style changes, when the focus changes with the tabs."
},
{
"code": null,
"e": 51312,
"s": 49671,
"text": "<!DOCTYPE html>\n<html>\n <head>\n <link href = \"https://cdnjs.cloudflare.com/ajax/libs/extjs/6.0.0/classic/theme-crisp/resources/theme-crisp-all.css\" \n rel = \"stylesheet\" />\n <script type = \"text/javascript\" \n src = \"https://cdnjs.cloudflare.com/ajax/libs/extjs/6.0.0/ext-all.js\"></script>\n \n <script type = \"text/javascript\">\n Ext.onReady(function(){\n Ext.create('Ext.Button', {\n renderTo: Ext.getElementById('button1'),\n text: 'Button1',\n \n listeners: {\n click: function() {\n Ext.MessageBox.alert('Alert box', 'Button 1 is clicked');\t\n }\n }\n });\n Ext.create('Ext.Button', {\n renderTo: Ext.getElementById('button2'),\n text: 'Button2',\n \n listeners: {\n click: function() {\n Ext.MessageBox.alert('Alert box', 'Button 2 is clicked');\t\n }\n }\n });\n Ext.create('Ext.Button', {\n renderTo: Ext.getElementById('button3'),\n text: 'Button3',\n \n listeners: {\n click: function() {\n Ext.MessageBox.alert('Alert box', 'Button 3 is clicked');\t\n }\n }\n });\n }); \n </script>\n </head>\n \n <body> <p>Please click the button to see event listener:</p>\n <span id = \"button3\"/>\n <span id = \"button2\"/>\n <span id = \"button1\"/>\n </body>\n</html>"
},
{
"code": null,
"e": 51478,
"s": 51312,
"text": "To see the effect, use tab for moving from the next button and shft+tab for focusing backward. Use enter and see how the focused button's related alert would pop up."
},
{
"code": null,
"e": 51525,
"s": 51478,
"text": "Please click the button to see event listener:"
},
{
"code": null,
"e": 51582,
"s": 51525,
"text": "ExtJS provides the theme aria for the visually impaired."
},
{
"code": null,
"e": 51675,
"s": 51582,
"text": "Following example shows the aria theme which is easily accessible for the visually impaired."
},
{
"code": null,
"e": 54565,
"s": 51675,
"text": "<!DOCTYPE html>\n<html>\n <head>\n <link href = \"https://cdnjs.cloudflare.com/ajax/libs/extjs/6.0.0/classic/theme-aria/resources/theme-aria-all.css\" \n rel = \"stylesheet\" />\n <script type = \"text/javascript\" \n src = \"https://cdnjs.cloudflare.com/ajax/libs/extjs/6.0.0/ext-all.js\"></script>\n \n <script type = \"text/javascript\">\n Ext.require([\n 'Ext.grid.*',\n 'Ext.data.*'\n ]);\n \n // Creation of data model\n Ext.define('StudentDataModel', {\n extend: 'Ext.data.Model',\n fields: [\n {name: 'name', mapping : 'name'},\n {name: 'age', mapping : 'age'},\n {name: 'marks', mapping : 'marks'}\n ]\n });\n\n Ext.onReady(function() {\n // Store data\n var myData = [\n { name : \"Asha\", age : \"16\", marks : \"90\" },\n { name : \"Vinit\", age : \"18\", marks : \"95\" },\n { name : \"Anand\", age : \"20\", marks : \"68\" },\n { name : \"Niharika\", age : \"21\", marks : \"86\" },\n { name : \"Manali\", age : \"22\", marks : \"57\" }\n ];\n \n // Creation of first grid store\n var firstGridStore = Ext.create('Ext.data.Store', {\n model: 'StudentDataModel',\n data: myData\n });\n \n // Creation of first grid\n var firstGrid = Ext.create('Ext.grid.Panel', {\n store : firstGridStore,\n columns :\n [{ \n header: \"Student Name\",\n dataIndex: 'name',\t\n id : 'name', \n flex: 1, \t\t\t\n sortable: true\n },{\n header: \"Age\", \n dataIndex: 'age',\n flex: .5, \n sortable: true\n },{\n header: \"Marks\",\n dataIndex: 'marks',\n flex: .5, \n sortable: true\n }],\n stripeRows : true,\n title : 'First Grid',\n margins : '0 2 0 0'\n });\n \n // Creation of a panel to show both the grids.\n var displayPanel = Ext.create('Ext.Panel', {\n width : 600,\n height : 200,\n \n layout : {\n type: 'hbox',\n align: 'stretch',\n padding: 5\n },\n renderTo : 'panel',\n defaults : { flex : 1 }, \n items : [ \n firstGrid\n ]\n });\n });\n </script>\n </head>\n \n <body>\n <div id = \"panel\" > </div>\n </body>\n</html>"
},
{
"code": null,
"e": 54759,
"s": 54565,
"text": "The above program will produce the following result. You can use tab and mouse up and down keys for moving the focus across the grid and the theme is basically for the visually impaired people."
},
{
"code": null,
"e": 54871,
"s": 54759,
"text": "Any JavaScript code can be debugged using alert() box or console.log() or with the debug pointer in a debugger."
},
{
"code": null,
"e": 55008,
"s": 54871,
"text": "Place an alert box in the code where you want to check the flow or any variable value. For example, alert('message to show' + variable);"
},
{
"code": null,
"e": 55121,
"s": 55008,
"text": "Debugger is the most important tool for any developer to check the issue and error in the code while developing."
},
{
"code": null,
"e": 55351,
"s": 55121,
"text": "Ext JS is a JavaScript framework, hence it can be easily debugged using developer tools provided by or specific to different browsers. All the major browsers have their developer tools available to test and debug JavaScript code."
},
{
"code": null,
"e": 55470,
"s": 55351,
"text": "Popular debuggers are IE development tool for IE, firebug for firefox, and chrome development tool for Chrome browser."
},
{
"code": null,
"e": 55609,
"s": 55470,
"text": "Chrome debugger comes with Chrome browser, however, firebug has to be installed specifically as it doesn’t come as a package with firefox."
},
{
"code": null,
"e": 55685,
"s": 55609,
"text": "Here is a link to install firebug for firefox browser http://getfirebug.com"
},
{
"code": null,
"e": 55762,
"s": 55685,
"text": "The shortcut to open the development tool in Windows OS is F12 keyboard key."
},
{
"code": null,
"e": 55807,
"s": 55762,
"text": "There are two ways to debug JavaScript code."
},
{
"code": null,
"e": 55952,
"s": 55807,
"text": "The first way, is to place console.log() in the code and see the value of the log, which will be printed in the console of the development tool."
},
{
"code": null,
"e": 56097,
"s": 55952,
"text": "The first way, is to place console.log() in the code and see the value of the log, which will be printed in the console of the development tool."
},
{
"code": null,
"e": 56816,
"s": 56097,
"text": "The second way is by using breakpoints in the development tool. Following is the process.\n\nOpen the file in all the available scripts under script tag.\nNow place a breakpoint to the line you want to debug.\nRun the application in the browser.\nNow, whenever the code flow will reach this line, it will break the code and stay there until the user runs the code by keys F6 (go to the next line of the code), F7 (go inside the function) or F8 (go to the next breakpoint or run the code if there is no more breakpoints) based on the flow you want to debug.\nYou can select the variable or the function you want to see the value of.\nYou can use the console to check the value or to check some changes in the browser itself.\n\n"
},
{
"code": null,
"e": 56906,
"s": 56816,
"text": "The second way is by using breakpoints in the development tool. Following is the process."
},
{
"code": null,
"e": 56967,
"s": 56906,
"text": "Open the file in all the available scripts under script tag."
},
{
"code": null,
"e": 57028,
"s": 56967,
"text": "Open the file in all the available scripts under script tag."
},
{
"code": null,
"e": 57082,
"s": 57028,
"text": "Now place a breakpoint to the line you want to debug."
},
{
"code": null,
"e": 57136,
"s": 57082,
"text": "Now place a breakpoint to the line you want to debug."
},
{
"code": null,
"e": 57172,
"s": 57136,
"text": "Run the application in the browser."
},
{
"code": null,
"e": 57208,
"s": 57172,
"text": "Run the application in the browser."
},
{
"code": null,
"e": 57518,
"s": 57208,
"text": "Now, whenever the code flow will reach this line, it will break the code and stay there until the user runs the code by keys F6 (go to the next line of the code), F7 (go inside the function) or F8 (go to the next breakpoint or run the code if there is no more breakpoints) based on the flow you want to debug."
},
{
"code": null,
"e": 57828,
"s": 57518,
"text": "Now, whenever the code flow will reach this line, it will break the code and stay there until the user runs the code by keys F6 (go to the next line of the code), F7 (go inside the function) or F8 (go to the next breakpoint or run the code if there is no more breakpoints) based on the flow you want to debug."
},
{
"code": null,
"e": 57902,
"s": 57828,
"text": "You can select the variable or the function you want to see the value of."
},
{
"code": null,
"e": 57976,
"s": 57902,
"text": "You can select the variable or the function you want to see the value of."
},
{
"code": null,
"e": 58067,
"s": 57976,
"text": "You can use the console to check the value or to check some changes in the browser itself."
},
{
"code": null,
"e": 58158,
"s": 58067,
"text": "You can use the console to check the value or to check some changes in the browser itself."
},
{
"code": null,
"e": 58231,
"s": 58158,
"text": "Following are a few inbuilt functions, which are heavily used in Ext JS."
},
{
"code": null,
"e": 58405,
"s": 58231,
"text": "This class checks the platform you are using, whether it is a phone or a desktop, a mac or Windows operating system. These are the following methods related to Ext.is class."
},
{
"code": null,
"e": 58422,
"s": 58405,
"text": "Ext.is.Platforms"
},
{
"code": null,
"e": 58485,
"s": 58422,
"text": "This function returns the platform available for this version."
},
{
"code": null,
"e": 58568,
"s": 58485,
"text": "For example, when you run the following function, it returns something like this −"
},
{
"code": null,
"e": 59138,
"s": 58568,
"text": "[Object { property = \"platform\", regex = RegExp, identity = \"iPhone\"}, \nObject { property = \"platform\", regex = RegExp, identity = \"iPod\"}, \nObject { property = \"userAgent\", regex = RegExp, identity = \"iPad\"}, \nObject { property = \"userAgent\", regex = RegExp, identity = \"Blackberry\"}, \nObject { property = \"userAgent\", regex = RegExp, identity = \"Android\"}, \nObject { property = \"platform\", regex = RegExp, identity = \"Mac\"}, \nObject { property = \"platform\", regex = RegExp, identity = \"Windows\"}, \nObject { property = \"platform\", regex = RegExp, identity = \"Linux\"}]\n"
},
{
"code": null,
"e": 59153,
"s": 59138,
"text": "Ext.is.Android"
},
{
"code": null,
"e": 59251,
"s": 59153,
"text": "This function will return true, if you are using Android operating system, else it returns false."
},
{
"code": null,
"e": 59266,
"s": 59251,
"text": "Ext.is.Desktop"
},
{
"code": null,
"e": 59369,
"s": 59266,
"text": "This function will return true, if you are using a desktop for the application, else it returns false."
},
{
"code": null,
"e": 59382,
"s": 59369,
"text": "Ext.is.Phone"
},
{
"code": null,
"e": 59464,
"s": 59382,
"text": "This function will return true, if you are using a mobile, else it returns false."
},
{
"code": null,
"e": 59478,
"s": 59464,
"text": "Ext.is.iPhone"
},
{
"code": null,
"e": 59557,
"s": 59478,
"text": "This function will return true if you are using iPhone, else it returns false."
},
{
"code": null,
"e": 59569,
"s": 59557,
"text": "Ext.is.iPod"
},
{
"code": null,
"e": 59647,
"s": 59569,
"text": "This function will return true, if you are using iPod, else it returns false."
},
{
"code": null,
"e": 59659,
"s": 59647,
"text": "Ext.is.iPad"
},
{
"code": null,
"e": 59740,
"s": 59659,
"text": "This function will return true, if you are using an iPad, else it returns false."
},
{
"code": null,
"e": 59755,
"s": 59740,
"text": "Ext.is.Windows"
},
{
"code": null,
"e": 59853,
"s": 59755,
"text": "This function will return true, if you are using Windows operating system, else it returns false."
},
{
"code": null,
"e": 59866,
"s": 59853,
"text": "Ext.is.Linux"
},
{
"code": null,
"e": 59962,
"s": 59866,
"text": "This function will return true, if you are using Linux operating system, else it returns false."
},
{
"code": null,
"e": 59980,
"s": 59962,
"text": "Ext.is.Blackberry"
},
{
"code": null,
"e": 60064,
"s": 59980,
"text": "This function will return true, if you are using Blackberry, else it returns false."
},
{
"code": null,
"e": 60075,
"s": 60064,
"text": "Ext.is.Mac"
},
{
"code": null,
"e": 60169,
"s": 60075,
"text": "This function will return true, if you are using Mac operating system, else it returns false."
},
{
"code": null,
"e": 60309,
"s": 60169,
"text": "As the name indicates, this class provides information if the feature is supported by the current environment of the browser/device or not."
},
{
"code": null,
"e": 60330,
"s": 60309,
"text": "Ext.supports.History"
},
{
"code": null,
"e": 60470,
"s": 60330,
"text": "It checks if the device supports HTML 5 history as window.history or not. If the device supports history, then it returns true, else false."
},
{
"code": null,
"e": 60495,
"s": 60470,
"text": "Ext.supports.GeoLocation"
},
{
"code": null,
"e": 60610,
"s": 60495,
"text": "It checks if the device supports geolocation method or not. Internally it checks for navigator.geolocation method."
},
{
"code": null,
"e": 60627,
"s": 60610,
"text": "Ext.supports.Svg"
},
{
"code": null,
"e": 60849,
"s": 60627,
"text": "It checks if the device supports HTML 5 feature scalable vector graphics (svg) method or not. Internally it checks for doc.createElementNS && !!doc.createElementNS( \"http:/\" + \"/www.w3.org/2000/svg\", \"svg\").createSVGRect."
},
{
"code": null,
"e": 60869,
"s": 60849,
"text": "Ext.supports.Canvas"
},
{
"code": null,
"e": 61067,
"s": 60869,
"text": "It checks if the device supports HTML 5 feature canvas to draw method or not. Internally it checks for doc.createElement('canvas').getContext and returns a value based on the output of this method."
},
{
"code": null,
"e": 61086,
"s": 61067,
"text": "Ext.supports.Range"
},
{
"code": null,
"e": 61156,
"s": 61086,
"text": "It checks if the browser supports document.createRange method or not."
},
{
"code": null,
"e": 61294,
"s": 61156,
"text": "Ext.String class has various methods to work with string data. The most used methods are encoding decoding, trim, toggle, urlAppend, etc."
},
{
"code": null,
"e": 61411,
"s": 61294,
"text": "Encoding Decoding function − These are the functions available in Ext.String class to encode and decode HTML values."
},
{
"code": null,
"e": 61433,
"s": 61411,
"text": "Ext.String.htmlEncode"
},
{
"code": null,
"e": 61497,
"s": 61433,
"text": "This function is used to encode html value to make it parsable."
},
{
"code": null,
"e": 61507,
"s": 61497,
"text": "Example −"
},
{
"code": null,
"e": 61609,
"s": 61507,
"text": "Ext.String.htmlEncode(\"< p > Hello World < /p >\"); \nOutput - \"< p > Hello World < /p >\".\n"
},
{
"code": null,
"e": 61631,
"s": 61609,
"text": "Ext.String.htmlDecode"
},
{
"code": null,
"e": 61687,
"s": 61631,
"text": "This function is used to decode the encoded html value."
},
{
"code": null,
"e": 61697,
"s": 61687,
"text": "Example −"
},
{
"code": null,
"e": 61798,
"s": 61697,
"text": "Ext.String.htmlDecode(\"< p > Hello World < /p >\");\nOutput - \"< p > Hello World < /p >\"\n"
},
{
"code": null,
"e": 61814,
"s": 61798,
"text": "Ext.String.trim"
},
{
"code": null,
"e": 61873,
"s": 61814,
"text": "This function is to trim the unwanted space in the string."
},
{
"code": null,
"e": 61928,
"s": 61873,
"text": "Ext.String.trim(' hello ');\nOutput – \"hello\""
},
{
"code": null,
"e": 61949,
"s": 61928,
"text": "Ext.String.urlAppend"
},
{
"code": null,
"e": 62006,
"s": 61949,
"text": "This method is used to append a value in the URL string."
},
{
"code": null,
"e": 62016,
"s": 62006,
"text": "Example −"
},
{
"code": null,
"e": 62233,
"s": 62016,
"text": "Ext.String.urlAppend('https://www.google.com' , 'hello'); \nOutput - \"https://www.google.com?hello\" \nExt.String.urlAppend('https://www.google.com?index=1' , 'hello'); \nOutput – \"https://www.google.com?index=1&hello\" \n"
},
{
"code": null,
"e": 62251,
"s": 62233,
"text": "Ext.String.toggle"
},
{
"code": null,
"e": 62319,
"s": 62251,
"text": "This function is to toggle the values between two different values."
},
{
"code": null,
"e": 62329,
"s": 62319,
"text": "Example −"
},
{
"code": null,
"e": 62649,
"s": 62329,
"text": "var toggleString = 'ASC' \ntoggleString = Ext.String.toggle(a, 'ASC', 'DESC');\nOutput – DESC as toggleString had value ASC. Now again, if we \nprint the same we will get toggleString = “ASC” this time, as \nit had value 'DESC'. \nIt is similar to ternary operator \ntoggleString = ((toggleString =='ASC')? 'DESC' : 'ASC' );\n"
},
{
"code": null,
"e": 62665,
"s": 62649,
"text": "Ext.userAgent()"
},
{
"code": null,
"e": 62803,
"s": 62665,
"text": "This function gives information about browser userAgent. UserAgent is to identify the browser and the operating system to the web server."
},
{
"code": null,
"e": 62946,
"s": 62803,
"text": "Example − If you are working in Mozilla, it returns something like: \"mozilla/5.0 (windows nt 6.1; wow64; rv:43.0) gecko/20100101 firefox/43.0\""
},
{
"code": null,
"e": 62971,
"s": 62946,
"text": "Version related function"
},
{
"code": null,
"e": 63173,
"s": 62971,
"text": "This function returns the version of the browser currently in use, if the function is called related to IE. In Firefox browser, it returns 0. These functions are Ext.firefoxVersion, Ext.ieVersion, etc."
},
{
"code": null,
"e": 63418,
"s": 63173,
"text": "Example − If you are using Firefox browser and you call the method Ext.ieVersion for fetching the version of IE, then it returns 0. If you are using the same method in IE browser, then it will return the version you are using such as 8, 9, etc."
},
{
"code": null,
"e": 63435,
"s": 63418,
"text": "Ext.getVersion()"
},
{
"code": null,
"e": 63492,
"s": 63435,
"text": "This function returns the current Ext JS version in use."
},
{
"code": null,
"e": 63599,
"s": 63492,
"text": "Example − If you call Ext.getVersion(), it returns an array of values such as version, short version, etc."
},
{
"code": null,
"e": 63700,
"s": 63599,
"text": "Ext.getVersion().version returns the current version of Ext JS used in the program, such as “4.2.2\"."
},
{
"code": null,
"e": 63726,
"s": 63700,
"text": "Browser related functions"
},
{
"code": null,
"e": 63862,
"s": 63726,
"text": "These functions return Boolean values based on the browser in use. These methods are Ext.isIE, Ext.isIE6, Ext.isFF06, and Ext.isChrome."
},
{
"code": null,
"e": 63990,
"s": 63862,
"text": "Example − If you are using Chrome browser, then the function Ext.isChrome will return true all, otherwise it will return false."
},
{
"code": null,
"e": 64003,
"s": 63990,
"text": "Ext.typeOf()"
},
{
"code": null,
"e": 64055,
"s": 64003,
"text": "This function returns the datatype of the variable."
},
{
"code": null,
"e": 64065,
"s": 64055,
"text": "Example −"
},
{
"code": null,
"e": 64162,
"s": 64065,
"text": "var a = 5; \nvar b = 'hello'; \nExt.typeOf(a); \nOutput – Number \nExt.typeOf(b);\nOutput - String"
},
{
"code": null,
"e": 64264,
"s": 64162,
"text": "DataType related methods − These functions return boolean value based on the datatype of the variable"
},
{
"code": null,
"e": 64274,
"s": 64264,
"text": "Example −"
},
{
"code": null,
"e": 64404,
"s": 64274,
"text": "var a = ['a', 'bc'];\nvar b = 'hello';\nvar c = 123;\nvar emptyVariable;\nvar definedVariable;\nfunction extraFunction(){return true;}"
},
{
"code": null,
"e": 64411,
"s": 64404,
"text": " Print"
},
{
"code": null,
"e": 64422,
"s": 64411,
"text": " Add Notes"
}
] |
Predict Lead Score (the Right Way) Using PyCaret | by Moez Ali | Towards Data Science
|
Leads are the driving force of many businesses today. With the advancement of subscription-based business models particularly in the start-up space, the ability to convert leads into paying customers is key to survival. In simple terms, a “lead” represents a potential customer interested in buying your product/service.
Normally when you acquire the lead, either through a third party service or by running a marketing campaign yourself, it typically includes information like:
Name and contact details of the lead
Lead attributes (demographic, social, customer preferences)
Source of origin (Facebook Ad, Website landing page, third party, etc.)
Time spent on the website, number of clicks, etc.
Referral details, etc.
A significant amount of time, money, and effort is spent by marketing and sales departments on lead management, a concept that we will take to encompass the three key phases of lead generation, qualification, and monetization.
Lead generation is the initiation of customer interest or inquiry into the products or services of your business. Leads are created with the intent of converting the interest or inquiry into sales. There is an unlimited number of third-party companies on the internet that promises to generate the best leads. However, you can also do it yourself by running marketing campaigns. The methods for generating leads typically fall under the umbrella of advertising, but may also include non-paid sources such as organic search engine results or referrals from existing customers.
Lead qualification refers to the process of determining which potential customers are most likely to make an actual purchase. It’s an integral part of the sales funnel, which often takes in many leads but only converts a fraction of them. Lead qualification in simple terms means assessing and prioritizing the leads to come up with the likelihood of conversion so that your marketing and sales department can chase the prioritized leads instead of all the leads which can often by in thousands.
Lead conversion is a phase where you finally convert a qualified lead into paying customer. It entails all the marketing practices that stimulate a desire to buy a product or service and push a lead towards a purchasing decision. This is a monetization or closing phase and the outcome of this generally defines the success of the overall marketing campaign.
Imagine your team has many leads (potential customers) but not enough resources to pursue them all. Whether you are a product-led business with tons of freemium users, have a great inbound funnel of leads, or simply an amazing door-to-door sales team, at the end of the day, you need to prioritize the time of your sales teams and give them the “best” leads.
The question is how do you do it so you maximize your win rate?
One simple way of doing this is by analyzing the historic data and look at attributes based on which the leads have converted into sales. For example, there could be a particular country, city, or postal code where leads have converted to sales 90% of the time historically. Similarly, your data can also tell you customers who have spent more than 20 minutes on your website are converted into sales most of the time. Using these business rules you can create a Lead Scoring System that attaches scores (higher the better) to each lead using these business rules.
The problem with this approach is, there is only so much you can cover with business rules. As your business expands, the type and variety of data you can collect will grow exponentially. At some point, a manual rule-based system will not be robust enough to continue to add value.
Here comes Machine Learning
You can approach the Leading Scoring System from a machine learning perspective, where you can train ML models on customer attributes, lead origin, referrals, and other details available and the target will be Lead Converted (Yes or No).
How do you get the target variable? Well, most CRM systems like Salesforce, Zoho, or Microsoft Dynamics can track the individual lead and their status. The status of the lead will help you create the target variable.
One word of caution is you have to make sure that you do not leak any information in the training dataset. For example, your CRM system could store the information regarding referral paid to third-party on lead conversion, imagine if you use that information in your training data, it is technically a leakage as you will only pay a referral fee on conversion, and this is something you know after the fact.
PyCaret is an open-source, low-code machine learning library and end-to-end model management tool in Python to automate machine learning workflows. Using PyCaret you can efficiently build and deploy end-to-end machine learning pipelines. To learn more about PyCaret, check out their GitHub.
# install pycaretpip install pycaret
For this tutorial, I am using a Lead Conversion dataset from Kaggle. The dataset contains over 9,000 leads with customer features such as lead origin, source of lead, total time spent on the website, total visits on the website, demographics information, and the target column Converted (indicating 1 for conversion and 0 for no conversion).
# import librariesimport pandas as pdimport numpy as np# read csv datadata = pd.read_csv('Leads.csv')data.head()
# check data infodata.info()
Notice that there are several columns that have many missing values. There are several ways to deal with missing values. I will leave it for PyCaret to automatically handle the missing values. If you would like to learn more about different methods of imputing missing values in PyCaret, check out this documentation link.
Intuitively time spent on the website and the activity score along with the source of lead are very important information when it comes to lead conversion. Let’s explore the relationship visually:
Notice that leads coming from the “Add Forms” are likely to convert into sales irrespective of the time spent on the website or the score. For lead originated through API or landing page of the website tells a different story. A higher score along with higher time spent on the website is more likely to convert leads into final sales.
Common to all modules in PyCaret, the setup is the first and the only mandatory step in any machine learning experiment performed in PyCaret. This function takes care of all the data preparation required prior to training models. Besides performing some basic default processing tasks, PyCaret also offers a wide array of pre-processing features. To learn more about all the preprocessing functionalities in PyCaret, you can see this link.
# init setupfrom pycaret.classification import *s = setup(data, target = 'Converted', ignore_features = ['Prospect ID', 'Lead Number'])
Upon initializing the setup function in PyCaret, it automatically profiles the dataset and infers the data types for all input variables. If everything is inferred correctly you can press enter to continue. You can also use numeric_features and categorical_features parameter in the setup to force/overwrite the data types.
Also, notice that I have passed ignore_features = ['Prospect ID', 'Lead Number'] in the setup function so that it is not considered when training the models. The good thing about this is PyCaret will not remove the column from the dataset, it will just ignore it behind the scene for model training. As such when you generate predictions at the end, you don’t need to worry about joining IDs back by yourself.
Now that data preparation is done, let’s start the training process by using compare_models functionality. This function trains all the algorithms available in the model library and evaluates multiple performance metrics using cross-validation.
# compare all modelsbest_model = compare_models(sort='AUC')
The best model based on AUC is Catboost Classifierwith an average 10 fold cross-validated AUC of 0.9864.
# print best_model parametersprint(best_model.get_all_params())# except for catboost you can do this:print(best_model)
AUC — ROC curve is a performance measurement for the classification problems at various threshold settings. ROC is a probability curve and AUC represents the degree or measure of separability. It tells how much the model is capable of distinguishing between classes. The higher the AUC, the better the model is at predicting positive and negative classes. While it is very helpful to assess and compare the performance of different models, it is not easy to translate this metric into business value.
# AUC Plotplot_model(best_model, plot = 'auc')
Unlike AUC-ROC, shap values do not tell you anything about model performance but instead, interpret the impact of having a certain value for a given feature in comparison to the prediction we’d make if that feature took some baseline value. In the chart below, the y-axis (left) has all the important features of the model, the x-axis is the Shapley value of associated features and the color scale (on right) is the actual value of the feature. Each dot on a graph at each feature is a customer lead (from the test set) — overlapping each other.
The higher the shap value is (x-axis), the higher the likelihood of positive class (which in this case is conversion). So reading from the top, I will interpret this as leads that are tagged as “will revert after reading the email” has a high shap value compared to the base meaning a higher likelihood of conversion. On the contrary, if you see the tag “Ringing”, is exactly the opposite where shap values are on the left side of the base value i.e. negative shap values meaning that this feature is working against conversion. To get a more detailed understanding of shap values, see this link.
# Shapley Valuesinterpret_model(best_model)
A feature importance plot is just another way to interpret model results. While Shap values only work for complex tree-based model, feature importance plot is more common and can be used for different families of models. Unlike shap values, feature importance does not tell us the impact of the feature on a particular class, it only tells us if the feature is important.
# Feature Importanceplot_model(best_model, plot = 'feature')
The confusion matrix is another way to look at model performance. Out of all the possible tools, this is perhaps the simplest one. It basically compared the predictions with actual labels and divide them into four quadrants:
True Positive (Prediction: Conversion, Actual: Conversion)
True Negative (Prediction: No Conversion, Actual: No Conversion)
False Positive (Prediction: Conversion, Actual: No Conversion)
False Negative (Prediction: No Conversion, Actual: Conversion)
If you sum up all the four quadrants, it will equal the number of customer leads in the test set (1667 + 70 + 84 + 952 = 2,773).
952 customers (bottom right quadrant) are true positives, these are the leads model predicted will convert and they converted;
70 leads are false positive (this is where you might have spent efforts that will go to waste);
84 leads are false negatives i.e. (missed opportunities); and
1,667 leads are true negatives (no impact).
# Confusion Matrixplot_model(best_model, plot = 'confusion_matrix')
So far we have prepared the data for modeling (PyCaret does that automatically when you run the setup function), trained multiple models to select the best model based on the AUC, analyzed performance via different plots such as AUC-ROC, Feature Importance, Confusion Matrix, and Shapley values. However, we haven’t answered the most important question yet:
What’s the business value of this model and why should we use this model?
In order to attach business value to this model, let us make few assumptions:
Lead converted into sales will yield $120 in Revenue for the first year
Time and efforts spent on chasing prioritized leads (as predicted by the model) is $15
Opportunities missed by the model (False negatives) yield negative $120 as opportunity cost (you may or may not add this as this is not the real cost but an opportunity cost, — totally depends on the use case)
If you just do a little maths here, you will arrive at $88,830 in profit. Here’s how:
This may be a good model but it is not a business-smart model as we haven't fed in the assumptions of cost/profit yet. By default, any machine learning algorithm will optimize conventional metrics like AUC. In order to achieve the business goal, we have to train, select, and optimize models using business metrics.
Thanks to PyCaret, it is extremely easy to achieve this using add_metric function.
# create a custom functiondef calculate_profit(y, y_pred): tp = np.where((y_pred==1) & (y==1), (120-15), 0) fp = np.where((y_pred==1) & (y==0), -15, 0) fn = np.where((y_pred==0) & (y==1), -120, 0) return np.sum([tp,fp,fn])# add metric to PyCaretadd_metric('profit', 'Profit', calculate_profit)
Now let’s run compare_models again:
# compare all modelsbest_model = compare_models(sort='Profit')
Notice that a new column Profit is added this time and Catboost Classifier is no more the best model based on Profit. It is Light Gradient Boosting Machine. Although the difference is not material in this example but depending on your data and assumptions, this could be millions of dollars sometimes.
# confusion matrixplot_model(best_model, plot = 'confusion_matrix')
The total number of customers is still the same (2,773 customers in the test set), what’s changed is now how the model is making errors over false positives and false negatives. Let’s put some $ value against it, using the same assumptions (as above):
The profit is now $89,925 compared to $88,830 when Catboost Classifier was used. This is a 1.2% lift which depending on the magnitude and cost of false positive and false negative could translate into millions of dollars. There are few other things you can do on top of this such as tune hyperparameters of your best model by explicitly optimizing Profit instead of AUC, Accuracy, Recall, Precision, or any other conventional metric.
Well, you must be asking now that we have selected the best model, how do I apply this model to new leads to generate the score? Well, that ain’t hard.
# create copy of datadata_new = data.copy()data_new.drop('Converted', axis=1, inplace=True)# generate labels using predict_modelpredict_model(best_model, data=data_new, raw_score=True)
Notice the last three columns are added to the dataset — Label (1 = conversion, 0 = no conversion), Score_0, and Score_1 is the probability for each class between 0 to 1. For example, the first observation Score_0 is 0.9973 meaning 99.7% probability for no conversion.
I am a regular blogger and I mostly write about PyCaret and its use-cases in the real world, If you would like to be notified automatically, you can follow me on Medium, LinkedIn, and Twitter.
There is no limit to what you can achieve using this lightweight workflow automation library in Python. If you find this useful, please do not forget to give us ⭐️ on our GitHub repository.
To hear more about PyCaret follow us on LinkedIn and Youtube.
Join us on our slack channel. Invite link here.
DocumentationBlogGitHubStackOverflowInstall PyCaretNotebook TutorialsContribute in PyCaret
|
[
{
"code": null,
"e": 493,
"s": 172,
"text": "Leads are the driving force of many businesses today. With the advancement of subscription-based business models particularly in the start-up space, the ability to convert leads into paying customers is key to survival. In simple terms, a “lead” represents a potential customer interested in buying your product/service."
},
{
"code": null,
"e": 651,
"s": 493,
"text": "Normally when you acquire the lead, either through a third party service or by running a marketing campaign yourself, it typically includes information like:"
},
{
"code": null,
"e": 688,
"s": 651,
"text": "Name and contact details of the lead"
},
{
"code": null,
"e": 748,
"s": 688,
"text": "Lead attributes (demographic, social, customer preferences)"
},
{
"code": null,
"e": 820,
"s": 748,
"text": "Source of origin (Facebook Ad, Website landing page, third party, etc.)"
},
{
"code": null,
"e": 870,
"s": 820,
"text": "Time spent on the website, number of clicks, etc."
},
{
"code": null,
"e": 893,
"s": 870,
"text": "Referral details, etc."
},
{
"code": null,
"e": 1120,
"s": 893,
"text": "A significant amount of time, money, and effort is spent by marketing and sales departments on lead management, a concept that we will take to encompass the three key phases of lead generation, qualification, and monetization."
},
{
"code": null,
"e": 1696,
"s": 1120,
"text": "Lead generation is the initiation of customer interest or inquiry into the products or services of your business. Leads are created with the intent of converting the interest or inquiry into sales. There is an unlimited number of third-party companies on the internet that promises to generate the best leads. However, you can also do it yourself by running marketing campaigns. The methods for generating leads typically fall under the umbrella of advertising, but may also include non-paid sources such as organic search engine results or referrals from existing customers."
},
{
"code": null,
"e": 2192,
"s": 1696,
"text": "Lead qualification refers to the process of determining which potential customers are most likely to make an actual purchase. It’s an integral part of the sales funnel, which often takes in many leads but only converts a fraction of them. Lead qualification in simple terms means assessing and prioritizing the leads to come up with the likelihood of conversion so that your marketing and sales department can chase the prioritized leads instead of all the leads which can often by in thousands."
},
{
"code": null,
"e": 2551,
"s": 2192,
"text": "Lead conversion is a phase where you finally convert a qualified lead into paying customer. It entails all the marketing practices that stimulate a desire to buy a product or service and push a lead towards a purchasing decision. This is a monetization or closing phase and the outcome of this generally defines the success of the overall marketing campaign."
},
{
"code": null,
"e": 2910,
"s": 2551,
"text": "Imagine your team has many leads (potential customers) but not enough resources to pursue them all. Whether you are a product-led business with tons of freemium users, have a great inbound funnel of leads, or simply an amazing door-to-door sales team, at the end of the day, you need to prioritize the time of your sales teams and give them the “best” leads."
},
{
"code": null,
"e": 2974,
"s": 2910,
"text": "The question is how do you do it so you maximize your win rate?"
},
{
"code": null,
"e": 3539,
"s": 2974,
"text": "One simple way of doing this is by analyzing the historic data and look at attributes based on which the leads have converted into sales. For example, there could be a particular country, city, or postal code where leads have converted to sales 90% of the time historically. Similarly, your data can also tell you customers who have spent more than 20 minutes on your website are converted into sales most of the time. Using these business rules you can create a Lead Scoring System that attaches scores (higher the better) to each lead using these business rules."
},
{
"code": null,
"e": 3821,
"s": 3539,
"text": "The problem with this approach is, there is only so much you can cover with business rules. As your business expands, the type and variety of data you can collect will grow exponentially. At some point, a manual rule-based system will not be robust enough to continue to add value."
},
{
"code": null,
"e": 3849,
"s": 3821,
"text": "Here comes Machine Learning"
},
{
"code": null,
"e": 4087,
"s": 3849,
"text": "You can approach the Leading Scoring System from a machine learning perspective, where you can train ML models on customer attributes, lead origin, referrals, and other details available and the target will be Lead Converted (Yes or No)."
},
{
"code": null,
"e": 4304,
"s": 4087,
"text": "How do you get the target variable? Well, most CRM systems like Salesforce, Zoho, or Microsoft Dynamics can track the individual lead and their status. The status of the lead will help you create the target variable."
},
{
"code": null,
"e": 4712,
"s": 4304,
"text": "One word of caution is you have to make sure that you do not leak any information in the training dataset. For example, your CRM system could store the information regarding referral paid to third-party on lead conversion, imagine if you use that information in your training data, it is technically a leakage as you will only pay a referral fee on conversion, and this is something you know after the fact."
},
{
"code": null,
"e": 5003,
"s": 4712,
"text": "PyCaret is an open-source, low-code machine learning library and end-to-end model management tool in Python to automate machine learning workflows. Using PyCaret you can efficiently build and deploy end-to-end machine learning pipelines. To learn more about PyCaret, check out their GitHub."
},
{
"code": null,
"e": 5040,
"s": 5003,
"text": "# install pycaretpip install pycaret"
},
{
"code": null,
"e": 5382,
"s": 5040,
"text": "For this tutorial, I am using a Lead Conversion dataset from Kaggle. The dataset contains over 9,000 leads with customer features such as lead origin, source of lead, total time spent on the website, total visits on the website, demographics information, and the target column Converted (indicating 1 for conversion and 0 for no conversion)."
},
{
"code": null,
"e": 5495,
"s": 5382,
"text": "# import librariesimport pandas as pdimport numpy as np# read csv datadata = pd.read_csv('Leads.csv')data.head()"
},
{
"code": null,
"e": 5524,
"s": 5495,
"text": "# check data infodata.info()"
},
{
"code": null,
"e": 5847,
"s": 5524,
"text": "Notice that there are several columns that have many missing values. There are several ways to deal with missing values. I will leave it for PyCaret to automatically handle the missing values. If you would like to learn more about different methods of imputing missing values in PyCaret, check out this documentation link."
},
{
"code": null,
"e": 6044,
"s": 5847,
"text": "Intuitively time spent on the website and the activity score along with the source of lead are very important information when it comes to lead conversion. Let’s explore the relationship visually:"
},
{
"code": null,
"e": 6380,
"s": 6044,
"text": "Notice that leads coming from the “Add Forms” are likely to convert into sales irrespective of the time spent on the website or the score. For lead originated through API or landing page of the website tells a different story. A higher score along with higher time spent on the website is more likely to convert leads into final sales."
},
{
"code": null,
"e": 6820,
"s": 6380,
"text": "Common to all modules in PyCaret, the setup is the first and the only mandatory step in any machine learning experiment performed in PyCaret. This function takes care of all the data preparation required prior to training models. Besides performing some basic default processing tasks, PyCaret also offers a wide array of pre-processing features. To learn more about all the preprocessing functionalities in PyCaret, you can see this link."
},
{
"code": null,
"e": 6956,
"s": 6820,
"text": "# init setupfrom pycaret.classification import *s = setup(data, target = 'Converted', ignore_features = ['Prospect ID', 'Lead Number'])"
},
{
"code": null,
"e": 7280,
"s": 6956,
"text": "Upon initializing the setup function in PyCaret, it automatically profiles the dataset and infers the data types for all input variables. If everything is inferred correctly you can press enter to continue. You can also use numeric_features and categorical_features parameter in the setup to force/overwrite the data types."
},
{
"code": null,
"e": 7690,
"s": 7280,
"text": "Also, notice that I have passed ignore_features = ['Prospect ID', 'Lead Number'] in the setup function so that it is not considered when training the models. The good thing about this is PyCaret will not remove the column from the dataset, it will just ignore it behind the scene for model training. As such when you generate predictions at the end, you don’t need to worry about joining IDs back by yourself."
},
{
"code": null,
"e": 7935,
"s": 7690,
"text": "Now that data preparation is done, let’s start the training process by using compare_models functionality. This function trains all the algorithms available in the model library and evaluates multiple performance metrics using cross-validation."
},
{
"code": null,
"e": 7995,
"s": 7935,
"text": "# compare all modelsbest_model = compare_models(sort='AUC')"
},
{
"code": null,
"e": 8100,
"s": 7995,
"text": "The best model based on AUC is Catboost Classifierwith an average 10 fold cross-validated AUC of 0.9864."
},
{
"code": null,
"e": 8219,
"s": 8100,
"text": "# print best_model parametersprint(best_model.get_all_params())# except for catboost you can do this:print(best_model)"
},
{
"code": null,
"e": 8720,
"s": 8219,
"text": "AUC — ROC curve is a performance measurement for the classification problems at various threshold settings. ROC is a probability curve and AUC represents the degree or measure of separability. It tells how much the model is capable of distinguishing between classes. The higher the AUC, the better the model is at predicting positive and negative classes. While it is very helpful to assess and compare the performance of different models, it is not easy to translate this metric into business value."
},
{
"code": null,
"e": 8767,
"s": 8720,
"text": "# AUC Plotplot_model(best_model, plot = 'auc')"
},
{
"code": null,
"e": 9314,
"s": 8767,
"text": "Unlike AUC-ROC, shap values do not tell you anything about model performance but instead, interpret the impact of having a certain value for a given feature in comparison to the prediction we’d make if that feature took some baseline value. In the chart below, the y-axis (left) has all the important features of the model, the x-axis is the Shapley value of associated features and the color scale (on right) is the actual value of the feature. Each dot on a graph at each feature is a customer lead (from the test set) — overlapping each other."
},
{
"code": null,
"e": 9911,
"s": 9314,
"text": "The higher the shap value is (x-axis), the higher the likelihood of positive class (which in this case is conversion). So reading from the top, I will interpret this as leads that are tagged as “will revert after reading the email” has a high shap value compared to the base meaning a higher likelihood of conversion. On the contrary, if you see the tag “Ringing”, is exactly the opposite where shap values are on the left side of the base value i.e. negative shap values meaning that this feature is working against conversion. To get a more detailed understanding of shap values, see this link."
},
{
"code": null,
"e": 9955,
"s": 9911,
"text": "# Shapley Valuesinterpret_model(best_model)"
},
{
"code": null,
"e": 10327,
"s": 9955,
"text": "A feature importance plot is just another way to interpret model results. While Shap values only work for complex tree-based model, feature importance plot is more common and can be used for different families of models. Unlike shap values, feature importance does not tell us the impact of the feature on a particular class, it only tells us if the feature is important."
},
{
"code": null,
"e": 10388,
"s": 10327,
"text": "# Feature Importanceplot_model(best_model, plot = 'feature')"
},
{
"code": null,
"e": 10613,
"s": 10388,
"text": "The confusion matrix is another way to look at model performance. Out of all the possible tools, this is perhaps the simplest one. It basically compared the predictions with actual labels and divide them into four quadrants:"
},
{
"code": null,
"e": 10672,
"s": 10613,
"text": "True Positive (Prediction: Conversion, Actual: Conversion)"
},
{
"code": null,
"e": 10737,
"s": 10672,
"text": "True Negative (Prediction: No Conversion, Actual: No Conversion)"
},
{
"code": null,
"e": 10800,
"s": 10737,
"text": "False Positive (Prediction: Conversion, Actual: No Conversion)"
},
{
"code": null,
"e": 10863,
"s": 10800,
"text": "False Negative (Prediction: No Conversion, Actual: Conversion)"
},
{
"code": null,
"e": 10992,
"s": 10863,
"text": "If you sum up all the four quadrants, it will equal the number of customer leads in the test set (1667 + 70 + 84 + 952 = 2,773)."
},
{
"code": null,
"e": 11119,
"s": 10992,
"text": "952 customers (bottom right quadrant) are true positives, these are the leads model predicted will convert and they converted;"
},
{
"code": null,
"e": 11215,
"s": 11119,
"text": "70 leads are false positive (this is where you might have spent efforts that will go to waste);"
},
{
"code": null,
"e": 11277,
"s": 11215,
"text": "84 leads are false negatives i.e. (missed opportunities); and"
},
{
"code": null,
"e": 11321,
"s": 11277,
"text": "1,667 leads are true negatives (no impact)."
},
{
"code": null,
"e": 11389,
"s": 11321,
"text": "# Confusion Matrixplot_model(best_model, plot = 'confusion_matrix')"
},
{
"code": null,
"e": 11747,
"s": 11389,
"text": "So far we have prepared the data for modeling (PyCaret does that automatically when you run the setup function), trained multiple models to select the best model based on the AUC, analyzed performance via different plots such as AUC-ROC, Feature Importance, Confusion Matrix, and Shapley values. However, we haven’t answered the most important question yet:"
},
{
"code": null,
"e": 11821,
"s": 11747,
"text": "What’s the business value of this model and why should we use this model?"
},
{
"code": null,
"e": 11899,
"s": 11821,
"text": "In order to attach business value to this model, let us make few assumptions:"
},
{
"code": null,
"e": 11971,
"s": 11899,
"text": "Lead converted into sales will yield $120 in Revenue for the first year"
},
{
"code": null,
"e": 12058,
"s": 11971,
"text": "Time and efforts spent on chasing prioritized leads (as predicted by the model) is $15"
},
{
"code": null,
"e": 12268,
"s": 12058,
"text": "Opportunities missed by the model (False negatives) yield negative $120 as opportunity cost (you may or may not add this as this is not the real cost but an opportunity cost, — totally depends on the use case)"
},
{
"code": null,
"e": 12354,
"s": 12268,
"text": "If you just do a little maths here, you will arrive at $88,830 in profit. Here’s how:"
},
{
"code": null,
"e": 12670,
"s": 12354,
"text": "This may be a good model but it is not a business-smart model as we haven't fed in the assumptions of cost/profit yet. By default, any machine learning algorithm will optimize conventional metrics like AUC. In order to achieve the business goal, we have to train, select, and optimize models using business metrics."
},
{
"code": null,
"e": 12753,
"s": 12670,
"text": "Thanks to PyCaret, it is extremely easy to achieve this using add_metric function."
},
{
"code": null,
"e": 13059,
"s": 12753,
"text": "# create a custom functiondef calculate_profit(y, y_pred): tp = np.where((y_pred==1) & (y==1), (120-15), 0) fp = np.where((y_pred==1) & (y==0), -15, 0) fn = np.where((y_pred==0) & (y==1), -120, 0) return np.sum([tp,fp,fn])# add metric to PyCaretadd_metric('profit', 'Profit', calculate_profit)"
},
{
"code": null,
"e": 13095,
"s": 13059,
"text": "Now let’s run compare_models again:"
},
{
"code": null,
"e": 13158,
"s": 13095,
"text": "# compare all modelsbest_model = compare_models(sort='Profit')"
},
{
"code": null,
"e": 13460,
"s": 13158,
"text": "Notice that a new column Profit is added this time and Catboost Classifier is no more the best model based on Profit. It is Light Gradient Boosting Machine. Although the difference is not material in this example but depending on your data and assumptions, this could be millions of dollars sometimes."
},
{
"code": null,
"e": 13528,
"s": 13460,
"text": "# confusion matrixplot_model(best_model, plot = 'confusion_matrix')"
},
{
"code": null,
"e": 13780,
"s": 13528,
"text": "The total number of customers is still the same (2,773 customers in the test set), what’s changed is now how the model is making errors over false positives and false negatives. Let’s put some $ value against it, using the same assumptions (as above):"
},
{
"code": null,
"e": 14214,
"s": 13780,
"text": "The profit is now $89,925 compared to $88,830 when Catboost Classifier was used. This is a 1.2% lift which depending on the magnitude and cost of false positive and false negative could translate into millions of dollars. There are few other things you can do on top of this such as tune hyperparameters of your best model by explicitly optimizing Profit instead of AUC, Accuracy, Recall, Precision, or any other conventional metric."
},
{
"code": null,
"e": 14366,
"s": 14214,
"text": "Well, you must be asking now that we have selected the best model, how do I apply this model to new leads to generate the score? Well, that ain’t hard."
},
{
"code": null,
"e": 14551,
"s": 14366,
"text": "# create copy of datadata_new = data.copy()data_new.drop('Converted', axis=1, inplace=True)# generate labels using predict_modelpredict_model(best_model, data=data_new, raw_score=True)"
},
{
"code": null,
"e": 14820,
"s": 14551,
"text": "Notice the last three columns are added to the dataset — Label (1 = conversion, 0 = no conversion), Score_0, and Score_1 is the probability for each class between 0 to 1. For example, the first observation Score_0 is 0.9973 meaning 99.7% probability for no conversion."
},
{
"code": null,
"e": 15013,
"s": 14820,
"text": "I am a regular blogger and I mostly write about PyCaret and its use-cases in the real world, If you would like to be notified automatically, you can follow me on Medium, LinkedIn, and Twitter."
},
{
"code": null,
"e": 15203,
"s": 15013,
"text": "There is no limit to what you can achieve using this lightweight workflow automation library in Python. If you find this useful, please do not forget to give us ⭐️ on our GitHub repository."
},
{
"code": null,
"e": 15265,
"s": 15203,
"text": "To hear more about PyCaret follow us on LinkedIn and Youtube."
},
{
"code": null,
"e": 15313,
"s": 15265,
"text": "Join us on our slack channel. Invite link here."
}
] |
Variable length arguments for Macros in C
|
We know that we can use variable length arguments for functions in C. For that we have to use ellipsis (...). Similarly for macros, we can use variable length arguments. Here also we have to include ellipsis, The ‘__VA_ARGS__’ is used to handle variable length arguments. Concatenation operator ‘##’ is used to concatenate the variable arguments.
In this example, the Macro will take variable length argument like the printf() or scanf() function. In this macro, we will print the filename, line number, and error messages. The first argument is pr. This is used to determine the priority i.e. whether it is normal info string or error
#include <stdio.h>
#define INFO 1
#define ERR 2
#define STD_OUT stdout
#define STD_ERR stderr
#define LOG_MESSAGE(pr, strm, msg, ...) do {\
char *str;\
if (pr == INFO)\
str = "INFORMATION";\
else if (pr == ERR)\
str = "ERROR";\
fprintf(strm, "[%s] : %s : %d : "msg" \n", \
str, __FILE__, __LINE__, ##__VA_ARGS__);\
} while (0)
int main(void) {
char *s = "Test String";
LOG_MESSAGE(ERR, STD_ERR, "Unable to open the file"); //here normal message will be printed
LOG_MESSAGE(INFO, STD_OUT, "%s is passed as argument", s); //pass string argument
LOG_MESSAGE(INFO, STD_OUT, "%d + %d = %d", 14, 16, (14 + 16)); //Provide integer
}
[ERROR] : D:\text.c : 21 : Unable to open the file
[INFORMATION] : D:\text.c : 23 : Test String is passed as argument
[INFORMATION] : D:\text.c : 25 : 14 + 16 = 30
|
[
{
"code": null,
"e": 1409,
"s": 1062,
"text": "We know that we can use variable length arguments for functions in C. For that we have to use ellipsis (...). Similarly for macros, we can use variable length arguments. Here also we have to include ellipsis, The ‘__VA_ARGS__’ is used to handle variable length arguments. Concatenation operator ‘##’ is used to concatenate the variable arguments."
},
{
"code": null,
"e": 1698,
"s": 1409,
"text": "In this example, the Macro will take variable length argument like the printf() or scanf() function. In this macro, we will print the filename, line number, and error messages. The first argument is pr. This is used to determine the priority i.e. whether it is normal info string or error"
},
{
"code": null,
"e": 2369,
"s": 1698,
"text": "#include <stdio.h>\n#define INFO 1\n#define ERR 2\n#define STD_OUT stdout\n#define STD_ERR stderr\n#define LOG_MESSAGE(pr, strm, msg, ...) do {\\\n char *str;\\\n if (pr == INFO)\\\n str = \"INFORMATION\";\\\n else if (pr == ERR)\\\n str = \"ERROR\";\\\n fprintf(strm, \"[%s] : %s : %d : \"msg\" \\n\", \\\n str, __FILE__, __LINE__, ##__VA_ARGS__);\\\n} while (0)\nint main(void) {\n char *s = \"Test String\";\n LOG_MESSAGE(ERR, STD_ERR, \"Unable to open the file\"); //here normal message will be printed\n LOG_MESSAGE(INFO, STD_OUT, \"%s is passed as argument\", s); //pass string argument\n LOG_MESSAGE(INFO, STD_OUT, \"%d + %d = %d\", 14, 16, (14 + 16)); //Provide integer\n}"
},
{
"code": null,
"e": 2533,
"s": 2369,
"text": "[ERROR] : D:\\text.c : 21 : Unable to open the file\n[INFORMATION] : D:\\text.c : 23 : Test String is passed as argument\n[INFORMATION] : D:\\text.c : 25 : 14 + 16 = 30"
}
] |
Class getResourceAsStream() method in Java with Examples - GeeksforGeeks
|
27 Dec, 2019
The getResourceAsStream() method of java.lang.Class class is used to get the resource with the specified resource of this class. The method returns the specified resource of this class in the form of InputStream object.
Syntax:
public InputStream getResourceAsStream(String resourceName)
Parameter: This method accepts a parameter resourceName which is the resource to get.
Return Value: This method returns the specified resource of this class in the form of InputStream objects.
Exception This method throws:
NullPointerException if name is null
Below programs demonstrate the getResourceAsStream() method.
Example 1:
// Java program to demonstrate// getResourceAsStream() method import java.util.*; public class Test { public Object obj; public static void main(String[] args) throws ClassNotFoundException { // returns the Class object for this class Class myClass = Class.forName("Test"); System.out.println("Class represented by myClass: " + myClass.toString()); String resourceName = "obj"; // Get the resource of myClass // using getResourceAsStream() method System.out.println( resourceName + " resource of myClass: " + myClass.getResourceAsStream(resourceName)); }}
Class represented by myClass: class Test
obj resource of myClass: null
Example 2:
// Java program to demonstrate// getResourceAsStream() method import java.util.*; class Main { private Object obj; public static void main(String[] args) throws ClassNotFoundException, NoSuchFieldException { // returns the Class object for this class Class myClass = Class.forName("Main"); System.out.println("Class represented by myClass: " + myClass.toString()); String resourceName = "obj"; try { // Get the resource of myClass // using getResourceAsStream() method System.out.println( resourceName + " resource of myClass: " + myClass.getResourceAsStream(resourceName)); } catch (Exception e) { System.out.println(e); } }}
Class represented by myClass: class Main
obj resource of myClass: null
Reference: https://docs.oracle.com/javase/9/docs/api/java/lang/Class.html#getResourceAsStream-java.lang.String-
Java-Functions
Java-lang package
Java.lang.Class
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Initialize an ArrayList in Java
Object Oriented Programming (OOPs) Concept in Java
Interfaces in Java
How to iterate any Map in Java
ArrayList in Java
Multidimensional Arrays in Java
Stack Class in Java
Stream In Java
Singleton Class in Java
Set in Java
|
[
{
"code": null,
"e": 24672,
"s": 24644,
"text": "\n27 Dec, 2019"
},
{
"code": null,
"e": 24892,
"s": 24672,
"text": "The getResourceAsStream() method of java.lang.Class class is used to get the resource with the specified resource of this class. The method returns the specified resource of this class in the form of InputStream object."
},
{
"code": null,
"e": 24900,
"s": 24892,
"text": "Syntax:"
},
{
"code": null,
"e": 24961,
"s": 24900,
"text": "public InputStream getResourceAsStream(String resourceName)\n"
},
{
"code": null,
"e": 25047,
"s": 24961,
"text": "Parameter: This method accepts a parameter resourceName which is the resource to get."
},
{
"code": null,
"e": 25154,
"s": 25047,
"text": "Return Value: This method returns the specified resource of this class in the form of InputStream objects."
},
{
"code": null,
"e": 25184,
"s": 25154,
"text": "Exception This method throws:"
},
{
"code": null,
"e": 25221,
"s": 25184,
"text": "NullPointerException if name is null"
},
{
"code": null,
"e": 25282,
"s": 25221,
"text": "Below programs demonstrate the getResourceAsStream() method."
},
{
"code": null,
"e": 25293,
"s": 25282,
"text": "Example 1:"
},
{
"code": "// Java program to demonstrate// getResourceAsStream() method import java.util.*; public class Test { public Object obj; public static void main(String[] args) throws ClassNotFoundException { // returns the Class object for this class Class myClass = Class.forName(\"Test\"); System.out.println(\"Class represented by myClass: \" + myClass.toString()); String resourceName = \"obj\"; // Get the resource of myClass // using getResourceAsStream() method System.out.println( resourceName + \" resource of myClass: \" + myClass.getResourceAsStream(resourceName)); }}",
"e": 25979,
"s": 25293,
"text": null
},
{
"code": null,
"e": 26051,
"s": 25979,
"text": "Class represented by myClass: class Test\nobj resource of myClass: null\n"
},
{
"code": null,
"e": 26062,
"s": 26051,
"text": "Example 2:"
},
{
"code": "// Java program to demonstrate// getResourceAsStream() method import java.util.*; class Main { private Object obj; public static void main(String[] args) throws ClassNotFoundException, NoSuchFieldException { // returns the Class object for this class Class myClass = Class.forName(\"Main\"); System.out.println(\"Class represented by myClass: \" + myClass.toString()); String resourceName = \"obj\"; try { // Get the resource of myClass // using getResourceAsStream() method System.out.println( resourceName + \" resource of myClass: \" + myClass.getResourceAsStream(resourceName)); } catch (Exception e) { System.out.println(e); } }}",
"e": 26878,
"s": 26062,
"text": null
},
{
"code": null,
"e": 26950,
"s": 26878,
"text": "Class represented by myClass: class Main\nobj resource of myClass: null\n"
},
{
"code": null,
"e": 27062,
"s": 26950,
"text": "Reference: https://docs.oracle.com/javase/9/docs/api/java/lang/Class.html#getResourceAsStream-java.lang.String-"
},
{
"code": null,
"e": 27077,
"s": 27062,
"text": "Java-Functions"
},
{
"code": null,
"e": 27095,
"s": 27077,
"text": "Java-lang package"
},
{
"code": null,
"e": 27111,
"s": 27095,
"text": "Java.lang.Class"
},
{
"code": null,
"e": 27116,
"s": 27111,
"text": "Java"
},
{
"code": null,
"e": 27121,
"s": 27116,
"text": "Java"
},
{
"code": null,
"e": 27219,
"s": 27121,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27251,
"s": 27219,
"text": "Initialize an ArrayList in Java"
},
{
"code": null,
"e": 27302,
"s": 27251,
"text": "Object Oriented Programming (OOPs) Concept in Java"
},
{
"code": null,
"e": 27321,
"s": 27302,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 27352,
"s": 27321,
"text": "How to iterate any Map in Java"
},
{
"code": null,
"e": 27370,
"s": 27352,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 27402,
"s": 27370,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 27422,
"s": 27402,
"text": "Stack Class in Java"
},
{
"code": null,
"e": 27437,
"s": 27422,
"text": "Stream In Java"
},
{
"code": null,
"e": 27461,
"s": 27437,
"text": "Singleton Class in Java"
}
] |
Count triplets with sum smaller than X | Practice | GeeksforGeeks
|
Given an array arr[] of distinct integers of size N and a value sum, the task is to find the count of triplets (i, j, k), having (i<j<k) with the sum of (arr[i] + arr[j] + arr[k]) smaller than the given value sum.
Example 1:
Input: N = 4, sum = 2
arr[] = {-2, 0, 1, 3}
Output: 2
Explanation: Below are triplets with
sum less than 2 (-2, 0, 1) and (-2, 0, 3).
Example 2:
Input: N = 5, sum = 12
arr[] = {5, 1, 3, 4, 7}
Output: 4
Explanation: Below are triplets with
sum less than 12 (1, 3, 4), (1, 3, 5),
(1, 3, 7) and (1, 4, 5).
Your Task:
This is a function problem. You don't need to take any input, as it is already accomplished by the driver code. You just need to complete the function countTriplets() that take array arr[], integer N and integer sum as parameters and returns the count of triplets.
Expected Time Complexity: O(N2).
Expected Auxiliary Space: O(1).
0
yuvrajranabtcse205 days ago
C++ ans in n^2 timecomplexiblity
int ans=0,right,lastdrop=n-1,ques; sort(arr,arr+n); for(int i=0;i<n-2;i++){ lastdrop=n-1; //this loop will have o(n) time complexibilty...therefore total=n^2 for(int j=i+1;j<=lastdrop;j++){ right=lastdrop; while(j<right){ ques=arr[i]+arr[j]+arr[right]; if(ques>=sum){ right-=1; lastdrop=right; } else if(ques<sum){ ans+=(right-j); lastdrop=right; break; } } } } return ans;}
0
gaurav119087902 weeks ago
class Solution{ long countTriplets(long ar[], int n,int sum) { long count=0; long res=0; Arrays.sort(ar); for(int i=n-1;i>=0;i--){ res=isPair(ar,0, i-1, sum-ar[i]); if(res>0){ count+=res; } res=0; } return count; } static long isPair(long ar[], int l, int r, long sum){ long res=0; while(l<r){ if(ar[l]+ar[r]<sum){ res++; l++; r--; } else if(ar[l]+ar[r]<=sum){ r--; } } return res; }}I am getting TLE. Why ?
0
anushkay009212 weeks ago
long countTriplets(long arr[], int n,int sum)
{
int count = 0 ;
Arrays.sort(arr);
for(int i = 0 ; i < n ; i++)
{
if(arr[i] < sum)
{
int j = i+1 ; int k = n-1;
while(j < k)
{
if(sum > arr[i] + arr[j] + arr[k])
{
count = count + (k - j);
j++;
}
else k--;
}
}
}
return count;
}
0
aasif23643 weeks ago
{ sort(arr , arr+n); long long cnt=0; for(int i=0 ; i<n-2 ; i++){ int j=i+1; int k=n-1; while(j < k){ long long s = arr[i] + arr[j] + arr[k]; if(s < sum){ cnt+=(k-j); j++; } else{ k--; } } } return cnt;}
+2
kunal7073 weeks ago
class Solution
{
long countTriplets(long arr[], int n,int sum)
{
Arrays.sort(arr);
int count=0;
for(int i=0;i<arr.length;i++){
int start=i+1;
int end=n-1;
while(start<end){
if(arr[i]+arr[start]+arr[end]>=sum){
end--;
}
else{
count+=end-start;
start++;
}
}
}
return count;
}
}
+1
dev1711 month ago
Simple C++ O(n^2), two pointers
#define ll long long
long long countTriplets(long long arr[], int n, long long sum)
{
ll ans=0;
sort(arr,arr+n);
for(int i=0;i<n-2;i++){
ll sum1=sum-arr[i];
int s=i+1,e=n-1;
while(s<e){
ll sum2=arr[s]+arr[e];
if(sum2<sum1){
ans+=e-s;
s++;
}else{
e--;
}
}
}
return ans;
}
0
zindgi barbad ho gya2 months ago
Solution is getting accepted even if (i < j < k) condition mentioned in question does not met.
Editorial also does not mention about the condition and the editorial solution is directly applicable here.
0
zindgi barbad ho gya
This comment was deleted.
+1
dipanshusharma93132 months ago
// java solution
class Solution{ long countTriplets(long arr[], int n,int sum) { Arrays.sort(arr); long t = 0; for(int i=0;i<n;i++){ int a = i+1; int b = n-1; while(a<b){ if(arr[i]+arr[a]+arr[b]<sum){ t = t+b-a; a++; } else{ b--; } } } return t; }}
+1
abhijain52 months ago
long long countTriplets(long long arr[], int n, long long sum)
{
sort(arr,arr+n);
long long count=0;
for(long long i=0;i<=n-3;i++)
{
for(long long low=i+1,high=n-1;low<high;)
{
long long s=arr[i]+arr[low]+arr[high];
if(s<sum)
{
count+=(high-low);
low++;
}
else
high--;
}
}
return count;
}
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
want to view the editorial?
Login to access your submissions.
Problem
Contest
Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.
|
[
{
"code": null,
"e": 452,
"s": 238,
"text": "Given an array arr[] of distinct integers of size N and a value sum, the task is to find the count of triplets (i, j, k), having (i<j<k) with the sum of (arr[i] + arr[j] + arr[k]) smaller than the given value sum."
},
{
"code": null,
"e": 464,
"s": 452,
"text": "\nExample 1:"
},
{
"code": null,
"e": 603,
"s": 464,
"text": "\nInput: N = 4, sum = 2\narr[] = {-2, 0, 1, 3}\nOutput: 2\nExplanation: Below are triplets with \nsum less than 2 (-2, 0, 1) and (-2, 0, 3). \n"
},
{
"code": null,
"e": 616,
"s": 605,
"text": "Example 2:"
},
{
"code": null,
"e": 778,
"s": 616,
"text": "\nInput: N = 5, sum = 12\narr[] = {5, 1, 3, 4, 7}\nOutput: 4\nExplanation: Below are triplets with \nsum less than 12 (1, 3, 4), (1, 3, 5), \n(1, 3, 7) and (1, 4, 5).\n"
},
{
"code": null,
"e": 1056,
"s": 778,
"text": "\nYour Task:\nThis is a function problem. You don't need to take any input, as it is already accomplished by the driver code. You just need to complete the function countTriplets() that take array arr[], integer N and integer sum as parameters and returns the count of triplets."
},
{
"code": null,
"e": 1122,
"s": 1056,
"text": "\nExpected Time Complexity: O(N2).\nExpected Auxiliary Space: O(1)."
},
{
"code": null,
"e": 1124,
"s": 1122,
"text": "0"
},
{
"code": null,
"e": 1152,
"s": 1124,
"text": "yuvrajranabtcse205 days ago"
},
{
"code": null,
"e": 1185,
"s": 1152,
"text": "C++ ans in n^2 timecomplexiblity"
},
{
"code": null,
"e": 1755,
"s": 1187,
"text": "int ans=0,right,lastdrop=n-1,ques; sort(arr,arr+n); for(int i=0;i<n-2;i++){ lastdrop=n-1; //this loop will have o(n) time complexibilty...therefore total=n^2 for(int j=i+1;j<=lastdrop;j++){ right=lastdrop; while(j<right){ ques=arr[i]+arr[j]+arr[right]; if(ques>=sum){ right-=1; lastdrop=right; } else if(ques<sum){ ans+=(right-j); lastdrop=right; break; } } } } return ans;} "
},
{
"code": null,
"e": 1757,
"s": 1755,
"text": "0"
},
{
"code": null,
"e": 1783,
"s": 1757,
"text": "gaurav119087902 weeks ago"
},
{
"code": null,
"e": 2422,
"s": 1783,
"text": "class Solution{ long countTriplets(long ar[], int n,int sum) { long count=0; long res=0; Arrays.sort(ar); for(int i=n-1;i>=0;i--){ res=isPair(ar,0, i-1, sum-ar[i]); if(res>0){ count+=res; } res=0; } return count; } static long isPair(long ar[], int l, int r, long sum){ long res=0; while(l<r){ if(ar[l]+ar[r]<sum){ res++; l++; r--; } else if(ar[l]+ar[r]<=sum){ r--; } } return res; }}I am getting TLE. Why ?"
},
{
"code": null,
"e": 2426,
"s": 2424,
"text": "0"
},
{
"code": null,
"e": 2451,
"s": 2426,
"text": "anushkay009212 weeks ago"
},
{
"code": null,
"e": 2986,
"s": 2451,
"text": " long countTriplets(long arr[], int n,int sum)\n {\n int count = 0 ;\n Arrays.sort(arr);\n for(int i = 0 ; i < n ; i++)\n {\n if(arr[i] < sum)\n {\n int j = i+1 ; int k = n-1;\n while(j < k)\n {\n if(sum > arr[i] + arr[j] + arr[k])\n {\n count = count + (k - j);\n j++;\n }\n else k--;\n }\n }\n }\n return count;\n }"
},
{
"code": null,
"e": 2988,
"s": 2986,
"text": "0"
},
{
"code": null,
"e": 3009,
"s": 2988,
"text": "aasif23643 weeks ago"
},
{
"code": null,
"e": 3382,
"s": 3009,
"text": " { sort(arr , arr+n); long long cnt=0; for(int i=0 ; i<n-2 ; i++){ int j=i+1; int k=n-1; while(j < k){ long long s = arr[i] + arr[j] + arr[k]; if(s < sum){ cnt+=(k-j); j++; } else{ k--; } } } return cnt;}"
},
{
"code": null,
"e": 3385,
"s": 3382,
"text": "+2"
},
{
"code": null,
"e": 3405,
"s": 3385,
"text": "kunal7073 weeks ago"
},
{
"code": null,
"e": 4028,
"s": 3405,
"text": "class Solution\n{\n long countTriplets(long arr[], int n,int sum)\n {\n Arrays.sort(arr); \n \n int count=0;\n for(int i=0;i<arr.length;i++){\n \n int start=i+1;\n int end=n-1;\n \n \n while(start<end){\n \n if(arr[i]+arr[start]+arr[end]>=sum){\n end--;\n \n }\n else{\n count+=end-start;\n start++;\n }\n \n }\n \n }\n\n return count;\n }\n}"
},
{
"code": null,
"e": 4031,
"s": 4028,
"text": "+1"
},
{
"code": null,
"e": 4049,
"s": 4031,
"text": "dev1711 month ago"
},
{
"code": null,
"e": 4081,
"s": 4049,
"text": "Simple C++ O(n^2), two pointers"
},
{
"code": null,
"e": 4675,
"s": 4081,
"text": "\t#define ll long long \n\tlong long countTriplets(long long arr[], int n, long long sum)\n\t{\n ll ans=0;\n sort(arr,arr+n);\n for(int i=0;i<n-2;i++){\n ll sum1=sum-arr[i];\n int s=i+1,e=n-1;\n while(s<e){\n ll sum2=arr[s]+arr[e];\n if(sum2<sum1){\n ans+=e-s;\n s++;\n }else{\n e--;\n }\n \n \n }\n }\n return ans;\n\t}"
},
{
"code": null,
"e": 4677,
"s": 4675,
"text": "0"
},
{
"code": null,
"e": 4710,
"s": 4677,
"text": "zindgi barbad ho gya2 months ago"
},
{
"code": null,
"e": 4806,
"s": 4710,
"text": "Solution is getting accepted even if (i < j < k) condition mentioned in question does not met. "
},
{
"code": null,
"e": 4914,
"s": 4806,
"text": "Editorial also does not mention about the condition and the editorial solution is directly applicable here."
},
{
"code": null,
"e": 4916,
"s": 4914,
"text": "0"
},
{
"code": null,
"e": 4937,
"s": 4916,
"text": "zindgi barbad ho gya"
},
{
"code": null,
"e": 4963,
"s": 4937,
"text": "This comment was deleted."
},
{
"code": null,
"e": 4966,
"s": 4963,
"text": "+1"
},
{
"code": null,
"e": 4997,
"s": 4966,
"text": "dipanshusharma93132 months ago"
},
{
"code": null,
"e": 5014,
"s": 4997,
"text": "// java solution"
},
{
"code": null,
"e": 5430,
"s": 5014,
"text": "class Solution{ long countTriplets(long arr[], int n,int sum) { Arrays.sort(arr); long t = 0; for(int i=0;i<n;i++){ int a = i+1; int b = n-1; while(a<b){ if(arr[i]+arr[a]+arr[b]<sum){ t = t+b-a; a++; } else{ b--; } } } return t; }}"
},
{
"code": null,
"e": 5433,
"s": 5430,
"text": "+1"
},
{
"code": null,
"e": 5455,
"s": 5433,
"text": "abhijain52 months ago"
},
{
"code": null,
"e": 5912,
"s": 5455,
"text": "long long countTriplets(long long arr[], int n, long long sum)\n\t{\n\t sort(arr,arr+n);\n\t long long count=0;\n\t for(long long i=0;i<=n-3;i++)\n\t {\n\t for(long long low=i+1,high=n-1;low<high;)\n\t {\n\t long long s=arr[i]+arr[low]+arr[high];\n\t if(s<sum)\n\t {\n\t count+=(high-low);\n\t low++;\n\t }\n\t else\n\t high--;\n\t }\n\t }\n\t return count;\n\t}"
},
{
"code": null,
"e": 6058,
"s": 5912,
"text": "We strongly recommend solving this problem on your own before viewing its editorial. Do you still\n want to view the editorial?"
},
{
"code": null,
"e": 6094,
"s": 6058,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 6104,
"s": 6094,
"text": "\nProblem\n"
},
{
"code": null,
"e": 6114,
"s": 6104,
"text": "\nContest\n"
},
{
"code": null,
"e": 6177,
"s": 6114,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 6325,
"s": 6177,
"text": "Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values."
},
{
"code": null,
"e": 6533,
"s": 6325,
"text": "Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints."
},
{
"code": null,
"e": 6639,
"s": 6533,
"text": "You can access the hints to get an idea about what is expected of you as well as the final solution code."
}
] |
C library function - toupper()
|
The C library function int toupper(int c) converts lowercase letter to uppercase.
Following is the declaration for toupper() function.
int toupper(int c);
c − This is the letter to be converted to uppercase.
c − This is the letter to be converted to uppercase.
This function returns uppercase equivalent to c, if such value exists, else c remains unchanged. The value is returned as an int value that can be implicitly casted to char.
The following example shows the usage of toupper() function.
#include <stdio.h>
#include <ctype.h>
int main () {
int i = 0;
char c;
char str[] = "Tutorials Point";
while(str[i]) {
putchar (toupper(str[i]));
i++;
}
return(0);
}
Let us compile and run the above program to produce the following result −
TUTORIALS POINT
12 Lectures
2 hours
Nishant Malik
12 Lectures
2.5 hours
Nishant Malik
48 Lectures
6.5 hours
Asif Hussain
12 Lectures
2 hours
Richa Maheshwari
20 Lectures
3.5 hours
Vandana Annavaram
44 Lectures
1 hours
Amit Diwan
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2089,
"s": 2007,
"text": "The C library function int toupper(int c) converts lowercase letter to uppercase."
},
{
"code": null,
"e": 2142,
"s": 2089,
"text": "Following is the declaration for toupper() function."
},
{
"code": null,
"e": 2162,
"s": 2142,
"text": "int toupper(int c);"
},
{
"code": null,
"e": 2215,
"s": 2162,
"text": "c − This is the letter to be converted to uppercase."
},
{
"code": null,
"e": 2268,
"s": 2215,
"text": "c − This is the letter to be converted to uppercase."
},
{
"code": null,
"e": 2442,
"s": 2268,
"text": "This function returns uppercase equivalent to c, if such value exists, else c remains unchanged. The value is returned as an int value that can be implicitly casted to char."
},
{
"code": null,
"e": 2503,
"s": 2442,
"text": "The following example shows the usage of toupper() function."
},
{
"code": null,
"e": 2708,
"s": 2503,
"text": "#include <stdio.h>\n#include <ctype.h>\n\nint main () {\n int i = 0;\n char c;\n char str[] = \"Tutorials Point\";\n \n while(str[i]) {\n putchar (toupper(str[i]));\n i++;\n }\n \n return(0);\n}"
},
{
"code": null,
"e": 2783,
"s": 2708,
"text": "Let us compile and run the above program to produce the following result −"
},
{
"code": null,
"e": 2800,
"s": 2783,
"text": "TUTORIALS POINT\n"
},
{
"code": null,
"e": 2833,
"s": 2800,
"text": "\n 12 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 2848,
"s": 2833,
"text": " Nishant Malik"
},
{
"code": null,
"e": 2883,
"s": 2848,
"text": "\n 12 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 2898,
"s": 2883,
"text": " Nishant Malik"
},
{
"code": null,
"e": 2933,
"s": 2898,
"text": "\n 48 Lectures \n 6.5 hours \n"
},
{
"code": null,
"e": 2947,
"s": 2933,
"text": " Asif Hussain"
},
{
"code": null,
"e": 2980,
"s": 2947,
"text": "\n 12 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 2998,
"s": 2980,
"text": " Richa Maheshwari"
},
{
"code": null,
"e": 3033,
"s": 2998,
"text": "\n 20 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 3052,
"s": 3033,
"text": " Vandana Annavaram"
},
{
"code": null,
"e": 3085,
"s": 3052,
"text": "\n 44 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 3097,
"s": 3085,
"text": " Amit Diwan"
},
{
"code": null,
"e": 3104,
"s": 3097,
"text": " Print"
},
{
"code": null,
"e": 3115,
"s": 3104,
"text": " Add Notes"
}
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.