title
stringlengths
3
221
text
stringlengths
17
477k
parsed
listlengths
0
3.17k
PyQt5 QCalendarWidget - Killing the timer - GeeksforGeeks
26 Jan, 2022 In this article we will see how we can kill the timer of the QCalendarWidget. In order to start the timer we use startTimer method, this method calls the timerEvent after the certain interval is passed. It starts a timer and returns a timer identifier, or returns zero if it could not start a timer. In order to do this we will use killTimer method with the QCalendarWidget object. Syntax : calendar.killTimer(timer_id) Argument : It takes integer as argument i.e timer ID Return : It return None Implementation Steps : :1. Create a Calendar class that inherits the QCalendarWidget2. Inside the Calendar class override the timerEvent and inside the event show the next month of calendar3. Create a main window class4. Create a Calendar object inside the main window5. Set various properties to the calendar6. Create a push button7. Add action to the push button, inside the action kill the timer Below is the implementation Python3 # importing librariesfrom PyQt5.QtWidgets import * from PyQt5 import QtCore, QtGuifrom PyQt5.QtGui import * from PyQt5.QtCore import * import sys # QCalendarWidget Classclass Calendar(QCalendarWidget): # constructor def __init__(self, parent = None): super(Calendar, self).__init__(parent) # overriding the timer event # this will show the next month def timerEvent(self, event): # show the next month window.calendar.showNextMonth() class Window(QMainWindow): def __init__(self): super().__init__() # setting title self.setWindowTitle("Python ") # setting geometry self.setGeometry(100, 100, 650, 400) # calling method self.UiComponents() # showing all the widgets self.show() # method for components def UiComponents(self): # creating a QCalendarWidget object # as Calendar class inherits QCalendarWidget self.calendar = Calendar(self) # setting geometry to the calendar self.calendar.setGeometry(50, 10, 400, 250) # setting cursor self.calendar.setCursor(Qt.PointingHandCursor) # starting the calendar timer # passing 1000 milliseconds as parameter self.timer_id = self.calendar.startTimer(1000) # creating a push button push = QPushButton("Kill Timer", self) # setting geometry to the push button push.setGeometry(100, 280, 120, 40) # adding action to the push button push.clicked.connect(self.do_Action) def do_Action(self): # killing the timer self.calendar.killTimer(self.timer_id) # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec()) Output: sagartomar9927 Python PyQt-QCalendarWidget Python-gui Python-PyQt Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Enumerate() in Python How to Install PIP on Windows ? Different ways to create Pandas Dataframe Python String | replace() Create a Pandas DataFrame from Lists Reading and Writing to text files in Python sum() function in Python *args and **kwargs in Python Print lists in Python (4 Different Ways)
[ { "code": null, "e": 24494, "s": 24466, "text": "\n26 Jan, 2022" }, { "code": null, "e": 24794, "s": 24494, "text": "In this article we will see how we can kill the timer of the QCalendarWidget. In order to start the timer we use startTimer method, this method calls the timerEvent after the certain interval is passed. It starts a timer and returns a timer identifier, or returns zero if it could not start a timer." }, { "code": null, "e": 24876, "s": 24794, "text": "In order to do this we will use killTimer method with the QCalendarWidget object." }, { "code": null, "e": 24914, "s": 24876, "text": "Syntax : calendar.killTimer(timer_id)" }, { "code": null, "e": 24967, "s": 24914, "text": "Argument : It takes integer as argument i.e timer ID" }, { "code": null, "e": 24991, "s": 24967, "text": "Return : It return None" }, { "code": null, "e": 25390, "s": 24991, "text": "Implementation Steps : :1. Create a Calendar class that inherits the QCalendarWidget2. Inside the Calendar class override the timerEvent and inside the event show the next month of calendar3. Create a main window class4. Create a Calendar object inside the main window5. Set various properties to the calendar6. Create a push button7. Add action to the push button, inside the action kill the timer" }, { "code": null, "e": 25418, "s": 25390, "text": "Below is the implementation" }, { "code": null, "e": 25426, "s": 25418, "text": "Python3" }, { "code": "# importing librariesfrom PyQt5.QtWidgets import * from PyQt5 import QtCore, QtGuifrom PyQt5.QtGui import * from PyQt5.QtCore import * import sys # QCalendarWidget Classclass Calendar(QCalendarWidget): # constructor def __init__(self, parent = None): super(Calendar, self).__init__(parent) # overriding the timer event # this will show the next month def timerEvent(self, event): # show the next month window.calendar.showNextMonth() class Window(QMainWindow): def __init__(self): super().__init__() # setting title self.setWindowTitle(\"Python \") # setting geometry self.setGeometry(100, 100, 650, 400) # calling method self.UiComponents() # showing all the widgets self.show() # method for components def UiComponents(self): # creating a QCalendarWidget object # as Calendar class inherits QCalendarWidget self.calendar = Calendar(self) # setting geometry to the calendar self.calendar.setGeometry(50, 10, 400, 250) # setting cursor self.calendar.setCursor(Qt.PointingHandCursor) # starting the calendar timer # passing 1000 milliseconds as parameter self.timer_id = self.calendar.startTimer(1000) # creating a push button push = QPushButton(\"Kill Timer\", self) # setting geometry to the push button push.setGeometry(100, 280, 120, 40) # adding action to the push button push.clicked.connect(self.do_Action) def do_Action(self): # killing the timer self.calendar.killTimer(self.timer_id) # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec())", "e": 27267, "s": 25426, "text": null }, { "code": null, "e": 27275, "s": 27267, "text": "Output:" }, { "code": null, "e": 27290, "s": 27275, "text": "sagartomar9927" }, { "code": null, "e": 27318, "s": 27290, "text": "Python PyQt-QCalendarWidget" }, { "code": null, "e": 27329, "s": 27318, "text": "Python-gui" }, { "code": null, "e": 27341, "s": 27329, "text": "Python-PyQt" }, { "code": null, "e": 27348, "s": 27341, "text": "Python" }, { "code": null, "e": 27446, "s": 27348, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27464, "s": 27446, "text": "Python Dictionary" }, { "code": null, "e": 27486, "s": 27464, "text": "Enumerate() in Python" }, { "code": null, "e": 27518, "s": 27486, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27560, "s": 27518, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 27586, "s": 27560, "text": "Python String | replace()" }, { "code": null, "e": 27623, "s": 27586, "text": "Create a Pandas DataFrame from Lists" }, { "code": null, "e": 27667, "s": 27623, "text": "Reading and Writing to text files in Python" }, { "code": null, "e": 27692, "s": 27667, "text": "sum() function in Python" }, { "code": null, "e": 27721, "s": 27692, "text": "*args and **kwargs in Python" } ]
Go - Range
The range keyword is used in for loop to iterate over items of an array, slice, channel or map. With array and slices, it returns the index of the item as integer. With maps, it returns the key of the next key-value pair. Range either returns one value or two. If only one value is used on the left of a range expression, it is the 1st value in the following table. The following paragraph shows how to use range − package main import "fmt" func main() { /* create a slice */ numbers := []int{0,1,2,3,4,5,6,7,8} /* print the numbers */ for i:= range numbers { fmt.Println("Slice item",i,"is",numbers[i]) } /* create a map*/ countryCapitalMap := map[string] string {"France":"Paris","Italy":"Rome","Japan":"Tokyo"} /* print map using keys*/ for country := range countryCapitalMap { fmt.Println("Capital of",country,"is",countryCapitalMap[country]) } /* print map using key-value*/ for country,capital := range countryCapitalMap { fmt.Println("Capital of",country,"is",capital) } } When the above code is compiled and executed, it produces the following result − Slice item 0 is 0 Slice item 1 is 1 Slice item 2 is 2 Slice item 3 is 3 Slice item 4 is 4 Slice item 5 is 5 Slice item 6 is 6 Slice item 7 is 7 Slice item 8 is 8 Capital of France is Paris Capital of Italy is Rome Capital of Japan is Tokyo Capital of France is Paris Capital of Italy is Rome Capital of Japan is Tokyo 64 Lectures 6.5 hours Ridhi Arora 20 Lectures 2.5 hours Asif Hussain 22 Lectures 4 hours Dilip Padmanabhan 48 Lectures 6 hours Arnab Chakraborty 7 Lectures 1 hours Aditya Kulkarni 44 Lectures 3 hours Arnab Chakraborty Print Add Notes Bookmark this page
[ { "code": null, "e": 2303, "s": 1937, "text": "The range keyword is used in for loop to iterate over items of an array, slice, channel or map. With array and slices, it returns the index of the item as integer. With maps, it returns the key of the next key-value pair. Range either returns one value or two. If only one value is used on the left of a range expression, it is the 1st value in the following table." }, { "code": null, "e": 2352, "s": 2303, "text": "The following paragraph shows how to use range −" }, { "code": null, "e": 2993, "s": 2352, "text": "package main\n\nimport \"fmt\"\n\nfunc main() {\n /* create a slice */\n numbers := []int{0,1,2,3,4,5,6,7,8} \n \n /* print the numbers */\n for i:= range numbers {\n fmt.Println(\"Slice item\",i,\"is\",numbers[i])\n }\n \n /* create a map*/\n countryCapitalMap := map[string] string {\"France\":\"Paris\",\"Italy\":\"Rome\",\"Japan\":\"Tokyo\"}\n \n /* print map using keys*/\n for country := range countryCapitalMap {\n fmt.Println(\"Capital of\",country,\"is\",countryCapitalMap[country])\n }\n \n /* print map using key-value*/\n for country,capital := range countryCapitalMap {\n fmt.Println(\"Capital of\",country,\"is\",capital)\n }\n}" }, { "code": null, "e": 3074, "s": 2993, "text": "When the above code is compiled and executed, it produces the following result −" }, { "code": null, "e": 3393, "s": 3074, "text": "Slice item 0 is 0\nSlice item 1 is 1\nSlice item 2 is 2\nSlice item 3 is 3\nSlice item 4 is 4\nSlice item 5 is 5\nSlice item 6 is 6\nSlice item 7 is 7\nSlice item 8 is 8\nCapital of France is Paris\nCapital of Italy is Rome\nCapital of Japan is Tokyo\nCapital of France is Paris\nCapital of Italy is Rome\nCapital of Japan is Tokyo\n" }, { "code": null, "e": 3428, "s": 3393, "text": "\n 64 Lectures \n 6.5 hours \n" }, { "code": null, "e": 3441, "s": 3428, "text": " Ridhi Arora" }, { "code": null, "e": 3476, "s": 3441, "text": "\n 20 Lectures \n 2.5 hours \n" }, { "code": null, "e": 3490, "s": 3476, "text": " Asif Hussain" }, { "code": null, "e": 3523, "s": 3490, "text": "\n 22 Lectures \n 4 hours \n" }, { "code": null, "e": 3542, "s": 3523, "text": " Dilip Padmanabhan" }, { "code": null, "e": 3575, "s": 3542, "text": "\n 48 Lectures \n 6 hours \n" }, { "code": null, "e": 3594, "s": 3575, "text": " Arnab Chakraborty" }, { "code": null, "e": 3626, "s": 3594, "text": "\n 7 Lectures \n 1 hours \n" }, { "code": null, "e": 3643, "s": 3626, "text": " Aditya Kulkarni" }, { "code": null, "e": 3676, "s": 3643, "text": "\n 44 Lectures \n 3 hours \n" }, { "code": null, "e": 3695, "s": 3676, "text": " Arnab Chakraborty" }, { "code": null, "e": 3702, "s": 3695, "text": " Print" }, { "code": null, "e": 3713, "s": 3702, "text": " Add Notes" } ]
How to efficiently implement k Queues in a single array?
23 Jun, 2022 We have discussed efficient implementation of k stack in an array. In this post, same for queue is discussed. Following is the detailed problem statement. Create a data structure kQueues that represents k queues. Implementation of kQueues should use only one array, i.e., k queues should use the same array for storing elements. Following functions must be supported by kQueues. enqueue(int x, int qn) –> adds x to queue number ‘qn’ where qn is from 0 to k-1 dequeue(int qn) –> deletes an element from queue number ‘qn’ where qn is from 0 to k-1 Method 1 (Divide the array in slots of size n/k): A simple way to implement k queues is to divide the array in k slots of size n/k each, and fix the slots for different queues, i.e., use arr[0] to arr[n/k-1] for the first queue, and arr[n/k] to arr[2n/k-1] for queue2 where arr[] is the array to be used to implement two queues and size of array be n. The problem with this method is an inefficient use of array space. An enqueue operation may result in overflow even if there is space available in arr[]. For example, consider k as 2 and array size n as 6. Let we enqueue 3 elements to first and do not enqueue anything to the second queue. When we enqueue the 4th element to the first queue, there will be overflow even if we have space for 3 more elements in the array. Method 2 (A space efficient implementation): The idea is similar to the stack post, here we need to use three extra arrays. In stack post, we needed two extra arrays, one more array is required because in queues, enqueue() and dequeue() operations are done at different ends. Following are the three extra arrays are used: front[]: This is of size k and stores indexes of front elements in all queues. rear[]: This is of size k and stores indexes of rear elements in all queues. next[]: This is of size n and stores indexes of next item for all items in array arr[]. front[]: This is of size k and stores indexes of front elements in all queues. rear[]: This is of size k and stores indexes of rear elements in all queues. next[]: This is of size n and stores indexes of next item for all items in array arr[]. Here arr[] is the actual array that stores k stacks. Together with k queues, a stack of free slots in arr[] is also maintained. The top of this stack is stored in a variable ‘free’. All entries in front[] are initialized as -1 to indicate that all queues are empty. All entries next[i] are initialized as i+1 because all slots are free initially and pointing to the next slot. Top of the free stack, ‘free’ is initialized as 0. Following is C++ implementation of the above idea. C++ Java Python3 C# Javascript // A C++ program to demonstrate implementation// of k queues in a single// array in time and space efficient way#include<iostream>#include<climits>using namespace std; // A C++ class to represent k queues// in a single array of size nclass kQueues{ // Array of size n to store actual // content to be stored in queue int *arr; // Array of size k to store indexes // of front elements of the queue int *front; // Array of size k to store indexes // of rear elements of queue int *rear; // Array of size n to store next // entry in all queues int *next; int n, k; int free; // To store the beginning index of the free list public: //constructor to create k queue // in an array of size n kQueues(int k, int n); // A utility function to check if // there is space available bool isFull() { return (free == -1); } // To enqueue an item in queue number // 'qn' where qn is from 0 to k-1 void enqueue(int item, int qn); // To dequeue an from queue number // 'qn' where qn is from 0 to k-1 int dequeue(int qn); // To check whether queue number // 'qn' is empty or not bool isEmpty(int qn) { return (front[qn] == -1); }}; // Constructor to create k queues// in an array of size nkQueues::kQueues(int k1, int n1){ // Initialize n and k, and allocate // memory for all arrays k = k1, n = n1; arr = new int[n]; front = new int[k]; rear = new int[k]; next = new int[n]; // Initialize all queues as empty for (int i = 0; i < k; i++) front[i] = -1; // Initialize all spaces as free free = 0; for (int i=0; i<n-1; i++) next[i] = i+1; next[n-1] = -1; // -1 is used to indicate end of free list} // To enqueue an item in queue number// 'qn' where qn is from 0 to k-1void kQueues::enqueue(int item, int qn){ // Overflow check if (isFull()) { cout << "\nQueue Overflow\n"; return; } int i = free; // Store index of first free slot // Update index of free slot to index of next slot in free list free = next[i]; if (isEmpty(qn)) front[qn] = i; else next[rear[qn]] = i; next[i] = -1; // Update next of rear and then rear for queue number 'qn' rear[qn] = i; // Put the item in array arr[i] = item;} // To dequeue an from queue number 'qn' where qn is from 0 to k-1int kQueues::dequeue(int qn){ // Underflow checkSAS if (isEmpty(qn)) { cout << "\nQueue Underflow\n"; return INT_MAX; } // Find index of front item in queue number 'qn' int i = front[qn]; // Change top to store next of previous top front[qn] = next[i]; // Attach the previous front to the // beginning of free list next[i] = free; free = i; // Return the previous front item return arr[i];} /* Driver program to test kStacks class */int main(){ // Let us create 3 queue in an array of size 10 int k = 3, n = 10; kQueues ks(k, n); // Let us put some items in queue number 2 ks.enqueue(15, 2); ks.enqueue(45, 2); // Let us put some items in queue number 1 ks.enqueue(17, 1); ks.enqueue(49, 1); ks.enqueue(39, 1); // Let us put some items in queue number 0 ks.enqueue(11, 0); ks.enqueue(9, 0); ks.enqueue(7, 0); cout << "Dequeued element from queue 2 is " << ks.dequeue(2) << endl; cout << "Dequeued element from queue 1 is " << ks.dequeue(1) << endl; cout << "Dequeued element from queue 0 is " << ks.dequeue(0) << endl; return 0;} // A Java program to demonstrate implementation of k queues in a single// array in time and space efficient waypublic class KQueues { int k; int n; int[] arr; int[] front; int[] rear; int[] next; int free; KQueues(int k, int n){ // Initialize n and k, and allocate memory for all arrays this.k = k; this.n = n; this.arr = new int[n]; this.front = new int[k]; this.rear = new int[k]; this.next = new int[n]; // Initialize all queues as empty for(int i= 0; i< k; i++) { front[i] = rear[i] = -1; } // Initialize all spaces as free free = 0; for(int i= 0; i< n-1; i++) { next[i] = i+1; } next[n-1] = -1; } public static void main(String[] args) { // Let us create 3 queue in an array of size 10 int k = 3, n = 10; KQueues ks= new KQueues(k, n); // Let us put some items in queue number 2 ks.enqueue(15, 2); ks.enqueue(45, 2); // Let us put some items in queue number 1 ks.enqueue(17, 1); ks.enqueue(49, 1); ks.enqueue(39, 1); // Let us put some items in queue number 0 ks.enqueue(11, 0); ks.enqueue(9, 0); ks.enqueue(7, 0); System.out.println("Dequeued element from queue 2 is " + ks.dequeue(2)); System.out.println("Dequeued element from queue 1 is " + ks.dequeue(1)); System.out.println("Dequeued element from queue 0 is " + ks.dequeue(0) ); } // To check whether queue number 'i' is empty or not private boolean isEmpty(int i) { return front[i] == -1; } // To dequeue an from queue number 'i' where i is from 0 to k-1 private boolean isFull(int i) { return free == -1; } // To enqueue an item in queue number 'j' where j is from 0 to k-1 private void enqueue(int item, int j) { if(isFull(j)) { System.out.println("queue overflow"); return; } int nextFree = next[free]; if(isEmpty(j)) { rear[j] = front[j] = free; }else { // Update next of rear and then rear for queue number 'j' next[rear[j]] = free; rear[j] = free; } next[free] = -1; // Put the item in array arr[free] = item; // Update index of free slot to index of next slot in free list free = nextFree; } // To dequeue an from queue number 'i' where i is from 0 to k-1 private int dequeue(int i) { // Underflow checkSAS if(isEmpty(i)) { System.out.println("Stack underflow"); return Integer.MIN_VALUE; } // Find index of front item in queue number 'i' int frontIndex = front[i]; // Change top to store next of previous top front[i] = next[frontIndex]; // Attach the previous front to the beginning of free list next[frontIndex] = free; free = frontIndex; return arr[frontIndex]; } } # A Python program to demonstrate implementation of k queues in a single# array in time and space efficient way class KQueues: def __init__(self, number_of_queues, array_length): self.number_of_queues = number_of_queues self.array_length = array_length self.array = [-1] * array_length self.front = [-1] * number_of_queues self.rear = [-1] * number_of_queues self.next_array = list(range(1, array_length)) self.next_array.append(-1) self.free = 0 # To check whether the current queue_number is empty or not def is_empty(self, queue_number): return True if self.front[queue_number] == -1 else False # To check whether the current queue_number is full or not def is_full(self, queue_number): return True if self.free == -1 else False # To enqueue the given item in the given queue_number where # queue_number is from 0 to number_of_queues-1 def enqueue(self, item, queue_number): if self.is_full(queue_number): print("Queue FULL") return next_free = self.next_array[self.free] if self.is_empty(queue_number): self.front[queue_number] = self.rear[queue_number] = self.free else: self.next_array[self.rear[queue_number]] = self.free self.rear[queue_number] = self.free self.next_array[self.free] = -1 self.array[self.free] = item self.free = next_free # To dequeue an item from the given queue_number where # queue_number is from 0 to number_of_queues-1 def dequeue(self, queue_number): if self.is_empty(queue_number): print("Queue EMPTY") return front_index = self.front[queue_number] self.front[queue_number] = self.next_array[front_index] self.next_array[front_index] = self.free self.free = front_index return self.array[front_index] if __name__ == "__main__": # Let us create 3 queue in an array of size 10 ks = KQueues(3, 10) # Let us put some items in queue number 2 ks.enqueue(15, 2) ks.enqueue(45, 2) # Let us put some items in queue number 1 ks.enqueue(17, 1); ks.enqueue(49, 1); ks.enqueue(39, 1); # Let us put some items in queue number 0 ks.enqueue(11, 0); ks.enqueue(9, 0); ks.enqueue(7, 0); print("Dequeued element from queue 2 is {}".format(ks.dequeue(2))) print("Dequeued element from queue 1 is {}".format(ks.dequeue(1))) print("Dequeued element from queue 0 is {}".format(ks.dequeue(0))) // A C# program to demonstrate implementation of k queues in a single// array in time and space efficient wayusing System;public class KQueues{ int k; int n; int[] arr; int[] front; int[] rear; int[] next; int free; KQueues(int k, int n) { // Initialize n and k, and // allocate memory for all arrays this.k = k; this.n = n; this.arr = new int[n]; this.front = new int[k]; this.rear = new int[k]; this.next = new int[n]; // Initialize all queues as empty for(int i = 0; i < k; i++) { front[i] = rear[i] = -1; } // Initialize all spaces as free free = 0; for(int i = 0; i < n - 1; i++) { next[i] = i + 1; } next[n - 1] = -1; } public static void Main(String[] args) { // Let us create 3 queue in an array of size 10 int k = 3, n = 10; KQueues ks = new KQueues(k, n); // Let us put some items in queue number 2 ks.enqueue(15, 2); ks.enqueue(45, 2); // Let us put some items in queue number 1 ks.enqueue(17, 1); ks.enqueue(49, 1); ks.enqueue(39, 1); // Let us put some items in queue number 0 ks.enqueue(11, 0); ks.enqueue(9, 0); ks.enqueue(7, 0); Console.WriteLine("Dequeued element from queue 2 is " + ks.dequeue(2)); Console.WriteLine("Dequeued element from queue 1 is " + ks.dequeue(1)); Console.WriteLine("Dequeued element from queue 0 is " + ks.dequeue(0) ); } // To check whether queue number 'i' is empty or not private bool isEmpty(int i) { return front[i] == -1; } // To dequeue an from queue // number 'i' where i is from 0 to k-1 private bool isFull(int i) { return free == -1; } // To enqueue an item in queue // number 'j' where j is from 0 to k-1 private void enqueue(int item, int j) { if(isFull(j)) { Console.WriteLine("queue overflow"); return; } int nextFree = next[free]; if(isEmpty(j)) { rear[j] = front[j] = free; } else { // Update next of rear and then // rear for queue number 'j' next[rear[j]] = free; rear[j] = free; } next[free] = -1; // Put the item in array arr[free] = item; // Update index of free slot to // index of next slot in free list free = nextFree; } // To dequeue an from queue // number 'i' where i is from 0 to k-1 private int dequeue(int i) { // Underflow checkSAS if(isEmpty(i)) { Console.WriteLine("Stack underflow"); return int.MinValue; } // Find index of front item in queue number 'i' int frontIndex = front[i]; // Change top to store next of previous top front[i] = next[frontIndex]; // Attach the previous front to the beginning of free list next[frontIndex] = free; free = frontIndex; return arr[frontIndex]; } } // This code is contributed by aashish1995 <script> // A Javascript program to demonstrate implementation of k queues in a single// array in time and space efficient wayclass KQueues{ constructor(k,n) { // Initialize n and k, and allocate memory for all arrays this.k = k; this.n = n; this.arr = new Array(n); this.front = new Array(k); this.rear = new Array(k); this.next = new Array(n); // Initialize all queues as empty for(let i= 0; i< k; i++) { this.front[i] = this.rear[i] = -1; } // Initialize all spaces as free this.free = 0; for(let i= 0; i< n-1; i++) { this.next[i] = i+1; } this.next[n-1] = -1; } // To check whether queue number 'i' is empty or not isEmpty(i) { return this.front[i] == -1; } // To dequeue an from queue number 'i' where i is from 0 to k-1 isFull(i) { return this.free == -1; } // To enqueue an item in queue number 'j' where j is from 0 to k-1 enqueue(item,j) { if(this.isFull(j)) { document.write("queue overflow<br>"); return; } let nextFree = this.next[this.free]; if(this.isEmpty(j)) { this.rear[j] = this.front[j] = this.free; }else { // Update next of rear and then rear for queue number 'j' this.next[this.rear[j]] = this.free; this.rear[j] = this.free; } this.next[this.free] = -1; // Put the item in array this.arr[this.free] = item; // Update index of free slot to index of next slot in free list this.free = nextFree; } // To dequeue an from queue number 'i' where i is from 0 to k-1 dequeue(i) { // Underflow checkSAS if(this.isEmpty(i)) { document.write("Stack underflow<br>"); return Number.MIN_VALUE; } // Find index of front item in queue number 'i' let frontIndex = this.front[i]; // Change top to store next of previous top this.front[i] = this.next[frontIndex]; // Attach the previous front to the beginning of free list this.next[frontIndex] = this.free; this.free = frontIndex; return this.arr[frontIndex]; }} // Let us create 3 queue in an array of size 10 let k = 3, n = 10; let ks= new KQueues(k, n); // Let us put some items in queue number 2 ks.enqueue(15, 2); ks.enqueue(45, 2); // Let us put some items in queue number 1 ks.enqueue(17, 1); ks.enqueue(49, 1); ks.enqueue(39, 1); // Let us put some items in queue number 0 ks.enqueue(11, 0); ks.enqueue(9, 0); ks.enqueue(7, 0); document.write("Dequeued element from queue 2 is " + ks.dequeue(2)+"<br>"); document.write("Dequeued element from queue 1 is " + ks.dequeue(1)+"<br>"); document.write("Dequeued element from queue 0 is " + ks.dequeue(0)+"<br>" ); // This code is contributed by avanitrachhadiya2155</script> Dequeued element from queue 2 is 15 Dequeued element from queue 1 is 17 Dequeued element from queue 0 is 11 Time complexities of enqueue() and dequeue() is O(1). The best part of the above implementation is, if there is a slot available in the queue, then an item can be enqueued in any of the queues, i.e., no wastage of space. This method requires some extra space. Space may not be an issue because queue items are typically large, for example, queues of employees, students, etc where every item is of hundreds of bytes. For such large queues, the extra space used is comparatively very less as we use three integer arrays as extra space. sidsm009 bejuzb viping74 raju pitta aashish1995 avanitrachhadiya2155 amartyaghoshgfg hardikkoriintern Accolite Queue Accolite Queue Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Breadth First Search or BFS for a Graph Level Order Binary Tree Traversal Queue in Python Queue Interface In Java Introduction to Data Structures Queue using Stacks What is Priority Queue | Introduction to Priority Queue What is Data Structure: Types, Classifications and Applications LRU Cache Implementation Circular Queue | Set 1 (Introduction and Array Implementation)
[ { "code": null, "e": 52, "s": 24, "text": "\n23 Jun, 2022" }, { "code": null, "e": 207, "s": 52, "text": "We have discussed efficient implementation of k stack in an array. In this post, same for queue is discussed. Following is the detailed problem statement." }, { "code": null, "e": 431, "s": 207, "text": "Create a data structure kQueues that represents k queues. Implementation of kQueues should use only one array, i.e., k queues should use the same array for storing elements. Following functions must be supported by kQueues." }, { "code": null, "e": 512, "s": 431, "text": "enqueue(int x, int qn) –> adds x to queue number ‘qn’ where qn is from 0 to k-1 " }, { "code": null, "e": 600, "s": 512, "text": "dequeue(int qn) –> deletes an element from queue number ‘qn’ where qn is from 0 to k-1 " }, { "code": null, "e": 650, "s": 600, "text": "Method 1 (Divide the array in slots of size n/k):" }, { "code": null, "e": 952, "s": 650, "text": "A simple way to implement k queues is to divide the array in k slots of size n/k each, and fix the slots for different queues, i.e., use arr[0] to arr[n/k-1] for the first queue, and arr[n/k] to arr[2n/k-1] for queue2 where arr[] is the array to be used to implement two queues and size of array be n." }, { "code": null, "e": 1373, "s": 952, "text": "The problem with this method is an inefficient use of array space. An enqueue operation may result in overflow even if there is space available in arr[]. For example, consider k as 2 and array size n as 6. Let we enqueue 3 elements to first and do not enqueue anything to the second queue. When we enqueue the 4th element to the first queue, there will be overflow even if we have space for 3 more elements in the array." }, { "code": null, "e": 1418, "s": 1373, "text": "Method 2 (A space efficient implementation):" }, { "code": null, "e": 1649, "s": 1418, "text": "The idea is similar to the stack post, here we need to use three extra arrays. In stack post, we needed two extra arrays, one more array is required because in queues, enqueue() and dequeue() operations are done at different ends." }, { "code": null, "e": 1697, "s": 1649, "text": "Following are the three extra arrays are used: " }, { "code": null, "e": 1942, "s": 1697, "text": "front[]: This is of size k and stores indexes of front elements in all queues. rear[]: This is of size k and stores indexes of rear elements in all queues. next[]: This is of size n and stores indexes of next item for all items in array arr[]. " }, { "code": null, "e": 2022, "s": 1942, "text": "front[]: This is of size k and stores indexes of front elements in all queues. " }, { "code": null, "e": 2100, "s": 2022, "text": "rear[]: This is of size k and stores indexes of rear elements in all queues. " }, { "code": null, "e": 2189, "s": 2100, "text": "next[]: This is of size n and stores indexes of next item for all items in array arr[]. " }, { "code": null, "e": 2242, "s": 2189, "text": "Here arr[] is the actual array that stores k stacks." }, { "code": null, "e": 2371, "s": 2242, "text": "Together with k queues, a stack of free slots in arr[] is also maintained. The top of this stack is stored in a variable ‘free’." }, { "code": null, "e": 2617, "s": 2371, "text": "All entries in front[] are initialized as -1 to indicate that all queues are empty. All entries next[i] are initialized as i+1 because all slots are free initially and pointing to the next slot. Top of the free stack, ‘free’ is initialized as 0." }, { "code": null, "e": 2669, "s": 2617, "text": "Following is C++ implementation of the above idea. " }, { "code": null, "e": 2673, "s": 2669, "text": "C++" }, { "code": null, "e": 2678, "s": 2673, "text": "Java" }, { "code": null, "e": 2686, "s": 2678, "text": "Python3" }, { "code": null, "e": 2689, "s": 2686, "text": "C#" }, { "code": null, "e": 2700, "s": 2689, "text": "Javascript" }, { "code": "// A C++ program to demonstrate implementation// of k queues in a single// array in time and space efficient way#include<iostream>#include<climits>using namespace std; // A C++ class to represent k queues// in a single array of size nclass kQueues{ // Array of size n to store actual // content to be stored in queue int *arr; // Array of size k to store indexes // of front elements of the queue int *front; // Array of size k to store indexes // of rear elements of queue int *rear; // Array of size n to store next // entry in all queues int *next; int n, k; int free; // To store the beginning index of the free list public: //constructor to create k queue // in an array of size n kQueues(int k, int n); // A utility function to check if // there is space available bool isFull() { return (free == -1); } // To enqueue an item in queue number // 'qn' where qn is from 0 to k-1 void enqueue(int item, int qn); // To dequeue an from queue number // 'qn' where qn is from 0 to k-1 int dequeue(int qn); // To check whether queue number // 'qn' is empty or not bool isEmpty(int qn) { return (front[qn] == -1); }}; // Constructor to create k queues// in an array of size nkQueues::kQueues(int k1, int n1){ // Initialize n and k, and allocate // memory for all arrays k = k1, n = n1; arr = new int[n]; front = new int[k]; rear = new int[k]; next = new int[n]; // Initialize all queues as empty for (int i = 0; i < k; i++) front[i] = -1; // Initialize all spaces as free free = 0; for (int i=0; i<n-1; i++) next[i] = i+1; next[n-1] = -1; // -1 is used to indicate end of free list} // To enqueue an item in queue number// 'qn' where qn is from 0 to k-1void kQueues::enqueue(int item, int qn){ // Overflow check if (isFull()) { cout << \"\\nQueue Overflow\\n\"; return; } int i = free; // Store index of first free slot // Update index of free slot to index of next slot in free list free = next[i]; if (isEmpty(qn)) front[qn] = i; else next[rear[qn]] = i; next[i] = -1; // Update next of rear and then rear for queue number 'qn' rear[qn] = i; // Put the item in array arr[i] = item;} // To dequeue an from queue number 'qn' where qn is from 0 to k-1int kQueues::dequeue(int qn){ // Underflow checkSAS if (isEmpty(qn)) { cout << \"\\nQueue Underflow\\n\"; return INT_MAX; } // Find index of front item in queue number 'qn' int i = front[qn]; // Change top to store next of previous top front[qn] = next[i]; // Attach the previous front to the // beginning of free list next[i] = free; free = i; // Return the previous front item return arr[i];} /* Driver program to test kStacks class */int main(){ // Let us create 3 queue in an array of size 10 int k = 3, n = 10; kQueues ks(k, n); // Let us put some items in queue number 2 ks.enqueue(15, 2); ks.enqueue(45, 2); // Let us put some items in queue number 1 ks.enqueue(17, 1); ks.enqueue(49, 1); ks.enqueue(39, 1); // Let us put some items in queue number 0 ks.enqueue(11, 0); ks.enqueue(9, 0); ks.enqueue(7, 0); cout << \"Dequeued element from queue 2 is \" << ks.dequeue(2) << endl; cout << \"Dequeued element from queue 1 is \" << ks.dequeue(1) << endl; cout << \"Dequeued element from queue 0 is \" << ks.dequeue(0) << endl; return 0;}", "e": 6250, "s": 2700, "text": null }, { "code": "// A Java program to demonstrate implementation of k queues in a single// array in time and space efficient waypublic class KQueues { int k; int n; int[] arr; int[] front; int[] rear; int[] next; int free; KQueues(int k, int n){ // Initialize n and k, and allocate memory for all arrays this.k = k; this.n = n; this.arr = new int[n]; this.front = new int[k]; this.rear = new int[k]; this.next = new int[n]; // Initialize all queues as empty for(int i= 0; i< k; i++) { front[i] = rear[i] = -1; } // Initialize all spaces as free free = 0; for(int i= 0; i< n-1; i++) { next[i] = i+1; } next[n-1] = -1; } public static void main(String[] args) { // Let us create 3 queue in an array of size 10 int k = 3, n = 10; KQueues ks= new KQueues(k, n); // Let us put some items in queue number 2 ks.enqueue(15, 2); ks.enqueue(45, 2); // Let us put some items in queue number 1 ks.enqueue(17, 1); ks.enqueue(49, 1); ks.enqueue(39, 1); // Let us put some items in queue number 0 ks.enqueue(11, 0); ks.enqueue(9, 0); ks.enqueue(7, 0); System.out.println(\"Dequeued element from queue 2 is \" + ks.dequeue(2)); System.out.println(\"Dequeued element from queue 1 is \" + ks.dequeue(1)); System.out.println(\"Dequeued element from queue 0 is \" + ks.dequeue(0) ); } // To check whether queue number 'i' is empty or not private boolean isEmpty(int i) { return front[i] == -1; } // To dequeue an from queue number 'i' where i is from 0 to k-1 private boolean isFull(int i) { return free == -1; } // To enqueue an item in queue number 'j' where j is from 0 to k-1 private void enqueue(int item, int j) { if(isFull(j)) { System.out.println(\"queue overflow\"); return; } int nextFree = next[free]; if(isEmpty(j)) { rear[j] = front[j] = free; }else { // Update next of rear and then rear for queue number 'j' next[rear[j]] = free; rear[j] = free; } next[free] = -1; // Put the item in array arr[free] = item; // Update index of free slot to index of next slot in free list free = nextFree; } // To dequeue an from queue number 'i' where i is from 0 to k-1 private int dequeue(int i) { // Underflow checkSAS if(isEmpty(i)) { System.out.println(\"Stack underflow\"); return Integer.MIN_VALUE; } // Find index of front item in queue number 'i' int frontIndex = front[i]; // Change top to store next of previous top front[i] = next[frontIndex]; // Attach the previous front to the beginning of free list next[frontIndex] = free; free = frontIndex; return arr[frontIndex]; } }", "e": 9544, "s": 6250, "text": null }, { "code": "# A Python program to demonstrate implementation of k queues in a single# array in time and space efficient way class KQueues: def __init__(self, number_of_queues, array_length): self.number_of_queues = number_of_queues self.array_length = array_length self.array = [-1] * array_length self.front = [-1] * number_of_queues self.rear = [-1] * number_of_queues self.next_array = list(range(1, array_length)) self.next_array.append(-1) self.free = 0 # To check whether the current queue_number is empty or not def is_empty(self, queue_number): return True if self.front[queue_number] == -1 else False # To check whether the current queue_number is full or not def is_full(self, queue_number): return True if self.free == -1 else False # To enqueue the given item in the given queue_number where # queue_number is from 0 to number_of_queues-1 def enqueue(self, item, queue_number): if self.is_full(queue_number): print(\"Queue FULL\") return next_free = self.next_array[self.free] if self.is_empty(queue_number): self.front[queue_number] = self.rear[queue_number] = self.free else: self.next_array[self.rear[queue_number]] = self.free self.rear[queue_number] = self.free self.next_array[self.free] = -1 self.array[self.free] = item self.free = next_free # To dequeue an item from the given queue_number where # queue_number is from 0 to number_of_queues-1 def dequeue(self, queue_number): if self.is_empty(queue_number): print(\"Queue EMPTY\") return front_index = self.front[queue_number] self.front[queue_number] = self.next_array[front_index] self.next_array[front_index] = self.free self.free = front_index return self.array[front_index] if __name__ == \"__main__\": # Let us create 3 queue in an array of size 10 ks = KQueues(3, 10) # Let us put some items in queue number 2 ks.enqueue(15, 2) ks.enqueue(45, 2) # Let us put some items in queue number 1 ks.enqueue(17, 1); ks.enqueue(49, 1); ks.enqueue(39, 1); # Let us put some items in queue number 0 ks.enqueue(11, 0); ks.enqueue(9, 0); ks.enqueue(7, 0); print(\"Dequeued element from queue 2 is {}\".format(ks.dequeue(2))) print(\"Dequeued element from queue 1 is {}\".format(ks.dequeue(1))) print(\"Dequeued element from queue 0 is {}\".format(ks.dequeue(0)))", "e": 12125, "s": 9544, "text": null }, { "code": "// A C# program to demonstrate implementation of k queues in a single// array in time and space efficient wayusing System;public class KQueues{ int k; int n; int[] arr; int[] front; int[] rear; int[] next; int free; KQueues(int k, int n) { // Initialize n and k, and // allocate memory for all arrays this.k = k; this.n = n; this.arr = new int[n]; this.front = new int[k]; this.rear = new int[k]; this.next = new int[n]; // Initialize all queues as empty for(int i = 0; i < k; i++) { front[i] = rear[i] = -1; } // Initialize all spaces as free free = 0; for(int i = 0; i < n - 1; i++) { next[i] = i + 1; } next[n - 1] = -1; } public static void Main(String[] args) { // Let us create 3 queue in an array of size 10 int k = 3, n = 10; KQueues ks = new KQueues(k, n); // Let us put some items in queue number 2 ks.enqueue(15, 2); ks.enqueue(45, 2); // Let us put some items in queue number 1 ks.enqueue(17, 1); ks.enqueue(49, 1); ks.enqueue(39, 1); // Let us put some items in queue number 0 ks.enqueue(11, 0); ks.enqueue(9, 0); ks.enqueue(7, 0); Console.WriteLine(\"Dequeued element from queue 2 is \" + ks.dequeue(2)); Console.WriteLine(\"Dequeued element from queue 1 is \" + ks.dequeue(1)); Console.WriteLine(\"Dequeued element from queue 0 is \" + ks.dequeue(0) ); } // To check whether queue number 'i' is empty or not private bool isEmpty(int i) { return front[i] == -1; } // To dequeue an from queue // number 'i' where i is from 0 to k-1 private bool isFull(int i) { return free == -1; } // To enqueue an item in queue // number 'j' where j is from 0 to k-1 private void enqueue(int item, int j) { if(isFull(j)) { Console.WriteLine(\"queue overflow\"); return; } int nextFree = next[free]; if(isEmpty(j)) { rear[j] = front[j] = free; } else { // Update next of rear and then // rear for queue number 'j' next[rear[j]] = free; rear[j] = free; } next[free] = -1; // Put the item in array arr[free] = item; // Update index of free slot to // index of next slot in free list free = nextFree; } // To dequeue an from queue // number 'i' where i is from 0 to k-1 private int dequeue(int i) { // Underflow checkSAS if(isEmpty(i)) { Console.WriteLine(\"Stack underflow\"); return int.MinValue; } // Find index of front item in queue number 'i' int frontIndex = front[i]; // Change top to store next of previous top front[i] = next[frontIndex]; // Attach the previous front to the beginning of free list next[frontIndex] = free; free = frontIndex; return arr[frontIndex]; } } // This code is contributed by aashish1995", "e": 15017, "s": 12125, "text": null }, { "code": "<script> // A Javascript program to demonstrate implementation of k queues in a single// array in time and space efficient wayclass KQueues{ constructor(k,n) { // Initialize n and k, and allocate memory for all arrays this.k = k; this.n = n; this.arr = new Array(n); this.front = new Array(k); this.rear = new Array(k); this.next = new Array(n); // Initialize all queues as empty for(let i= 0; i< k; i++) { this.front[i] = this.rear[i] = -1; } // Initialize all spaces as free this.free = 0; for(let i= 0; i< n-1; i++) { this.next[i] = i+1; } this.next[n-1] = -1; } // To check whether queue number 'i' is empty or not isEmpty(i) { return this.front[i] == -1; } // To dequeue an from queue number 'i' where i is from 0 to k-1 isFull(i) { return this.free == -1; } // To enqueue an item in queue number 'j' where j is from 0 to k-1 enqueue(item,j) { if(this.isFull(j)) { document.write(\"queue overflow<br>\"); return; } let nextFree = this.next[this.free]; if(this.isEmpty(j)) { this.rear[j] = this.front[j] = this.free; }else { // Update next of rear and then rear for queue number 'j' this.next[this.rear[j]] = this.free; this.rear[j] = this.free; } this.next[this.free] = -1; // Put the item in array this.arr[this.free] = item; // Update index of free slot to index of next slot in free list this.free = nextFree; } // To dequeue an from queue number 'i' where i is from 0 to k-1 dequeue(i) { // Underflow checkSAS if(this.isEmpty(i)) { document.write(\"Stack underflow<br>\"); return Number.MIN_VALUE; } // Find index of front item in queue number 'i' let frontIndex = this.front[i]; // Change top to store next of previous top this.front[i] = this.next[frontIndex]; // Attach the previous front to the beginning of free list this.next[frontIndex] = this.free; this.free = frontIndex; return this.arr[frontIndex]; }} // Let us create 3 queue in an array of size 10 let k = 3, n = 10; let ks= new KQueues(k, n); // Let us put some items in queue number 2 ks.enqueue(15, 2); ks.enqueue(45, 2); // Let us put some items in queue number 1 ks.enqueue(17, 1); ks.enqueue(49, 1); ks.enqueue(39, 1); // Let us put some items in queue number 0 ks.enqueue(11, 0); ks.enqueue(9, 0); ks.enqueue(7, 0); document.write(\"Dequeued element from queue 2 is \" + ks.dequeue(2)+\"<br>\"); document.write(\"Dequeued element from queue 1 is \" + ks.dequeue(1)+\"<br>\"); document.write(\"Dequeued element from queue 0 is \" + ks.dequeue(0)+\"<br>\" ); // This code is contributed by avanitrachhadiya2155</script>", "e": 18302, "s": 15017, "text": null }, { "code": null, "e": 18410, "s": 18302, "text": "Dequeued element from queue 2 is 15\nDequeued element from queue 1 is 17\nDequeued element from queue 0 is 11" }, { "code": null, "e": 18464, "s": 18410, "text": "Time complexities of enqueue() and dequeue() is O(1)." }, { "code": null, "e": 18945, "s": 18464, "text": "The best part of the above implementation is, if there is a slot available in the queue, then an item can be enqueued in any of the queues, i.e., no wastage of space. This method requires some extra space. Space may not be an issue because queue items are typically large, for example, queues of employees, students, etc where every item is of hundreds of bytes. For such large queues, the extra space used is comparatively very less as we use three integer arrays as extra space." }, { "code": null, "e": 18954, "s": 18945, "text": "sidsm009" }, { "code": null, "e": 18961, "s": 18954, "text": "bejuzb" }, { "code": null, "e": 18970, "s": 18961, "text": "viping74" }, { "code": null, "e": 18981, "s": 18970, "text": "raju pitta" }, { "code": null, "e": 18993, "s": 18981, "text": "aashish1995" }, { "code": null, "e": 19014, "s": 18993, "text": "avanitrachhadiya2155" }, { "code": null, "e": 19030, "s": 19014, "text": "amartyaghoshgfg" }, { "code": null, "e": 19047, "s": 19030, "text": "hardikkoriintern" }, { "code": null, "e": 19056, "s": 19047, "text": "Accolite" }, { "code": null, "e": 19062, "s": 19056, "text": "Queue" }, { "code": null, "e": 19071, "s": 19062, "text": "Accolite" }, { "code": null, "e": 19077, "s": 19071, "text": "Queue" }, { "code": null, "e": 19175, "s": 19077, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 19215, "s": 19175, "text": "Breadth First Search or BFS for a Graph" }, { "code": null, "e": 19249, "s": 19215, "text": "Level Order Binary Tree Traversal" }, { "code": null, "e": 19265, "s": 19249, "text": "Queue in Python" }, { "code": null, "e": 19289, "s": 19265, "text": "Queue Interface In Java" }, { "code": null, "e": 19321, "s": 19289, "text": "Introduction to Data Structures" }, { "code": null, "e": 19340, "s": 19321, "text": "Queue using Stacks" }, { "code": null, "e": 19396, "s": 19340, "text": "What is Priority Queue | Introduction to Priority Queue" }, { "code": null, "e": 19460, "s": 19396, "text": "What is Data Structure: Types, Classifications and Applications" }, { "code": null, "e": 19485, "s": 19460, "text": "LRU Cache Implementation" } ]
Split String with Dot (.) in Java
Let’s say the following is our string. String str = "This is demo text.This is sample text!"; To split a string with dot, use the split() method in Java. str.split("[.]", 0); The following is the complete example. Live Demo public class Demo { public static void main(String[] args) { String str = "This is demo text.This is sample text!"; String[] res = str.split("[.]", 0); for(String myStr: res) { System.out.println(myStr); } } } This is demo text This is sample text!
[ { "code": null, "e": 1226, "s": 1187, "text": "Let’s say the following is our string." }, { "code": null, "e": 1281, "s": 1226, "text": "String str = \"This is demo text.This is sample text!\";" }, { "code": null, "e": 1341, "s": 1281, "text": "To split a string with dot, use the split() method in Java." }, { "code": null, "e": 1362, "s": 1341, "text": "str.split(\"[.]\", 0);" }, { "code": null, "e": 1401, "s": 1362, "text": "The following is the complete example." }, { "code": null, "e": 1412, "s": 1401, "text": " Live Demo" }, { "code": null, "e": 1668, "s": 1412, "text": "public class Demo {\n public static void main(String[] args) {\n String str = \"This is demo text.This is sample text!\";\n String[] res = str.split(\"[.]\", 0);\n for(String myStr: res) {\n System.out.println(myStr);\n }\n }\n}" }, { "code": null, "e": 1707, "s": 1668, "text": "This is demo text\nThis is sample text!" } ]
How to convert Float to Int in Python?
18 Aug, 2020 Converting a float value to an int is done by Type conversion, which is an explicit method of converting an operand to a specific type. However, it is to be noted that such type of conversion may tend to be a lossy one (loss of data). Converting an int value like 2 to floating-point will result in 2.0, such types of conversion are safe as there would be no loss of data, but converting 3.4 to an int value will result in 3 leading to a lossy conversion. Examples: Input: 3.3 Output: 3 Input: 5.99 Output: 5 Method 1: Conversion using int(): To convert a float value to int we make use of the built-in int() function, this function trims the values after the decimal point and returns only the integer/whole number part. Syntax: int(x) Return: integer value Example 1: Number of type float is converted to a result of type int. Python3 # conversion from float to int num = 9.3 # printing data type of 'num' print('type:', type(num).__name__) # conversion to intnum = int(num) # printing data type of 'num' print('converted value:', num, ', type:', type(num).__name__) Output: type: float converted value: 9 , type: int Example 2: In most cases the int() function rounds off the result to an integer lesser than or equal to the input, but the behavior is neither definite nor predictable. One such example is shown below. Python3 # example of unpredictable # behaviour of int() num1 = 5.9num2 = 5.99999999999999999999 num1 = int(num1)num2 = int(num2) print(num1, num2, sep = '\n') Output: 5 6 Method 2: Conversion using math.floor() and math.ceil(). A float value can be converted to an int value no larger than the input by using the math.floor() function, whereas it can also be converted to an int value which is the smallest integer greater than the input using math.ceil() function. The math module is to be imported in order to use these methods. Syntax: math.floor(x) Parameter: x: This is a numeric expression. Returns: largest integer not greater than x. Syntax: math.ceil(x) Parameter: x: This is a numeric expression. Returns: Smallest integer not less than x. Example : In the below example conversion from float to int has been achieved using the floor() and ceil() methods, the former returns an int no larger than the input and the latter returns the smallest integer larger than the input. Python3 # conversion using floor and ceil . # importing math moduleimport math num = 5.6 floor_value = math.floor(num) ceil_value = math.ceil(num) print("the result using floor() : ", floor_value , ', type : ',type(floor_value).__name__) print("the result using ceil() : ", ceil_value, ', type: ', type(ceil_value).__name__) Output: the result using floor() : 5 , type : int the result using ceil() : 6 , type: int python-basics Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Different ways to create Pandas Dataframe Enumerate() in Python Read a file line by line in Python Python String | replace() How to Install PIP on Windows ? *args and **kwargs in Python Python Classes and Objects Iterate over a list in Python Python OOPs Concepts Convert integer to string in Python
[ { "code": null, "e": 28, "s": 0, "text": "\n18 Aug, 2020" }, { "code": null, "e": 495, "s": 28, "text": "Converting a float value to an int is done by Type conversion, which is an explicit method of converting an operand to a specific type. However, it is to be noted that such type of conversion may tend to be a lossy one (loss of data). Converting an int value like 2 to floating-point will result in 2.0, such types of conversion are safe as there would be no loss of data, but converting 3.4 to an int value will result in 3 leading to a lossy conversion. Examples: " }, { "code": null, "e": 544, "s": 495, "text": "Input: 3.3 \nOutput: 3 \n\nInput: 5.99\nOutput: 5\n" }, { "code": null, "e": 578, "s": 544, "text": "Method 1: Conversion using int():" }, { "code": null, "e": 757, "s": 578, "text": "To convert a float value to int we make use of the built-in int() function, this function trims the values after the decimal point and returns only the integer/whole number part." }, { "code": null, "e": 773, "s": 757, "text": "Syntax: int(x) " }, { "code": null, "e": 795, "s": 773, "text": "Return: integer value" }, { "code": null, "e": 865, "s": 795, "text": "Example 1: Number of type float is converted to a result of type int." }, { "code": null, "e": 873, "s": 865, "text": "Python3" }, { "code": "# conversion from float to int num = 9.3 # printing data type of 'num' print('type:', type(num).__name__) # conversion to intnum = int(num) # printing data type of 'num' print('converted value:', num, ', type:', type(num).__name__)", "e": 1126, "s": 873, "text": null }, { "code": null, "e": 1134, "s": 1126, "text": "Output:" }, { "code": null, "e": 1177, "s": 1134, "text": "type: float\nconverted value: 9 , type: int" }, { "code": null, "e": 1379, "s": 1177, "text": "Example 2: In most cases the int() function rounds off the result to an integer lesser than or equal to the input, but the behavior is neither definite nor predictable. One such example is shown below." }, { "code": null, "e": 1387, "s": 1379, "text": "Python3" }, { "code": "# example of unpredictable # behaviour of int() num1 = 5.9num2 = 5.99999999999999999999 num1 = int(num1)num2 = int(num2) print(num1, num2, sep = '\\n')", "e": 1541, "s": 1387, "text": null }, { "code": null, "e": 1549, "s": 1541, "text": "Output:" }, { "code": null, "e": 1553, "s": 1549, "text": "5\n6" }, { "code": null, "e": 1610, "s": 1553, "text": "Method 2: Conversion using math.floor() and math.ceil()." }, { "code": null, "e": 1913, "s": 1610, "text": "A float value can be converted to an int value no larger than the input by using the math.floor() function, whereas it can also be converted to an int value which is the smallest integer greater than the input using math.ceil() function. The math module is to be imported in order to use these methods." }, { "code": null, "e": 1935, "s": 1913, "text": "Syntax: math.floor(x)" }, { "code": null, "e": 1946, "s": 1935, "text": "Parameter:" }, { "code": null, "e": 1979, "s": 1946, "text": "x: This is a numeric expression." }, { "code": null, "e": 2024, "s": 1979, "text": "Returns: largest integer not greater than x." }, { "code": null, "e": 2045, "s": 2024, "text": "Syntax: math.ceil(x)" }, { "code": null, "e": 2056, "s": 2045, "text": "Parameter:" }, { "code": null, "e": 2089, "s": 2056, "text": "x: This is a numeric expression." }, { "code": null, "e": 2132, "s": 2089, "text": "Returns: Smallest integer not less than x." }, { "code": null, "e": 2366, "s": 2132, "text": "Example : In the below example conversion from float to int has been achieved using the floor() and ceil() methods, the former returns an int no larger than the input and the latter returns the smallest integer larger than the input." }, { "code": null, "e": 2374, "s": 2366, "text": "Python3" }, { "code": "# conversion using floor and ceil . # importing math moduleimport math num = 5.6 floor_value = math.floor(num) ceil_value = math.ceil(num) print(\"the result using floor() : \", floor_value , ', type : ',type(floor_value).__name__) print(\"the result using ceil() : \", ceil_value, ', type: ', type(ceil_value).__name__)", "e": 2727, "s": 2374, "text": null }, { "code": null, "e": 2735, "s": 2727, "text": "Output:" }, { "code": null, "e": 2822, "s": 2735, "text": "the result using floor() : 5 , type : int\nthe result using ceil() : 6 , type: int" }, { "code": null, "e": 2836, "s": 2822, "text": "python-basics" }, { "code": null, "e": 2843, "s": 2836, "text": "Python" }, { "code": null, "e": 2941, "s": 2843, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2983, "s": 2941, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 3005, "s": 2983, "text": "Enumerate() in Python" }, { "code": null, "e": 3040, "s": 3005, "text": "Read a file line by line in Python" }, { "code": null, "e": 3066, "s": 3040, "text": "Python String | replace()" }, { "code": null, "e": 3098, "s": 3066, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 3127, "s": 3098, "text": "*args and **kwargs in Python" }, { "code": null, "e": 3154, "s": 3127, "text": "Python Classes and Objects" }, { "code": null, "e": 3184, "s": 3154, "text": "Iterate over a list in Python" }, { "code": null, "e": 3205, "s": 3184, "text": "Python OOPs Concepts" } ]
Search Pattern (Rabin-Karp Algorithm) | Practice | GeeksforGeeks
Given two strings, one is a text string and other is a pattern string. The task is to print the indexes of all the occurences of pattern string in the text string. For printing, Starting Index of a string should be taken as 1. Example 1: Input: S = "batmanandrobinarebat", pat = "bat" Output: 1 18 Explanation: The string "bat" occurs twice in S, one starts are index 1 and the other at index 18. ​Example 2: Input: S = "abesdu", pat = "edu" Output: -1 Explanation: There's not substring "edu" present in S. Your Task: You don't need to read input or print anything. Your task is to complete the function search() which takes the string S and the string pat as inputs and returns an array denoting the start indices (1-based) of substring pat in the string S. Expected Time Complexity: O(|S|*|pat|). Expected Auxiliary Space: O(1). Constraints: 1<=|S|<=105 1<=|pat|<|S| -1 nitinmahobe1112 weeks ago //simple c++ solution vector <int> search(string pat, string str) { vector<int> ans;for(int i=0;i<str.length();i++){ int j=i; string check=""; int k=0; while(str[j]==pat[k]) { check+=str[j]; if(check==pat) { ans.push_back(i+1); break; } j++; k++; }}if(ans.size()==0){ ans.push_back(-1);}return ans; } 0 aloksinghbais022 weeks ago C++ solution having time complexity as O(|txt|*|pat|) and auxiliary space complexity as O(1) is as follows :- Execution Time :- 0.03 / 3.4 sec vector <int> search(string pat, string txt){ vector<int> ans; for(int i = 0; i < txt.length(); i++){ if(pat[0] == txt[i]){ int j, k; for(j = i, k = 0; j < txt.length() && k < pat.length(); j++,k++){ if(txt[j] != pat[k]) break; } if(k == pat.length()){ ans.push_back(i+1); } } } if(!ans.size()) ans.push_back(-1); return (ans); } 0 amarrajsmart1971 month ago //C++ CODE // Time Taken 0.1/3.4 //***********Without Using Rabin-Krap Algorithm****************** vector <int> search(string pat, string txt) { //code here. vector <int> v; int n=txt.length(); int m=pat.length(); for(int i=0;i<n;i++) { if(txt.substr(i,m)==pat) { v.push_back(i+1); } } if(!v.empty()) return v; else { v.push_back(-1); return v; } } 0 ravi1010prakash1 month ago class Solution{ public:void fillLPS(string str,int *lps) { int n=str.length(),len=0; //int lps[n]; lps[0]=0; int i=1; while(i<n){ if(str[i]==str[len]) {len++;lps[i]=len;i++;} else {if(len==0){lps[i]=0;i++;} else{len=lps[len-1];} } }} vector <int> search(string pat, string txt) { vector<int>v; int n=txt.length(); int m=pat.length(); int lps[m]; int j=0,i=0; fillLPS(pat,lps); while(i<n) { if(pat[j]==txt[i]) { i++; j++; } if(j==m) { v.push_back(i-j+1); j=lps[j-1]; } else if(i<n&&pat[j]!=txt[i]) { if(j==0) i++; else j=lps[j-1]; } } if(v.size()==0) { v.push_back(-1); return v; } return v; } 0 rajesh02gfg2 months ago SLIDING WINDOW TECHNIQUE || 0.1 SEC vector <int> search(string pat, string txt) { vector<int> v; int idx=1; // according to this question For printing, Starting Index of a string should be taken as 1. string curr=""; int i=0; for(; i<pat.length(); i++) { curr+=txt[i]; } if(pat==curr) v.push_back(idx); for(; i<txt.length(); i++) { curr=curr.substr(1); idx++; curr+=txt[i]; if(pat==curr) v.push_back(idx); } if(v.empty()) v.push_back(-1); return v; } 0 gdhikshith12 months ago vector<int>v; for(int i=0;txt[i]!='\0';i++) { string sub=txt.substr(i,pat.length()); if(sub==pat) { v.push_back(i+1); } } if(v.empty()) return vector<int>{-1}; return v; +1 kake13373 months ago long long t=0,p=0,h=1;// avoid overflows int n=txt.length(), m=pat.length(); int q=1000000007; // "q" should be as big as possible(at least range of txt.length()+7, in this case range of txt.length() is 10^5 so "q" should be at least 10^5+7) int d=256;// d=256 always work(range of char) for(int i=1;i<m;i++) h=(h*d)%q; for(int i=0;i<m;i++) { t=(t*d+txt[i])%q; p=(p*d+pat[i])%q; } vector<int> v; for(int i=0;i<=n-m;i++) { if(t==p) { if(txt.substr(i,m)==pat) v.push_back(i+1); } if(i<n-m){ t=(d*(t-h*txt[i])+txt[i+m])%q; if(t<0) t+=q; } } if(v.size()==0) { v.push_back(-1); return v; } return v; 0 manishmaheshwari81333 months ago JAVA CODE Time Complexity: O(|S|*|pat|)Space Complexity: O(1) **without Rabin-Karp Algorithm** class Solution { ArrayList<Integer> search(String pat, String S) { ArrayList<Integer> arr=new ArrayList<>(); if(!S.contains(pat)){ arr.add(-1); return arr; } int n=pat.length(); for(int i=0;i<=S.length()-n;i++){ if(pat.equals(S.substring(i,i+n))){ arr.add(i+1); } } return arr; } } 0 akashindranagar3 months ago *********Java Code **********Total Time (0.6) class Solution{ ArrayList<Integer> search(String pat, String S) { // your code here ArrayList<Integer>list=new ArrayList<Integer>(); if(!S.contains(pat)) { list.add(-1); return list; } for(int i=0;i<S.length()-pat.length()+1;i++) if(S.substring(i,i+pat.length()).equals(pat)) list.add(i+1); return list; }} -1 imranwahid4 months ago Easy C++ solution https://ide.geeksforgeeks.org/8m9q5HjfzY 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": 465, "s": 238, "text": "Given two strings, one is a text string and other is a pattern string. The task is to print the indexes of all the occurences of pattern string in the text string. For printing, Starting Index of a string should be taken as 1." }, { "code": null, "e": 476, "s": 465, "text": "Example 1:" }, { "code": null, "e": 637, "s": 476, "text": "Input:\nS = \"batmanandrobinarebat\", pat = \"bat\"\nOutput: 1 18\nExplanation: The string \"bat\" occurs twice\nin S, one starts are index 1 and the other\nat index 18. \n" }, { "code": null, "e": 652, "s": 637, "text": "​Example 2:" }, { "code": null, "e": 753, "s": 652, "text": "Input: \nS = \"abesdu\", pat = \"edu\"\nOutput: -1\nExplanation: There's not substring \"edu\"\npresent in S.\n" }, { "code": null, "e": 1007, "s": 753, "text": "\nYour Task:\nYou don't need to read input or print anything. Your task is to complete the function search() which takes the string S and the string pat as inputs and returns an array denoting the start indices (1-based) of substring pat in the string S. " }, { "code": null, "e": 1080, "s": 1007, "text": "\nExpected Time Complexity: O(|S|*|pat|).\nExpected Auxiliary Space: O(1)." }, { "code": null, "e": 1119, "s": 1080, "text": "\nConstraints:\n1<=|S|<=105\n1<=|pat|<|S|" }, { "code": null, "e": 1124, "s": 1121, "text": "-1" }, { "code": null, "e": 1150, "s": 1124, "text": "nitinmahobe1112 weeks ago" }, { "code": null, "e": 1172, "s": 1150, "text": "//simple c++ solution" }, { "code": null, "e": 1489, "s": 1174, "text": " vector <int> search(string pat, string str) { vector<int> ans;for(int i=0;i<str.length();i++){ int j=i; string check=\"\"; int k=0; while(str[j]==pat[k]) { check+=str[j]; if(check==pat) { ans.push_back(i+1); break; } j++; k++; }}if(ans.size()==0){ ans.push_back(-1);}return ans; }" }, { "code": null, "e": 1491, "s": 1489, "text": "0" }, { "code": null, "e": 1518, "s": 1491, "text": "aloksinghbais022 weeks ago" }, { "code": null, "e": 1629, "s": 1518, "text": "C++ solution having time complexity as O(|txt|*|pat|) and auxiliary space complexity as O(1) is as follows :- " }, { "code": null, "e": 1664, "s": 1631, "text": "Execution Time :- 0.03 / 3.4 sec" }, { "code": null, "e": 2232, "s": 1666, "text": "vector <int> search(string pat, string txt){ vector<int> ans; for(int i = 0; i < txt.length(); i++){ if(pat[0] == txt[i]){ int j, k; for(j = i, k = 0; j < txt.length() && k < pat.length(); j++,k++){ if(txt[j] != pat[k]) break; } if(k == pat.length()){ ans.push_back(i+1); } } } if(!ans.size()) ans.push_back(-1); return (ans); }" }, { "code": null, "e": 2234, "s": 2232, "text": "0" }, { "code": null, "e": 2261, "s": 2234, "text": "amarrajsmart1971 month ago" }, { "code": null, "e": 2272, "s": 2261, "text": "//C++ CODE" }, { "code": null, "e": 2295, "s": 2272, "text": "// Time Taken 0.1/3.4 " }, { "code": null, "e": 2361, "s": 2295, "text": "//***********Without Using Rabin-Krap Algorithm******************" }, { "code": null, "e": 2406, "s": 2361, "text": " vector <int> search(string pat, string txt)" }, { "code": null, "e": 2416, "s": 2406, "text": " {" }, { "code": null, "e": 2441, "s": 2416, "text": " //code here." }, { "code": null, "e": 2470, "s": 2441, "text": " vector <int> v;" }, { "code": null, "e": 2503, "s": 2470, "text": " int n=txt.length();" }, { "code": null, "e": 2536, "s": 2503, "text": " int m=pat.length();" }, { "code": null, "e": 2569, "s": 2536, "text": " for(int i=0;i<n;i++)" }, { "code": null, "e": 2583, "s": 2569, "text": " {" }, { "code": null, "e": 2627, "s": 2583, "text": " if(txt.substr(i,m)==pat)" }, { "code": null, "e": 2648, "s": 2627, "text": " {" }, { "code": null, "e": 2714, "s": 2673, "text": " v.push_back(i+1);" }, { "code": null, "e": 2735, "s": 2714, "text": " }" }, { "code": null, "e": 2765, "s": 2751, "text": " }" }, { "code": null, "e": 2792, "s": 2765, "text": " if(!v.empty())" }, { "code": null, "e": 2814, "s": 2792, "text": " return v;" }, { "code": null, "e": 2831, "s": 2814, "text": " else" }, { "code": null, "e": 2845, "s": 2831, "text": " {" }, { "code": null, "e": 2878, "s": 2845, "text": " v.push_back(-1);" }, { "code": null, "e": 2904, "s": 2878, "text": " return v;" }, { "code": null, "e": 2918, "s": 2904, "text": " }" }, { "code": null, "e": 2941, "s": 2931, "text": " }" }, { "code": null, "e": 2943, "s": 2941, "text": "0" }, { "code": null, "e": 2970, "s": 2943, "text": "ravi1010prakash1 month ago" }, { "code": null, "e": 4088, "s": 2970, "text": "class Solution{ public:void fillLPS(string str,int *lps) { int n=str.length(),len=0; //int lps[n]; lps[0]=0; int i=1; while(i<n){ if(str[i]==str[len]) {len++;lps[i]=len;i++;} else {if(len==0){lps[i]=0;i++;} else{len=lps[len-1];} } }} vector <int> search(string pat, string txt) { vector<int>v; int n=txt.length(); int m=pat.length(); int lps[m]; int j=0,i=0; fillLPS(pat,lps); while(i<n) { if(pat[j]==txt[i]) { i++; j++; } if(j==m) { v.push_back(i-j+1); j=lps[j-1]; } else if(i<n&&pat[j]!=txt[i]) { if(j==0) i++; else j=lps[j-1]; } } if(v.size()==0) { v.push_back(-1); return v; } return v; }" }, { "code": null, "e": 4090, "s": 4088, "text": "0" }, { "code": null, "e": 4114, "s": 4090, "text": "rajesh02gfg2 months ago" }, { "code": null, "e": 4150, "s": 4114, "text": "SLIDING WINDOW TECHNIQUE || 0.1 SEC" }, { "code": null, "e": 4777, "s": 4150, "text": "vector <int> search(string pat, string txt) { vector<int> v; int idx=1; // according to this question For printing, Starting Index of a string should be taken as 1. string curr=\"\"; int i=0; for(; i<pat.length(); i++) { curr+=txt[i]; } if(pat==curr) v.push_back(idx); for(; i<txt.length(); i++) { curr=curr.substr(1); idx++; curr+=txt[i]; if(pat==curr) v.push_back(idx); } if(v.empty()) v.push_back(-1); return v; }" }, { "code": null, "e": 4779, "s": 4777, "text": "0" }, { "code": null, "e": 4803, "s": 4779, "text": "gdhikshith12 months ago" }, { "code": null, "e": 5097, "s": 4803, "text": "vector<int>v; for(int i=0;txt[i]!='\\0';i++) { string sub=txt.substr(i,pat.length()); if(sub==pat) { v.push_back(i+1); } } if(v.empty()) return vector<int>{-1}; return v;" }, { "code": null, "e": 5100, "s": 5097, "text": "+1" }, { "code": null, "e": 5121, "s": 5100, "text": "kake13373 months ago" }, { "code": null, "e": 6145, "s": 5121, "text": " long long t=0,p=0,h=1;// avoid overflows\n int n=txt.length(), m=pat.length();\n \n int q=1000000007; // \"q\" should be as big as possible(at least range of txt.length()+7, in this case range of txt.length() is 10^5 so \"q\" should be at least 10^5+7)\n \n int d=256;// d=256 always work(range of char)\n for(int i=1;i<m;i++)\n h=(h*d)%q;\n for(int i=0;i<m;i++)\n {\n t=(t*d+txt[i])%q;\n p=(p*d+pat[i])%q;\n }\n vector<int> v;\n for(int i=0;i<=n-m;i++)\n {\n if(t==p)\n {\n if(txt.substr(i,m)==pat)\n v.push_back(i+1);\n }\n if(i<n-m){\n t=(d*(t-h*txt[i])+txt[i+m])%q;\n if(t<0)\n t+=q;\n }\n }\n if(v.size()==0)\n {\n v.push_back(-1);\n return v;\n }\n return v;" }, { "code": null, "e": 6147, "s": 6145, "text": "0" }, { "code": null, "e": 6180, "s": 6147, "text": "manishmaheshwari81333 months ago" }, { "code": null, "e": 6190, "s": 6180, "text": "JAVA CODE" }, { "code": null, "e": 6242, "s": 6190, "text": "Time Complexity: O(|S|*|pat|)Space Complexity: O(1)" }, { "code": null, "e": 6275, "s": 6242, "text": "**without Rabin-Karp Algorithm**" }, { "code": null, "e": 6702, "s": 6275, "text": "class Solution\n{\n ArrayList<Integer> search(String pat, String S)\n {\n ArrayList<Integer> arr=new ArrayList<>();\n if(!S.contains(pat)){\n arr.add(-1);\n return arr;\n }\n \n int n=pat.length();\n for(int i=0;i<=S.length()-n;i++){\n if(pat.equals(S.substring(i,i+n))){\n arr.add(i+1);\n }\n }\n return arr;\n }\n}" }, { "code": null, "e": 6706, "s": 6704, "text": "0" }, { "code": null, "e": 6734, "s": 6706, "text": "akashindranagar3 months ago" }, { "code": null, "e": 6780, "s": 6734, "text": "*********Java Code **********Total Time (0.6)" }, { "code": null, "e": 7175, "s": 6780, "text": "class Solution{ ArrayList<Integer> search(String pat, String S) { // your code here ArrayList<Integer>list=new ArrayList<Integer>(); if(!S.contains(pat)) { list.add(-1); return list; } for(int i=0;i<S.length()-pat.length()+1;i++) if(S.substring(i,i+pat.length()).equals(pat)) list.add(i+1); return list; }}" }, { "code": null, "e": 7178, "s": 7175, "text": "-1" }, { "code": null, "e": 7201, "s": 7178, "text": "imranwahid4 months ago" }, { "code": null, "e": 7219, "s": 7201, "text": "Easy C++ solution" }, { "code": null, "e": 7260, "s": 7219, "text": "https://ide.geeksforgeeks.org/8m9q5HjfzY" }, { "code": null, "e": 7406, "s": 7260, "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": 7442, "s": 7406, "text": " Login to access your submissions. " }, { "code": null, "e": 7452, "s": 7442, "text": "\nProblem\n" }, { "code": null, "e": 7462, "s": 7452, "text": "\nContest\n" }, { "code": null, "e": 7525, "s": 7462, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 7673, "s": 7525, "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": 7881, "s": 7673, "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": 7987, "s": 7881, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
Arrays in Java - GeeksforGeeks
31 Mar, 2022 An array in Java is a group of like-typed variables referred to by a common name. Arrays in Java work differently than they do in C/C++. Following are some important points about Java arrays. In Java, all arrays are dynamically allocated. (discussed below) Since arrays are objects in Java, we can find their length using the object property length. This is different from C/C++, where we find length using sizeof. A Java array variable can also be declared like other variables with [] after the data type. The variables in the array are ordered, and each has an index beginning from 0. Java array can be also be used as a static field, a local variable, or a method parameter. The size of an array must be specified by int or short value and not long. The direct superclass of an array type is Object. Every array type implements the interfaces Cloneable and java.io.Serializable. An array can contain primitives (int, char, etc.) and object (or non-primitive) references of a class depending on the definition of the array. In the case of primitive data types, the actual values are stored in contiguous memory locations. In the case of class objects, the actual objects are stored in a heap segment. One-Dimensional Arrays: The general form of a one-dimensional array declaration is type var-name[]; OR type[] var-name; An array declaration has two components: the type and the name. type declares the element type of the array. The element type determines the data type of each element that comprises the array. Like an array of integers, we can also create an array of other primitive data types like char, float, double, etc., or user-defined data types (objects of a class). Thus, the element type for the array determines what type of data the array will hold. Example: // both are valid declarations int intArray[]; or int[] intArray; byte byteArray[]; short shortsArray[]; boolean booleanArray[]; long longArray[]; float floatArray[]; double doubleArray[]; char charArray[]; // an array of references to objects of // the class MyClass (a class created by // user) MyClass myClassArray[]; Object[] ao, // array of Object Collection[] ca; // array of Collection // of unknown type Although the first declaration establishes that intArray is an array variable, no actual array exists. It merely tells the compiler that this variable (intArray) will hold an array of the integer type. To link intArray with an actual, physical array of integers, you must allocate one using new and assign it to intArray. When an array is declared, only a reference of an array is created. To create or give memory to the array, you create an array like this: The general form of new as it applies to one-dimensional arrays appears as follows: var-name = new type [size]; Here, type specifies the type of data being allocated, size determines the number of elements in the array, and var-name is the name of the array variable that is linked to the array. To use new to allocate an array, you must specify the type and number of elements to allocate. Example: int intArray[]; //declaring array intArray = new int[20]; // allocating memory to array OR int[] intArray = new int[20]; // combining both statements in one Note : The elements in the array allocated by new will automatically be initialized to zero (for numeric types), false (for boolean), or null (for reference types). Refer Default array values in JavaObtaining an array is a two-step process. First, you must declare a variable of the desired array type. Second, you must allocate the memory to hold the array, using new, and assign it to the array variable. Thus, in Java, all arrays are dynamically allocated. The elements in the array allocated by new will automatically be initialized to zero (for numeric types), false (for boolean), or null (for reference types). Refer Default array values in Java Obtaining an array is a two-step process. First, you must declare a variable of the desired array type. Second, you must allocate the memory to hold the array, using new, and assign it to the array variable. Thus, in Java, all arrays are dynamically allocated. In a situation where the size of the array and variables of the array are already known, array literals can be used. int[] intArray = new int[]{ 1,2,3,4,5,6,7,8,9,10 }; // Declaring array literal The length of this array determines the length of the created array. There is no need to write the new int[] part in the latest versions of Java. Each element in the array is accessed via its index. The index begins with 0 and ends at (total array size)-1. All the elements of array can be accessed using Java for Loop. // accessing the elements of the specified array for (int i = 0; i < arr.length; i++) System.out.println("Element at index " + i + " : "+ arr[i]); Implementation: Java // Java program to illustrate creating an array// of integers, puts some values in the array,// and prints each value to standard output. class GFG{ public static void main (String[] args) { // declares an Array of integers. int[] arr; // allocating memory for 5 integers. arr = new int[5]; // initialize the first elements of the array arr[0] = 10; // initialize the second elements of the array arr[1] = 20; //so on... arr[2] = 30; arr[3] = 40; arr[4] = 50; // accessing the elements of the specified array for (int i = 0; i < arr.length; i++) System.out.println("Element at index " + i + " : "+ arr[i]); }} Element at index 0 : 10 Element at index 1 : 20 Element at index 2 : 30 Element at index 3 : 40 Element at index 4 : 50 Time Complexity: O(n) Auxiliary Space : O(1) You can also access java arrays using foreach loops. An array of objects is created like an array of primitive type data items in the following way. Student[] arr = new Student[7]; //student is a user-defined class The studentArray contains seven memory spaces each of the size of student class in which the address of seven Student objects can be stored. The Student objects have to be instantiated using the constructor of the Student class, and their references should be assigned to the array elements in the following way. Student[] arr = new Student[5]; Java // Java program to illustrate creating// an array of objects class Student{ public int roll_no; public String name; Student(int roll_no, String name) { this.roll_no = roll_no; this.name = name; }} // Elements of the array are objects of a class Student.public class GFG{ public static void main (String[] args) { // declares an Array of integers. Student[] arr; // allocating memory for 5 objects of type Student. arr = new Student[5]; // initialize the first elements of the array arr[0] = new Student(1,"aman"); // initialize the second elements of the array arr[1] = new Student(2,"vaibhav"); // so on... arr[2] = new Student(3,"shikar"); arr[3] = new Student(4,"dharmesh"); arr[4] = new Student(5,"mohit"); // accessing the elements of the specified array for (int i = 0; i < arr.length; i++) System.out.println("Element at " + i + " : " + arr[i].roll_no +" "+ arr[i].name); }} Element at 0 : 1 aman Element at 1 : 2 vaibhav Element at 2 : 3 shikar Element at 3 : 4 dharmesh Element at 4 : 5 mohit Time Complexity: O(n) Auxiliary Space : O(1) JVM throws ArrayIndexOutOfBoundsException to indicate that the array has been accessed with an illegal index. The index is either negative or greater than or equal to the size of an array. Java public class GFG{ public static void main (String[] args) { int[] arr = new int[2]; arr[0] = 10; arr[1] = 20; for (int i = 0; i <= arr.length; i++) System.out.println(arr[i]); }} Runtime error Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 2 at GFG.main(File.java:12) Output 10 20 Multidimensional arrays are arrays of arrays with each element of the array holding the reference of other arrays. These are also known as Jagged Arrays. A multidimensional array is created by appending one set of square brackets ([]) per dimension. Examples: int[][] intArray = new int[10][20]; //a 2D array or matrix int[][][] intArray = new int[10][20][10]; //a 3D array Java public class multiDimensional{ public static void main(String args[]) { // declaring and initializing 2D array int arr[][] = { {2,7,9},{3,6,1},{7,4,2} }; // printing 2D array for (int i=0; i< 3 ; i++) { for (int j=0; j < 3 ; j++) System.out.print(arr[i][j] + " "); System.out.println(); } }} 2 7 9 3 6 1 7 4 2 Like variables, we can also pass arrays to methods. For example, the below program passes the array to method sum to calculate the sum of the array’s values. Java // Java program to demonstrate// passing of array to method public class Test{ // Driver method public static void main(String args[]) { int arr[] = {3, 1, 2, 5, 4}; // passing array to method m1 sum(arr); } public static void sum(int[] arr) { // getting sum of array values int sum = 0; for (int i = 0; i < arr.length; i++) sum+=arr[i]; System.out.println("sum of array values : " + sum); }} sum of array values : 15 Time Complexity: O(n) Auxiliary Space : O(1) As usual, a method can also return an array. For example, the below program returns an array from method m1. Java // Java program to demonstrate// return of array from method class Test{ // Driver method public static void main(String args[]) { int arr[] = m1(); for (int i = 0; i < arr.length; i++) System.out.print(arr[i]+" "); } public static int[] m1() { // returning array return new int[]{1,2,3}; }} 1 2 3 Time Complexity: O(n) Auxiliary Space : O(1) Every array has an associated Class object, shared with all other arrays with the same component type. Java // Java program to demonstrate// Class Objects for Arrays class Test{ public static void main(String args[]) { int intArray[] = new int[3]; byte byteArray[] = new byte[3]; short shortsArray[] = new short[3]; // array of Strings String[] strArray = new String[3]; System.out.println(intArray.getClass()); System.out.println(intArray.getClass().getSuperclass()); System.out.println(byteArray.getClass()); System.out.println(shortsArray.getClass()); System.out.println(strArray.getClass()); }} class [I class java.lang.Object class [B class [S class [Ljava.lang.String; Explanation: The string “[I” is the run-time type signature for the class object “array with component type int.”The only direct superclass of an array type is java.lang.Object.The string “[B” is the run-time type signature for the class object “array with component type byte.”The string “[S” is the run-time type signature for the class object “array with component type short.”The string “[L” is the run-time type signature for the class object “array with component type of a Class.” The Class name is then followed. The string “[I” is the run-time type signature for the class object “array with component type int.” The only direct superclass of an array type is java.lang.Object. The string “[B” is the run-time type signature for the class object “array with component type byte.” The string “[S” is the run-time type signature for the class object “array with component type short.” The string “[L” is the run-time type signature for the class object “array with component type of a Class.” The Class name is then followed. Now, as you know that arrays are objects of a class, and a direct superclass of arrays is a class Object. The members of an array type are all of the following: The public final field length, which contains the number of components of the array. Length may be positive or zero. All the members inherited from class Object; the only method of Object that is not inherited is its clone method. The public method clone(), which overrides the clone method in class Object and throws no checked exceptions. When you clone a single-dimensional array, such as Object[], a “deep copy” is performed with the new array containing copies of the original array’s elements as opposed to references. Java // Java program to demonstrate// cloning of one-dimensional arrays class Test{ public static void main(String args[]) { int intArray[] = {1,2,3}; int cloneArray[] = intArray.clone(); // will print false as deep copy is created // for one-dimensional array System.out.println(intArray == cloneArray); for (int i = 0; i < cloneArray.length; i++) { System.out.print(cloneArray[i]+" "); } }} false 1 2 3 A clone of a multi-dimensional array (like Object[][]) is a “shallow copy,” however, which is to say that it creates only a single new array with each element array a reference to an original element array, but subarrays are shared. Java // Java program to demonstrate// cloning of multi-dimensional arrays class Test{ public static void main(String args[]) { int intArray[][] = {{1,2,3},{4,5}}; int cloneArray[][] = intArray.clone(); // will print false System.out.println(intArray == cloneArray); // will print true as shallow copy is created // i.e. sub-arrays are shared System.out.println(intArray[0] == cloneArray[0]); System.out.println(intArray[1] == cloneArray[1]); }} false true true Related Articles: Jagged Array in Java For-each loop in Java Arrays class in Java This article is contributed by Nitsdheerendra and Gaurav Miglani. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. PranjalDeshmukh VaiBzZk ArvindKumarMaurya shubham_singh nitinp12 theohollweg nishkarshgandhi rishavnitro Java-Arrays java-basics Arrays Java Arrays Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Top 50 Array Coding Problems for Interviews Largest Sum Contiguous Subarray Linear Search Maximum and minimum of an array using minimum number of comparisons Multidimensional Arrays in Java Split() String method in Java with examples For-each loop in Java Reverse a string in Java Arrays.sort() in Java with examples HashMap in Java with Examples
[ { "code": null, "e": 37678, "s": 37650, "text": "\n31 Mar, 2022" }, { "code": null, "e": 37871, "s": 37678, "text": "An array in Java is a group of like-typed variables referred to by a common name. Arrays in Java work differently than they do in C/C++. Following are some important points about Java arrays. " }, { "code": null, "e": 37936, "s": 37871, "text": "In Java, all arrays are dynamically allocated. (discussed below)" }, { "code": null, "e": 38094, "s": 37936, "text": "Since arrays are objects in Java, we can find their length using the object property length. This is different from C/C++, where we find length using sizeof." }, { "code": null, "e": 38187, "s": 38094, "text": "A Java array variable can also be declared like other variables with [] after the data type." }, { "code": null, "e": 38267, "s": 38187, "text": "The variables in the array are ordered, and each has an index beginning from 0." }, { "code": null, "e": 38358, "s": 38267, "text": "Java array can be also be used as a static field, a local variable, or a method parameter." }, { "code": null, "e": 38433, "s": 38358, "text": "The size of an array must be specified by int or short value and not long." }, { "code": null, "e": 38483, "s": 38433, "text": "The direct superclass of an array type is Object." }, { "code": null, "e": 38562, "s": 38483, "text": "Every array type implements the interfaces Cloneable and java.io.Serializable." }, { "code": null, "e": 38885, "s": 38562, "text": "An array can contain primitives (int, char, etc.) and object (or non-primitive) references of a class depending on the definition of the array. In the case of primitive data types, the actual values are stored in contiguous memory locations. In the case of class objects, the actual objects are stored in a heap segment. " }, { "code": null, "e": 38910, "s": 38885, "text": "One-Dimensional Arrays: " }, { "code": null, "e": 38970, "s": 38910, "text": "The general form of a one-dimensional array declaration is " }, { "code": null, "e": 39007, "s": 38970, "text": "type var-name[];\nOR\ntype[] var-name;" }, { "code": null, "e": 39454, "s": 39007, "text": "An array declaration has two components: the type and the name. type declares the element type of the array. The element type determines the data type of each element that comprises the array. Like an array of integers, we can also create an array of other primitive data types like char, float, double, etc., or user-defined data types (objects of a class). Thus, the element type for the array determines what type of data the array will hold. " }, { "code": null, "e": 39464, "s": 39454, "text": "Example: " }, { "code": null, "e": 39912, "s": 39464, "text": "// both are valid declarations\nint intArray[]; \nor int[] intArray; \n\nbyte byteArray[];\nshort shortsArray[];\nboolean booleanArray[];\nlong longArray[];\nfloat floatArray[];\ndouble doubleArray[];\nchar charArray[];\n\n// an array of references to objects of\n// the class MyClass (a class created by\n// user)\nMyClass myClassArray[]; \n\nObject[] ao, // array of Object\nCollection[] ca; // array of Collection\n // of unknown type" }, { "code": null, "e": 40235, "s": 39912, "text": "Although the first declaration establishes that intArray is an array variable, no actual array exists. It merely tells the compiler that this variable (intArray) will hold an array of the integer type. To link intArray with an actual, physical array of integers, you must allocate one using new and assign it to intArray. " }, { "code": null, "e": 40458, "s": 40235, "text": "When an array is declared, only a reference of an array is created. To create or give memory to the array, you create an array like this: The general form of new as it applies to one-dimensional arrays appears as follows: " }, { "code": null, "e": 40486, "s": 40458, "text": "var-name = new type [size];" }, { "code": null, "e": 40765, "s": 40486, "text": "Here, type specifies the type of data being allocated, size determines the number of elements in the array, and var-name is the name of the array variable that is linked to the array. To use new to allocate an array, you must specify the type and number of elements to allocate." }, { "code": null, "e": 40775, "s": 40765, "text": "Example: " }, { "code": null, "e": 40867, "s": 40775, "text": "int intArray[]; //declaring array\nintArray = new int[20]; // allocating memory to array" }, { "code": null, "e": 40871, "s": 40867, "text": "OR " }, { "code": null, "e": 40937, "s": 40871, "text": "int[] intArray = new int[20]; // combining both statements in one" }, { "code": null, "e": 40945, "s": 40937, "text": "Note : " }, { "code": null, "e": 41398, "s": 40945, "text": "The elements in the array allocated by new will automatically be initialized to zero (for numeric types), false (for boolean), or null (for reference types). Refer Default array values in JavaObtaining an array is a two-step process. First, you must declare a variable of the desired array type. Second, you must allocate the memory to hold the array, using new, and assign it to the array variable. Thus, in Java, all arrays are dynamically allocated." }, { "code": null, "e": 41591, "s": 41398, "text": "The elements in the array allocated by new will automatically be initialized to zero (for numeric types), false (for boolean), or null (for reference types). Refer Default array values in Java" }, { "code": null, "e": 41852, "s": 41591, "text": "Obtaining an array is a two-step process. First, you must declare a variable of the desired array type. Second, you must allocate the memory to hold the array, using new, and assign it to the array variable. Thus, in Java, all arrays are dynamically allocated." }, { "code": null, "e": 41970, "s": 41852, "text": "In a situation where the size of the array and variables of the array are already known, array literals can be used. " }, { "code": null, "e": 42052, "s": 41970, "text": " int[] intArray = new int[]{ 1,2,3,4,5,6,7,8,9,10 }; \n // Declaring array literal" }, { "code": null, "e": 42121, "s": 42052, "text": "The length of this array determines the length of the created array." }, { "code": null, "e": 42198, "s": 42121, "text": "There is no need to write the new int[] part in the latest versions of Java." }, { "code": null, "e": 42372, "s": 42198, "text": "Each element in the array is accessed via its index. The index begins with 0 and ends at (total array size)-1. All the elements of array can be accessed using Java for Loop." }, { "code": null, "e": 42555, "s": 42372, "text": " // accessing the elements of the specified array\nfor (int i = 0; i < arr.length; i++)\n System.out.println(\"Element at index \" + i + \n \" : \"+ arr[i]);" }, { "code": null, "e": 42571, "s": 42555, "text": "Implementation:" }, { "code": null, "e": 42576, "s": 42571, "text": "Java" }, { "code": "// Java program to illustrate creating an array// of integers, puts some values in the array,// and prints each value to standard output. class GFG{ public static void main (String[] args) { // declares an Array of integers. int[] arr; // allocating memory for 5 integers. arr = new int[5]; // initialize the first elements of the array arr[0] = 10; // initialize the second elements of the array arr[1] = 20; //so on... arr[2] = 30; arr[3] = 40; arr[4] = 50; // accessing the elements of the specified array for (int i = 0; i < arr.length; i++) System.out.println(\"Element at index \" + i + \" : \"+ arr[i]); }}", "e": 43373, "s": 42576, "text": null }, { "code": null, "e": 43493, "s": 43373, "text": "Element at index 0 : 10\nElement at index 1 : 20\nElement at index 2 : 30\nElement at index 3 : 40\nElement at index 4 : 50" }, { "code": null, "e": 43515, "s": 43493, "text": "Time Complexity: O(n)" }, { "code": null, "e": 43538, "s": 43515, "text": "Auxiliary Space : O(1)" }, { "code": null, "e": 43593, "s": 43538, "text": "You can also access java arrays using foreach loops. " }, { "code": null, "e": 43690, "s": 43593, "text": "An array of objects is created like an array of primitive type data items in the following way. " }, { "code": null, "e": 43757, "s": 43690, "text": " Student[] arr = new Student[7]; //student is a user-defined class" }, { "code": null, "e": 44071, "s": 43757, "text": "The studentArray contains seven memory spaces each of the size of student class in which the address of seven Student objects can be stored. The Student objects have to be instantiated using the constructor of the Student class, and their references should be assigned to the array elements in the following way. " }, { "code": null, "e": 44103, "s": 44071, "text": "Student[] arr = new Student[5];" }, { "code": null, "e": 44108, "s": 44103, "text": "Java" }, { "code": "// Java program to illustrate creating// an array of objects class Student{ public int roll_no; public String name; Student(int roll_no, String name) { this.roll_no = roll_no; this.name = name; }} // Elements of the array are objects of a class Student.public class GFG{ public static void main (String[] args) { // declares an Array of integers. Student[] arr; // allocating memory for 5 objects of type Student. arr = new Student[5]; // initialize the first elements of the array arr[0] = new Student(1,\"aman\"); // initialize the second elements of the array arr[1] = new Student(2,\"vaibhav\"); // so on... arr[2] = new Student(3,\"shikar\"); arr[3] = new Student(4,\"dharmesh\"); arr[4] = new Student(5,\"mohit\"); // accessing the elements of the specified array for (int i = 0; i < arr.length; i++) System.out.println(\"Element at \" + i + \" : \" + arr[i].roll_no +\" \"+ arr[i].name); }}", "e": 45166, "s": 44108, "text": null }, { "code": null, "e": 45286, "s": 45166, "text": "Element at 0 : 1 aman\nElement at 1 : 2 vaibhav\nElement at 2 : 3 shikar\nElement at 3 : 4 dharmesh\nElement at 4 : 5 mohit" }, { "code": null, "e": 45308, "s": 45286, "text": "Time Complexity: O(n)" }, { "code": null, "e": 45331, "s": 45308, "text": "Auxiliary Space : O(1)" }, { "code": null, "e": 45520, "s": 45331, "text": "JVM throws ArrayIndexOutOfBoundsException to indicate that the array has been accessed with an illegal index. The index is either negative or greater than or equal to the size of an array." }, { "code": null, "e": 45525, "s": 45520, "text": "Java" }, { "code": "public class GFG{ public static void main (String[] args) { int[] arr = new int[2]; arr[0] = 10; arr[1] = 20; for (int i = 0; i <= arr.length; i++) System.out.println(arr[i]); }}", "e": 45753, "s": 45525, "text": null }, { "code": null, "e": 45768, "s": 45753, "text": "Runtime error " }, { "code": null, "e": 45869, "s": 45768, "text": "Exception in thread \"main\" java.lang.ArrayIndexOutOfBoundsException: 2\n at GFG.main(File.java:12)" }, { "code": null, "e": 45876, "s": 45869, "text": "Output" }, { "code": null, "e": 45882, "s": 45876, "text": "10\n20" }, { "code": null, "e": 46143, "s": 45882, "text": "Multidimensional arrays are arrays of arrays with each element of the array holding the reference of other arrays. These are also known as Jagged Arrays. A multidimensional array is created by appending one set of square brackets ([]) per dimension. Examples: " }, { "code": null, "e": 46257, "s": 46143, "text": "int[][] intArray = new int[10][20]; //a 2D array or matrix\nint[][][] intArray = new int[10][20][10]; //a 3D array" }, { "code": null, "e": 46262, "s": 46257, "text": "Java" }, { "code": "public class multiDimensional{ public static void main(String args[]) { // declaring and initializing 2D array int arr[][] = { {2,7,9},{3,6,1},{7,4,2} }; // printing 2D array for (int i=0; i< 3 ; i++) { for (int j=0; j < 3 ; j++) System.out.print(arr[i][j] + \" \"); System.out.println(); } }}", "e": 46644, "s": 46262, "text": null }, { "code": null, "e": 46665, "s": 46644, "text": "2 7 9 \n3 6 1 \n7 4 2 " }, { "code": null, "e": 46823, "s": 46665, "text": "Like variables, we can also pass arrays to methods. For example, the below program passes the array to method sum to calculate the sum of the array’s values." }, { "code": null, "e": 46828, "s": 46823, "text": "Java" }, { "code": "// Java program to demonstrate// passing of array to method public class Test{ // Driver method public static void main(String args[]) { int arr[] = {3, 1, 2, 5, 4}; // passing array to method m1 sum(arr); } public static void sum(int[] arr) { // getting sum of array values int sum = 0; for (int i = 0; i < arr.length; i++) sum+=arr[i]; System.out.println(\"sum of array values : \" + sum); }}", "e": 47338, "s": 46828, "text": null }, { "code": null, "e": 47363, "s": 47338, "text": "sum of array values : 15" }, { "code": null, "e": 47385, "s": 47363, "text": "Time Complexity: O(n)" }, { "code": null, "e": 47408, "s": 47385, "text": "Auxiliary Space : O(1)" }, { "code": null, "e": 47518, "s": 47408, "text": "As usual, a method can also return an array. For example, the below program returns an array from method m1. " }, { "code": null, "e": 47523, "s": 47518, "text": "Java" }, { "code": "// Java program to demonstrate// return of array from method class Test{ // Driver method public static void main(String args[]) { int arr[] = m1(); for (int i = 0; i < arr.length; i++) System.out.print(arr[i]+\" \"); } public static int[] m1() { // returning array return new int[]{1,2,3}; }}", "e": 47894, "s": 47523, "text": null }, { "code": null, "e": 47901, "s": 47894, "text": "1 2 3 " }, { "code": null, "e": 47923, "s": 47901, "text": "Time Complexity: O(n)" }, { "code": null, "e": 47946, "s": 47923, "text": "Auxiliary Space : O(1)" }, { "code": null, "e": 48050, "s": 47946, "text": "Every array has an associated Class object, shared with all other arrays with the same component type. " }, { "code": null, "e": 48055, "s": 48050, "text": "Java" }, { "code": "// Java program to demonstrate// Class Objects for Arrays class Test{ public static void main(String args[]) { int intArray[] = new int[3]; byte byteArray[] = new byte[3]; short shortsArray[] = new short[3]; // array of Strings String[] strArray = new String[3]; System.out.println(intArray.getClass()); System.out.println(intArray.getClass().getSuperclass()); System.out.println(byteArray.getClass()); System.out.println(shortsArray.getClass()); System.out.println(strArray.getClass()); }}", "e": 48643, "s": 48055, "text": null }, { "code": null, "e": 48719, "s": 48643, "text": "class [I\nclass java.lang.Object\nclass [B\nclass [S\nclass [Ljava.lang.String;" }, { "code": null, "e": 48733, "s": 48719, "text": "Explanation: " }, { "code": null, "e": 49241, "s": 48733, "text": "The string “[I” is the run-time type signature for the class object “array with component type int.”The only direct superclass of an array type is java.lang.Object.The string “[B” is the run-time type signature for the class object “array with component type byte.”The string “[S” is the run-time type signature for the class object “array with component type short.”The string “[L” is the run-time type signature for the class object “array with component type of a Class.” The Class name is then followed." }, { "code": null, "e": 49342, "s": 49241, "text": "The string “[I” is the run-time type signature for the class object “array with component type int.”" }, { "code": null, "e": 49407, "s": 49342, "text": "The only direct superclass of an array type is java.lang.Object." }, { "code": null, "e": 49509, "s": 49407, "text": "The string “[B” is the run-time type signature for the class object “array with component type byte.”" }, { "code": null, "e": 49612, "s": 49509, "text": "The string “[S” is the run-time type signature for the class object “array with component type short.”" }, { "code": null, "e": 49753, "s": 49612, "text": "The string “[L” is the run-time type signature for the class object “array with component type of a Class.” The Class name is then followed." }, { "code": null, "e": 49915, "s": 49753, "text": "Now, as you know that arrays are objects of a class, and a direct superclass of arrays is a class Object. The members of an array type are all of the following: " }, { "code": null, "e": 50032, "s": 49915, "text": "The public final field length, which contains the number of components of the array. Length may be positive or zero." }, { "code": null, "e": 50146, "s": 50032, "text": "All the members inherited from class Object; the only method of Object that is not inherited is its clone method." }, { "code": null, "e": 50256, "s": 50146, "text": "The public method clone(), which overrides the clone method in class Object and throws no checked exceptions." }, { "code": null, "e": 50440, "s": 50256, "text": "When you clone a single-dimensional array, such as Object[], a “deep copy” is performed with the new array containing copies of the original array’s elements as opposed to references." }, { "code": null, "e": 50445, "s": 50440, "text": "Java" }, { "code": "// Java program to demonstrate// cloning of one-dimensional arrays class Test{ public static void main(String args[]) { int intArray[] = {1,2,3}; int cloneArray[] = intArray.clone(); // will print false as deep copy is created // for one-dimensional array System.out.println(intArray == cloneArray); for (int i = 0; i < cloneArray.length; i++) { System.out.print(cloneArray[i]+\" \"); } }}", "e": 50932, "s": 50445, "text": null }, { "code": null, "e": 50945, "s": 50932, "text": "false\n1 2 3 " }, { "code": null, "e": 51181, "s": 50947, "text": "A clone of a multi-dimensional array (like Object[][]) is a “shallow copy,” however, which is to say that it creates only a single new array with each element array a reference to an original element array, but subarrays are shared. " }, { "code": null, "e": 51186, "s": 51181, "text": "Java" }, { "code": "// Java program to demonstrate// cloning of multi-dimensional arrays class Test{ public static void main(String args[]) { int intArray[][] = {{1,2,3},{4,5}}; int cloneArray[][] = intArray.clone(); // will print false System.out.println(intArray == cloneArray); // will print true as shallow copy is created // i.e. sub-arrays are shared System.out.println(intArray[0] == cloneArray[0]); System.out.println(intArray[1] == cloneArray[1]); }}", "e": 51730, "s": 51186, "text": null }, { "code": null, "e": 51746, "s": 51730, "text": "false\ntrue\ntrue" }, { "code": null, "e": 51765, "s": 51746, "text": "Related Articles: " }, { "code": null, "e": 51786, "s": 51765, "text": "Jagged Array in Java" }, { "code": null, "e": 51808, "s": 51786, "text": "For-each loop in Java" }, { "code": null, "e": 51829, "s": 51808, "text": "Arrays class in Java" }, { "code": null, "e": 52271, "s": 51829, "text": "This article is contributed by Nitsdheerendra and Gaurav Miglani. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 52287, "s": 52271, "text": "PranjalDeshmukh" }, { "code": null, "e": 52295, "s": 52287, "text": "VaiBzZk" }, { "code": null, "e": 52313, "s": 52295, "text": "ArvindKumarMaurya" }, { "code": null, "e": 52327, "s": 52313, "text": "shubham_singh" }, { "code": null, "e": 52336, "s": 52327, "text": "nitinp12" }, { "code": null, "e": 52348, "s": 52336, "text": "theohollweg" }, { "code": null, "e": 52364, "s": 52348, "text": "nishkarshgandhi" }, { "code": null, "e": 52376, "s": 52364, "text": "rishavnitro" }, { "code": null, "e": 52388, "s": 52376, "text": "Java-Arrays" }, { "code": null, "e": 52400, "s": 52388, "text": "java-basics" }, { "code": null, "e": 52407, "s": 52400, "text": "Arrays" }, { "code": null, "e": 52412, "s": 52407, "text": "Java" }, { "code": null, "e": 52419, "s": 52412, "text": "Arrays" }, { "code": null, "e": 52424, "s": 52419, "text": "Java" }, { "code": null, "e": 52522, "s": 52424, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 52531, "s": 52522, "text": "Comments" }, { "code": null, "e": 52544, "s": 52531, "text": "Old Comments" }, { "code": null, "e": 52588, "s": 52544, "text": "Top 50 Array Coding Problems for Interviews" }, { "code": null, "e": 52620, "s": 52588, "text": "Largest Sum Contiguous Subarray" }, { "code": null, "e": 52634, "s": 52620, "text": "Linear Search" }, { "code": null, "e": 52702, "s": 52634, "text": "Maximum and minimum of an array using minimum number of comparisons" }, { "code": null, "e": 52734, "s": 52702, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 52778, "s": 52734, "text": "Split() String method in Java with examples" }, { "code": null, "e": 52800, "s": 52778, "text": "For-each loop in Java" }, { "code": null, "e": 52825, "s": 52800, "text": "Reverse a string in Java" }, { "code": null, "e": 52861, "s": 52825, "text": "Arrays.sort() in Java with examples" } ]
Design Patterns - Adapter Pattern
Adapter pattern works as a bridge between two incompatible interfaces. This type of design pattern comes under structural pattern as this pattern combines the capability of two independent interfaces. This pattern involves a single class which is responsible to join functionalities of independent or incompatible interfaces. A real life example could be a case of card reader which acts as an adapter between memory card and a laptop. You plugin the memory card into card reader and card reader into the laptop so that memory card can be read via laptop. We are demonstrating use of Adapter pattern via following example in which an audio player device can play mp3 files only and wants to use an advanced audio player capable of playing vlc and mp4 files. We have a MediaPlayer interface and a concrete class AudioPlayer implementing the MediaPlayer interface. AudioPlayer can play mp3 format audio files by default. We are having another interface AdvancedMediaPlayer and concrete classes implementing the AdvancedMediaPlayer interface. These classes can play vlc and mp4 format files. We want to make AudioPlayer to play other formats as well. To attain this, we have created an adapter class MediaAdapter which implements the MediaPlayer interface and uses AdvancedMediaPlayer objects to play the required format. AudioPlayer uses the adapter class MediaAdapter passing it the desired audio type without knowing the actual class which can play the desired format. AdapterPatternDemo, our demo class will use AudioPlayer class to play various formats. Create interfaces for Media Player and Advanced Media Player. MediaPlayer.java public interface MediaPlayer { public void play(String audioType, String fileName); } AdvancedMediaPlayer.java public interface AdvancedMediaPlayer { public void playVlc(String fileName); public void playMp4(String fileName); } Create concrete classes implementing the AdvancedMediaPlayer interface. VlcPlayer.java public class VlcPlayer implements AdvancedMediaPlayer{ @Override public void playVlc(String fileName) { System.out.println("Playing vlc file. Name: "+ fileName); } @Override public void playMp4(String fileName) { //do nothing } } Mp4Player.java public class Mp4Player implements AdvancedMediaPlayer{ @Override public void playVlc(String fileName) { //do nothing } @Override public void playMp4(String fileName) { System.out.println("Playing mp4 file. Name: "+ fileName); } } Create adapter class implementing the MediaPlayer interface. MediaAdapter.java public class MediaAdapter implements MediaPlayer { AdvancedMediaPlayer advancedMusicPlayer; public MediaAdapter(String audioType){ if(audioType.equalsIgnoreCase("vlc") ){ advancedMusicPlayer = new VlcPlayer(); }else if (audioType.equalsIgnoreCase("mp4")){ advancedMusicPlayer = new Mp4Player(); } } @Override public void play(String audioType, String fileName) { if(audioType.equalsIgnoreCase("vlc")){ advancedMusicPlayer.playVlc(fileName); } else if(audioType.equalsIgnoreCase("mp4")){ advancedMusicPlayer.playMp4(fileName); } } } Create concrete class implementing the MediaPlayer interface. AudioPlayer.java public class AudioPlayer implements MediaPlayer { MediaAdapter mediaAdapter; @Override public void play(String audioType, String fileName) { //inbuilt support to play mp3 music files if(audioType.equalsIgnoreCase("mp3")){ System.out.println("Playing mp3 file. Name: " + fileName); } //mediaAdapter is providing support to play other file formats else if(audioType.equalsIgnoreCase("vlc") || audioType.equalsIgnoreCase("mp4")){ mediaAdapter = new MediaAdapter(audioType); mediaAdapter.play(audioType, fileName); } else{ System.out.println("Invalid media. " + audioType + " format not supported"); } } } Use the AudioPlayer to play different types of audio formats. AdapterPatternDemo.java public class AdapterPatternDemo { public static void main(String[] args) { AudioPlayer audioPlayer = new AudioPlayer(); audioPlayer.play("mp3", "beyond the horizon.mp3"); audioPlayer.play("mp4", "alone.mp4"); audioPlayer.play("vlc", "far far away.vlc"); audioPlayer.play("avi", "mind me.avi"); } } Verify the output. Playing mp3 file. Name: beyond the horizon.mp3 Playing mp4 file. Name: alone.mp4 Playing vlc file. Name: far far away.vlc Invalid media. avi format not supported 102 Lectures 10 hours Arnab Chakraborty 30 Lectures 3 hours Arnab Chakraborty 31 Lectures 4 hours Arnab Chakraborty 43 Lectures 1.5 hours Manoj Kumar 7 Lectures 1 hours Zach Miller 54 Lectures 4 hours Sasha Miller Print Add Notes Bookmark this page
[ { "code": null, "e": 2952, "s": 2751, "text": "Adapter pattern works as a bridge between two incompatible interfaces. This type of design pattern comes under structural pattern as this pattern combines the capability of two independent interfaces." }, { "code": null, "e": 3307, "s": 2952, "text": "This pattern involves a single class which is responsible to join functionalities of independent or incompatible interfaces. A real life example could be a case of card reader which acts as an adapter between memory card and a laptop. You plugin the memory card into card reader and card reader into the laptop so that memory card can be read via laptop." }, { "code": null, "e": 3510, "s": 3307, "text": "We are demonstrating use of Adapter pattern via following example in which an audio player device can play mp3 files only and wants to use an advanced audio player capable of playing vlc and mp4 files. " }, { "code": null, "e": 3671, "s": 3510, "text": "We have a MediaPlayer interface and a concrete class AudioPlayer implementing the MediaPlayer interface. AudioPlayer can play mp3 format audio files by default." }, { "code": null, "e": 3841, "s": 3671, "text": "We are having another interface AdvancedMediaPlayer and concrete classes implementing the AdvancedMediaPlayer interface. These classes can play vlc and mp4 format files." }, { "code": null, "e": 4071, "s": 3841, "text": "We want to make AudioPlayer to play other formats as well. To attain this, we have created an adapter class MediaAdapter which implements the MediaPlayer interface and uses AdvancedMediaPlayer objects to play the required format." }, { "code": null, "e": 4308, "s": 4071, "text": "AudioPlayer uses the adapter class MediaAdapter passing it the desired audio type without knowing the actual class which can play the desired format. AdapterPatternDemo, our demo class will use AudioPlayer class to play various formats." }, { "code": null, "e": 4370, "s": 4308, "text": "Create interfaces for Media Player and Advanced Media Player." }, { "code": null, "e": 4387, "s": 4370, "text": "MediaPlayer.java" }, { "code": null, "e": 4476, "s": 4387, "text": "public interface MediaPlayer {\n public void play(String audioType, String fileName);\n}" }, { "code": null, "e": 4501, "s": 4476, "text": "AdvancedMediaPlayer.java" }, { "code": null, "e": 4625, "s": 4501, "text": "public interface AdvancedMediaPlayer {\t\n public void playVlc(String fileName);\n public void playMp4(String fileName);\n}" }, { "code": null, "e": 4697, "s": 4625, "text": "Create concrete classes implementing the AdvancedMediaPlayer interface." }, { "code": null, "e": 4712, "s": 4697, "text": "VlcPlayer.java" }, { "code": null, "e": 4975, "s": 4712, "text": "public class VlcPlayer implements AdvancedMediaPlayer{\n @Override\n public void playVlc(String fileName) {\n System.out.println(\"Playing vlc file. Name: \"+ fileName);\t\t\n }\n\n @Override\n public void playMp4(String fileName) {\n //do nothing\n }\n}" }, { "code": null, "e": 4990, "s": 4975, "text": "Mp4Player.java" }, { "code": null, "e": 5254, "s": 4990, "text": "public class Mp4Player implements AdvancedMediaPlayer{\n\n @Override\n public void playVlc(String fileName) {\n //do nothing\n }\n\n @Override\n public void playMp4(String fileName) {\n System.out.println(\"Playing mp4 file. Name: \"+ fileName);\t\t\n }\n}" }, { "code": null, "e": 5315, "s": 5254, "text": "Create adapter class implementing the MediaPlayer interface." }, { "code": null, "e": 5333, "s": 5315, "text": "MediaAdapter.java" }, { "code": null, "e": 5986, "s": 5333, "text": "public class MediaAdapter implements MediaPlayer {\n\n AdvancedMediaPlayer advancedMusicPlayer;\n\n public MediaAdapter(String audioType){\n \n if(audioType.equalsIgnoreCase(\"vlc\") ){\n advancedMusicPlayer = new VlcPlayer();\t\t\t\n \n }else if (audioType.equalsIgnoreCase(\"mp4\")){\n advancedMusicPlayer = new Mp4Player();\n }\t\n }\n\n @Override\n public void play(String audioType, String fileName) {\n \n if(audioType.equalsIgnoreCase(\"vlc\")){\n advancedMusicPlayer.playVlc(fileName);\n }\n else if(audioType.equalsIgnoreCase(\"mp4\")){\n advancedMusicPlayer.playMp4(fileName);\n }\n }\n}" }, { "code": null, "e": 6048, "s": 5986, "text": "Create concrete class implementing the MediaPlayer interface." }, { "code": null, "e": 6065, "s": 6048, "text": "AudioPlayer.java" }, { "code": null, "e": 6789, "s": 6065, "text": "public class AudioPlayer implements MediaPlayer {\n MediaAdapter mediaAdapter; \n\n @Override\n public void play(String audioType, String fileName) {\t\t\n\n //inbuilt support to play mp3 music files\n if(audioType.equalsIgnoreCase(\"mp3\")){\n System.out.println(\"Playing mp3 file. Name: \" + fileName);\t\t\t\n } \n \n //mediaAdapter is providing support to play other file formats\n else if(audioType.equalsIgnoreCase(\"vlc\") || audioType.equalsIgnoreCase(\"mp4\")){\n mediaAdapter = new MediaAdapter(audioType);\n mediaAdapter.play(audioType, fileName);\n }\n \n else{\n System.out.println(\"Invalid media. \" + audioType + \" format not supported\");\n }\n } \n}" }, { "code": null, "e": 6851, "s": 6789, "text": "Use the AudioPlayer to play different types of audio formats." }, { "code": null, "e": 6875, "s": 6851, "text": "AdapterPatternDemo.java" }, { "code": null, "e": 7210, "s": 6875, "text": "public class AdapterPatternDemo {\n public static void main(String[] args) {\n AudioPlayer audioPlayer = new AudioPlayer();\n\n audioPlayer.play(\"mp3\", \"beyond the horizon.mp3\");\n audioPlayer.play(\"mp4\", \"alone.mp4\");\n audioPlayer.play(\"vlc\", \"far far away.vlc\");\n audioPlayer.play(\"avi\", \"mind me.avi\");\n }\n}" }, { "code": null, "e": 7229, "s": 7210, "text": "Verify the output." }, { "code": null, "e": 7392, "s": 7229, "text": "Playing mp3 file. Name: beyond the horizon.mp3\nPlaying mp4 file. Name: alone.mp4\nPlaying vlc file. Name: far far away.vlc\nInvalid media. avi format not supported\n" }, { "code": null, "e": 7427, "s": 7392, "text": "\n 102 Lectures \n 10 hours \n" }, { "code": null, "e": 7446, "s": 7427, "text": " Arnab Chakraborty" }, { "code": null, "e": 7479, "s": 7446, "text": "\n 30 Lectures \n 3 hours \n" }, { "code": null, "e": 7498, "s": 7479, "text": " Arnab Chakraborty" }, { "code": null, "e": 7531, "s": 7498, "text": "\n 31 Lectures \n 4 hours \n" }, { "code": null, "e": 7550, "s": 7531, "text": " Arnab Chakraborty" }, { "code": null, "e": 7585, "s": 7550, "text": "\n 43 Lectures \n 1.5 hours \n" }, { "code": null, "e": 7598, "s": 7585, "text": " Manoj Kumar" }, { "code": null, "e": 7630, "s": 7598, "text": "\n 7 Lectures \n 1 hours \n" }, { "code": null, "e": 7643, "s": 7630, "text": " Zach Miller" }, { "code": null, "e": 7676, "s": 7643, "text": "\n 54 Lectures \n 4 hours \n" }, { "code": null, "e": 7690, "s": 7676, "text": " Sasha Miller" }, { "code": null, "e": 7697, "s": 7690, "text": " Print" }, { "code": null, "e": 7708, "s": 7697, "text": " Add Notes" } ]
D3.js mouse() Function - GeeksforGeeks
13 Aug, 2020 The d3.mouse() function in D3.js is used to return the x-coordinate and y-coordinate of the current event. If the event is clicked then it returns the x and y position of the click. Syntax: d3.mouse(container); Parameters: This function accepts a single parameter as mentioned above and described below: container: It is the name of the container or the HTML tag to which the event is attached. Return Values: It returns the array of coordinates x and y. Below examples illustrate the D3.js mouse() function In JavaScript: Example1: HTML <!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" path1tent="width=device-width, initial-scale=1.0"/> <title>D3.js mouse() Function</title> </head> <style> div { width: 200px; height: 200px; background-color: green; } </style> <body> <div></div> <script src="https://d3js.org/d3.v4.min.js"> </script> <script src="https://d3js.org/d3-selection.v1.min.js"> </script> <script> let btn = document.querySelector("div"); var div = d3.select("div"); div.on("click", createDot); function createDot() { // Using d3.mouse() function let pos = d3.mouse(this); console.log(pos); } </script> </body></html> Output: Example 2: HTML <!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" path1tent="width=device-width, initial-scale=1.0"/> <title>D3.js mouse() Function</title> </head> <style> .div { width: 200px; height: 200px; background-color: green; overflow: hidden; } div { background-color: red; width: 10px; height: 10px; } </style> <body> <h2>click on the box</h2> <div class="div"></div> <script src="https://d3js.org/d3.v4.min.js"> </script> <script src="https://d3js.org/d3-selection.v1.min.js"> </script> <script> let btn = document.querySelector("div"); var div = d3.select("div"); div.on("click", createDot); function createDot() { // Using d3.mouse() function let pos = d3.mouse(this); console.log(pos); d3.select("div") .append("div") .style("background-color", "white") .style("position", "absolute") .style("margin-left", `${pos[0] - 10}px`) .style("margin-right", `${pos[0] - 10}px`) .style("margin-top", `${pos[1] - 10}px`) .style("margin-bottom", `${pos[1] - 10}px`); } </script> </body></html> Output: Before clicking the box: After clicking the box: D3.js JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Difference between var, let and const keywords in JavaScript Convert a string to an integer 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 ? Top 10 Front End Developer Skills That You Need in 2022 Installation of Node.js on Linux Top 10 Projects For Beginners To Practice HTML and CSS Skills How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 24187, "s": 24159, "text": "\n13 Aug, 2020" }, { "code": null, "e": 24369, "s": 24187, "text": "The d3.mouse() function in D3.js is used to return the x-coordinate and y-coordinate of the current event. If the event is clicked then it returns the x and y position of the click." }, { "code": null, "e": 24377, "s": 24369, "text": "Syntax:" }, { "code": null, "e": 24399, "s": 24377, "text": "d3.mouse(container);\n" }, { "code": null, "e": 24492, "s": 24399, "text": "Parameters: This function accepts a single parameter as mentioned above and described below:" }, { "code": null, "e": 24583, "s": 24492, "text": "container: It is the name of the container or the HTML tag to which the event is attached." }, { "code": null, "e": 24643, "s": 24583, "text": "Return Values: It returns the array of coordinates x and y." }, { "code": null, "e": 24711, "s": 24643, "text": "Below examples illustrate the D3.js mouse() function In JavaScript:" }, { "code": null, "e": 24721, "s": 24711, "text": "Example1:" }, { "code": null, "e": 24726, "s": 24721, "text": "HTML" }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\" /> <meta name=\"viewport\" path1tent=\"width=device-width, initial-scale=1.0\"/> <title>D3.js mouse() Function</title> </head> <style> div { width: 200px; height: 200px; background-color: green; } </style> <body> <div></div> <script src=\"https://d3js.org/d3.v4.min.js\"> </script> <script src=\"https://d3js.org/d3-selection.v1.min.js\"> </script> <script> let btn = document.querySelector(\"div\"); var div = d3.select(\"div\"); div.on(\"click\", createDot); function createDot() { // Using d3.mouse() function let pos = d3.mouse(this); console.log(pos); } </script> </body></html>", "e": 25653, "s": 24726, "text": null }, { "code": null, "e": 25661, "s": 25653, "text": "Output:" }, { "code": null, "e": 25672, "s": 25661, "text": "Example 2:" }, { "code": null, "e": 25677, "s": 25672, "text": "HTML" }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\" /> <meta name=\"viewport\" path1tent=\"width=device-width, initial-scale=1.0\"/> <title>D3.js mouse() Function</title> </head> <style> .div { width: 200px; height: 200px; background-color: green; overflow: hidden; } div { background-color: red; width: 10px; height: 10px; } </style> <body> <h2>click on the box</h2> <div class=\"div\"></div> <script src=\"https://d3js.org/d3.v4.min.js\"> </script> <script src=\"https://d3js.org/d3-selection.v1.min.js\"> </script> <script> let btn = document.querySelector(\"div\"); var div = d3.select(\"div\"); div.on(\"click\", createDot); function createDot() { // Using d3.mouse() function let pos = d3.mouse(this); console.log(pos); d3.select(\"div\") .append(\"div\") .style(\"background-color\", \"white\") .style(\"position\", \"absolute\") .style(\"margin-left\", `${pos[0] - 10}px`) .style(\"margin-right\", `${pos[0] - 10}px`) .style(\"margin-top\", `${pos[1] - 10}px`) .style(\"margin-bottom\", `${pos[1] - 10}px`); } </script> </body></html>", "e": 27202, "s": 25677, "text": null }, { "code": null, "e": 27210, "s": 27202, "text": "Output:" }, { "code": null, "e": 27235, "s": 27210, "text": "Before clicking the box:" }, { "code": null, "e": 27259, "s": 27235, "text": "After clicking the box:" }, { "code": null, "e": 27265, "s": 27259, "text": "D3.js" }, { "code": null, "e": 27276, "s": 27265, "text": "JavaScript" }, { "code": null, "e": 27293, "s": 27276, "text": "Web Technologies" }, { "code": null, "e": 27391, "s": 27293, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27400, "s": 27391, "text": "Comments" }, { "code": null, "e": 27413, "s": 27400, "text": "Old Comments" }, { "code": null, "e": 27474, "s": 27413, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 27519, "s": 27474, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 27591, "s": 27519, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 27643, "s": 27591, "text": "How to append HTML code to a div using JavaScript ?" }, { "code": null, "e": 27689, "s": 27643, "text": "How to Open URL in New Tab using JavaScript ?" }, { "code": null, "e": 27745, "s": 27689, "text": "Top 10 Front End Developer Skills That You Need in 2022" }, { "code": null, "e": 27778, "s": 27745, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 27840, "s": 27778, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 27883, "s": 27840, "text": "How to fetch data from an API in ReactJS ?" } ]
How to draw an average line for a scatter plot in MatPlotLib?
To draw an average line for a plot in matplotlib, we can take the following steps − Set the figure size and adjust the padding between and around the subplots. Set the figure size and adjust the padding between and around the subplots. Make x and y data points using numpy. Make x and y data points using numpy. Use subplots() method to create a figure and a set of subplots. Use subplots() method to create a figure and a set of subplots. Use plot() method for x and y data points. Use plot() method for x and y data points. Find the average value of the array, x. Find the average value of the array, x. Plot x and y_avg data points using plot() method. Plot x and y_avg data points using plot() method. Place a legend on the figure. Place a legend on the figure. To display the figure, use show() method. To display the figure, use show() method. import numpy as np from matplotlib import pyplot as plt plt.rcParams["figure.figsize"] = [7.50, 3.50] plt.rcParams["figure.autolayout"] = True x = np.array([3, 4, 5, 6, 7, 8, 9]) y = np.array([6, 5, 4, 3, 2, 1, 6]) fig, ax = plt.subplots() ax.plot(x, y, 'o-', label='line plot') y_avg = [np.mean(x)] * len(x) ax.plot(x, y_avg, color='red', lw=6, ls='--', label="average plot") plt.legend(loc=0) plt.show()
[ { "code": null, "e": 1146, "s": 1062, "text": "To draw an average line for a plot in matplotlib, we can take the following steps −" }, { "code": null, "e": 1222, "s": 1146, "text": "Set the figure size and adjust the padding between and around the subplots." }, { "code": null, "e": 1298, "s": 1222, "text": "Set the figure size and adjust the padding between and around the subplots." }, { "code": null, "e": 1336, "s": 1298, "text": "Make x and y data points using numpy." }, { "code": null, "e": 1374, "s": 1336, "text": "Make x and y data points using numpy." }, { "code": null, "e": 1438, "s": 1374, "text": "Use subplots() method to create a figure and a set of subplots." }, { "code": null, "e": 1502, "s": 1438, "text": "Use subplots() method to create a figure and a set of subplots." }, { "code": null, "e": 1545, "s": 1502, "text": "Use plot() method for x and y data points." }, { "code": null, "e": 1588, "s": 1545, "text": "Use plot() method for x and y data points." }, { "code": null, "e": 1628, "s": 1588, "text": "Find the average value of the array, x." }, { "code": null, "e": 1668, "s": 1628, "text": "Find the average value of the array, x." }, { "code": null, "e": 1718, "s": 1668, "text": "Plot x and y_avg data points using plot() method." }, { "code": null, "e": 1768, "s": 1718, "text": "Plot x and y_avg data points using plot() method." }, { "code": null, "e": 1798, "s": 1768, "text": "Place a legend on the figure." }, { "code": null, "e": 1828, "s": 1798, "text": "Place a legend on the figure." }, { "code": null, "e": 1870, "s": 1828, "text": "To display the figure, use show() method." }, { "code": null, "e": 1912, "s": 1870, "text": "To display the figure, use show() method." }, { "code": null, "e": 2322, "s": 1912, "text": "import numpy as np\nfrom matplotlib import pyplot as plt\n\nplt.rcParams[\"figure.figsize\"] = [7.50, 3.50]\nplt.rcParams[\"figure.autolayout\"] = True\n\nx = np.array([3, 4, 5, 6, 7, 8, 9])\ny = np.array([6, 5, 4, 3, 2, 1, 6])\n\nfig, ax = plt.subplots()\nax.plot(x, y, 'o-', label='line plot')\ny_avg = [np.mean(x)] * len(x)\nax.plot(x, y_avg, color='red', lw=6, ls='--', label=\"average plot\")\n\nplt.legend(loc=0)\nplt.show()" } ]
Speeding up your Algorithms Part 4— Dask | by Puneet Grover | Towards Data Science
This is the fourth post in a series I am writing. All posts are here: Speed Up your Algorithms Part 1 — PyTorchSpeed Up your Algorithms Part 2 — NumbaSpeed Up your Algorithms Part 3 — ParallelizationSpeed Up your Algorithms Part 4 — Dask Speed Up your Algorithms Part 1 — PyTorch Speed Up your Algorithms Part 2 — Numba Speed Up your Algorithms Part 3 — Parallelization Speed Up your Algorithms Part 4 — Dask And these goes with Jupyter Notebooks available here: [Github-SpeedUpYourAlgorithms] and [Kaggle] (Edit-1/2/2019) — Added more info/possible usage of Dask.distributed.LocalCluster IntroductionData TypesDelayedDistributedMachine LearningFurther ReadingReferences Introduction Data Types Delayed Distributed Machine Learning Further Reading References NOTE:This post goes with Jupyter Notebook available in my Repo on Github:[SpeedUpYourAlgorithms-Dask]and on Kaggle:[SpeedUpYourAlgorithms-Dask] With increasing need for parallelization of Machine Learning algorithms, because of exponential increase in data sizes and even model sizes, it would have been really helpful if we had a tool which could help us parallelize our Pandas's DataFrame handling, which could parallilize our Numpy's computations, and even parallelize our Machine Learning algorithms (maybe algorithms from sklearn and tensorflow) without much hassle. But such a library does exist, and its name is Dask. Dask is a parallel computing library which doesn’t just help parallelize existing Machine Learning tools ( Pandas andNumpy)[i.e. using High Level Collection], but also helps parallelize low level tasks/functions and can handle complex interactions between these functions by making a tasks’ graph.[i.e. using Low Level Schedulers] This is similar to Threading or multiprocessing modules of Python. They also have a separate Machine Learning library, dask-ml, which has integration with existing libraries such as sklearn, xgboost and tensorflow. Dask parallelizes tasks given to it by making a graph of interactions between the tasks. It will be really helpful to visualize what you are doing by using Dask's .visualize() method which is available with all of its data types and with complex chain of tasks you compute. This method will output a graph of your tasks, and if your tasks have many nodes at each level(i.e. your tasks chain structure have many independent tasks at many levels, such as parallelizable task on chunks of data), then Dask will be able to parallelize them. Note:Dask is still a relatively new project. It has a long way to go. Still if you don't want to go through learning a completely new API (like in case of PySpark) Dask is your best option, which surely will get better and better in future. Still Spark/PySpark is ways ahead and will still keep on improving. It is a well established Apache project. I will publish a post on PySpark in coming months.(Today: April'19)If you want to start with PySpark, read this comment here. Each data type in Dask provides a distributed version of existing data types, such as DataFrame from Pandas, ndarray's from numpy, and list from Python. These data types can be larger than your memory, Dask will run computations on your data parallel(y) in Blocked manner. Blocked in the sense that they perform large computations by performing many small computations, i.e. in blocks, and number of blocks are total number of chunks. a) Array: Dask Array operates on very large arrays, by dividing them into chunks and executing those blocks parallely. It has many of numpy methods available which you can use to get speedup. But some of them are not implemented. Dask Array can read from any array like structure given it supports numpy like slicing and has .shape property by using dask.array.from_array method. It can also read from .npy and .zarr files. import dask.array as daimport numpy as nparr = numpy.random.randint(1, 1000, (10000, 10000))darr = da.from_array(arr, chunks=(1000, 1000))# It will make chunks, each of size (1000, 1000)darr.npartitioins# 100 It can be used when your arrays are really heavy (i.e. they won’t fit into memory) and numpy won’t be able to do anything about that. So, Dask divides them into chunks of arrays and operate on them in parallel for you. Now, Dask does lazy evaluation of every method. So, to actually compute the value of a function, you have to use .compute() method. It will compute the result parallely in blocks, parallelizing every independent task at that time. result = darr.compute() b) DataFrame: Similar to Dask Arrays, Dask DataFrames parallelize computation on very large Data Files, which won’t fit on memory, by dividing files into chunks and computing functions to those blocks parallely. import dask.dataframe as dddf = dd.read_csv("BigFile(s).csv", blocksize=50e6) Now you can apply/use most of the functions available in pandas library and apply it here. agg = df.groupby(["column"]).aggregate(["sum", "mean", "max", "min"])agg.columns = new_column_names # see in notebookdf_new = df.merge(agg.reset_index(), on="column", how="left")df_new.compute().head() c) Bag: Dask Bags parallelizes computation on Python's list like objects which contains elements of many data types. It is useful when you are trying to process some semi-structured data like JSON blobs or log files. import dask.bag as dbb = db.from_txt("BigSemiStructuredData.txt")b.take(1) Dask bags reads line by line and .take method outputs tuple of number of lines specified. Dask Bag implements operations like map, filter, fold, and groupby on such collections of Python objects. It does this in parallel with a small memory footprint using Python iterators. It is similar to a parallel version of PyToolz or a Pythonic version of the PySpark RDD. filtered = b.filter(lambda x: x["Name"]=="James")\ .map(lambda x: x["Address"] = "New_Address")filtered.compute() If your task is a little simple and you are not able to or don’t want to do that with these High Level Collections, then you can use Low Level Schedulers which help you to parallelize your code/algorithm using dask.delayed interface. dask.delayed also does lazy computation. import dask.delayed as delay@delaydef sq(x): return x**2@delay def add(x, y): return x+y@delay def sum(arr): sum=0 for i in range(len(arr)): sum+=arr[i] return sum You can add complex interactions between these functions according to your needs using results from previous tasks as an argument to next ones. Dask will not compute these functions right away, rather it will make a graph for your tasks, effectively incorporating interactions between functions that you use. inputs = list(np.arange(1, 11))#Will be addin' dask.delayed to listtemp = []for i in range(len(inputs)): temp.append(sq(inputs[i])) # Compute sq of inputs and save # delayed in listinputs=temp; temp = []for i in range(0, len(inputs)-1, 2): temp.append(add(inputs[i]+inputs[i+1])) # Add two consecutive # results from prev stepinputs = tempresult = sum(inputs) # Sum all results from prev stepresults.compute() You can add delay to any parallelizable code with many possible small blocks and get a speedup. It can be many functions you want to compute like in example above or maybe reading a number of files in parallel using pandas.read_csv. Firstly, until now we have using Dask's default Scheduler for computing results of our tasks. But you can change them according to your needs from the options available from Dask. Dask comes with four available schedulers: “threaded”: a scheduler backed by a thread pool “processes”: a scheduler backed by a process pool “single-threaded” (aka “sync”): a synchronous scheduler, good for debugging distributed: a distributed scheduler for executing graphs on multiple machines result.compute(scheduler="single-threaded") # for debugging# Ordask.config.set(scheduler="single-threaded")result.compute()NOTE: (from official page here)Threaded tasks will work well when the functions called release the GIL, whereas multiprocessing will always have a slower start-up time and suffer where a lot of communication is required between tasks.# And you can get the scheduler by the one of these commands:dask.threaded.get, dask.multiprocessing.get, dask.local.get_sync# last one for "single-threaded" But, Dask has one more scheduler, dask.distributed, and it can be preferred for following reasons: It provides access to asynchronous API, notably Futures,It provides a diagnostic dashboard that can provide valuable insight on performance and progress, andIt handles data locality with more sophistication, and so can be more efficient than the multiprocessing scheduler on workloads that require multiple processes. It provides access to asynchronous API, notably Futures, It provides a diagnostic dashboard that can provide valuable insight on performance and progress, and It handles data locality with more sophistication, and so can be more efficient than the multiprocessing scheduler on workloads that require multiple processes. You can create Dask's dask.distributed Scheduler by importing and creating a Client. from dask.distributed import Clientclient = Client() # Set up a local cluster# You can navigate to http://localhost:8787/status to see the # diagnostic dashboard if you have Bokeh installed. Now you can submit your tasks to this cluster by using client.submit method, giving function and arguments as its parameters. And then we can gather our result by either using client.gather or .result method. sent = client.submit(sq, 4) # sq: square functionresult = client.gather(sent) # Or sent.result() You can also look at progress of your task in current cell only by using dask.distributed.progress. And you can also explicitly opt to wait for a task to complete by using dask.distributed.wait. For more information look here. Note: (Local Cluster)At times you will notice that Dask is exceeding memory use, even though it is dividing tasks. It could be happening to you because of the function you are trying to use on your dataset wants most of your data for processing, and multiprocessing can make things worse as all workers might try to copy dataset to memory. This can happen in aggregating cases.Or maybe you want to restrict Dask to use only specific amount of memory. In these cases you can use Dask.distributed.LocalCluster parameters and pass them to Client() to make a LocalCluster using cores of your Local machines.from dask.distributed import Client, LocalClusterclient = Client(n_workers=1, threads_per_worker=1, processes=False, memory_limit='25GB', scheduler_port=0, silence_logs=True, diagnostics_port=0)client 'scheduler_port=0' and 'diagnostics_port=0' will choose random port number for this particular client. With 'processes=False' dask's client won't copy dataset, which would have happened for every process you might have made.You can tune your client as per your needs or limitations, and for more info you can look into parameters of LocalCluster.You can also use multiple clients on same machine at different ports. Dask also has library which helps in running most popular Machine Learning libraries in parallel, like sklearn, tensorflow and xgboost. In Machine Learning there are a couple of distinct scaling problems you might face. The scaling strategy depends on which problem you’re facing: Large Models: Data fits in RAM, but training takes too long. Many hyperparameter combinations, a large ensemble of many models, etc.Large Datasets: Data is larger than RAM, and sampling isn’t an option. Large Models: Data fits in RAM, but training takes too long. Many hyperparameter combinations, a large ensemble of many models, etc. Large Datasets: Data is larger than RAM, and sampling isn’t an option. So, you should: For in-memory fit-able problems, just use scikit-learn (or your favorite ML library); For large models, use dask_ml.joblib and your favorite scikit-learn estimator; and For large datasets, use dask_ml estimators. a) Preprocessing: dask_ml.preprocessing contains some of the functions from sklearn like RobustScalar, StandardScalar, LabelEncoder, OneHotEncoder, PolynomialFeatures etc., and some of its own such as Categorizer, DummyEncoder, OrdinalEncoder etc. You can use them as you have been using them with Pandas's DataFrame. from dask_ml.preprocessing import RobustScalardf = da.read_csv("BigFile.csv", chunks=50000)rsc = RobustScalar()df["column"] = rsc.fit_transform(df["column"]) And you can make a pipeline from sklearn's make_pipeline method using preprocessing methods of Dask on Dask's DataFrame. b) Hyper Parameter Search: Dask has methods from sklearn for hyperparameter search such as GridSearchCV, RandomizedSearchCV etc. from dask_ml.datasets import make_regressionfrom dask_ml.model_selection import train_test_split, GridSearchCVX, y = make_regression(chunks=50000)xtr, ytr, xval, yval = test_train_split(X, y)gsearch = GridSearchCV(estimator, param_grid, cv=10)gsearch.fit(xtr, ytr) And if you are using partial_fit with your estimators, you can use dask-ml's IncrementalSearchCV. NOTE: (from Dask)If you want to use post-fit tasks like scoring and prediction, then underlying estimators scoring method is used. If your estimator, possibly from sklearn is not able to handle large dataset, then wrap your estimator around "dask_ml.wrappers.ParallelPostFit". It can parallelize methods like "predict", "predict_proba", "transform" etc. c) Models/Estimators: Dask has some of the Linear Models (LinearRegression, LogisticRegression etc.), some Clustering Models ( Kmeans and SpectralClustering), a method to operate with Tensorflow clusters, methods to train XGBoost models using Dask. You can use sklearn's models with Dask, if your training data is small, maybe with with ParallelPostFit wrapper (if your test data is large). from sklearn.linear_model import ElasticNetfrom dask_ml.wrappers import ParallelPostFitel = ParallelPostFit(estimator=ElasticNet())el.fit(Xtrain, ytrain)preds = el.predict(Xtest) If your dataset is not large but your model is big, then you can use joblib. Many sklearns algorithms were written for parallel execution (you might have used n_jobs=-1 argument), using joblib which makes use of threads and processes to parallelize workload. To use Dask to parallelize you can create a Client (you have to) and then wrap your code around with joblib.parallel_backend('dask'):. import dask_ml.joblibfrom sklearn.externals import joblibclient = Client()with joblib.parallel_backend('dask'): # your scikit-learn codeNOTE: Note that the Dask joblib backend is useful for scaling out CPU-bound workloads; workloads with datasets that fit in RAM, but have many individual operations that can be done in parallel. To scale out to RAM-bound workloads (larger-than-memory datasets) you should use Dask's inbuilt models and methods. And if you training data is too big which cannot fit into memory, then you should use Dask's inbuilt estimators to get a speedup. You can also use Dask's wrapper.Incremental which uses underlying estimator’s partial_fit method to train on whole dataset but it is sequential in nature. Dask's inbuilt estimators scale well for large datasets with variety of optimization algorithms like admm, lbfgs, gradient_descent etc. and with regularizers like L1, L2, ElasticNet etc. from dask_ml.linear_model import LogisticRegressionlr = LogisticRegression()lr.fit(X, y, solver="lbfgs") For one more example using Dask you can read Dask's section in my post here. It is a complete walk-through from exploration to training the model. https://mybinder.org/v2/gh/dask/dask-examples/master?urlpath=labhttps://towardsdatascience.com/how-i-learned-to-love-parallelized-applies-with-python-pandas-dask-and-numba-f06b0b367138https://docs.dask.org/en/latest/https://ml.dask.org https://mybinder.org/v2/gh/dask/dask-examples/master?urlpath=lab https://towardsdatascience.com/how-i-learned-to-love-parallelized-applies-with-python-pandas-dask-and-numba-f06b0b367138 https://docs.dask.org/en/latest/ https://ml.dask.org https://ml.dask.orghttps://docs.dask.org/en/latest/ https://ml.dask.org https://docs.dask.org/en/latest/ Suggestions and reviews are welcome.Thank you for reading! Signed: Some rights reserved
[ { "code": null, "e": 242, "s": 172, "text": "This is the fourth post in a series I am writing. All posts are here:" }, { "code": null, "e": 410, "s": 242, "text": "Speed Up your Algorithms Part 1 — PyTorchSpeed Up your Algorithms Part 2 — NumbaSpeed Up your Algorithms Part 3 — ParallelizationSpeed Up your Algorithms Part 4 — Dask" }, { "code": null, "e": 452, "s": 410, "text": "Speed Up your Algorithms Part 1 — PyTorch" }, { "code": null, "e": 492, "s": 452, "text": "Speed Up your Algorithms Part 2 — Numba" }, { "code": null, "e": 542, "s": 492, "text": "Speed Up your Algorithms Part 3 — Parallelization" }, { "code": null, "e": 581, "s": 542, "text": "Speed Up your Algorithms Part 4 — Dask" }, { "code": null, "e": 635, "s": 581, "text": "And these goes with Jupyter Notebooks available here:" }, { "code": null, "e": 679, "s": 635, "text": "[Github-SpeedUpYourAlgorithms] and [Kaggle]" }, { "code": null, "e": 761, "s": 679, "text": "(Edit-1/2/2019) — Added more info/possible usage of Dask.distributed.LocalCluster" }, { "code": null, "e": 843, "s": 761, "text": "IntroductionData TypesDelayedDistributedMachine LearningFurther ReadingReferences" }, { "code": null, "e": 856, "s": 843, "text": "Introduction" }, { "code": null, "e": 867, "s": 856, "text": "Data Types" }, { "code": null, "e": 875, "s": 867, "text": "Delayed" }, { "code": null, "e": 887, "s": 875, "text": "Distributed" }, { "code": null, "e": 904, "s": 887, "text": "Machine Learning" }, { "code": null, "e": 920, "s": 904, "text": "Further Reading" }, { "code": null, "e": 931, "s": 920, "text": "References" }, { "code": null, "e": 1075, "s": 931, "text": "NOTE:This post goes with Jupyter Notebook available in my Repo on Github:[SpeedUpYourAlgorithms-Dask]and on Kaggle:[SpeedUpYourAlgorithms-Dask]" }, { "code": null, "e": 1503, "s": 1075, "text": "With increasing need for parallelization of Machine Learning algorithms, because of exponential increase in data sizes and even model sizes, it would have been really helpful if we had a tool which could help us parallelize our Pandas's DataFrame handling, which could parallilize our Numpy's computations, and even parallelize our Machine Learning algorithms (maybe algorithms from sklearn and tensorflow) without much hassle." }, { "code": null, "e": 1954, "s": 1503, "text": "But such a library does exist, and its name is Dask. Dask is a parallel computing library which doesn’t just help parallelize existing Machine Learning tools ( Pandas andNumpy)[i.e. using High Level Collection], but also helps parallelize low level tasks/functions and can handle complex interactions between these functions by making a tasks’ graph.[i.e. using Low Level Schedulers] This is similar to Threading or multiprocessing modules of Python." }, { "code": null, "e": 2102, "s": 1954, "text": "They also have a separate Machine Learning library, dask-ml, which has integration with existing libraries such as sklearn, xgboost and tensorflow." }, { "code": null, "e": 2639, "s": 2102, "text": "Dask parallelizes tasks given to it by making a graph of interactions between the tasks. It will be really helpful to visualize what you are doing by using Dask's .visualize() method which is available with all of its data types and with complex chain of tasks you compute. This method will output a graph of your tasks, and if your tasks have many nodes at each level(i.e. your tasks chain structure have many independent tasks at many levels, such as parallelizable task on chunks of data), then Dask will be able to parallelize them." }, { "code": null, "e": 3115, "s": 2639, "text": "Note:Dask is still a relatively new project. It has a long way to go. Still if you don't want to go through learning a completely new API (like in case of PySpark) Dask is your best option, which surely will get better and better in future. Still Spark/PySpark is ways ahead and will still keep on improving. It is a well established Apache project. I will publish a post on PySpark in coming months.(Today: April'19)If you want to start with PySpark, read this comment here." }, { "code": null, "e": 3550, "s": 3115, "text": "Each data type in Dask provides a distributed version of existing data types, such as DataFrame from Pandas, ndarray's from numpy, and list from Python. These data types can be larger than your memory, Dask will run computations on your data parallel(y) in Blocked manner. Blocked in the sense that they perform large computations by performing many small computations, i.e. in blocks, and number of blocks are total number of chunks." }, { "code": null, "e": 3560, "s": 3550, "text": "a) Array:" }, { "code": null, "e": 3780, "s": 3560, "text": "Dask Array operates on very large arrays, by dividing them into chunks and executing those blocks parallely. It has many of numpy methods available which you can use to get speedup. But some of them are not implemented." }, { "code": null, "e": 3974, "s": 3780, "text": "Dask Array can read from any array like structure given it supports numpy like slicing and has .shape property by using dask.array.from_array method. It can also read from .npy and .zarr files." }, { "code": null, "e": 4183, "s": 3974, "text": "import dask.array as daimport numpy as nparr = numpy.random.randint(1, 1000, (10000, 10000))darr = da.from_array(arr, chunks=(1000, 1000))# It will make chunks, each of size (1000, 1000)darr.npartitioins# 100" }, { "code": null, "e": 4402, "s": 4183, "text": "It can be used when your arrays are really heavy (i.e. they won’t fit into memory) and numpy won’t be able to do anything about that. So, Dask divides them into chunks of arrays and operate on them in parallel for you." }, { "code": null, "e": 4633, "s": 4402, "text": "Now, Dask does lazy evaluation of every method. So, to actually compute the value of a function, you have to use .compute() method. It will compute the result parallely in blocks, parallelizing every independent task at that time." }, { "code": null, "e": 4657, "s": 4633, "text": "result = darr.compute()" }, { "code": null, "e": 4671, "s": 4657, "text": "b) DataFrame:" }, { "code": null, "e": 4869, "s": 4671, "text": "Similar to Dask Arrays, Dask DataFrames parallelize computation on very large Data Files, which won’t fit on memory, by dividing files into chunks and computing functions to those blocks parallely." }, { "code": null, "e": 4947, "s": 4869, "text": "import dask.dataframe as dddf = dd.read_csv(\"BigFile(s).csv\", blocksize=50e6)" }, { "code": null, "e": 5038, "s": 4947, "text": "Now you can apply/use most of the functions available in pandas library and apply it here." }, { "code": null, "e": 5240, "s": 5038, "text": "agg = df.groupby([\"column\"]).aggregate([\"sum\", \"mean\", \"max\", \"min\"])agg.columns = new_column_names # see in notebookdf_new = df.merge(agg.reset_index(), on=\"column\", how=\"left\")df_new.compute().head()" }, { "code": null, "e": 5248, "s": 5240, "text": "c) Bag:" }, { "code": null, "e": 5457, "s": 5248, "text": "Dask Bags parallelizes computation on Python's list like objects which contains elements of many data types. It is useful when you are trying to process some semi-structured data like JSON blobs or log files." }, { "code": null, "e": 5532, "s": 5457, "text": "import dask.bag as dbb = db.from_txt(\"BigSemiStructuredData.txt\")b.take(1)" }, { "code": null, "e": 5622, "s": 5532, "text": "Dask bags reads line by line and .take method outputs tuple of number of lines specified." }, { "code": null, "e": 5896, "s": 5622, "text": "Dask Bag implements operations like map, filter, fold, and groupby on such collections of Python objects. It does this in parallel with a small memory footprint using Python iterators. It is similar to a parallel version of PyToolz or a Pythonic version of the PySpark RDD." }, { "code": null, "e": 6030, "s": 5896, "text": "filtered = b.filter(lambda x: x[\"Name\"]==\"James\")\\ .map(lambda x: x[\"Address\"] = \"New_Address\")filtered.compute()" }, { "code": null, "e": 6305, "s": 6030, "text": "If your task is a little simple and you are not able to or don’t want to do that with these High Level Collections, then you can use Low Level Schedulers which help you to parallelize your code/algorithm using dask.delayed interface. dask.delayed also does lazy computation." }, { "code": null, "e": 6484, "s": 6305, "text": "import dask.delayed as delay@delaydef sq(x): return x**2@delay def add(x, y): return x+y@delay def sum(arr): sum=0 for i in range(len(arr)): sum+=arr[i] return sum" }, { "code": null, "e": 6793, "s": 6484, "text": "You can add complex interactions between these functions according to your needs using results from previous tasks as an argument to next ones. Dask will not compute these functions right away, rather it will make a graph for your tasks, effectively incorporating interactions between functions that you use." }, { "code": null, "e": 7285, "s": 6793, "text": "inputs = list(np.arange(1, 11))#Will be addin' dask.delayed to listtemp = []for i in range(len(inputs)): temp.append(sq(inputs[i])) # Compute sq of inputs and save # delayed in listinputs=temp; temp = []for i in range(0, len(inputs)-1, 2): temp.append(add(inputs[i]+inputs[i+1])) # Add two consecutive # results from prev stepinputs = tempresult = sum(inputs) # Sum all results from prev stepresults.compute()" }, { "code": null, "e": 7518, "s": 7285, "text": "You can add delay to any parallelizable code with many possible small blocks and get a speedup. It can be many functions you want to compute like in example above or maybe reading a number of files in parallel using pandas.read_csv." }, { "code": null, "e": 7698, "s": 7518, "text": "Firstly, until now we have using Dask's default Scheduler for computing results of our tasks. But you can change them according to your needs from the options available from Dask." }, { "code": null, "e": 7741, "s": 7698, "text": "Dask comes with four available schedulers:" }, { "code": null, "e": 7789, "s": 7741, "text": "“threaded”: a scheduler backed by a thread pool" }, { "code": null, "e": 7839, "s": 7789, "text": "“processes”: a scheduler backed by a process pool" }, { "code": null, "e": 7915, "s": 7839, "text": "“single-threaded” (aka “sync”): a synchronous scheduler, good for debugging" }, { "code": null, "e": 7994, "s": 7915, "text": "distributed: a distributed scheduler for executing graphs on multiple machines" }, { "code": null, "e": 8509, "s": 7994, "text": "result.compute(scheduler=\"single-threaded\") # for debugging# Ordask.config.set(scheduler=\"single-threaded\")result.compute()NOTE: (from official page here)Threaded tasks will work well when the functions called release the GIL, whereas multiprocessing will always have a slower start-up time and suffer where a lot of communication is required between tasks.# And you can get the scheduler by the one of these commands:dask.threaded.get, dask.multiprocessing.get, dask.local.get_sync# last one for \"single-threaded\"" }, { "code": null, "e": 8608, "s": 8509, "text": "But, Dask has one more scheduler, dask.distributed, and it can be preferred for following reasons:" }, { "code": null, "e": 8926, "s": 8608, "text": "It provides access to asynchronous API, notably Futures,It provides a diagnostic dashboard that can provide valuable insight on performance and progress, andIt handles data locality with more sophistication, and so can be more efficient than the multiprocessing scheduler on workloads that require multiple processes." }, { "code": null, "e": 8983, "s": 8926, "text": "It provides access to asynchronous API, notably Futures," }, { "code": null, "e": 9085, "s": 8983, "text": "It provides a diagnostic dashboard that can provide valuable insight on performance and progress, and" }, { "code": null, "e": 9246, "s": 9085, "text": "It handles data locality with more sophistication, and so can be more efficient than the multiprocessing scheduler on workloads that require multiple processes." }, { "code": null, "e": 9331, "s": 9246, "text": "You can create Dask's dask.distributed Scheduler by importing and creating a Client." }, { "code": null, "e": 9522, "s": 9331, "text": "from dask.distributed import Clientclient = Client() # Set up a local cluster# You can navigate to http://localhost:8787/status to see the # diagnostic dashboard if you have Bokeh installed." }, { "code": null, "e": 9731, "s": 9522, "text": "Now you can submit your tasks to this cluster by using client.submit method, giving function and arguments as its parameters. And then we can gather our result by either using client.gather or .result method." }, { "code": null, "e": 9828, "s": 9731, "text": "sent = client.submit(sq, 4) # sq: square functionresult = client.gather(sent) # Or sent.result()" }, { "code": null, "e": 10023, "s": 9828, "text": "You can also look at progress of your task in current cell only by using dask.distributed.progress. And you can also explicitly opt to wait for a task to complete by using dask.distributed.wait." }, { "code": null, "e": 10055, "s": 10023, "text": "For more information look here." }, { "code": null, "e": 11306, "s": 10055, "text": "Note: (Local Cluster)At times you will notice that Dask is exceeding memory use, even though it is dividing tasks. It could be happening to you because of the function you are trying to use on your dataset wants most of your data for processing, and multiprocessing can make things worse as all workers might try to copy dataset to memory. This can happen in aggregating cases.Or maybe you want to restrict Dask to use only specific amount of memory. In these cases you can use Dask.distributed.LocalCluster parameters and pass them to Client() to make a LocalCluster using cores of your Local machines.from dask.distributed import Client, LocalClusterclient = Client(n_workers=1, threads_per_worker=1, processes=False, memory_limit='25GB', scheduler_port=0, silence_logs=True, diagnostics_port=0)client 'scheduler_port=0' and 'diagnostics_port=0' will choose random port number for this particular client. With 'processes=False' dask's client won't copy dataset, which would have happened for every process you might have made.You can tune your client as per your needs or limitations, and for more info you can look into parameters of LocalCluster.You can also use multiple clients on same machine at different ports." }, { "code": null, "e": 11442, "s": 11306, "text": "Dask also has library which helps in running most popular Machine Learning libraries in parallel, like sklearn, tensorflow and xgboost." }, { "code": null, "e": 11587, "s": 11442, "text": "In Machine Learning there are a couple of distinct scaling problems you might face. The scaling strategy depends on which problem you’re facing:" }, { "code": null, "e": 11790, "s": 11587, "text": "Large Models: Data fits in RAM, but training takes too long. Many hyperparameter combinations, a large ensemble of many models, etc.Large Datasets: Data is larger than RAM, and sampling isn’t an option." }, { "code": null, "e": 11923, "s": 11790, "text": "Large Models: Data fits in RAM, but training takes too long. Many hyperparameter combinations, a large ensemble of many models, etc." }, { "code": null, "e": 11994, "s": 11923, "text": "Large Datasets: Data is larger than RAM, and sampling isn’t an option." }, { "code": null, "e": 12010, "s": 11994, "text": "So, you should:" }, { "code": null, "e": 12096, "s": 12010, "text": "For in-memory fit-able problems, just use scikit-learn (or your favorite ML library);" }, { "code": null, "e": 12179, "s": 12096, "text": "For large models, use dask_ml.joblib and your favorite scikit-learn estimator; and" }, { "code": null, "e": 12223, "s": 12179, "text": "For large datasets, use dask_ml estimators." }, { "code": null, "e": 12241, "s": 12223, "text": "a) Preprocessing:" }, { "code": null, "e": 12471, "s": 12241, "text": "dask_ml.preprocessing contains some of the functions from sklearn like RobustScalar, StandardScalar, LabelEncoder, OneHotEncoder, PolynomialFeatures etc., and some of its own such as Categorizer, DummyEncoder, OrdinalEncoder etc." }, { "code": null, "e": 12541, "s": 12471, "text": "You can use them as you have been using them with Pandas's DataFrame." }, { "code": null, "e": 12699, "s": 12541, "text": "from dask_ml.preprocessing import RobustScalardf = da.read_csv(\"BigFile.csv\", chunks=50000)rsc = RobustScalar()df[\"column\"] = rsc.fit_transform(df[\"column\"])" }, { "code": null, "e": 12820, "s": 12699, "text": "And you can make a pipeline from sklearn's make_pipeline method using preprocessing methods of Dask on Dask's DataFrame." }, { "code": null, "e": 12847, "s": 12820, "text": "b) Hyper Parameter Search:" }, { "code": null, "e": 12949, "s": 12847, "text": "Dask has methods from sklearn for hyperparameter search such as GridSearchCV, RandomizedSearchCV etc." }, { "code": null, "e": 13214, "s": 12949, "text": "from dask_ml.datasets import make_regressionfrom dask_ml.model_selection import train_test_split, GridSearchCVX, y = make_regression(chunks=50000)xtr, ytr, xval, yval = test_train_split(X, y)gsearch = GridSearchCV(estimator, param_grid, cv=10)gsearch.fit(xtr, ytr)" }, { "code": null, "e": 13312, "s": 13214, "text": "And if you are using partial_fit with your estimators, you can use dask-ml's IncrementalSearchCV." }, { "code": null, "e": 13666, "s": 13312, "text": "NOTE: (from Dask)If you want to use post-fit tasks like scoring and prediction, then underlying estimators scoring method is used. If your estimator, possibly from sklearn is not able to handle large dataset, then wrap your estimator around \"dask_ml.wrappers.ParallelPostFit\". It can parallelize methods like \"predict\", \"predict_proba\", \"transform\" etc." }, { "code": null, "e": 13688, "s": 13666, "text": "c) Models/Estimators:" }, { "code": null, "e": 13915, "s": 13688, "text": "Dask has some of the Linear Models (LinearRegression, LogisticRegression etc.), some Clustering Models ( Kmeans and SpectralClustering), a method to operate with Tensorflow clusters, methods to train XGBoost models using Dask." }, { "code": null, "e": 14057, "s": 13915, "text": "You can use sklearn's models with Dask, if your training data is small, maybe with with ParallelPostFit wrapper (if your test data is large)." }, { "code": null, "e": 14236, "s": 14057, "text": "from sklearn.linear_model import ElasticNetfrom dask_ml.wrappers import ParallelPostFitel = ParallelPostFit(estimator=ElasticNet())el.fit(Xtrain, ytrain)preds = el.predict(Xtest)" }, { "code": null, "e": 14630, "s": 14236, "text": "If your dataset is not large but your model is big, then you can use joblib. Many sklearns algorithms were written for parallel execution (you might have used n_jobs=-1 argument), using joblib which makes use of threads and processes to parallelize workload. To use Dask to parallelize you can create a Client (you have to) and then wrap your code around with joblib.parallel_backend('dask'):." }, { "code": null, "e": 15080, "s": 14630, "text": "import dask_ml.joblibfrom sklearn.externals import joblibclient = Client()with joblib.parallel_backend('dask'): # your scikit-learn codeNOTE: Note that the Dask joblib backend is useful for scaling out CPU-bound workloads; workloads with datasets that fit in RAM, but have many individual operations that can be done in parallel. To scale out to RAM-bound workloads (larger-than-memory datasets) you should use Dask's inbuilt models and methods." }, { "code": null, "e": 15365, "s": 15080, "text": "And if you training data is too big which cannot fit into memory, then you should use Dask's inbuilt estimators to get a speedup. You can also use Dask's wrapper.Incremental which uses underlying estimator’s partial_fit method to train on whole dataset but it is sequential in nature." }, { "code": null, "e": 15552, "s": 15365, "text": "Dask's inbuilt estimators scale well for large datasets with variety of optimization algorithms like admm, lbfgs, gradient_descent etc. and with regularizers like L1, L2, ElasticNet etc." }, { "code": null, "e": 15657, "s": 15552, "text": "from dask_ml.linear_model import LogisticRegressionlr = LogisticRegression()lr.fit(X, y, solver=\"lbfgs\")" }, { "code": null, "e": 15804, "s": 15657, "text": "For one more example using Dask you can read Dask's section in my post here. It is a complete walk-through from exploration to training the model." }, { "code": null, "e": 16040, "s": 15804, "text": "https://mybinder.org/v2/gh/dask/dask-examples/master?urlpath=labhttps://towardsdatascience.com/how-i-learned-to-love-parallelized-applies-with-python-pandas-dask-and-numba-f06b0b367138https://docs.dask.org/en/latest/https://ml.dask.org" }, { "code": null, "e": 16105, "s": 16040, "text": "https://mybinder.org/v2/gh/dask/dask-examples/master?urlpath=lab" }, { "code": null, "e": 16226, "s": 16105, "text": "https://towardsdatascience.com/how-i-learned-to-love-parallelized-applies-with-python-pandas-dask-and-numba-f06b0b367138" }, { "code": null, "e": 16259, "s": 16226, "text": "https://docs.dask.org/en/latest/" }, { "code": null, "e": 16279, "s": 16259, "text": "https://ml.dask.org" }, { "code": null, "e": 16331, "s": 16279, "text": "https://ml.dask.orghttps://docs.dask.org/en/latest/" }, { "code": null, "e": 16351, "s": 16331, "text": "https://ml.dask.org" }, { "code": null, "e": 16384, "s": 16351, "text": "https://docs.dask.org/en/latest/" }, { "code": null, "e": 16443, "s": 16384, "text": "Suggestions and reviews are welcome.Thank you for reading!" }, { "code": null, "e": 16451, "s": 16443, "text": "Signed:" } ]
VBA - WeekDay
The WeekDay function returns an integer from 1 to 7 that represents the day of the week for the specified date. Weekday(date[,firstdayofweek]) Date − A required parameter. The weekday will return a specified date. Date − A required parameter. The weekday will return a specified date. Firstdayofweek − An optional parameter. Specifies the first day of the week. It can take the following values. 0 = vbUseSystemDayOfWeek - Use National Language Support (NLS) API setting 1 = vbSunday - Sunday 2 = vbMonday - Monday 3 = vbTuesday - Tuesday 4 = vbWednesday - Wednesday 5 = vbThursday - Thursday 6 = vbFriday - Friday 7 = vbSaturday - Saturday Firstdayofweek − An optional parameter. Specifies the first day of the week. It can take the following values. 0 = vbUseSystemDayOfWeek - Use National Language Support (NLS) API setting 0 = vbUseSystemDayOfWeek - Use National Language Support (NLS) API setting 1 = vbSunday - Sunday 1 = vbSunday - Sunday 2 = vbMonday - Monday 2 = vbMonday - Monday 3 = vbTuesday - Tuesday 3 = vbTuesday - Tuesday 4 = vbWednesday - Wednesday 4 = vbWednesday - Wednesday 5 = vbThursday - Thursday 5 = vbThursday - Thursday 6 = vbFriday - Friday 6 = vbFriday - Friday 7 = vbSaturday - Saturday 7 = vbSaturday - Saturday Add a button and add the following function. Private Sub Constant_demo_Click() msgbox("Line 1: " & Weekday("2013-05-16",1)) msgbox("Line 2: " & Weekday("2013-05-16",2)) msgbox("Line 3: " & Weekday("2013-05-16",2)) msgbox("Line 4: " & Weekday("2010-02-16")) msgbox("Line 5: " & Weekday("2010-02-17")) msgbox("Line 6: " & Weekday("2010-02-18")) End Sub When you execute the above function, it produces the following output. Line 1: 5 Line 2: 4 Line 3: 4 Line 4: 3 Line 5: 4 Line 6: 5 101 Lectures 6 hours Pavan Lalwani 41 Lectures 3 hours Arnold Higuit 80 Lectures 5.5 hours Prashant Panchal 25 Lectures 2 hours Prashant Panchal 26 Lectures 2 hours Arnold Higuit 92 Lectures 10.5 hours Vijay Kumar Parvatha Reddy Print Add Notes Bookmark this page
[ { "code": null, "e": 2047, "s": 1935, "text": "The WeekDay function returns an integer from 1 to 7 that represents the day of the week for the specified date." }, { "code": null, "e": 2081, "s": 2047, "text": "Weekday(date[,firstdayofweek]) \n" }, { "code": null, "e": 2152, "s": 2081, "text": "Date − A required parameter. The weekday will return a specified date." }, { "code": null, "e": 2223, "s": 2152, "text": "Date − A required parameter. The weekday will return a specified date." }, { "code": null, "e": 2582, "s": 2223, "text": "Firstdayofweek − An optional parameter. Specifies the first day of the week. It can take the following values.\n\n0 = vbUseSystemDayOfWeek - Use National Language Support (NLS) API setting\n1 = vbSunday - Sunday\n2 = vbMonday - Monday\n3 = vbTuesday - Tuesday\n4 = vbWednesday - Wednesday\n5 = vbThursday - Thursday\n6 = vbFriday - Friday\n7 = vbSaturday - Saturday\n\n" }, { "code": null, "e": 2693, "s": 2582, "text": "Firstdayofweek − An optional parameter. Specifies the first day of the week. It can take the following values." }, { "code": null, "e": 2768, "s": 2693, "text": "0 = vbUseSystemDayOfWeek - Use National Language Support (NLS) API setting" }, { "code": null, "e": 2843, "s": 2768, "text": "0 = vbUseSystemDayOfWeek - Use National Language Support (NLS) API setting" }, { "code": null, "e": 2865, "s": 2843, "text": "1 = vbSunday - Sunday" }, { "code": null, "e": 2887, "s": 2865, "text": "1 = vbSunday - Sunday" }, { "code": null, "e": 2909, "s": 2887, "text": "2 = vbMonday - Monday" }, { "code": null, "e": 2931, "s": 2909, "text": "2 = vbMonday - Monday" }, { "code": null, "e": 2955, "s": 2931, "text": "3 = vbTuesday - Tuesday" }, { "code": null, "e": 2979, "s": 2955, "text": "3 = vbTuesday - Tuesday" }, { "code": null, "e": 3007, "s": 2979, "text": "4 = vbWednesday - Wednesday" }, { "code": null, "e": 3035, "s": 3007, "text": "4 = vbWednesday - Wednesday" }, { "code": null, "e": 3061, "s": 3035, "text": "5 = vbThursday - Thursday" }, { "code": null, "e": 3087, "s": 3061, "text": "5 = vbThursday - Thursday" }, { "code": null, "e": 3109, "s": 3087, "text": "6 = vbFriday - Friday" }, { "code": null, "e": 3131, "s": 3109, "text": "6 = vbFriday - Friday" }, { "code": null, "e": 3157, "s": 3131, "text": "7 = vbSaturday - Saturday" }, { "code": null, "e": 3183, "s": 3157, "text": "7 = vbSaturday - Saturday" }, { "code": null, "e": 3228, "s": 3183, "text": "Add a button and add the following function." }, { "code": null, "e": 3552, "s": 3228, "text": "Private Sub Constant_demo_Click()\n msgbox(\"Line 1: \" & Weekday(\"2013-05-16\",1))\n msgbox(\"Line 2: \" & Weekday(\"2013-05-16\",2))\n msgbox(\"Line 3: \" & Weekday(\"2013-05-16\",2))\n msgbox(\"Line 4: \" & Weekday(\"2010-02-16\"))\n msgbox(\"Line 5: \" & Weekday(\"2010-02-17\"))\n msgbox(\"Line 6: \" & Weekday(\"2010-02-18\"))\nEnd Sub" }, { "code": null, "e": 3623, "s": 3552, "text": "When you execute the above function, it produces the following output." }, { "code": null, "e": 3684, "s": 3623, "text": "Line 1: 5\nLine 2: 4\nLine 3: 4\nLine 4: 3\nLine 5: 4\nLine 6: 5\n" }, { "code": null, "e": 3718, "s": 3684, "text": "\n 101 Lectures \n 6 hours \n" }, { "code": null, "e": 3733, "s": 3718, "text": " Pavan Lalwani" }, { "code": null, "e": 3766, "s": 3733, "text": "\n 41 Lectures \n 3 hours \n" }, { "code": null, "e": 3781, "s": 3766, "text": " Arnold Higuit" }, { "code": null, "e": 3816, "s": 3781, "text": "\n 80 Lectures \n 5.5 hours \n" }, { "code": null, "e": 3834, "s": 3816, "text": " Prashant Panchal" }, { "code": null, "e": 3867, "s": 3834, "text": "\n 25 Lectures \n 2 hours \n" }, { "code": null, "e": 3885, "s": 3867, "text": " Prashant Panchal" }, { "code": null, "e": 3918, "s": 3885, "text": "\n 26 Lectures \n 2 hours \n" }, { "code": null, "e": 3933, "s": 3918, "text": " Arnold Higuit" }, { "code": null, "e": 3969, "s": 3933, "text": "\n 92 Lectures \n 10.5 hours \n" }, { "code": null, "e": 3997, "s": 3969, "text": " Vijay Kumar Parvatha Reddy" }, { "code": null, "e": 4004, "s": 3997, "text": " Print" }, { "code": null, "e": 4015, "s": 4004, "text": " Add Notes" } ]
AutoML Gentle Introduction | Towards Data Science
Automated Machine Learning or AutoML according to Wikipedia is the process of automating the process of applying machine learning to real-world problems. AutoML intended to produce a complete pipeline from raw data into the deployable machine learning model. In a simpler term, AutoML capable to automatically create a machine learning model without prior knowledge of the model previously. AutoML itself is still one of the most sought of in the Artificial Intelligence field. Until 2019 or recently, AutoML is in the peak of people’s expectations of Artificial Intelligence. For whatever reasons that make people hype about AutoML, it could not be denied that this AutoML would quite change how people work in the Data Science field. As a data scientist, I also applying AutoML in my everyday work. AutoML is the future but it is not like it does not have any downside to it. Few things I take note about AutoML are: It would not replace the work of data scientists. We as human after all the ones who decide which result is viable to be produced and deployed. Data is still the most important thing. You could throw any raw data into the model, but without any preprocessing or further knowledge about the data; no good result would be present. The prediction metric is the only aim. In the data science job, the prediction model is not necessarily the only thing we want. Most of the time, what we want is an explanation from the model about the data. If you aim to know what features are the most important, then AutoML is not the way to go. With some downside, AutoML is still a breakthrough in the Data Science field and it is a given as a Data Scientist to learn about it. In this article, I want to give an introduction of how to implement AutoML and one of the AutoML modules; TPOT. TPOT is a Python AutoML module that optimizes machine learning pipelines. It will intelligently explore thousands of possible pipelines to find the best one for your data and once it finished searching (or you get tired of waiting), it provides you with the Python code for the best pipeline it found so you can tinker with the pipeline from there. Most of the python code explored in TPOT is based on the Python module Scikit-learn (not limited, but most of it) which most people work in ML with Python would familiar with. The exploration process is based on genetic programming. According to Wikipedia, It is a technique of evolving programs where we start from the population of unfit (usually random) programs, fit for a particular task by applying operations analogous to natural genetic processes to the population of programs. In a simpler term, it starts from a random ML model and by a random process of selecting the model (and the parameter), it would go to the direction of the best model. There are many technical biological terms in the parameter used by TPOT but I would explain some of the important parameters to use later. TPOT are both used for classification and regression problems, basically, a supervised learning problem where we need target data to be predicted. Let’s try using TPOT with an example. For learning purposes, I would use the Heart Disease dataset I acquire from Kaggle. The snapshot of the data is shown below. import pandas as pdheart = pd.read_csv('heart.csv')heart.head() You could read the explanation of each column in the source, but this dataset is dealing with a classification problem; whether someone had heart disease or not. I would not do any data preprocessing as my intention is just to give an example of how TPOT works. To start we need to install the module first. The recommendation to use TPOT is to use Anaconda Distribution of Python as many of the necessary modules are pre-existing there. We then install the module through pip or conda. #Using pippip install tpot#or if you prefer condaconda install -c conda-forge tpot Now we are ready to try our AutoML using the TPOT module. Let’s import all the modules and prepares the data we would use. #Import the TPOT specific for classification problemfrom tpot import TPOTClassifier#We use the train_test_split to divide the data into the training data and the testing datafrom sklearn.model_selection import train_test_split#Dividing the data. I take 20% of the data as test data and set the random_state for repeatabilityX_train, X_test, y_train, y_test = train_test_split(heart.drop('target', axis = 1), heart['target'], test_size = 0.2, random_state = 101) All the preparation is set, now let’s try using AutoML by TPOT for the classification problem. tpot = TPOTClassifier(generations=100, population_size=100, offspring_size=None, scoring='accuracy', max_time_mins=None, max_eval_time_mins=5, random_state=101, warm_start=True, early_stop=20, verbosity=2) It seems there are many parameters in this classifier, and yes it is. You could check all the parameter exist in the TPOTClassifier here but I would explain some of the important parameters below: generations control the number of iterations to the run pipeline optimization process. population_size control the number of individuals to retain in the genetic programming population every generation. offspring_size control the number of offspring to produce in each genetic programming generation. By default, it is equal to the size of the generations. In total, TPOT will evaluate population_size + generations × offspring_size pipelines. So, above we would have 100 + 100 × 100 which equals 10100 pipelines to evaluate. Other important parameters are: scoring control function used to evaluate the quality of a given pipeline for the classification problem. See the scoring function here for the scoring function that could be used. max_time_mins control how many minutes TPOT has to optimize the pipeline. If it is none, then TPOT would not have any time limit to do optimization. max_eval_time_mins control how many minutes TPOT has to evaluate a single pipeline. Higher time means TPOT could evaluate a more complex pipeline but would take longer. warm_start is a Flag indicating whether the TPOT instance will reuse the population from previous calls. Setting the warm_start=True can be useful for running TPOT for a short time on a dataset, checking the results, then resuming the TPOT run from where it left off. early_stop control how many generations TPOT checks whether there is no improvement in the optimization process. If there is no more improvement after the given number, then TPOT would stop the optimization process. From the parameter above, let’s try to fit the TPOTClassifier with our training data. tpot.fit(X_train, y_train) The optimization process would be looks like below: The optimization process would stop if every pipeline has been evaluated, reach the time limit, hit the early stop limit, or simply terminated. Here is what happens to the AutoML process we try before. It seems the pipeline has reached the maximum early stop number and arrive at the best pipeline. Of course, as it is a randomized process, I could end up with a completely different model if I ran it once more. Let’s check the model performance if we test it against the test data. We could use the optimized TPOT model to be used as a predictive model. from sklearn.metrics import classification_reportprint(classification_report(y_test, tpot.predict(X_test))) The model seems quite good despite no preprocessing are done although I bet we could achieve a much better model if we analyze the data but let’s leave it there. Now, if you rather have a complete set of pipelines exported automatically, you could do it by using the following code. #Give any name you want but still contain the .py extensiontpot.export('tpot_heart_classifier.py') The complete pipeline would show up in your folder, exactly in the folder where your notebook to work at. If you open that file, it would look like below: As we can see, not only we get the best pipelines but we also get a complete rundown of the process. I just show you how the AutoML using TPOT is used. The process is simple and the result is not bad from the evaluation standpoint. Although, AutoML is not a tool to achieve the final result model; in fact, AutoML only serves as the beginning of the model optimization because it could pinpoint which direction for us to go. If you are not subscribed as a Medium Member, please consider subscribing through my referral.
[ { "code": null, "e": 649, "s": 171, "text": "Automated Machine Learning or AutoML according to Wikipedia is the process of automating the process of applying machine learning to real-world problems. AutoML intended to produce a complete pipeline from raw data into the deployable machine learning model. In a simpler term, AutoML capable to automatically create a machine learning model without prior knowledge of the model previously. AutoML itself is still one of the most sought of in the Artificial Intelligence field." }, { "code": null, "e": 972, "s": 649, "text": "Until 2019 or recently, AutoML is in the peak of people’s expectations of Artificial Intelligence. For whatever reasons that make people hype about AutoML, it could not be denied that this AutoML would quite change how people work in the Data Science field. As a data scientist, I also applying AutoML in my everyday work." }, { "code": null, "e": 1090, "s": 972, "text": "AutoML is the future but it is not like it does not have any downside to it. Few things I take note about AutoML are:" }, { "code": null, "e": 1234, "s": 1090, "text": "It would not replace the work of data scientists. We as human after all the ones who decide which result is viable to be produced and deployed." }, { "code": null, "e": 1419, "s": 1234, "text": "Data is still the most important thing. You could throw any raw data into the model, but without any preprocessing or further knowledge about the data; no good result would be present." }, { "code": null, "e": 1718, "s": 1419, "text": "The prediction metric is the only aim. In the data science job, the prediction model is not necessarily the only thing we want. Most of the time, what we want is an explanation from the model about the data. If you aim to know what features are the most important, then AutoML is not the way to go." }, { "code": null, "e": 1964, "s": 1718, "text": "With some downside, AutoML is still a breakthrough in the Data Science field and it is a given as a Data Scientist to learn about it. In this article, I want to give an introduction of how to implement AutoML and one of the AutoML modules; TPOT." }, { "code": null, "e": 2489, "s": 1964, "text": "TPOT is a Python AutoML module that optimizes machine learning pipelines. It will intelligently explore thousands of possible pipelines to find the best one for your data and once it finished searching (or you get tired of waiting), it provides you with the Python code for the best pipeline it found so you can tinker with the pipeline from there. Most of the python code explored in TPOT is based on the Python module Scikit-learn (not limited, but most of it) which most people work in ML with Python would familiar with." }, { "code": null, "e": 3106, "s": 2489, "text": "The exploration process is based on genetic programming. According to Wikipedia, It is a technique of evolving programs where we start from the population of unfit (usually random) programs, fit for a particular task by applying operations analogous to natural genetic processes to the population of programs. In a simpler term, it starts from a random ML model and by a random process of selecting the model (and the parameter), it would go to the direction of the best model. There are many technical biological terms in the parameter used by TPOT but I would explain some of the important parameters to use later." }, { "code": null, "e": 3291, "s": 3106, "text": "TPOT are both used for classification and regression problems, basically, a supervised learning problem where we need target data to be predicted. Let’s try using TPOT with an example." }, { "code": null, "e": 3416, "s": 3291, "text": "For learning purposes, I would use the Heart Disease dataset I acquire from Kaggle. The snapshot of the data is shown below." }, { "code": null, "e": 3480, "s": 3416, "text": "import pandas as pdheart = pd.read_csv('heart.csv')heart.head()" }, { "code": null, "e": 3742, "s": 3480, "text": "You could read the explanation of each column in the source, but this dataset is dealing with a classification problem; whether someone had heart disease or not. I would not do any data preprocessing as my intention is just to give an example of how TPOT works." }, { "code": null, "e": 3967, "s": 3742, "text": "To start we need to install the module first. The recommendation to use TPOT is to use Anaconda Distribution of Python as many of the necessary modules are pre-existing there. We then install the module through pip or conda." }, { "code": null, "e": 4050, "s": 3967, "text": "#Using pippip install tpot#or if you prefer condaconda install -c conda-forge tpot" }, { "code": null, "e": 4173, "s": 4050, "text": "Now we are ready to try our AutoML using the TPOT module. Let’s import all the modules and prepares the data we would use." }, { "code": null, "e": 4635, "s": 4173, "text": "#Import the TPOT specific for classification problemfrom tpot import TPOTClassifier#We use the train_test_split to divide the data into the training data and the testing datafrom sklearn.model_selection import train_test_split#Dividing the data. I take 20% of the data as test data and set the random_state for repeatabilityX_train, X_test, y_train, y_test = train_test_split(heart.drop('target', axis = 1), heart['target'], test_size = 0.2, random_state = 101)" }, { "code": null, "e": 4730, "s": 4635, "text": "All the preparation is set, now let’s try using AutoML by TPOT for the classification problem." }, { "code": null, "e": 5137, "s": 4730, "text": "tpot = TPOTClassifier(generations=100, population_size=100, offspring_size=None, scoring='accuracy', max_time_mins=None, max_eval_time_mins=5, random_state=101, warm_start=True, early_stop=20, verbosity=2)" }, { "code": null, "e": 5334, "s": 5137, "text": "It seems there are many parameters in this classifier, and yes it is. You could check all the parameter exist in the TPOTClassifier here but I would explain some of the important parameters below:" }, { "code": null, "e": 5421, "s": 5334, "text": "generations control the number of iterations to the run pipeline optimization process." }, { "code": null, "e": 5537, "s": 5421, "text": "population_size control the number of individuals to retain in the genetic programming population every generation." }, { "code": null, "e": 5691, "s": 5537, "text": "offspring_size control the number of offspring to produce in each genetic programming generation. By default, it is equal to the size of the generations." }, { "code": null, "e": 5860, "s": 5691, "text": "In total, TPOT will evaluate population_size + generations × offspring_size pipelines. So, above we would have 100 + 100 × 100 which equals 10100 pipelines to evaluate." }, { "code": null, "e": 5892, "s": 5860, "text": "Other important parameters are:" }, { "code": null, "e": 6073, "s": 5892, "text": "scoring control function used to evaluate the quality of a given pipeline for the classification problem. See the scoring function here for the scoring function that could be used." }, { "code": null, "e": 6222, "s": 6073, "text": "max_time_mins control how many minutes TPOT has to optimize the pipeline. If it is none, then TPOT would not have any time limit to do optimization." }, { "code": null, "e": 6391, "s": 6222, "text": "max_eval_time_mins control how many minutes TPOT has to evaluate a single pipeline. Higher time means TPOT could evaluate a more complex pipeline but would take longer." }, { "code": null, "e": 6659, "s": 6391, "text": "warm_start is a Flag indicating whether the TPOT instance will reuse the population from previous calls. Setting the warm_start=True can be useful for running TPOT for a short time on a dataset, checking the results, then resuming the TPOT run from where it left off." }, { "code": null, "e": 6875, "s": 6659, "text": "early_stop control how many generations TPOT checks whether there is no improvement in the optimization process. If there is no more improvement after the given number, then TPOT would stop the optimization process." }, { "code": null, "e": 6961, "s": 6875, "text": "From the parameter above, let’s try to fit the TPOTClassifier with our training data." }, { "code": null, "e": 6988, "s": 6961, "text": "tpot.fit(X_train, y_train)" }, { "code": null, "e": 7040, "s": 6988, "text": "The optimization process would be looks like below:" }, { "code": null, "e": 7242, "s": 7040, "text": "The optimization process would stop if every pipeline has been evaluated, reach the time limit, hit the early stop limit, or simply terminated. Here is what happens to the AutoML process we try before." }, { "code": null, "e": 7453, "s": 7242, "text": "It seems the pipeline has reached the maximum early stop number and arrive at the best pipeline. Of course, as it is a randomized process, I could end up with a completely different model if I ran it once more." }, { "code": null, "e": 7596, "s": 7453, "text": "Let’s check the model performance if we test it against the test data. We could use the optimized TPOT model to be used as a predictive model." }, { "code": null, "e": 7704, "s": 7596, "text": "from sklearn.metrics import classification_reportprint(classification_report(y_test, tpot.predict(X_test)))" }, { "code": null, "e": 7866, "s": 7704, "text": "The model seems quite good despite no preprocessing are done although I bet we could achieve a much better model if we analyze the data but let’s leave it there." }, { "code": null, "e": 7987, "s": 7866, "text": "Now, if you rather have a complete set of pipelines exported automatically, you could do it by using the following code." }, { "code": null, "e": 8086, "s": 7987, "text": "#Give any name you want but still contain the .py extensiontpot.export('tpot_heart_classifier.py')" }, { "code": null, "e": 8241, "s": 8086, "text": "The complete pipeline would show up in your folder, exactly in the folder where your notebook to work at. If you open that file, it would look like below:" }, { "code": null, "e": 8342, "s": 8241, "text": "As we can see, not only we get the best pipelines but we also get a complete rundown of the process." }, { "code": null, "e": 8666, "s": 8342, "text": "I just show you how the AutoML using TPOT is used. The process is simple and the result is not bad from the evaluation standpoint. Although, AutoML is not a tool to achieve the final result model; in fact, AutoML only serves as the beginning of the model optimization because it could pinpoint which direction for us to go." } ]
Find Last Digit of a^b for Large Numbers in C++
In this problem, we are given two numbers a and b. Our task is to find Last Digit of a^b for Large Numbers. Let’s take an example to understand the problem, Input: a = 4 b = 124 Output: 6 Explanation: The value of a^b is 4.523128486 * 1074 The solution to the problem is based on the fact that all the exponents of a number will be repeated after 4 exponent values. So, we will find the value of b%4. Also, for any base value, the last digit of its power is decided by the last digit of the base value. So, the resultant value will be calculated as Last value of a ^ (b%4) Live Demo #include <bits/stdc++.h> using namespace std; int calcModulus(char b[], int a) { int mod = 0; for (int i = 0; i < strlen(b); i++) mod = (mod * 10 + b[i] - '0') % a; return mod; } int calcLastDigitInExpo(char a[], char b[]) { int len_a = strlen(a), len_b = strlen(b); if (len_a == 1 && len_b == 1 && b[0] == '0' && a[0] == '0') return 1; if (len_b == 1 && b[0] == '0') return 1; if (len_a == 1 && a[0] == '0') return 0; int exponent = (calcModulus(b, 4) == 0) ? 4 : calcModulus(b, 4); int base = a[len_a - 1] - '0'; int result = pow(base, exponent); return result % 10; } int main() { char a[] = "559", b[] = "4532"; cout<<"The last digit in of the value is "<<calcLastDigitInExpo(a, b); return 0; } The last digit in of the value is 1
[ { "code": null, "e": 1171, "s": 1062, "text": "In this problem, we are given two numbers a and b. Our task is to find Last Digit of a^b for Large Numbers. " }, { "code": null, "e": 1221, "s": 1171, "text": "Let’s take an example to understand the problem, " }, { "code": null, "e": 1242, "s": 1221, "text": "Input: a = 4 b = 124" }, { "code": null, "e": 1252, "s": 1242, "text": "Output: 6" }, { "code": null, "e": 1266, "s": 1252, "text": "Explanation: " }, { "code": null, "e": 1305, "s": 1266, "text": "The value of a^b is 4.523128486 * 1074" }, { "code": null, "e": 1431, "s": 1305, "text": "The solution to the problem is based on the fact that all the exponents of a number will be repeated after 4 exponent values." }, { "code": null, "e": 1568, "s": 1431, "text": "So, we will find the value of b%4. Also, for any base value, the last digit of its power is decided by the last digit of the base value." }, { "code": null, "e": 1614, "s": 1568, "text": "So, the resultant value will be calculated as" }, { "code": null, "e": 1639, "s": 1614, "text": "Last value of a ^ (b%4)" }, { "code": null, "e": 1649, "s": 1639, "text": "Live Demo" }, { "code": null, "e": 2422, "s": 1649, "text": "#include <bits/stdc++.h>\nusing namespace std;\n\nint calcModulus(char b[], int a)\n{\n int mod = 0;\n\n for (int i = 0; i < strlen(b); i++)\n mod = (mod * 10 + b[i] - '0') % a;\n\n return mod;\n}\n\nint calcLastDigitInExpo(char a[], char b[]) {\n\n int len_a = strlen(a), len_b = strlen(b);\n\n if (len_a == 1 && len_b == 1 && b[0] == '0' && a[0] == '0')\n return 1;\n if (len_b == 1 && b[0] == '0')\n return 1;\n if (len_a == 1 && a[0] == '0')\n return 0;\n\n int exponent = (calcModulus(b, 4) == 0) ? 4 : calcModulus(b, 4);\n int base = a[len_a - 1] - '0';\n int result = pow(base, exponent);\n return result % 10;\n}\n\nint main()\n{\n char a[] = \"559\", b[] = \"4532\";\n cout<<\"The last digit in of the value is \"<<calcLastDigitInExpo(a, b);\n return 0;\n}" }, { "code": null, "e": 2458, "s": 2422, "text": "The last digit in of the value is 1" } ]
Batch Script - Relational Operators
Relational operators allow of the comparison of objects. Below are the relational operators available. The following code snippet shows how the various operators can be used. @echo off SET /A a = 5 SET /A b = 10 if %a% EQU %b% echo A is equal to than B if %a% NEQ %b% echo A is not equal to than B if %a% LSS %b% echo A is less than B if %a% LEQ %b% echo A is less than or equal B if %a% GTR %b% echo A is greater than B if %a% GEQ %b% echo A is greater than or equal to B The above command produces the following output. A is not equal to than B A is less than B A is less than or equal B Print Add Notes Bookmark this page
[ { "code": null, "e": 2272, "s": 2169, "text": "Relational operators allow of the comparison of objects. Below are the relational operators available." }, { "code": null, "e": 2344, "s": 2272, "text": "The following code snippet shows how the various operators can be used." }, { "code": null, "e": 2649, "s": 2344, "text": "@echo off \nSET /A a = 5 \nSET /A b = 10 \nif %a% EQU %b% echo A is equal to than B \nif %a% NEQ %b% echo A is not equal to than B \nif %a% LSS %b% echo A is less than B \nif %a% LEQ %b% echo A is less than or equal B\nif %a% GTR %b% echo A is greater than B \nif %a% GEQ %b% echo A is greater than or equal to B" }, { "code": null, "e": 2698, "s": 2649, "text": "The above command produces the following output." }, { "code": null, "e": 2767, "s": 2698, "text": "A is not equal to than B\nA is less than B\nA is less than or equal B\n" }, { "code": null, "e": 2774, "s": 2767, "text": " Print" }, { "code": null, "e": 2785, "s": 2774, "text": " Add Notes" } ]
Minimum Steps | Practice | GeeksforGeeks
Anuj has challenged Arun to climb N stairs but at only in powers of P and Q. Now Arun being a lazy guy wants to do this in minimum number of steps possible. So he has asked for your help to calculate the minimum number of steps he requires to take for climbing N stairs ( 1 step = some power of P or Q stairs (including zeroth power) ). Example 1: Input: N = 15, P = 2, Q = 3 Output: 3 Explanation: We can make 15 by (8,4,3) or (9,3,3) both takes 3 steps. Example 2: Input: N = 19, P = 4, Q = 3 Output: 2 Explanation: In the second case, we can make 19 by (16,3) which is 2 steps. Your Task: You don't need to read input or print anything. Your task is to complete the function moves() which takes three integers N, P and Q as inputs and returns the number of steps that Arun needs to take to climb N stairs in powers of P & Q. If fit is not possible print -1. Expected Time Complexity: O(N. log(N)) Expected Auxiliary Space: O(N. log(N)) Constraints: 1 ≤ N, P, Q ≤ 105 No Comments to load 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": 575, "s": 238, "text": "Anuj has challenged Arun to climb N stairs but at only in powers of P and Q. Now Arun being a lazy guy wants to do this in minimum number of steps possible. So he has asked for your help to calculate the minimum number of steps he requires to take for climbing N stairs ( 1 step = some power of P or Q stairs (including zeroth power) )." }, { "code": null, "e": 587, "s": 575, "text": "\nExample 1:" }, { "code": null, "e": 696, "s": 587, "text": "Input: \nN = 15, P = 2, Q = 3\nOutput:\n3\nExplanation:\nWe can make 15 by (8,4,3)\nor (9,3,3) both takes 3 steps." }, { "code": null, "e": 709, "s": 698, "text": "Example 2:" }, { "code": null, "e": 824, "s": 709, "text": "Input: \nN = 19, P = 4, Q = 3\nOutput:\n2\nExplanation:\nIn the second case, we can make\n19 by (16,3) which is 2 steps." }, { "code": null, "e": 1110, "s": 826, "text": "Your Task: \nYou don't need to read input or print anything. Your task is to complete the function moves() which takes three integers N, P and Q as inputs and returns the number of steps that Arun needs to take to climb N stairs in powers of P & Q. If fit is not possible print -1.\n " }, { "code": null, "e": 1190, "s": 1110, "text": "Expected Time Complexity: O(N. log(N))\nExpected Auxiliary Space: O(N. log(N))\n " }, { "code": null, "e": 1221, "s": 1190, "text": "Constraints:\n1 ≤ N, P, Q ≤ 105" }, { "code": null, "e": 1241, "s": 1221, "text": "No Comments to load" }, { "code": null, "e": 1387, "s": 1241, "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": 1423, "s": 1387, "text": " Login to access your submissions. " }, { "code": null, "e": 1433, "s": 1423, "text": "\nProblem\n" }, { "code": null, "e": 1443, "s": 1433, "text": "\nContest\n" }, { "code": null, "e": 1506, "s": 1443, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 1654, "s": 1506, "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": 1862, "s": 1654, "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": 1968, "s": 1862, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
Exploratory Factor Analysis in R. Learning by doing | by Anh T. Dang | Towards Data Science
Factor analysis is a statistical method used to search for some unobserved variables called factors from observed variables called factors. This beginning of the method was named exploratory factor analysis (EFA). Another variation of factor analysis is confirmatory factor analysis (CFA) will not be explored in this article. Factor analysis is used in many areas of statistical analysis such as marketing, social sciences, psychology, and so on. The libraries that we’ll need are as follows: psych, corrplot, psynch and so on. library(psych)library(corrplot)library("psych")library(ggplot2)library(car) We first need to fetch sample data from the server. This is a raw data set, so each row row represents a person’s survery. # Dataseturl <- “https://raw.githubusercontent.com/housecricket/data/main/efa/sample1.csv"data_survey <- read.csv(url, sep = “,”) We also look at the dataset before we run any analysis. describe(data_survey) We use the dim function to retrieve the dimension of the dataset. dim(data_survey) In our data frame, we have an ID variable in the first column. So, we can use a -1 in the column index to remove the first column and save our data to a new object. dat <- data_survey[ , -1] head(dat) We also should take a look at the correlations among our variables to determine if factor analysis is appropriate. datamatrix <- cor(dat[,c(-13)])corrplot(datamatrix, method="number") X <- data[,-c(13)]Y <- data[,13] The Kaiser-Meyer-Olkin (KMO) used to measure sampling adequacy is a better measure of factorability. KMO(r=cor(X)) According to Kaiser’s (1974) guidelines, a suggested cutoff for determining the factorability of the sample data is KMO ≥ 60. The total KMO is 0.83, indicating that, based on this test, we can probably conduct a factor analysis. cortest.bartlett(X) Small values (8.84e-290 < 0.05) of the significance level indicate that a factor analysis may be useful with our data. det(cor(X) We have a positive determinant, which means the factor analysis will probably run. library(ggplot2)fafitfree <- fa(dat,nfactors = ncol(X), rotate = "none")n_factors <- length(fafitfree$e.values)scree <- data.frame( Factor_n = as.factor(1:n_factors), Eigenvalue = fafitfree$e.values)ggplot(scree, aes(x = Factor_n, y = Eigenvalue, group = 1)) + geom_point() + geom_line() + xlab("Number of factors") + ylab("Initial eigenvalue") + labs( title = "Scree Plot", subtitle = "(Based on the unreduced correlation matrix)") We can use the parallel() function from the nFactors package (Raiche & Magis, 2020) to perform a parallel analysis. parallel <- fa.parallel(X) ## Parallel analysis suggests that the number of factors = 4 and the number of components = 3 fa.none <- fa(r=X, nfactors = 4, # covar = FALSE, SMC = TRUE, fm=”pa”, # type of factor analysis we want to use (“pa” is principal axis factoring) max.iter=100, # (50 is the default, but we have changed it to 100 rotate=”varimax”) # none rotationprint(fa.none) factanal.none <- factanal(X, factors=4, scores = c("regression"), rotation = "varimax")print(factanal.none) fa.diagram(fa.none) head(fa.var$scores) regdata <- cbind(dat[“QD”], fa.var$scores)#Labeling the datanames(regdata) <- c(“QD”, “F1”, “F2”, “F3”, “F4”)head(regdata) #Splitting the data 70:30#Random number generator, set seed.set.seed(100)indices= sample(1:nrow(regdata), 0.7*nrow(regdata))train=regdata[indices,]test = regdata[-indices,] model.fa.score = lm(Satisfaction~., train)summary(model.fa.score) Our model equation can be written as: Y = 3.55309 + 0.72628 x F1 + 0.29138 x F2 + 0.06935 x F3 + 0.62753 x F4 vif(model.fa.score) #Model Performance metrics:pred_test <- predict(model.fa.score, newdata = test, type = “response”)pred_testtest$QD_Predicted <- pred_testhead(test[c(“QD”,”QD_Predicted”)], 10) Today, we reviewed the preliminary steps to factor analysis including examining the data and the assumptions required for factor analysis and how to determine the number of factors to retain.
[ { "code": null, "e": 312, "s": 172, "text": "Factor analysis is a statistical method used to search for some unobserved variables called factors from observed variables called factors." }, { "code": null, "e": 386, "s": 312, "text": "This beginning of the method was named exploratory factor analysis (EFA)." }, { "code": null, "e": 499, "s": 386, "text": "Another variation of factor analysis is confirmatory factor analysis (CFA) will not be explored in this article." }, { "code": null, "e": 620, "s": 499, "text": "Factor analysis is used in many areas of statistical analysis such as marketing, social sciences, psychology, and so on." }, { "code": null, "e": 701, "s": 620, "text": "The libraries that we’ll need are as follows: psych, corrplot, psynch and so on." }, { "code": null, "e": 777, "s": 701, "text": "library(psych)library(corrplot)library(\"psych\")library(ggplot2)library(car)" }, { "code": null, "e": 900, "s": 777, "text": "We first need to fetch sample data from the server. This is a raw data set, so each row row represents a person’s survery." }, { "code": null, "e": 1030, "s": 900, "text": "# Dataseturl <- “https://raw.githubusercontent.com/housecricket/data/main/efa/sample1.csv\"data_survey <- read.csv(url, sep = “,”)" }, { "code": null, "e": 1086, "s": 1030, "text": "We also look at the dataset before we run any analysis." }, { "code": null, "e": 1108, "s": 1086, "text": "describe(data_survey)" }, { "code": null, "e": 1174, "s": 1108, "text": "We use the dim function to retrieve the dimension of the dataset." }, { "code": null, "e": 1191, "s": 1174, "text": "dim(data_survey)" }, { "code": null, "e": 1356, "s": 1191, "text": "In our data frame, we have an ID variable in the first column. So, we can use a -1 in the column index to remove the first column and save our data to a new object." }, { "code": null, "e": 1392, "s": 1356, "text": "dat <- data_survey[ , -1] head(dat)" }, { "code": null, "e": 1507, "s": 1392, "text": "We also should take a look at the correlations among our variables to determine if factor analysis is appropriate." }, { "code": null, "e": 1576, "s": 1507, "text": "datamatrix <- cor(dat[,c(-13)])corrplot(datamatrix, method=\"number\")" }, { "code": null, "e": 1609, "s": 1576, "text": "X <- data[,-c(13)]Y <- data[,13]" }, { "code": null, "e": 1710, "s": 1609, "text": "The Kaiser-Meyer-Olkin (KMO) used to measure sampling adequacy is a better measure of factorability." }, { "code": null, "e": 1724, "s": 1710, "text": "KMO(r=cor(X))" }, { "code": null, "e": 1953, "s": 1724, "text": "According to Kaiser’s (1974) guidelines, a suggested cutoff for determining the factorability of the sample data is KMO ≥ 60. The total KMO is 0.83, indicating that, based on this test, we can probably conduct a factor analysis." }, { "code": null, "e": 1973, "s": 1953, "text": "cortest.bartlett(X)" }, { "code": null, "e": 2092, "s": 1973, "text": "Small values (8.84e-290 < 0.05) of the significance level indicate that a factor analysis may be useful with our data." }, { "code": null, "e": 2103, "s": 2092, "text": "det(cor(X)" }, { "code": null, "e": 2186, "s": 2103, "text": "We have a positive determinant, which means the factor analysis will probably run." }, { "code": null, "e": 2640, "s": 2186, "text": "library(ggplot2)fafitfree <- fa(dat,nfactors = ncol(X), rotate = \"none\")n_factors <- length(fafitfree$e.values)scree <- data.frame( Factor_n = as.factor(1:n_factors), Eigenvalue = fafitfree$e.values)ggplot(scree, aes(x = Factor_n, y = Eigenvalue, group = 1)) + geom_point() + geom_line() + xlab(\"Number of factors\") + ylab(\"Initial eigenvalue\") + labs( title = \"Scree Plot\", subtitle = \"(Based on the unreduced correlation matrix)\")" }, { "code": null, "e": 2756, "s": 2640, "text": "We can use the parallel() function from the nFactors package (Raiche & Magis, 2020) to perform a parallel analysis." }, { "code": null, "e": 2783, "s": 2756, "text": "parallel <- fa.parallel(X)" }, { "code": null, "e": 2879, "s": 2783, "text": "## Parallel analysis suggests that the number of factors = 4 and the number of components = 3" }, { "code": null, "e": 3142, "s": 2879, "text": "fa.none <- fa(r=X, nfactors = 4, # covar = FALSE, SMC = TRUE, fm=”pa”, # type of factor analysis we want to use (“pa” is principal axis factoring) max.iter=100, # (50 is the default, but we have changed it to 100 rotate=”varimax”) # none rotationprint(fa.none)" }, { "code": null, "e": 3250, "s": 3142, "text": "factanal.none <- factanal(X, factors=4, scores = c(\"regression\"), rotation = \"varimax\")print(factanal.none)" }, { "code": null, "e": 3270, "s": 3250, "text": "fa.diagram(fa.none)" }, { "code": null, "e": 3290, "s": 3270, "text": "head(fa.var$scores)" }, { "code": null, "e": 3413, "s": 3290, "text": "regdata <- cbind(dat[“QD”], fa.var$scores)#Labeling the datanames(regdata) <- c(“QD”, “F1”, “F2”, “F3”, “F4”)head(regdata)" }, { "code": null, "e": 3586, "s": 3413, "text": "#Splitting the data 70:30#Random number generator, set seed.set.seed(100)indices= sample(1:nrow(regdata), 0.7*nrow(regdata))train=regdata[indices,]test = regdata[-indices,]" }, { "code": null, "e": 3652, "s": 3586, "text": "model.fa.score = lm(Satisfaction~., train)summary(model.fa.score)" }, { "code": null, "e": 3762, "s": 3652, "text": "Our model equation can be written as: Y = 3.55309 + 0.72628 x F1 + 0.29138 x F2 + 0.06935 x F3 + 0.62753 x F4" }, { "code": null, "e": 3782, "s": 3762, "text": "vif(model.fa.score)" }, { "code": null, "e": 3958, "s": 3782, "text": "#Model Performance metrics:pred_test <- predict(model.fa.score, newdata = test, type = “response”)pred_testtest$QD_Predicted <- pred_testhead(test[c(“QD”,”QD_Predicted”)], 10)" } ]
Digital Root of a given large integer using Recursion - GeeksforGeeks
25 Oct, 2021 The digital root of a positive integer is found by summing the digits of the integer. If the resulting value is a single digit then that digit is the digital root. If the resulting value contains two or more digits, those digits are summed and the process is repeated. This is continued as long as necessary to obtain a single digit.Given a large number N, the task is to find its digital root. The input number may be large and it may not be possible to store even if we use long long int.Examples: Input: N = 675987890789756545689070986776987 Output: 5 Explanation: Sum of individual digit of the above number = 212 Sum of individual digit of 212 = 5 So the Digital root is 5Input: num = 876598758938317432685778263 Output: 2 Explanation: Sum of individual digit of the above number = 155 Sum of individual digit of 155 = 11 Sum of individual digit of 11 = 2 So the Digital root is 2 Approach: Find out all the digits of a number.Add all the number one by one.If the final sum contains more than one digit, Call the recursive function again to make it a single digit.The result obtained in the single-digit is the Digital Root of the number. Find out all the digits of a number. Add all the number one by one. If the final sum contains more than one digit, Call the recursive function again to make it a single digit. The result obtained in the single-digit is the Digital Root of the number. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ program to print the digital// root of a given very large number #include <iostream>using namespace std; // Function to convert given// sum into stringstring convertToString(int sum){ string str = ""; // Loop to extract digit one by one // from the given sum and concatenate // into the string while (sum) { // Type casting for concatenation str = str + (char)((sum % 10) + '0'); sum = sum / 10; } // Return converted string return str;} // Function to get individual digit// sum from stringstring GetIndividulaDigitSum(string str, int len){ int sum = 0; // Loop to get individual digit sum for (int i = 0; i < len; i++) { sum = sum + str[i] - '0'; } // Function call to convert // sum into string return convertToString(sum);} // Function to calculate the digital// root of a very large numberint GetDigitalRoot(string str){ // Base condition if (str.length() == 1) { return str[0] - '0'; } // Function call to get // individual digit sum str = GetIndividulaDigitSum( str, str.length()); // Recursive function to get digital // root of a very large number return GetDigitalRoot(str);}int main(){ string str = "675987890789756545689070986776987"; // Function to print final digit cout << GetDigitalRoot(str);} // Java program to print the digital// root of a given very large numberclass GFG{ // Function to convert given// sum into Stringstatic String convertToString(int sum){ String str = ""; // Loop to extract digit one by one // from the given sum and concatenate // into the String while (sum > 0) { // Type casting for concatenation str = str + (char)((sum % 10) + '0'); sum = sum / 10; } // Return converted String return str;} // Function to get individual digit// sum from Stringstatic String GetIndividulaDigitSum(String str, int len){ int sum = 0; // Loop to get individual digit sum for (int i = 0; i < len; i++) { sum = sum + str.charAt(i) - '0'; } // Function call to convert // sum into String return convertToString(sum);} // Function to calculate the digital// root of a very large numberstatic int GetDigitalRoot(String str){ // Base condition if (str.length() == 1) { return str.charAt(0) - '0'; } // Function call to get // individual digit sum str = GetIndividulaDigitSum( str, str.length()); // Recursive function to get digital // root of a very large number return GetDigitalRoot(str);} // Driver codepublic static void main(String[] args){ String str = "675987890789756545689070986776987"; // Function to print final digit System.out.print(GetDigitalRoot(str));}} // This code is contributed by sapnasingh4991 # Python3 program to print the digital# root of a given very large number # Function to convert given# sum into stringdef convertToString(sum): str1 = "" # Loop to extract digit one by one # from the given sum and concatenate # into the string while (sum): # Type casting for concatenation str1 = str1 + chr((sum % 10) + ord('0')) sum = sum // 10 # Return converted string return str1 # Function to get individual digit# sum from stringdef GetIndividulaDigitSum(str1, len1): sum = 0 # Loop to get individual digit sum for i in range(len1): sum = sum + ord(str1[i]) - ord('0') # Function call to convert # sum into string return convertToString(sum) # Function to calculate the digital# root of a very large numberdef GetDigitalRoot(str1): # Base condition if (len(str1) == 1): return ord(str1[0] ) - ord('0') # Function call to get # individual digit sum str1 = GetIndividulaDigitSum(str1,len(str1)) # Recursive function to get digital # root of a very large number return GetDigitalRoot(str1) if __name__ == '__main__': str1 = "675987890789756545689070986776987" # Function to print final digit print(GetDigitalRoot(str1)) # This code is contributed by Surendra_Gangwar // C# program to print the digital// root of a given very large numberusing System;class GFG{ // Function to convert given// sum into Stringstatic String convertToString(int sum){ String str = ""; // Loop to extract digit one by one // from the given sum and concatenate // into the String while (sum > 0) { // Type casting for concatenation str = str + (char)((sum % 10) + '0'); sum = sum / 10; } // Return converted String return str;} // Function to get individual digit// sum from Stringstatic String GetIndividulaDigitSum(String str, int len){ int sum = 0; // Loop to get individual digit sum for (int i = 0; i < len; i++) { sum = sum + str[i] - '0'; } // Function call to convert // sum into String return convertToString(sum);} // Function to calculate the digital// root of a very large numberstatic int GetDigitalRoot(String str){ // Base condition if (str.Length == 1) { return str[0] - '0'; } // Function call to get // individual digit sum str = GetIndividulaDigitSum(str, str.Length); // Recursive function to get digital // root of a very large number return GetDigitalRoot(str);} // Driver codepublic static void Main(String[] args){ String str = "675987890789756545689070986776987"; // Function to print readonly digit Console.Write(GetDigitalRoot(str));}} // This code is contributed by Rajput-Ji <script> // Javascript program to print the digital // root of a given very large number // Function to convert given // sum into string function convertToString(sum) { let str = ""; // Loop to extract digit one by one // from the given sum and concatenate // into the string while (sum > 0) { // Type casting for concatenation str = str + String.fromCharCode((sum % 10) + '0'.charCodeAt()); sum = parseInt(sum / 10, 10); } // Return converted string return str; } // Function to get individual digit // sum from string function GetIndividulaDigitSum(str, len) { let sum = 0; // Loop to get individual digit sum for (let i = 0; i < len; i++) { sum = sum + str[i].charCodeAt() - '0'.charCodeAt(); } // Function call to convert // sum into string return convertToString(sum); } // Function to calculate the digital // root of a very large number function GetDigitalRoot(str) { // Base condition if (str.length == 1) { return (str[0].charCodeAt() - '0'.charCodeAt()); } // Function call to get // individual digit sum str = GetIndividulaDigitSum(str, str.length); // Recursive function to get digital // root of a very large number return GetDigitalRoot(str); } let str = "675987890789756545689070986776987"; // Function to print final digit document.write(GetDigitalRoot(str)); // This code is contributed by mukesh07.</script> 5 SURENDRA_GANGWAR sapnasingh4991 Akanksha_Rai Rajput-Ji anikaseth98 simranarora5sos mukesh07 ACM-ICPC large-numbers number-digits root Mathematical Recursion Strings Strings Mathematical Recursion Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Merge two sorted arrays Modulo Operator (%) in C/C++ with Examples Prime Numbers Program to find sum of elements in a given array The Knight's tour problem | Backtracking-1 Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum) Recursion Program for Tower of Hanoi Backtracking | Introduction Write a program to reverse digits of a number
[ { "code": null, "e": 24727, "s": 24699, "text": "\n25 Oct, 2021" }, { "code": null, "e": 25228, "s": 24727, "text": "The digital root of a positive integer is found by summing the digits of the integer. If the resulting value is a single digit then that digit is the digital root. If the resulting value contains two or more digits, those digits are summed and the process is repeated. This is continued as long as necessary to obtain a single digit.Given a large number N, the task is to find its digital root. The input number may be large and it may not be possible to store even if we use long long int.Examples: " }, { "code": null, "e": 25616, "s": 25228, "text": "Input: N = 675987890789756545689070986776987 Output: 5 Explanation: Sum of individual digit of the above number = 212 Sum of individual digit of 212 = 5 So the Digital root is 5Input: num = 876598758938317432685778263 Output: 2 Explanation: Sum of individual digit of the above number = 155 Sum of individual digit of 155 = 11 Sum of individual digit of 11 = 2 So the Digital root is 2 " }, { "code": null, "e": 25628, "s": 25616, "text": "Approach: " }, { "code": null, "e": 25876, "s": 25628, "text": "Find out all the digits of a number.Add all the number one by one.If the final sum contains more than one digit, Call the recursive function again to make it a single digit.The result obtained in the single-digit is the Digital Root of the number." }, { "code": null, "e": 25913, "s": 25876, "text": "Find out all the digits of a number." }, { "code": null, "e": 25944, "s": 25913, "text": "Add all the number one by one." }, { "code": null, "e": 26052, "s": 25944, "text": "If the final sum contains more than one digit, Call the recursive function again to make it a single digit." }, { "code": null, "e": 26127, "s": 26052, "text": "The result obtained in the single-digit is the Digital Root of the number." }, { "code": null, "e": 26180, "s": 26127, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 26184, "s": 26180, "text": "C++" }, { "code": null, "e": 26189, "s": 26184, "text": "Java" }, { "code": null, "e": 26197, "s": 26189, "text": "Python3" }, { "code": null, "e": 26200, "s": 26197, "text": "C#" }, { "code": null, "e": 26211, "s": 26200, "text": "Javascript" }, { "code": "// C++ program to print the digital// root of a given very large number #include <iostream>using namespace std; // Function to convert given// sum into stringstring convertToString(int sum){ string str = \"\"; // Loop to extract digit one by one // from the given sum and concatenate // into the string while (sum) { // Type casting for concatenation str = str + (char)((sum % 10) + '0'); sum = sum / 10; } // Return converted string return str;} // Function to get individual digit// sum from stringstring GetIndividulaDigitSum(string str, int len){ int sum = 0; // Loop to get individual digit sum for (int i = 0; i < len; i++) { sum = sum + str[i] - '0'; } // Function call to convert // sum into string return convertToString(sum);} // Function to calculate the digital// root of a very large numberint GetDigitalRoot(string str){ // Base condition if (str.length() == 1) { return str[0] - '0'; } // Function call to get // individual digit sum str = GetIndividulaDigitSum( str, str.length()); // Recursive function to get digital // root of a very large number return GetDigitalRoot(str);}int main(){ string str = \"675987890789756545689070986776987\"; // Function to print final digit cout << GetDigitalRoot(str);}", "e": 27594, "s": 26211, "text": null }, { "code": "// Java program to print the digital// root of a given very large numberclass GFG{ // Function to convert given// sum into Stringstatic String convertToString(int sum){ String str = \"\"; // Loop to extract digit one by one // from the given sum and concatenate // into the String while (sum > 0) { // Type casting for concatenation str = str + (char)((sum % 10) + '0'); sum = sum / 10; } // Return converted String return str;} // Function to get individual digit// sum from Stringstatic String GetIndividulaDigitSum(String str, int len){ int sum = 0; // Loop to get individual digit sum for (int i = 0; i < len; i++) { sum = sum + str.charAt(i) - '0'; } // Function call to convert // sum into String return convertToString(sum);} // Function to calculate the digital// root of a very large numberstatic int GetDigitalRoot(String str){ // Base condition if (str.length() == 1) { return str.charAt(0) - '0'; } // Function call to get // individual digit sum str = GetIndividulaDigitSum( str, str.length()); // Recursive function to get digital // root of a very large number return GetDigitalRoot(str);} // Driver codepublic static void main(String[] args){ String str = \"675987890789756545689070986776987\"; // Function to print final digit System.out.print(GetDigitalRoot(str));}} // This code is contributed by sapnasingh4991", "e": 29098, "s": 27594, "text": null }, { "code": "# Python3 program to print the digital# root of a given very large number # Function to convert given# sum into stringdef convertToString(sum): str1 = \"\" # Loop to extract digit one by one # from the given sum and concatenate # into the string while (sum): # Type casting for concatenation str1 = str1 + chr((sum % 10) + ord('0')) sum = sum // 10 # Return converted string return str1 # Function to get individual digit# sum from stringdef GetIndividulaDigitSum(str1, len1): sum = 0 # Loop to get individual digit sum for i in range(len1): sum = sum + ord(str1[i]) - ord('0') # Function call to convert # sum into string return convertToString(sum) # Function to calculate the digital# root of a very large numberdef GetDigitalRoot(str1): # Base condition if (len(str1) == 1): return ord(str1[0] ) - ord('0') # Function call to get # individual digit sum str1 = GetIndividulaDigitSum(str1,len(str1)) # Recursive function to get digital # root of a very large number return GetDigitalRoot(str1) if __name__ == '__main__': str1 = \"675987890789756545689070986776987\" # Function to print final digit print(GetDigitalRoot(str1)) # This code is contributed by Surendra_Gangwar", "e": 30382, "s": 29098, "text": null }, { "code": "// C# program to print the digital// root of a given very large numberusing System;class GFG{ // Function to convert given// sum into Stringstatic String convertToString(int sum){ String str = \"\"; // Loop to extract digit one by one // from the given sum and concatenate // into the String while (sum > 0) { // Type casting for concatenation str = str + (char)((sum % 10) + '0'); sum = sum / 10; } // Return converted String return str;} // Function to get individual digit// sum from Stringstatic String GetIndividulaDigitSum(String str, int len){ int sum = 0; // Loop to get individual digit sum for (int i = 0; i < len; i++) { sum = sum + str[i] - '0'; } // Function call to convert // sum into String return convertToString(sum);} // Function to calculate the digital// root of a very large numberstatic int GetDigitalRoot(String str){ // Base condition if (str.Length == 1) { return str[0] - '0'; } // Function call to get // individual digit sum str = GetIndividulaDigitSum(str, str.Length); // Recursive function to get digital // root of a very large number return GetDigitalRoot(str);} // Driver codepublic static void Main(String[] args){ String str = \"675987890789756545689070986776987\"; // Function to print readonly digit Console.Write(GetDigitalRoot(str));}} // This code is contributed by Rajput-Ji", "e": 31823, "s": 30382, "text": null }, { "code": "<script> // Javascript program to print the digital // root of a given very large number // Function to convert given // sum into string function convertToString(sum) { let str = \"\"; // Loop to extract digit one by one // from the given sum and concatenate // into the string while (sum > 0) { // Type casting for concatenation str = str + String.fromCharCode((sum % 10) + '0'.charCodeAt()); sum = parseInt(sum / 10, 10); } // Return converted string return str; } // Function to get individual digit // sum from string function GetIndividulaDigitSum(str, len) { let sum = 0; // Loop to get individual digit sum for (let i = 0; i < len; i++) { sum = sum + str[i].charCodeAt() - '0'.charCodeAt(); } // Function call to convert // sum into string return convertToString(sum); } // Function to calculate the digital // root of a very large number function GetDigitalRoot(str) { // Base condition if (str.length == 1) { return (str[0].charCodeAt() - '0'.charCodeAt()); } // Function call to get // individual digit sum str = GetIndividulaDigitSum(str, str.length); // Recursive function to get digital // root of a very large number return GetDigitalRoot(str); } let str = \"675987890789756545689070986776987\"; // Function to print final digit document.write(GetDigitalRoot(str)); // This code is contributed by mukesh07.</script>", "e": 33498, "s": 31823, "text": null }, { "code": null, "e": 33500, "s": 33498, "text": "5" }, { "code": null, "e": 33519, "s": 33502, "text": "SURENDRA_GANGWAR" }, { "code": null, "e": 33534, "s": 33519, "text": "sapnasingh4991" }, { "code": null, "e": 33547, "s": 33534, "text": "Akanksha_Rai" }, { "code": null, "e": 33557, "s": 33547, "text": "Rajput-Ji" }, { "code": null, "e": 33569, "s": 33557, "text": "anikaseth98" }, { "code": null, "e": 33585, "s": 33569, "text": "simranarora5sos" }, { "code": null, "e": 33594, "s": 33585, "text": "mukesh07" }, { "code": null, "e": 33603, "s": 33594, "text": "ACM-ICPC" }, { "code": null, "e": 33617, "s": 33603, "text": "large-numbers" }, { "code": null, "e": 33631, "s": 33617, "text": "number-digits" }, { "code": null, "e": 33636, "s": 33631, "text": "root" }, { "code": null, "e": 33649, "s": 33636, "text": "Mathematical" }, { "code": null, "e": 33659, "s": 33649, "text": "Recursion" }, { "code": null, "e": 33667, "s": 33659, "text": "Strings" }, { "code": null, "e": 33675, "s": 33667, "text": "Strings" }, { "code": null, "e": 33688, "s": 33675, "text": "Mathematical" }, { "code": null, "e": 33698, "s": 33688, "text": "Recursion" }, { "code": null, "e": 33796, "s": 33698, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 33805, "s": 33796, "text": "Comments" }, { "code": null, "e": 33818, "s": 33805, "text": "Old Comments" }, { "code": null, "e": 33842, "s": 33818, "text": "Merge two sorted arrays" }, { "code": null, "e": 33885, "s": 33842, "text": "Modulo Operator (%) in C/C++ with Examples" }, { "code": null, "e": 33899, "s": 33885, "text": "Prime Numbers" }, { "code": null, "e": 33948, "s": 33899, "text": "Program to find sum of elements in a given array" }, { "code": null, "e": 33991, "s": 33948, "text": "The Knight's tour problem | Backtracking-1" }, { "code": null, "e": 34076, "s": 33991, "text": "Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)" }, { "code": null, "e": 34086, "s": 34076, "text": "Recursion" }, { "code": null, "e": 34113, "s": 34086, "text": "Program for Tower of Hanoi" }, { "code": null, "e": 34141, "s": 34113, "text": "Backtracking | Introduction" } ]
C++ Program to Find the Mode in a Data Set
This is a C++ program to find the Mode in a data set. Begin function insertinset() to insert data in the set. Create newnode and temp(t) node. Node to be inserted in the list using newnode. If head is null then assign new node to head and increase the count. During insertion perform insertion sort for sorting data. If the newnode->data is equal to any of the element present in the set, then just increment count. End #include <iostream> using namespace std; struct set // a structure set to declare variables { int data; int cnt; set *n; }; set* insertinset(set *head, int n) { set *newnode = new set; //to use structure set’s variables. set *t = new set; newnode->data = n; newnode->cnt = 0; newnode->n = NULL; if(head == NULL) { head = newnode; head->cnt++; return head; } else { t = head; if(newnode->data < head->data) { newnode->n = head; head = newnode; newnode->cnt++; return head; } else if(newnode->data == head->data) { head->cnt++; return head; } while(t->n!= NULL) { if(newnode->data == (t->n)->data) { (t->n)->cnt++; return head; } if(newnode->data < (t->n)->data) break; t=t->n; } newnode->n = t->n; t->n = newnode; newnode->cnt++; return head; } } int main() { int n, i, num, max = 0, c; set *head = new set; head = NULL; cout<<"\nEnter the number of data element to be sorted: "; cin>>n; for(i = 0; i < n; i++) { cout<<"Enter element "<<i+1<<": "; cin>>num; head = insertinset(head, num); //call the function } cout<<"\nSorted Distinct Data "; while(head != NULL) // if head is not equal to null { if(max < head->cnt) { c = head->data; max = head->cnt; } cout<<"->"<<head->data<<"("<<head->cnt<<")"; //return the count of the data. head = head->n; } cout<<"\nThe Mode of given data set is "<<c<<" and occurred "<<max<<" times."; return 0; } Enter the number of data element to be sorted: 10 Enter element 1: 1 Enter element 2: 2 Enter element 3: 0 Enter element 4: 2 Enter element 5: 3 Enter element 6: 7 Enter element 7: 6 Enter element 8: 2 Enter element 9: 1 Enter element 10: 1 Sorted Distinct Data ->0(1)->1(3)->2(3)->3(1)->6(1)->7(1) The Mode of given data set is 1 and occurred 3 times.
[ { "code": null, "e": 1116, "s": 1062, "text": "This is a C++ program to find the Mode in a data set." }, { "code": null, "e": 1512, "s": 1116, "text": "Begin\n function insertinset() to insert data in the set.\n Create newnode and temp(t) node.\n Node to be inserted in the list using newnode.\n If head is null then\n assign new node to head and increase the count.\n During insertion perform insertion sort for sorting data.\n If the newnode->data is equal to any of the element present in the set,\n then just increment count.\nEnd" }, { "code": null, "e": 3188, "s": 1512, "text": "#include <iostream>\nusing namespace std;\nstruct set // a structure set to declare variables\n{\n int data;\n int cnt;\n set *n;\n};\nset* insertinset(set *head, int n) {\n set *newnode = new set; //to use structure set’s variables.\n set *t = new set;\n newnode->data = n;\n newnode->cnt = 0;\n newnode->n = NULL;\n if(head == NULL) {\n head = newnode;\n head->cnt++;\n return head;\n } else {\n t = head;\n if(newnode->data < head->data) {\n newnode->n = head;\n head = newnode;\n newnode->cnt++;\n return head;\n } else if(newnode->data == head->data) {\n head->cnt++;\n return head;\n }\n while(t->n!= NULL) {\n if(newnode->data == (t->n)->data) {\n (t->n)->cnt++;\n return head;\n }\n if(newnode->data < (t->n)->data)\n break;\n t=t->n;\n }\n newnode->n = t->n;\n t->n = newnode;\n newnode->cnt++;\n return head;\n }\n}\nint main() {\n int n, i, num, max = 0, c;\n set *head = new set;\n head = NULL;\n cout<<\"\\nEnter the number of data element to be sorted: \";\n cin>>n;\n for(i = 0; i < n; i++) {\n cout<<\"Enter element \"<<i+1<<\": \";\n cin>>num;\n head = insertinset(head, num); //call the function\n }\n cout<<\"\\nSorted Distinct Data \";\n while(head != NULL) // if head is not equal to null\n {\n if(max < head->cnt) {\n c = head->data;\n max = head->cnt;\n }\n cout<<\"->\"<<head->data<<\"(\"<<head->cnt<<\")\"; //return the count of the data.\n head = head->n;\n }\n cout<<\"\\nThe Mode of given data set is \"<<c<<\" and occurred \"<<max<<\" times.\";\n return 0;\n}" }, { "code": null, "e": 3541, "s": 3188, "text": "Enter the number of data element to be sorted: 10\nEnter element 1: 1\nEnter element 2: 2\nEnter element 3: 0\nEnter element 4: 2\nEnter element 5: 3\nEnter element 6: 7\nEnter element 7: 6\nEnter element 8: 2\nEnter element 9: 1\nEnter element 10: 1\nSorted Distinct Data ->0(1)->1(3)->2(3)->3(1)->6(1)->7(1)\nThe Mode of given data set is 1 and occurred 3 times." } ]
Batch Script - Deleting from the Registry
Deleting from the registry is done via the REG DEL command. Note that in order to delete values from the registry you need to have sufficient privileges on the system to perform this operation. The REG DELETE command has the following variations. In the second variation, the default value will be removed and in the last variation all the values under the specified key will be removed. REG DELETE [ROOT\]RegKey /v ValueName [/f] REG DELETE [ROOT\]RegKey /ve [/f] REG DELETE [ROOT\]RegKey /va [/f] Where ValueName − The value, under the selected RegKey, to edit. ValueName − The value, under the selected RegKey, to edit. /f − Force an update without prompting "Value exists, overwrite Y/N". /f − Force an update without prompting "Value exists, overwrite Y/N". @echo off REG DELETE HKEY_CURRENT_USER\Console /v Test /f REG QUERY HKEY_CURRENT_USER\Console /v Test In the above example, the first part is to delete a key into the registry under the location HKEY_CURRENT_USER\Console. This key has the name of Test. The second command just displays what was deleted to the registry by using the REG QUERY command. From this command, we should expect an error, just to ensure that our key was in fact deleted. Following will be the output of the above program. The first line of the output shows that the ‘Delete’ functionality was successful and the second output shows an error which was expected to confirm that indeed our key was deleted from the registry. The operation completed successfully. ERROR: The system was unable to find the specified registry key or value. Print Add Notes Bookmark this page
[ { "code": null, "e": 2363, "s": 2169, "text": "Deleting from the registry is done via the REG DEL command. Note that in order to delete values from the registry you need to have sufficient privileges on the system to perform this operation." }, { "code": null, "e": 2557, "s": 2363, "text": "The REG DELETE command has the following variations. In the second variation, the default value will be removed and in the last variation all the values under the specified key will be removed." }, { "code": null, "e": 2677, "s": 2557, "text": "REG DELETE [ROOT\\]RegKey /v ValueName [/f] \n REG DELETE [ROOT\\]RegKey /ve [/f] \n REG DELETE [ROOT\\]RegKey /va [/f]\n" }, { "code": null, "e": 2683, "s": 2677, "text": "Where" }, { "code": null, "e": 2742, "s": 2683, "text": "ValueName − The value, under the selected RegKey, to edit." }, { "code": null, "e": 2801, "s": 2742, "text": "ValueName − The value, under the selected RegKey, to edit." }, { "code": null, "e": 2871, "s": 2801, "text": "/f − Force an update without prompting \"Value exists, overwrite Y/N\"." }, { "code": null, "e": 2941, "s": 2871, "text": "/f − Force an update without prompting \"Value exists, overwrite Y/N\"." }, { "code": null, "e": 3043, "s": 2941, "text": "@echo off\nREG DELETE HKEY_CURRENT_USER\\Console /v Test /f\nREG QUERY HKEY_CURRENT_USER\\Console /v Test" }, { "code": null, "e": 3387, "s": 3043, "text": "In the above example, the first part is to delete a key into the registry under the location HKEY_CURRENT_USER\\Console. This key has the name of Test. The second command just displays what was deleted to the registry by using the REG QUERY command. From this command, we should expect an error, just to ensure that our key was in fact deleted." }, { "code": null, "e": 3638, "s": 3387, "text": "Following will be the output of the above program. The first line of the output shows that the ‘Delete’ functionality was successful and the second output shows an error which was expected to confirm that indeed our key was deleted from the registry." }, { "code": null, "e": 3752, "s": 3638, "text": "The operation completed successfully. \nERROR: The system was unable to find the specified registry key or value.\n" }, { "code": null, "e": 3759, "s": 3752, "text": " Print" }, { "code": null, "e": 3770, "s": 3759, "text": " Add Notes" } ]
C Program to Find a pair with the given difference - GeeksforGeeks
21 Dec, 2021 Given an unsorted array and a number n, find if there exists a pair of elements in the array whose difference is n. Examples: Input: arr[] = {5, 20, 3, 2, 50, 80}, n = 78 Output: Pair Found: (2, 80) Input: arr[] = {90, 70, 20, 80, 50}, n = 45 Output: No Such Pair The simplest method is to run two loops, the outer loop picks the first element (smaller element) and the inner loop looks for the element picked by outer loop plus n. Time complexity of this method is O(n^2).We can use sorting and Binary Search to improve time complexity to O(nLogn). The first step is to sort the array in ascending order. Once the array is sorted, traverse the array from left to right, and for each element arr[i], binary search for arr[i] + n in arr[i+1..n-1]. If the element is found, return the pair. Both first and second steps take O(nLogn). So overall complexity is O(nLogn). The second step of the above algorithm can be improved to O(n). The first step remain same. The idea for second step is take two index variables i and j, initialize them as 0 and 1 respectively. Now run a linear loop. If arr[j] – arr[i] is smaller than n, we need to look for greater arr[j], so increment j. If arr[j] – arr[i] is greater than n, we need to look for greater arr[i], so increment i. Thanks to Aashish Barnwal for suggesting this approach. The following code is only for the second step of the algorithm, it assumes that the array is already sorted. C // C program to find a pair with the given difference#include <stdio.h> // The function assumes that the array is sorted bool findPair(int arr[], int size, int n){ // Initialize positions of two elements int i = 0; int j = 1; // Search for a pair while (i<size && j<size) { if (i != j && arr[j]-arr[i] == n) { printf("Pair Found: (%d, %d)", arr[i], arr[j]); return true; } else if (arr[j]-arr[i] < n) j++; else i++; } printf("No such pair"); return false;} // Driver program to test above functionint main(){ int arr[] = {1, 8, 30, 40, 100}; int size = sizeof(arr)/sizeof(arr[0]); int n = 60; findPair(arr, size, n); return 0;} Output: Pair Found: (40, 100) Hashing can also be used to solve this problem. Create an empty hash table HT. Traverse the array, use array elements as hash keys and enter them in HT. Traverse the array again look for value n + arr[i] in HT. Please refer complete article on Find a pair with the given difference for more details! Amazon Binary Search Visa C Language C Programs Searching Sorting Amazon Visa Searching Sorting Binary Search Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. TCP Server-Client implementation in C Multithreading in C Exception Handling in C++ Arrow operator -> in C/C++ with Examples 'this' pointer in C++ Strings in C Arrow operator -> in C/C++ with Examples UDP Server-Client implementation in C C Program to read contents of Whole File Header files in C/C++ and its uses
[ { "code": null, "e": 24286, "s": 24258, "text": "\n21 Dec, 2021" }, { "code": null, "e": 24414, "s": 24286, "text": "Given an unsorted array and a number n, find if there exists a pair of elements in the array whose difference is n. Examples: " }, { "code": null, "e": 24553, "s": 24414, "text": "Input: arr[] = {5, 20, 3, 2, 50, 80}, n = 78\nOutput: Pair Found: (2, 80)\n\nInput: arr[] = {90, 70, 20, 80, 50}, n = 45\nOutput: No Such Pair" }, { "code": null, "e": 25724, "s": 24555, "text": "The simplest method is to run two loops, the outer loop picks the first element (smaller element) and the inner loop looks for the element picked by outer loop plus n. Time complexity of this method is O(n^2).We can use sorting and Binary Search to improve time complexity to O(nLogn). The first step is to sort the array in ascending order. Once the array is sorted, traverse the array from left to right, and for each element arr[i], binary search for arr[i] + n in arr[i+1..n-1]. If the element is found, return the pair. Both first and second steps take O(nLogn). So overall complexity is O(nLogn). The second step of the above algorithm can be improved to O(n). The first step remain same. The idea for second step is take two index variables i and j, initialize them as 0 and 1 respectively. Now run a linear loop. If arr[j] – arr[i] is smaller than n, we need to look for greater arr[j], so increment j. If arr[j] – arr[i] is greater than n, we need to look for greater arr[i], so increment i. Thanks to Aashish Barnwal for suggesting this approach. The following code is only for the second step of the algorithm, it assumes that the array is already sorted. " }, { "code": null, "e": 25726, "s": 25724, "text": "C" }, { "code": "// C program to find a pair with the given difference#include <stdio.h> // The function assumes that the array is sorted bool findPair(int arr[], int size, int n){ // Initialize positions of two elements int i = 0; int j = 1; // Search for a pair while (i<size && j<size) { if (i != j && arr[j]-arr[i] == n) { printf(\"Pair Found: (%d, %d)\", arr[i], arr[j]); return true; } else if (arr[j]-arr[i] < n) j++; else i++; } printf(\"No such pair\"); return false;} // Driver program to test above functionint main(){ int arr[] = {1, 8, 30, 40, 100}; int size = sizeof(arr)/sizeof(arr[0]); int n = 60; findPair(arr, size, n); return 0;}", "e": 26483, "s": 25726, "text": null }, { "code": null, "e": 26493, "s": 26483, "text": "Output: " }, { "code": null, "e": 26515, "s": 26493, "text": "Pair Found: (40, 100)" }, { "code": null, "e": 26728, "s": 26515, "text": "Hashing can also be used to solve this problem. Create an empty hash table HT. Traverse the array, use array elements as hash keys and enter them in HT. Traverse the array again look for value n + arr[i] in HT. " }, { "code": null, "e": 26817, "s": 26728, "text": "Please refer complete article on Find a pair with the given difference for more details!" }, { "code": null, "e": 26824, "s": 26817, "text": "Amazon" }, { "code": null, "e": 26838, "s": 26824, "text": "Binary Search" }, { "code": null, "e": 26843, "s": 26838, "text": "Visa" }, { "code": null, "e": 26854, "s": 26843, "text": "C Language" }, { "code": null, "e": 26865, "s": 26854, "text": "C Programs" }, { "code": null, "e": 26875, "s": 26865, "text": "Searching" }, { "code": null, "e": 26883, "s": 26875, "text": "Sorting" }, { "code": null, "e": 26890, "s": 26883, "text": "Amazon" }, { "code": null, "e": 26895, "s": 26890, "text": "Visa" }, { "code": null, "e": 26905, "s": 26895, "text": "Searching" }, { "code": null, "e": 26913, "s": 26905, "text": "Sorting" }, { "code": null, "e": 26927, "s": 26913, "text": "Binary Search" }, { "code": null, "e": 27025, "s": 26927, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27063, "s": 27025, "text": "TCP Server-Client implementation in C" }, { "code": null, "e": 27083, "s": 27063, "text": "Multithreading in C" }, { "code": null, "e": 27109, "s": 27083, "text": "Exception Handling in C++" }, { "code": null, "e": 27150, "s": 27109, "text": "Arrow operator -> in C/C++ with Examples" }, { "code": null, "e": 27172, "s": 27150, "text": "'this' pointer in C++" }, { "code": null, "e": 27185, "s": 27172, "text": "Strings in C" }, { "code": null, "e": 27226, "s": 27185, "text": "Arrow operator -> in C/C++ with Examples" }, { "code": null, "e": 27264, "s": 27226, "text": "UDP Server-Client implementation in C" }, { "code": null, "e": 27305, "s": 27264, "text": "C Program to read contents of Whole File" } ]
Optimising a Machine Learning Model with the Confusion Matrix | by Rebecca Vickery | Towards Data Science
The confusion matrix, in machine learning, is a grid of values that help to evaluate the performance of supervised classification models. From this grid, you can also compute a number of metrics to give a score for the model these include precision, recall and the F1-score. Although on the surface this grid is quite simple, and the measures require only high-school level mathematics to calculate the concepts behind the matrix can be difficult to grasp. In the following post I will give a simple introduction to the following: The Confusion MatrixPrecision, recall and the F1-scoreA walkthrough in python illustrating how to choose the right metric and optimise the performance of your model to maximise that metric The Confusion Matrix Precision, recall and the F1-score A walkthrough in python illustrating how to choose the right metric and optimise the performance of your model to maximise that metric For this explanation let’s suppose we were working on a binary classification problem to detect whether or not a transaction is fraudulent. Our model uses characteristics of the user and transaction and returns 1 if the transaction is predicted to be fraudulent and 0 if not. Given that machine learning models are rarely 100% accurate there is going to be a level of risk in deploying this model. If we incorrectly classify a non-fraudulent transaction as fraud then we may well lose that transaction, and possibly even the future customers business. On the other hand, if we incorrectly detect a fraudulent transaction as non-fraudulent then we might stand to lose the value of that transaction. The confusion matrix essentially places the resulting predictions into four groups. They are as follows: True positive (TP): the model predicts fraud and the transaction is indeed fraudulent. False positive (FP): the model predicts fraud but the transaction is not fraudulent. True negative (TN): the model predicts not fraud and the transaction is not fraudulent. False negative (FN): the model predicts not fraud but the transaction is in fact fraudulent. To illustrate how a confusion matrix looks I am going to be using some manufactured data. There are a few python libraries that make constructing confusion matrices fairly simple, below are a couple of examples; Scikit-learn sklearn.metrics.confusion_matrix(y_true, y_pred, labels=None, sample_weight=None) creates a very simple grid. from sklearn.metrics import confusion_matrixy_true = [0,1,1,0,1,0,0,0,1,1]y_pred = [0,1,0,0,1,0,0,1,0,1]confusion_matrix(y_true, y_pred, labels=[0,1]) The pandas_ml library produces a more readable output. from pandas_ml import ConfusionMatrixConfusionMatrix(y_true, y_pred) Let’s use the grid to determine the numbers for each of the 4 groups we discussed above. There are 3 samples where the model predicted fraud and the transaction is fraudulent, so TP = 3. This is the number in the bottom right-hand corner where the row and column are both True. There is 1 sample where the model predicted fraud but the transaction was not fraudulent, so FP = 1. There are 2 samples where the model predicted not fraud but the transaction was fraudulent, so FN = 2. There are 4 samples where the model correctly predicted not fraud and the transaction was fraudulent, so TN = 4. If we were in a business and a model such as this was going to be deployed and used to drive a value outcome there are a few things that the confusion matrix can help to determine. These include: How good is the model at determining a fraudulent transaction? How good is the model at differentiating a fraudulent transaction and a non-fraudulent transaction? How many times does the model incorrectly predict that a fraudulent transaction is not fraudulent? The measures that I mentioned earlier that you can derive from the confusion matrix can help to answer these questions. There are a number of metrics that can be derived from the confusion matrix which all measure the performance of the model. I am going to cover explanations for three of the most commonly used. Precision: This is essentially a measure of out of all the samples predicted to be fraud how many were correct. The calculation is, therefore; TP / (TP + FP) Recall (sensitivity): This is a measure of for those samples that were fraudulent how many were correctly predicted as fraudulent. TP /(TP + FN) The difference between these two metrics is subtle but very important. If we optimise for precision then we will get fewer false positives (fewer non-fraudulent transactions classified as fraud), 0 false positives would give a perfect score of 1. If we optimise for recall then we get fewer false negatives so we are catching more fraudulent transactions but this may be at the detriment of incorrectly classifying more non-fraudulent transactions as fraud. F1-score: is what is known as the ‘harmonic average’ of precision and recall. The F1-score, therefore, gives a good indicator of the overall accuracy of a classifier, whilst precision and recall give information about the areas in which specifically the model is performing well or not so well. Maximising the F1 score would create a balanced model which has the optimal score for both precision and recall. Which metric you choose to optimise for will very much depend on the use case. There are several methods that tune a machine learning model for a particular metric that suits your specific use case. One example is the scikit-learn GridSearchCV which has a scoring parameter which allows you to select a given metric. This function performs cross-validated grid-search over a parameter grid and returns the optimal parameters for the model based on the scoring metric you provide. In the next part of this post, I will walk through an example of optimising a model using GridSearchCV . First import the relevant libraries. import wgetimport pandas as pdimport numpy as npfrom sklearn.model_selection import train_test_splitfrom sklearn.linear_model import LogisticRegressionfrom sklearn.metrics import classification_reportfrom pandas_ml import ConfusionMatrixfrom sklearn.metrics import precision_scorefrom sklearn.metrics import recall_scorefrom sklearn.metrics import f1_scorefrom sklearn.datasets import load_breast_cancerfrom sklearn.model_selection import GridSearchCVfrom pandas_ml import ConfusionMatrix For this example, I am going to use a simple data set which consists of attributes for a sample of patients and an indicator describing whether or not they have breast cancer. This can be obtained directly from scikit-learn using the code below. X, y = load_breast_cancer(return_X_y=True) In this dataset, the malignant class is actually the negative class. To make the resulting confusion matrix easier to interpret I will relabel them so that the malignant class is positive. for i in range(len(y)): if y[i] > 0: y[i] = 0 elif y[i] < 1: y[i] = 1 Next, I am splitting the data into test and train sets. X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.33) I will then train a simple logistic regression model and use the model to make some predictions. rf = LogisticRegression()model = rf.fit(X_train, y_train)y_pred = rf.predict(X_test)ConfusionMatrix(y_test, y_pred) The confusion matrix looks like this. Let’s calculate the metrics. print('Precision is:'+str(round(precision_score(y_test, y_pred),2)))print('Recall is:'+str(round(recall_score(y_test, y_pred, average='binary'),2)))print('F1 score is:'+str(round(f1_score(y_test, y_pred, average='binary'),2))) The model performs quite well for all metrics. However, if we were going to use this model in place of a doctors diagnosis for breast cancer then even 8 false negatives would be too many. So for this use case we would want to minimise false negatives and therefore want to optimise the model for recall. Now we are going to implement GridSearchCV and optimise the model for this metric. First, we create a hyperparameter search space for two selected LogisticRegression parameters. penalty = ['l1', 'l2']C = np.logspace(0, 4, 10)hyperparameters = dict(C=C, penalty=penalty) We then call the logistic regression model and call GridSearchCV with the scoring parameter selected as recall. lr = LogisticRegression()clf = GridSearchCV(lr, hyperparameters, cv=5, verbose=0, scoring='recall') Now we fit GridSearchCV and print the best parameters for recall. best_model = clf.fit(X_train, y_train)print('Best Penalty:', best_model.best_estimator_.get_params()['penalty'])print('Best C:', round(best_model.best_estimator_.get_params()['C'],2)) Let’s now print the confusion matrix and metrics for the best model. y_pred_gs = best_model.predict(X_test)cm_gs = ConfusionMatrix(y_test, y_pred_gs)print(cm_gs)print('Precision is:'+str(round(precision_score(y_test, y_pred_gs),2)))print('Recall is:'+str(round(recall_score(y_test, y_pred_gs, average='binary'),2)))print('F1 score is:'+str(round(f1_score(y_test, y_pred_gs, average='binary'),2))) You can see from these results that the recall score is now higher and we have also improved both precision and recall. The model is now better at predicting the correct labels both for malignant and benign cases. There are many other metrics that are important to fully evaluate the performance of a classification model including specificity, AUC and ROC. However, I think those require an article of their own — this is a good one. Thanks for reading!
[ { "code": null, "e": 629, "s": 172, "text": "The confusion matrix, in machine learning, is a grid of values that help to evaluate the performance of supervised classification models. From this grid, you can also compute a number of metrics to give a score for the model these include precision, recall and the F1-score. Although on the surface this grid is quite simple, and the measures require only high-school level mathematics to calculate the concepts behind the matrix can be difficult to grasp." }, { "code": null, "e": 703, "s": 629, "text": "In the following post I will give a simple introduction to the following:" }, { "code": null, "e": 892, "s": 703, "text": "The Confusion MatrixPrecision, recall and the F1-scoreA walkthrough in python illustrating how to choose the right metric and optimise the performance of your model to maximise that metric" }, { "code": null, "e": 913, "s": 892, "text": "The Confusion Matrix" }, { "code": null, "e": 948, "s": 913, "text": "Precision, recall and the F1-score" }, { "code": null, "e": 1083, "s": 948, "text": "A walkthrough in python illustrating how to choose the right metric and optimise the performance of your model to maximise that metric" }, { "code": null, "e": 1359, "s": 1083, "text": "For this explanation let’s suppose we were working on a binary classification problem to detect whether or not a transaction is fraudulent. Our model uses characteristics of the user and transaction and returns 1 if the transaction is predicted to be fraudulent and 0 if not." }, { "code": null, "e": 1781, "s": 1359, "text": "Given that machine learning models are rarely 100% accurate there is going to be a level of risk in deploying this model. If we incorrectly classify a non-fraudulent transaction as fraud then we may well lose that transaction, and possibly even the future customers business. On the other hand, if we incorrectly detect a fraudulent transaction as non-fraudulent then we might stand to lose the value of that transaction." }, { "code": null, "e": 1886, "s": 1781, "text": "The confusion matrix essentially places the resulting predictions into four groups. They are as follows:" }, { "code": null, "e": 1973, "s": 1886, "text": "True positive (TP): the model predicts fraud and the transaction is indeed fraudulent." }, { "code": null, "e": 2058, "s": 1973, "text": "False positive (FP): the model predicts fraud but the transaction is not fraudulent." }, { "code": null, "e": 2146, "s": 2058, "text": "True negative (TN): the model predicts not fraud and the transaction is not fraudulent." }, { "code": null, "e": 2239, "s": 2146, "text": "False negative (FN): the model predicts not fraud but the transaction is in fact fraudulent." }, { "code": null, "e": 2329, "s": 2239, "text": "To illustrate how a confusion matrix looks I am going to be using some manufactured data." }, { "code": null, "e": 2451, "s": 2329, "text": "There are a few python libraries that make constructing confusion matrices fairly simple, below are a couple of examples;" }, { "code": null, "e": 2574, "s": 2451, "text": "Scikit-learn sklearn.metrics.confusion_matrix(y_true, y_pred, labels=None, sample_weight=None) creates a very simple grid." }, { "code": null, "e": 2725, "s": 2574, "text": "from sklearn.metrics import confusion_matrixy_true = [0,1,1,0,1,0,0,0,1,1]y_pred = [0,1,0,0,1,0,0,1,0,1]confusion_matrix(y_true, y_pred, labels=[0,1])" }, { "code": null, "e": 2780, "s": 2725, "text": "The pandas_ml library produces a more readable output." }, { "code": null, "e": 2849, "s": 2780, "text": "from pandas_ml import ConfusionMatrixConfusionMatrix(y_true, y_pred)" }, { "code": null, "e": 2938, "s": 2849, "text": "Let’s use the grid to determine the numbers for each of the 4 groups we discussed above." }, { "code": null, "e": 3127, "s": 2938, "text": "There are 3 samples where the model predicted fraud and the transaction is fraudulent, so TP = 3. This is the number in the bottom right-hand corner where the row and column are both True." }, { "code": null, "e": 3228, "s": 3127, "text": "There is 1 sample where the model predicted fraud but the transaction was not fraudulent, so FP = 1." }, { "code": null, "e": 3331, "s": 3228, "text": "There are 2 samples where the model predicted not fraud but the transaction was fraudulent, so FN = 2." }, { "code": null, "e": 3444, "s": 3331, "text": "There are 4 samples where the model correctly predicted not fraud and the transaction was fraudulent, so TN = 4." }, { "code": null, "e": 3640, "s": 3444, "text": "If we were in a business and a model such as this was going to be deployed and used to drive a value outcome there are a few things that the confusion matrix can help to determine. These include:" }, { "code": null, "e": 3703, "s": 3640, "text": "How good is the model at determining a fraudulent transaction?" }, { "code": null, "e": 3803, "s": 3703, "text": "How good is the model at differentiating a fraudulent transaction and a non-fraudulent transaction?" }, { "code": null, "e": 3902, "s": 3803, "text": "How many times does the model incorrectly predict that a fraudulent transaction is not fraudulent?" }, { "code": null, "e": 4022, "s": 3902, "text": "The measures that I mentioned earlier that you can derive from the confusion matrix can help to answer these questions." }, { "code": null, "e": 4216, "s": 4022, "text": "There are a number of metrics that can be derived from the confusion matrix which all measure the performance of the model. I am going to cover explanations for three of the most commonly used." }, { "code": null, "e": 4359, "s": 4216, "text": "Precision: This is essentially a measure of out of all the samples predicted to be fraud how many were correct. The calculation is, therefore;" }, { "code": null, "e": 4374, "s": 4359, "text": "TP / (TP + FP)" }, { "code": null, "e": 4505, "s": 4374, "text": "Recall (sensitivity): This is a measure of for those samples that were fraudulent how many were correctly predicted as fraudulent." }, { "code": null, "e": 4519, "s": 4505, "text": "TP /(TP + FN)" }, { "code": null, "e": 4977, "s": 4519, "text": "The difference between these two metrics is subtle but very important. If we optimise for precision then we will get fewer false positives (fewer non-fraudulent transactions classified as fraud), 0 false positives would give a perfect score of 1. If we optimise for recall then we get fewer false negatives so we are catching more fraudulent transactions but this may be at the detriment of incorrectly classifying more non-fraudulent transactions as fraud." }, { "code": null, "e": 5055, "s": 4977, "text": "F1-score: is what is known as the ‘harmonic average’ of precision and recall." }, { "code": null, "e": 5464, "s": 5055, "text": "The F1-score, therefore, gives a good indicator of the overall accuracy of a classifier, whilst precision and recall give information about the areas in which specifically the model is performing well or not so well. Maximising the F1 score would create a balanced model which has the optimal score for both precision and recall. Which metric you choose to optimise for will very much depend on the use case." }, { "code": null, "e": 5865, "s": 5464, "text": "There are several methods that tune a machine learning model for a particular metric that suits your specific use case. One example is the scikit-learn GridSearchCV which has a scoring parameter which allows you to select a given metric. This function performs cross-validated grid-search over a parameter grid and returns the optimal parameters for the model based on the scoring metric you provide." }, { "code": null, "e": 6007, "s": 5865, "text": "In the next part of this post, I will walk through an example of optimising a model using GridSearchCV . First import the relevant libraries." }, { "code": null, "e": 6496, "s": 6007, "text": "import wgetimport pandas as pdimport numpy as npfrom sklearn.model_selection import train_test_splitfrom sklearn.linear_model import LogisticRegressionfrom sklearn.metrics import classification_reportfrom pandas_ml import ConfusionMatrixfrom sklearn.metrics import precision_scorefrom sklearn.metrics import recall_scorefrom sklearn.metrics import f1_scorefrom sklearn.datasets import load_breast_cancerfrom sklearn.model_selection import GridSearchCVfrom pandas_ml import ConfusionMatrix" }, { "code": null, "e": 6742, "s": 6496, "text": "For this example, I am going to use a simple data set which consists of attributes for a sample of patients and an indicator describing whether or not they have breast cancer. This can be obtained directly from scikit-learn using the code below." }, { "code": null, "e": 6785, "s": 6742, "text": "X, y = load_breast_cancer(return_X_y=True)" }, { "code": null, "e": 6974, "s": 6785, "text": "In this dataset, the malignant class is actually the negative class. To make the resulting confusion matrix easier to interpret I will relabel them so that the malignant class is positive." }, { "code": null, "e": 7064, "s": 6974, "text": "for i in range(len(y)): if y[i] > 0: y[i] = 0 elif y[i] < 1: y[i] = 1" }, { "code": null, "e": 7120, "s": 7064, "text": "Next, I am splitting the data into test and train sets." }, { "code": null, "e": 7194, "s": 7120, "text": "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.33)" }, { "code": null, "e": 7291, "s": 7194, "text": "I will then train a simple logistic regression model and use the model to make some predictions." }, { "code": null, "e": 7407, "s": 7291, "text": "rf = LogisticRegression()model = rf.fit(X_train, y_train)y_pred = rf.predict(X_test)ConfusionMatrix(y_test, y_pred)" }, { "code": null, "e": 7445, "s": 7407, "text": "The confusion matrix looks like this." }, { "code": null, "e": 7474, "s": 7445, "text": "Let’s calculate the metrics." }, { "code": null, "e": 7701, "s": 7474, "text": "print('Precision is:'+str(round(precision_score(y_test, y_pred),2)))print('Recall is:'+str(round(recall_score(y_test, y_pred, average='binary'),2)))print('F1 score is:'+str(round(f1_score(y_test, y_pred, average='binary'),2)))" }, { "code": null, "e": 8088, "s": 7701, "text": "The model performs quite well for all metrics. However, if we were going to use this model in place of a doctors diagnosis for breast cancer then even 8 false negatives would be too many. So for this use case we would want to minimise false negatives and therefore want to optimise the model for recall. Now we are going to implement GridSearchCV and optimise the model for this metric." }, { "code": null, "e": 8183, "s": 8088, "text": "First, we create a hyperparameter search space for two selected LogisticRegression parameters." }, { "code": null, "e": 8275, "s": 8183, "text": "penalty = ['l1', 'l2']C = np.logspace(0, 4, 10)hyperparameters = dict(C=C, penalty=penalty)" }, { "code": null, "e": 8387, "s": 8275, "text": "We then call the logistic regression model and call GridSearchCV with the scoring parameter selected as recall." }, { "code": null, "e": 8487, "s": 8387, "text": "lr = LogisticRegression()clf = GridSearchCV(lr, hyperparameters, cv=5, verbose=0, scoring='recall')" }, { "code": null, "e": 8553, "s": 8487, "text": "Now we fit GridSearchCV and print the best parameters for recall." }, { "code": null, "e": 8737, "s": 8553, "text": "best_model = clf.fit(X_train, y_train)print('Best Penalty:', best_model.best_estimator_.get_params()['penalty'])print('Best C:', round(best_model.best_estimator_.get_params()['C'],2))" }, { "code": null, "e": 8806, "s": 8737, "text": "Let’s now print the confusion matrix and metrics for the best model." }, { "code": null, "e": 9134, "s": 8806, "text": "y_pred_gs = best_model.predict(X_test)cm_gs = ConfusionMatrix(y_test, y_pred_gs)print(cm_gs)print('Precision is:'+str(round(precision_score(y_test, y_pred_gs),2)))print('Recall is:'+str(round(recall_score(y_test, y_pred_gs, average='binary'),2)))print('F1 score is:'+str(round(f1_score(y_test, y_pred_gs, average='binary'),2)))" }, { "code": null, "e": 9348, "s": 9134, "text": "You can see from these results that the recall score is now higher and we have also improved both precision and recall. The model is now better at predicting the correct labels both for malignant and benign cases." }, { "code": null, "e": 9569, "s": 9348, "text": "There are many other metrics that are important to fully evaluate the performance of a classification model including specificity, AUC and ROC. However, I think those require an article of their own — this is a good one." } ]
How can I save a HashMap to Sharedpreferences in Android Kotlin?
This example demonstrates how to save a HashMap to Sharedpreferences in Android Kotlin. Step 1 − Create a new project in Android Studio, go to File ? New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main.xml. <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/rlMain" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_margin="16dp" android:orientation="vertical"> <EditText android:id="@+id/etName" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="Name" android:inputType="text" /> <EditText android:id="@+id/etAge" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="Age" android:inputType="number" /> <EditText android:id="@+id/etGame" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="Favourite game" android:inputType="text" /> <Button android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="16dp" android:onClick="saveLocal" android:text="save local" /> <TextView android:id="@+id/textView" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="20dp" android:textColor="@android:color/background_dark" android:textSize="24sp" android:textStyle="bold|italic" /> </LinearLayout> Step 3 − Add the following code to src/MainActivity.kt import android.content.Context import android.content.SharedPreferences import android.os.Bundle import android.view.View import android.widget.EditText import android.widget.TextView import android.widget.Toast import androidx.appcompat.app.AppCompatActivity import org.json.JSONObject import java.util.* import kotlin.collections.HashMap class MainActivity : AppCompatActivity() { private val mapKey = "map" lateinit var etName: EditText lateinit var etAge: EditText lateinit var etGame: EditText lateinit var textView: TextView override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) title = "KotlinApp" textView = findViewById(R.id.textView) etName = findViewById(R.id.etName) etAge = findViewById(R.id.etAge) etGame = findViewById(R.id.etGame) val outputMap: Map<String, Any> = loadMap() if (outputMap.containsKey("name")) etName.setText(Objects.requireNonNull(outputMap["name"]).toString()) if (outputMap.containsKey("age")) etAge.setText(Objects.requireNonNull(outputMap["age"]).toString()) if (outputMap.containsKey("game")) etGame.setText(Objects.requireNonNull(outputMap["game"]).toString()) } private fun loadMap(): Map<String, Any> { val outputMap: Map<String, Any> = HashMap() val pSharedPref = applicationContext.getSharedPreferences( "MyVariables", Context.MODE_PRIVATE ) if (pSharedPref != null) { val jsonString = pSharedPref.getString(mapKey, JSONObject().toString()) val jsonObject = JSONObject(jsonString) val keysItr = jsonObject.keys() while (keysItr.hasNext()) { val key = keysItr.next() outputMap[key] } } return outputMap } fun saveLocal(view: View) { val name = etName.text.toString().trim() val age = etAge.text.toString().trim() val game = etGame.text.toString().trim() when { name.isEmpty() -> { etName.error = "*required" etName.requestFocus() } age.isEmpty() -> { etAge.error = "*required" etAge.requestFocus() } game.isEmpty() -> { etGame.error = "*required" etGame.requestFocus() } else -> { val inputMap: MutableMap<String, Any> = HashMap() inputMap["name"] = name inputMap["age"] = age inputMap["game"] = game saveMap(inputMap) Toast.makeText(applicationContext, "Saved Locally!", Toast.LENGTH_SHORT).show() textView.text = inputMap.toString() } } } private fun saveMap(inputMap: MutableMap<String, Any>) { val sharedPreferences: SharedPreferences = applicationContext.getSharedPreferences( "MyVariables", Context.MODE_PRIVATE ) val jsonObject = JSONObject(inputMap) val jsonString = jsonObject.toString() val editor: SharedPreferences.Editor = sharedPreferences.edit() editor.remove(mapKey).apply() editor.putString(mapKey, jsonString) editor.commit() } } Step 4 − Add the following code to androidManifest.xml <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="app.com.myapplication"> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest> Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click the Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen
[ { "code": null, "e": 1150, "s": 1062, "text": "This example demonstrates how to save a HashMap to Sharedpreferences in Android Kotlin." }, { "code": null, "e": 1279, "s": 1150, "text": "Step 1 − Create a new project in Android Studio, go to File ? New Project and fill all required details to create a new project." }, { "code": null, "e": 1344, "s": 1279, "text": "Step 2 − Add the following code to res/layout/activity_main.xml." }, { "code": null, "e": 2723, "s": 1344, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n android:id=\"@+id/rlMain\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n android:layout_margin=\"16dp\"\n android:orientation=\"vertical\">\n <EditText\n android:id=\"@+id/etName\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"wrap_content\"\n android:hint=\"Name\"\n android:inputType=\"text\" />\n <EditText\n android:id=\"@+id/etAge\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"wrap_content\"\n android:hint=\"Age\"\n android:inputType=\"number\" />\n <EditText\n android:id=\"@+id/etGame\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"wrap_content\"\n android:hint=\"Favourite game\"\n android:inputType=\"text\" />\n <Button\n android:layout_width=\"match_parent\"\n android:layout_height=\"wrap_content\"\n android:layout_marginTop=\"16dp\"\n android:onClick=\"saveLocal\"\n android:text=\"save local\" />\n <TextView\n android:id=\"@+id/textView\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"wrap_content\"\n android:layout_marginTop=\"20dp\"\n android:textColor=\"@android:color/background_dark\"\n android:textSize=\"24sp\"\n android:textStyle=\"bold|italic\" />\n</LinearLayout>" }, { "code": null, "e": 2778, "s": 2723, "text": "Step 3 − Add the following code to src/MainActivity.kt" }, { "code": null, "e": 5993, "s": 2778, "text": "import android.content.Context\nimport android.content.SharedPreferences\nimport android.os.Bundle\nimport android.view.View\nimport android.widget.EditText\nimport android.widget.TextView\nimport android.widget.Toast\nimport androidx.appcompat.app.AppCompatActivity\nimport org.json.JSONObject\nimport java.util.*\nimport kotlin.collections.HashMap\nclass MainActivity : AppCompatActivity() {\n private val mapKey = \"map\"\n lateinit var etName: EditText\n lateinit var etAge: EditText\n lateinit var etGame: EditText\n lateinit var textView: TextView\n override fun onCreate(savedInstanceState: Bundle?) {\n super.onCreate(savedInstanceState)\n setContentView(R.layout.activity_main)\n title = \"KotlinApp\"\n textView = findViewById(R.id.textView)\n etName = findViewById(R.id.etName)\n etAge = findViewById(R.id.etAge)\n etGame = findViewById(R.id.etGame)\n val outputMap: Map<String, Any> = loadMap()\n if (outputMap.containsKey(\"name\"))\n etName.setText(Objects.requireNonNull(outputMap[\"name\"]).toString())\n if (outputMap.containsKey(\"age\"))\n etAge.setText(Objects.requireNonNull(outputMap[\"age\"]).toString())\n if (outputMap.containsKey(\"game\"))\n etGame.setText(Objects.requireNonNull(outputMap[\"game\"]).toString())\n }\n private fun loadMap(): Map<String, Any> {\n val outputMap: Map<String, Any> = HashMap()\n val pSharedPref = applicationContext.getSharedPreferences(\n \"MyVariables\", Context.MODE_PRIVATE\n )\n if (pSharedPref != null) {\n val jsonString = pSharedPref.getString(mapKey, JSONObject().toString())\n val jsonObject = JSONObject(jsonString)\n val keysItr = jsonObject.keys()\n while (keysItr.hasNext()) {\n val key = keysItr.next()\n outputMap[key]\n }\n }\n return outputMap\n }\n fun saveLocal(view: View) {\n val name = etName.text.toString().trim()\n val age = etAge.text.toString().trim()\n val game = etGame.text.toString().trim()\n when {\n name.isEmpty() -> {\n etName.error = \"*required\"\n etName.requestFocus()\n }\n age.isEmpty() -> {\n etAge.error = \"*required\"\n etAge.requestFocus()\n }\n game.isEmpty() -> {\n etGame.error = \"*required\"\n etGame.requestFocus()\n }\n else -> {\n val inputMap: MutableMap<String, Any> = HashMap()\n inputMap[\"name\"] = name\n inputMap[\"age\"] = age\n inputMap[\"game\"] = game\n saveMap(inputMap)\n Toast.makeText(applicationContext, \"Saved Locally!\", Toast.LENGTH_SHORT).show()\n textView.text = inputMap.toString()\n }\n }\n }\n private fun saveMap(inputMap: MutableMap<String, Any>) {\n val sharedPreferences: SharedPreferences = applicationContext.getSharedPreferences(\n \"MyVariables\", Context.MODE_PRIVATE\n )\n val jsonObject = JSONObject(inputMap)\n val jsonString = jsonObject.toString()\n val editor: SharedPreferences.Editor = sharedPreferences.edit()\n editor.remove(mapKey).apply()\n editor.putString(mapKey, jsonString)\n editor.commit()\n }\n}" }, { "code": null, "e": 6048, "s": 5993, "text": "Step 4 − Add the following code to androidManifest.xml" }, { "code": null, "e": 6725, "s": 6048, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\" package=\"app.com.myapplication\">\n <application\n android:allowBackup=\"true\"\n android:icon=\"@mipmap/ic_launcher\"\n android:label=\"@string/app_name\"\n android:roundIcon=\"@mipmap/ic_launcher_round\"\n android:supportsRtl=\"true\"\n android:theme=\"@style/AppTheme\">\n <activity android:name=\".MainActivity\">\n <intent-filter>\n <action android:name=\"android.intent.action.MAIN\" />\n <category android:name=\"android.intent.category.LAUNCHER\" />\n </intent-filter>\n </activity>\n </application>\n</manifest>" }, { "code": null, "e": 7073, "s": 6725, "text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click the Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen" } ]
Future class in Dart Programming
There are different classes and keywords in Dart which we can use when we want to run Asynchronous code. The future class allows us to run asynchronous code and we can also avoid the callback hell with the help of it. A future mainly represents the result of an asynchronous operation. In Dart, there are many standards library calls that return a future, some of them are − http.get http.get SharedPreference.getInstance() SharedPreference.getInstance() A future in Dart can have two states, these are − Completed - When the operation of the future finishes and the future complete with a value or with an error. Completed - When the operation of the future finishes and the future complete with a value or with an error. Uncompleted - When a function is called, and it returned a future, the function queues up and returns an uncompleted future. Uncompleted - When a function is called, and it returned a future, the function queues up and returns an uncompleted future. Future<T> In Dart, if a future doesn't produce any usable value then the future's type is Future<void>. Also, if the function doesn't explicitly return any value, then the return type is also Future<void>. Let's consider a small example where we are declaring a future that will display a message in a delayed fashion. Consider the example shown below: Future<void> printDelayedMessage() { return Future.delayed(Duration(seconds: 4), () => print('Delayed Output.')); } void main() { printDelayedMessage(); print('First output ...'); } In the above example, we have a function named printDelayedMessage() that returns a future of type void, and we have a future that is using a method named delayed through which we are able to print the delayed output to the terminal. First output ... Delayed Output. It should be noted the second line of the output will be printed after 4 seconds. Futures in Dart also allows us to register callbacks with the help of the then methods. Consider an example shown below − void main() { var userEmailFuture = getUserEmail(); // register callback userEmailFuture.then((userId) => print(userId)); print('Hello'); } // method which computes a future Future<String> getUserEmail() { // simulate a long network call return Future.delayed(Duration(seconds: 4), () => "[email protected]"); } Hello [email protected]
[ { "code": null, "e": 1348, "s": 1062, "text": "There are different classes and keywords in Dart which we can use when we want to run Asynchronous code. The future class allows us to run asynchronous code and we can also avoid the callback hell with the help of it. A future mainly represents the result of an asynchronous operation." }, { "code": null, "e": 1437, "s": 1348, "text": "In Dart, there are many standards library calls that return a future, some of them are −" }, { "code": null, "e": 1446, "s": 1437, "text": "http.get" }, { "code": null, "e": 1455, "s": 1446, "text": "http.get" }, { "code": null, "e": 1486, "s": 1455, "text": "SharedPreference.getInstance()" }, { "code": null, "e": 1517, "s": 1486, "text": "SharedPreference.getInstance()" }, { "code": null, "e": 1567, "s": 1517, "text": "A future in Dart can have two states, these are −" }, { "code": null, "e": 1676, "s": 1567, "text": "Completed - When the operation of the future finishes and the future complete with a value or with an error." }, { "code": null, "e": 1785, "s": 1676, "text": "Completed - When the operation of the future finishes and the future complete with a value or with an error." }, { "code": null, "e": 1910, "s": 1785, "text": "Uncompleted - When a function is called, and it returned a future, the function queues up and returns an uncompleted future." }, { "code": null, "e": 2035, "s": 1910, "text": "Uncompleted - When a function is called, and it returned a future, the function queues up and returns an uncompleted future." }, { "code": null, "e": 2045, "s": 2035, "text": "Future<T>" }, { "code": null, "e": 2241, "s": 2045, "text": "In Dart, if a future doesn't produce any usable value then the future's type is Future<void>. Also, if the function doesn't explicitly return any value, then the return type is also Future<void>." }, { "code": null, "e": 2354, "s": 2241, "text": "Let's consider a small example where we are declaring a future that will display a message in a delayed fashion." }, { "code": null, "e": 2586, "s": 2354, "text": "Consider the example shown below:\n Future<void> printDelayedMessage() {\n return Future.delayed(Duration(seconds: 4), () => print('Delayed Output.'));\n}\n\nvoid main() {\n printDelayedMessage();\n print('First output ...');\n}" }, { "code": null, "e": 2820, "s": 2586, "text": "In the above example, we have a function named printDelayedMessage() that returns a future of type void, and we have a future that is using a method named delayed through which we are able to print the delayed output to the terminal." }, { "code": null, "e": 2853, "s": 2820, "text": "First output ...\nDelayed Output." }, { "code": null, "e": 2935, "s": 2853, "text": "It should be noted the second line of the output will be printed after 4 seconds." }, { "code": null, "e": 3023, "s": 2935, "text": "Futures in Dart also allows us to register callbacks with the help of the then methods." }, { "code": null, "e": 3057, "s": 3023, "text": "Consider an example shown below −" }, { "code": null, "e": 3395, "s": 3057, "text": "void main() {\n var userEmailFuture = getUserEmail();\n // register callback\n userEmailFuture.then((userId) => print(userId));\n print('Hello');\n}\n\n// method which computes a future\nFuture<String> getUserEmail() {\n // simulate a long network call\n return Future.delayed(Duration(seconds: 4), () => \"[email protected]\");\n}" }, { "code": null, "e": 3426, "s": 3395, "text": "Hello\[email protected]" } ]
Tryit Editor v3.7
CSS Style Images Tryit: Image hover - Fade in a box
[ { "code": null, "e": 26, "s": 9, "text": "CSS Style Images" } ]
Still using Accuracy as a Classification Metric? | by Pranav Kaushik | Towards Data Science
Accuracy is the most common evaluation metric for classification models because of its simplicity and interpretation. But when you have a multiclass classification problem in hand, say, for example, with 15 different target classes, looking at the standard accuracy of the model might be misleading. This is where “top N” accuracies might be of some use, and in this post, I’ll take you through the basic intuition and python implementation of top N accuracies. Before we get into top N accuracy, a small refresher on standard accuracy metric: Accuracy is the fraction of total records that are correctly predicted by the model. Accuracy = (Number of correctly predicted records / Total number of records) or Accuracy = (TP+TN) / (TP+TN+FP+FN) When you have a lot of different classes, the classification model might not be able to predict the right class exactly. This especially becomes a problem in NLP cases like text classification, where you have a vast number of features, and the data is not adequately clustered across classes. So looking at your standard accuracy metric might be misleading at times. As I said earlier, measuring the top N accuracies might help in overcoming this issue. Top N accuracy is not any different metric, but it’s just standard accuracy of the true class being equal to any of the N most probable classes predicted by the classification model. Top 1 accuracy is the accuracy where true class matches with the most probable classes predicted by the model, which is the same as our standard accuracy. Top 2 accuracy is the accuracy where true class matches with any one of the 2 most probable classes predicted by the model. Top 3 accuracy is the accuracy where true class matches with any one of the 3 most probable classes predicted by the model. And in the same way, we can measure the top 4, top 5, top 6, and so on. Let me show you an example to understand better. Consider having to classify records into respective animals (dog, cat, lion, tiger, and elephant). The table shows the true class and predicted class of 6 records. From this, we’ll be getting an accuracy of 50%, which is not so satisfying. Now let’s find out the top 2 accuracies for this problem. The table shows the true class and 2 most probable classes for the same set of records. With this, we get an accuracy of 83%, which is a significant increase compared to the previous one. This is the basic intuition behind finding top N accuracies. I hope you would have understood the significance of measuring the top N accuracies. Even if the classification model cannot predict the exact class, looking at the top 2 or top 3 accuracies might be of use in many situations, especially if there are a lot of different classes like 15 or 20. Now I’ll show you some code to find top N accuracies using python. Unfortunately, sci-kit learn doesn’t have any inbuilt function for this. So I’ve defined a function here that you can directly copy and use in your problems. After importing the required libraries and preprocessing the data, run the provided function. def top_n_accuracy(X,y,n,classifier): X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2) vectorizer = TfidfVectorizer(min_df=2) X_train_sparse = vectorizer.fit_transform(X_train) feature_names = vectorizer.get_feature_names() test = vectorizer.transform(X_test) clf = classifier clf.fit(X_train_sparse,y_train) predictions = clf.predict(test) probs = clf.predict_proba(test) topn = np.argsort(probs, axis = 1)[:,-n:] y_true = np.array(y_test) return np.mean(np.array([1 if y_true[k] in topn[k] else 0 for k in range(len(topn))])) You can call the function by providing the following parameters: X = feature variablesy = target classn = top N that you want to measure (for example n=2 for top 2)Classifier = classification model that you want to use (example LogisticRegression()) X = feature variables y = target class n = top N that you want to measure (for example n=2 for top 2) Classifier = classification model that you want to use (example LogisticRegression()) I’ve defined this function for text classification, but you can simply remove the lines having vectorizer instance and use it for standard classification.
[ { "code": null, "e": 633, "s": 171, "text": "Accuracy is the most common evaluation metric for classification models because of its simplicity and interpretation. But when you have a multiclass classification problem in hand, say, for example, with 15 different target classes, looking at the standard accuracy of the model might be misleading. This is where “top N” accuracies might be of some use, and in this post, I’ll take you through the basic intuition and python implementation of top N accuracies." }, { "code": null, "e": 715, "s": 633, "text": "Before we get into top N accuracy, a small refresher on standard accuracy metric:" }, { "code": null, "e": 915, "s": 715, "text": "Accuracy is the fraction of total records that are correctly predicted by the model. Accuracy = (Number of correctly predicted records / Total number of records) or Accuracy = (TP+TN) / (TP+TN+FP+FN)" }, { "code": null, "e": 1369, "s": 915, "text": "When you have a lot of different classes, the classification model might not be able to predict the right class exactly. This especially becomes a problem in NLP cases like text classification, where you have a vast number of features, and the data is not adequately clustered across classes. So looking at your standard accuracy metric might be misleading at times. As I said earlier, measuring the top N accuracies might help in overcoming this issue." }, { "code": null, "e": 1552, "s": 1369, "text": "Top N accuracy is not any different metric, but it’s just standard accuracy of the true class being equal to any of the N most probable classes predicted by the classification model." }, { "code": null, "e": 1707, "s": 1552, "text": "Top 1 accuracy is the accuracy where true class matches with the most probable classes predicted by the model, which is the same as our standard accuracy." }, { "code": null, "e": 1831, "s": 1707, "text": "Top 2 accuracy is the accuracy where true class matches with any one of the 2 most probable classes predicted by the model." }, { "code": null, "e": 1955, "s": 1831, "text": "Top 3 accuracy is the accuracy where true class matches with any one of the 3 most probable classes predicted by the model." }, { "code": null, "e": 2027, "s": 1955, "text": "And in the same way, we can measure the top 4, top 5, top 6, and so on." }, { "code": null, "e": 2240, "s": 2027, "text": "Let me show you an example to understand better. Consider having to classify records into respective animals (dog, cat, lion, tiger, and elephant). The table shows the true class and predicted class of 6 records." }, { "code": null, "e": 2462, "s": 2240, "text": "From this, we’ll be getting an accuracy of 50%, which is not so satisfying. Now let’s find out the top 2 accuracies for this problem. The table shows the true class and 2 most probable classes for the same set of records." }, { "code": null, "e": 2623, "s": 2462, "text": "With this, we get an accuracy of 83%, which is a significant increase compared to the previous one. This is the basic intuition behind finding top N accuracies." }, { "code": null, "e": 2916, "s": 2623, "text": "I hope you would have understood the significance of measuring the top N accuracies. Even if the classification model cannot predict the exact class, looking at the top 2 or top 3 accuracies might be of use in many situations, especially if there are a lot of different classes like 15 or 20." }, { "code": null, "e": 3141, "s": 2916, "text": "Now I’ll show you some code to find top N accuracies using python. Unfortunately, sci-kit learn doesn’t have any inbuilt function for this. So I’ve defined a function here that you can directly copy and use in your problems." }, { "code": null, "e": 3235, "s": 3141, "text": "After importing the required libraries and preprocessing the data, run the provided function." }, { "code": null, "e": 3799, "s": 3235, "text": "def top_n_accuracy(X,y,n,classifier): X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2) vectorizer = TfidfVectorizer(min_df=2) X_train_sparse = vectorizer.fit_transform(X_train) feature_names = vectorizer.get_feature_names() test = vectorizer.transform(X_test) clf = classifier clf.fit(X_train_sparse,y_train) predictions = clf.predict(test) probs = clf.predict_proba(test) topn = np.argsort(probs, axis = 1)[:,-n:] y_true = np.array(y_test) return np.mean(np.array([1 if y_true[k] in topn[k] else 0 for k in range(len(topn))]))" }, { "code": null, "e": 3864, "s": 3799, "text": "You can call the function by providing the following parameters:" }, { "code": null, "e": 4049, "s": 3864, "text": "X = feature variablesy = target classn = top N that you want to measure (for example n=2 for top 2)Classifier = classification model that you want to use (example LogisticRegression())" }, { "code": null, "e": 4071, "s": 4049, "text": "X = feature variables" }, { "code": null, "e": 4088, "s": 4071, "text": "y = target class" }, { "code": null, "e": 4151, "s": 4088, "text": "n = top N that you want to measure (for example n=2 for top 2)" }, { "code": null, "e": 4237, "s": 4151, "text": "Classifier = classification model that you want to use (example LogisticRegression())" } ]
DTD - Quick Guide
XML Document Type Declaration, commonly known as DTD, is a way to describe precisely the XML language. DTDs check the validity of structure and vocabulary of an XML document against the grammatical rules of the appropriate XML language. An XML document can be defined as − Well-formed − If the XML document adheres to all the general XML rules such as tags must be properly nested, opening and closing tags must be balanced, and empty tags must end with '/>', then it is called as well-formed. OR Well-formed − If the XML document adheres to all the general XML rules such as tags must be properly nested, opening and closing tags must be balanced, and empty tags must end with '/>', then it is called as well-formed. OR Valid − An XML document said to be valid when it is not only well-formed, but it also conforms to available DTD that specifies which tags it uses, what attributes those tags can contain, and which tags can occur inside other tags, among other properties. Valid − An XML document said to be valid when it is not only well-formed, but it also conforms to available DTD that specifies which tags it uses, what attributes those tags can contain, and which tags can occur inside other tags, among other properties. The following diagram represents that a DTD is used to structure the XML document − DTD can be classified on its declaration basis in the XML document, such as − Internal DTD Internal DTD External DTD External DTD When a DTD is declared within the file it is called Internal DTD and if it is declared in a separate file it is called External DTD. We will learn more about these in the chapter DTD Syntax Following are some important points that a DTD describes − the elements that can appear in an XML document. the elements that can appear in an XML document. the order in which they can appear. the order in which they can appear. optional and mandatory elements. optional and mandatory elements. element attributes and whether they are optional or mandatory. element attributes and whether they are optional or mandatory. whether attributes can have default values. whether attributes can have default values. Documentation − You can define your own format for the XML files. Looking at this document a user/developer can understand the structure of the data. Documentation − You can define your own format for the XML files. Looking at this document a user/developer can understand the structure of the data. Validation − It gives a way to check the validity of XML files by checking whether the elements appear in the right order, mandatory elements and attributes are in place, the elements and attributes have not been inserted in an incorrect way, and so on. Validation − It gives a way to check the validity of XML files by checking whether the elements appear in the right order, mandatory elements and attributes are in place, the elements and attributes have not been inserted in an incorrect way, and so on. It does not support the namespaces. Namespace is a mechanism by which element and attribute names can be assigned to groups. However, in a DTD namespaces have to be defined within the DTD, which violates the purpose of using namespaces. It does not support the namespaces. Namespace is a mechanism by which element and attribute names can be assigned to groups. However, in a DTD namespaces have to be defined within the DTD, which violates the purpose of using namespaces. It supports only the text string data type. It supports only the text string data type. It is not object oriented. Hence, the concept of inheritance cannot be applied on the DTDs. It is not object oriented. Hence, the concept of inheritance cannot be applied on the DTDs. Limited possibilities to express the cardinality for elements. Limited possibilities to express the cardinality for elements. An XML DTD can be either specified inside the document, or it can be kept in a separate document and then the document can be linked to the DTD document to use it. Basic syntax of a DTD is as follows − <!DOCTYPE element DTD identifier [ declaration1 declaration2 ........ ]> In the above syntax − DTD starts with <!DOCTYPE delimiter. DTD starts with <!DOCTYPE delimiter. An element tells the parser to parse the document from the specified root element. An element tells the parser to parse the document from the specified root element. DTD identifier is an identifier for the document type definition, which may be the path to a file on the system or URL to a file on the internet. If the DTD is pointing to external path, it is called external subset. DTD identifier is an identifier for the document type definition, which may be the path to a file on the system or URL to a file on the internet. If the DTD is pointing to external path, it is called external subset. The square brackets [ ] enclose an optional list of entity declarations called internal subset. The square brackets [ ] enclose an optional list of entity declarations called internal subset. A DTD is referred to as an internal DTD if elements are declared within the XML files. To reference it as internal DTD, standalone attribute in XML declaration must be set to yes. This means the declaration works independent of external source. The syntax of internal DTD is as shown − <!DOCTYPE root-element [element-declarations]> where root-element is the name of root element and element-declarations is where you declare the elements. Following is a simple example of internal DTD − <?xml version = "1.0" encoding = "UTF-8" standalone = "yes" ?> <!DOCTYPE address [ <!ELEMENT address (name,company,phone)> <!ELEMENT name (#PCDATA)> <!ELEMENT company (#PCDATA)> <!ELEMENT phone (#PCDATA)> ]> <address> <name>Tanmay Patil</name> <company>TutorialsPoint</company> <phone>(011) 123-4567</phone> </address> Let us go through the above code − Start Declaration − Begin the XML declaration with following statement. <?xml version = "1.0" encoding = "UTF-8" standalone = "yes" ?> DTD − Immediately after the XML header, the document type declaration follows, commonly referred to as the DOCTYPE − <!DOCTYPE address [ The DOCTYPE declaration has an exclamation mark (!) at the start of the element name. The DOCTYPE informs the parser that a DTD is associated with this XML document. DTD Body − The DOCTYPE declaration is followed by body of the DTD, where you declare elements, attributes, entities, and notations − <!ELEMENT address (name,company,phone)> <!ELEMENT name (#PCDATA)> <!ELEMENT company (#PCDATA)> <!ELEMENT phone_no (#PCDATA)> Several elements are declared here that make up the vocabulary of the <name> document. <!ELEMENT name (#PCDATA)> defines the element name to be of type "#PCDATA". Here #PCDATA means parse-able text data. End Declaration − Finally, the declaration section of the DTD is closed using a closing bracket and a closing angle bracket (]>). This effectively ends the definition, and thereafter, the XML document follows immediately. The document type declaration must appear at the start of the document (preceded only by the XML header) - it is not permitted anywhere else within the document. The document type declaration must appear at the start of the document (preceded only by the XML header) - it is not permitted anywhere else within the document. Similar to the DOCTYPE declaration, the element declarations must start with an exclamation mark. Similar to the DOCTYPE declaration, the element declarations must start with an exclamation mark. The Name in the document type declaration must match the element type of the root element. The Name in the document type declaration must match the element type of the root element. In external DTD elements are declared outside the XML file. They are accessed by specifying the system attributes which may be either the legal .dtd file or a valid URL. To reference it as external DTD, standalone attribute in the XML declaration must be set as no. This means, declaration includes information from the external source. Following is the syntax for external DTD − <!DOCTYPE root-element SYSTEM "file-name"> where file-name is the file with .dtd extension. The following example shows external DTD usage − <?xml version = "1.0" encoding = "UTF-8" standalone = "no" ?> <!DOCTYPE address SYSTEM "address.dtd"> <address> <name>Tanmay Patil</name> <company>TutorialsPoint</company> <phone>(011) 123-4567</phone> </address> The content of the DTD file address.dtd are as shown − <!ELEMENT address (name,company,phone)> <!ELEMENT name (#PCDATA)> <!ELEMENT company (#PCDATA)> <!ELEMENT phone (#PCDATA)> You can refer to an external DTD by either using system identifiers or public identifiers. System Identifiers A system identifier enables you to specify the location of an external file containing DTD declarations. Syntax is as follows − <!DOCTYPE name SYSTEM "address.dtd" [...]> As you can see it contains keyword SYSTEM and a URI reference pointing to the location of the document. Public Identifiers Public identifiers provide a mechanism to locate DTD resources and are written as below − <!DOCTYPE name PUBLIC "-//Beginning XML//DTD Address Example//EN"> As you can see, it begins with keyword PUBLIC, followed by a specialized identifier. Public identifiers are used to identify an entry in a catalog. Public identifiers can follow any format, however, a commonly used format is called Formal Public Identifiers, or FPIs. This chapter will discuss about XML Components from DTD perspective. A DTD will basically contain declarations of the following XML components − Element Element Attributes Attributes Entities Entities XML elements can be defined as building blocks of an XML document. Elements can behave as a container to hold text, elements, attributes, media objects or mix of all. Each XML document contains one or more elements, the boundaries of which are either delimited by start-tags and end-tags, or empty elements. Below is a simple example of XML elements <name> Tutorials Point </name> As you can see we have defined a <name> tag. There's a text between start and end tag of <name>. Elements, when used in an XML-DTD, need to be declared which will be discussed in detail in the chapter DTD Elements. Attributes are part of the XML elements. An element can have any number of unique attributes. Attributes give more information about the XML element or more precisely it defines a property of the element. An XML attribute is always a name-value pair. Below is a simple example of XML attributes − <img src = "flower.jpg"/> Here img is the element name whereas src is an attribute name and flower.jpg is a value given for the attribute src. If attributes are used in an XML DTD then these need to be declared which will be discussed in detail in the chapter DTD Attributes Entities are placeholders in XML. These can be declared in the document prolog or in a DTD. Entities can be primarily categorized as − Built-in entities Built-in entities Character entities Character entities General entities General entities Parameter entities Parameter entities There are five built-in entities that play in well-formed XML, they are − ampersand: &amp; ampersand: &amp; Single quote: &apos; Single quote: &apos; Greater than: &gt; Greater than: &gt; Less than: &lt; Less than: &lt; Double quote: " Double quote: " We will study more about entity declarations in XML DTD in detail in the chapter DTD Entities XML elements can be defined as building blocks of an XML document. Elements can behave as a container to hold text, elements, attributes, media objects or mix of all. A DTD element is declared with an ELEMENT declaration. When an XML file is validated by DTD, parser initially checks for the root element and then the child elements are validated. All DTD element declarations have this general form − <!ELEMENT elementname (content)> ELEMENT declaration is used to indicate the parser that you are about to define an element. ELEMENT declaration is used to indicate the parser that you are about to define an element. elementname is the element name (also called the generic identifier) that you are defining. elementname is the element name (also called the generic identifier) that you are defining. content defines what content (if any) can go within the element. content defines what content (if any) can go within the element. Content of elements declaration in a DTD can be categorized as below − Empty content Empty content Element content Element content Mixed content Mixed content Any content Any content This is a special case of element declaration. This element declaration does not contain any content. These are declared with the keyword EMPTY. Syntax Following is the syntax for empty element declaration − <!ELEMENT elementname EMPTY > In the above syntax − ELEMENT is the element declaration of category EMPTY ELEMENT is the element declaration of category EMPTY elementname is the name of empty element. elementname is the name of empty element. Example Following is a simple example demonstrating empty element declaration − <?xml version = "1.0"?> <!DOCTYPE hr[ <!ELEMENT address EMPTY> ]> <address /> In this example address is declared as an empty element. The markup for address element would appear as <address />. In element declaration with element content, the content would be allowable elements within parentheses. We can also include more than one element. Syntax Following is a syntax of element declaration with element content − <!ELEMENT elementname (child1, child2...)> ELEMENT is the element declaration tag ELEMENT is the element declaration tag elementname is the name of the element. elementname is the name of the element. child1, child2.. are the elements and each element must have its own definition within the DTD. child1, child2.. are the elements and each element must have its own definition within the DTD. Example Below example demonstrates a simple example for element declaration with element content − <?xml version = "1.0" encoding = "UTF-8" standalone = "yes" ?> <!DOCTYPE address [ <!ELEMENT address (name,company,phone)> <!ELEMENT name (#PCDATA)> <!ELEMENT company (#PCDATA)> <!ELEMENT phone (#PCDATA)> ]> <address> <name>Tanmay Patil</name> <company>TutorialsPoint</company> <phone>(011) 123-4567</phone> </address> In the above example, address is the parent element and name, company and phone_no are its child elements. Below table shows the list of operators and syntax rules which can be applied in defining child elements − <!ELEMENT address (name+)> Child element name can occur one or more times inside the element name address. <!ELEMENT address (name*)> Child element name can occur zero or more times inside the element name address. <!ELEMENT address (name?)> Child element name can occur zero or one time inside the element name address. <!ELEMENT address (name, company)> Sequence of child elements name, company, which must occur in the same order inside the element name address. <!ELEMENT address (name | company)> It allows you to choose either of child elements i.e. name or company, which must occur in inside the element name address. We need to follow certain rules if there is more than one element content − Sequences − Often the elements within DTD documents must appear in a distinct order. If this is the case, you define the content using a sequence. The declaration indicates that the <address> element must have exactly three children - <name>, <company>, and <phone> - and that they must appear in this order. For example − Sequences − Often the elements within DTD documents must appear in a distinct order. If this is the case, you define the content using a sequence. The declaration indicates that the <address> element must have exactly three children - <name>, <company>, and <phone> - and that they must appear in this order. For example − <!ELEMENT address (name,company,phone)> Choices − Suppose you need to allow one element or another, but not both. In such cases you must use the pipe (|) character. The pipe functions as an exclusive OR. For example − Choices − Suppose you need to allow one element or another, but not both. In such cases you must use the pipe (|) character. The pipe functions as an exclusive OR. For example − <!ELEMENT address (mobile | landline)> This is the combination of (#PCDATA) and children elements. PCDATA stands for parsed character data, that is, text that is not markup. Within mixed content models, text can appear by itself or it can be interspersed between elements. The rules for mixed content models are similar to the element content as discussed in the previous section. Syntax Following is a generic syntax for mixed element content − <!ELEMENT elementname (#PCDATA|child1|child2)*> ELEMENT is the element declaration tag. ELEMENT is the element declaration tag. elementname is the name of the element. elementname is the name of the element. PCDATA is the text that is not markup. #PCDATA must come first in the mixed content declaration. PCDATA is the text that is not markup. #PCDATA must come first in the mixed content declaration. child1, child2.. are the elements and each element must have its own definition within the DTD. child1, child2.. are the elements and each element must have its own definition within the DTD. The operator (*) must follow the mixed content declaration if children elements are included The operator (*) must follow the mixed content declaration if children elements are included The (#PCDATA) and children element declarations must be separated by the (|) operator. The (#PCDATA) and children element declarations must be separated by the (|) operator. Example Following is a simple example demonstrating the mixed content element declaration in a DTD. <?xml version = "1.0" encoding = "UTF-8" standalone = "yes" ?> <!DOCTYPE address [ <!ELEMENT address (#PCDATA|name)*> <!ELEMENT name (#PCDATA)> ]> <address> Here's a bit of text mixed up with the child element. <name> Tanmay Patil </name> </address> You can declare an element using the ANY keyword in the content. It is most often referred to as mixed category element. ANY is useful when you have yet to decide the allowable contents of the element. Syntax Following is the syntax for declaring elements with ANY content − <!ELEMENT elementname ANY> Here, the ANY keyword indicates that text (PCDATA) and/or any elements declared within the DTD can be used within the content of the <elementname> element. They can be used in any order any number of times. However, the ANY keyword does not allow you to include elements that are not declared within the DTD. Example Following is a simple example demonstrating the element declaration with ANY content − <?xml version = "1.0" encoding = "UTF-8" standalone = "yes" ?> <!DOCTYPE address [ <!ELEMENT address ANY> ]> <address> Here's a bit of sample text </address> In this chapter we will discuss about DTD Attributes. Attribute gives more information about an element or more precisely it defines a property of an element. An XML attribute is always in the form of a name-value pair. An element can have any number of unique attributes. Attribute declaration is very much similar to element declarations in many ways except one; instead of declaring allowable content for elements, you declare a list of allowable attributes for each element. These lists are called ATTLIST declaration. Basic syntax of DTD attributes declaration is as follows − <!ATTLIST element-name attribute-name attribute-type attribute-value> In the above syntax − The DTD attributes start with <!ATTLIST keyword if the element contains the attribute. The DTD attributes start with <!ATTLIST keyword if the element contains the attribute. element-name specifies the name of the element to which the attribute applies. element-name specifies the name of the element to which the attribute applies. attribute-name specifies the name of the attribute which is included with the element-name. attribute-name specifies the name of the attribute which is included with the element-name. attribute-type defines the type of attributes. We will discuss more on this in the following sections. attribute-type defines the type of attributes. We will discuss more on this in the following sections. attribute-value takes a fixed value that the attributes must define. We will discuss more on this in the following sections. attribute-value takes a fixed value that the attributes must define. We will discuss more on this in the following sections. Below is a simple example for attribute declaration in DTD − <?xml version = "1.0"?> <!DOCTYPE address [ <!ELEMENT address ( name )> <!ELEMENT name ( #PCDATA )> <!ATTLIST name id CDATA #REQUIRED> ]> <address> <name id = "123">Tanmay Patil</name> </address> Let us go through the above code − Begin with the XML declaration with the following statement − Begin with the XML declaration with the following statement − <?xml version = "1.0"?> Immediately following the XML header is the document type declaration, commonly referred to as the DOCTYPE as shown below − The DOCTYPE informs the parser that a DTD is associated with this XML document. The DOCTYPE declaration has an exclamation mark (!) at the start of the element name. Immediately following the XML header is the document type declaration, commonly referred to as the DOCTYPE as shown below − The DOCTYPE informs the parser that a DTD is associated with this XML document. The DOCTYPE declaration has an exclamation mark (!) at the start of the element name. <!DOCTYPE address [ Following is the body of DTD. Here we have declared element and attribute − Following is the body of DTD. Here we have declared element and attribute − <!ELEMENT address ( name )> <!ELEMENT name ( #PCDATA )> Attribute id for the element name is defined as given below − Here attribute type is CDATA and its value is #REQUIRED. Attribute id for the element name is defined as given below − Here attribute type is CDATA and its value is #REQUIRED. <!ATTLIST name id CDATA #REQUIRED> All attributes used in an XML document must be declared in the Document Type Definition (DTD) using an Attribute-List Declaration All attributes used in an XML document must be declared in the Document Type Definition (DTD) using an Attribute-List Declaration Attributes may only appear in start or empty tags. Attributes may only appear in start or empty tags. The keyword ATTLIST must be in upper case The keyword ATTLIST must be in upper case No duplicate attribute names will be allowed within the attribute list for a given element. No duplicate attribute names will be allowed within the attribute list for a given element. When declaring attributes, you can specify how the processor should handle the data that appears in the value. We can categorize attribute types in three main categories − String type String type Tokenized types Tokenized types Enumerated types Enumerated types Following table provides a summary of the different attribute types − CDATA CDATA is character data (text and not markup). It is a String Attribute Type. ID It is a unique identifier of the attribute. It should not appear more than once. It is a Tokenized Attribute Type. IDREF It is used to reference an ID of another element. It is used to establish connections between elements. It is a Tokenized Attribute Type. IDREFS It is used to reference multiple ID's. It is a Tokenized Attribute Type. ENTITY It represents an external entity in the document. It is a Tokenized Attribute Type. ENTITIES It represents a list of external entities in the document. It is a Tokenized Attribute Type. NMTOKEN It is similar to CDATA and the attribute value consists of a valid XML name. It is a Tokenized Attribute Type. NMTOKENS It is similar to CDATA and the attribute value consists a list of valid XML name. It is a Tokenized Attribute Type. NOTATION An element will be referenced to a notation declared in the DTD document. It is an Enumerated Attribute Type. Enumeration It allows defining a specific list of values where one of the values must match. It is an Enumerated Attribute Type. Within each attribute declaration, you must specify how the value will appear in the document. You can specify if an attribute − can have a default value can have a default value can have a fixed value can have a fixed value is required is required is implied is implied It contains the default value. The values can be enclosed in single quotes(') or double quotes("). Syntax Following is the syntax of value − <!ATTLIST element-name attribute-name attribute-type "default-value"> where default-value is the attribute value defined. Example Following is a simple example of attribute declaration with default value − <?xml version = "1.0"?> <!DOCTYPE address [ <!ELEMENT address ( name )> <!ELEMENT name ( #PCDATA )> <!ATTLIST name id CDATA "0"> ]> <address> <name id = "123"> Tanmay Patil </name> </address> In this example we have name element with attribute id whose default value is 0. The default value is been enclosed within the double quotes. #FIXED keyword followed by the fixed value is used when you want to specify that the attribute value is constant and cannot be changed. A common use of fixed attributes is specifying version numbers. Syntax Following is the syntax of fixed values − <!ATTLIST element-name attribute-name attribute-type #FIXED "value" > where #FIXED is an attribute value defined. Example Following is a simple example of attribute declaration with FIXED value − <?xml version = "1.0"?> <!DOCTYPE address [ <!ELEMENT address (company)*> <!ELEMENT company (#PCDATA)> <!ATTLIST company name NMTOKEN #FIXED "tutorialspoint"> ]> <address> <company name = "tutorialspoint">we are a free online teaching faculty</company> </address> In this example we have used the keyword #FIXED where it indicates that the value "tutorialspoint" is the only value for the attribute name of element <company>. If we try to change the attribute value then it gives an error. Following is an invalid DTD − <?xml version = "1.0"?> <!DOCTYPE address [ <!ELEMENT address (company)*> <!ELEMENT company (#PCDATA)> <!ATTLIST company name NMTOKEN #FIXED "tutorialspoint"> ]> <address> <company name = "abc">we are a free online teaching faculty</company> </address> Whenever you want specify that an attribute is required, use #REQUIRED keyword. Syntax Following is the syntax of #REQUIRED − <!ATTLIST element-name attribute-name attribute-type #REQUIRED> where #REQUIRED is an attribute type defined. Example Following is a simple example of DTD attribute declaration with #REQUIRED keyword − <?xml version = "1.0"?> <!DOCTYPE address [ <!ELEMENT address ( name )> <!ELEMENT name ( #PCDATA )> <!ATTLIST name id CDATA #REQUIRED> ]> <address> <name id = "123"> Tanmay Patil </name> </address> In this example we have used #REQUIRED keyword to specify that the attribute id must be provided for the element-name name When declaring attributes you must always specify a value declaration. If the attribute you are declaring has no default value, has no fixed value, and is not required, then you must declare that the attribute as implied. Keyword #IMPLIED is used to specify an attribute as implied. Syntax Following is the syntax of #IMPLIED − <!ATTLIST element-name attribute-name attribute-type #IMPLIED> where #IMPLIED is an attribute type defined. Example Following is a simple example of #IMPLIED <?xml version = "1.0"?> <!DOCTYPE address [ <!ELEMENT address ( name )> <!ELEMENT name ( #PCDATA )> <!ATTLIST name id CDATA #IMPLIED> ]> <address> <name /> </address> In this example we have used the keyword #IMPLIED as we do not want to specify any attributes to be included in element name. It is optional. Entities are used to define shortcuts to special characters within the XML documents. Entities can be primarily of four types − Built-in entities Built-in entities Character entities Character entities General entities General entities Parameter entities Parameter entities In general, entities can be declared internally or externally. Let us understand each of these and their syntax as follows − If an entity is declared within a DTD it is called as internal entity. Syntax Following is the syntax for internal entity declaration − <!ENTITY entity_name "entity_value"> In the above syntax − entity_name is the name of entity followed by its value within the double quotes or single quote. entity_name is the name of entity followed by its value within the double quotes or single quote. entity_value holds the value for the entity name. entity_value holds the value for the entity name. The entity value of the Internal Entity is de-referenced by adding prefix & to the entity name i.e. &entity_name. The entity value of the Internal Entity is de-referenced by adding prefix & to the entity name i.e. &entity_name. Example Following is a simple example for internal entity declaration − <?xml version = "1.0" encoding = "UTF-8" standalone = "yes"?> <!DOCTYPE address [ <!ELEMENT address (#PCDATA)> <!ENTITY name "Tanmay patil"> <!ENTITY company "TutorialsPoint"> <!ENTITY phone_no "(011) 123-4567"> ]> <address> &name; &company; &phone_no; </address> In the above example, the respective entity names name, company and phone_no are replaced by their values in the XML document. The entity values are de-referenced by adding prefix & to the entity name. Save this file as sample.xml and open it in any browser, you will notice that the entity values for name, company, phone_no are replaced respectively. If an entity is declared outside a DTD it is called as external entity. You can refer to an external Entity by either using system identifiers or public identifiers. Syntax Following is the syntax for External Entity declaration − <!ENTITY name SYSTEM "URI/URL"> In the above syntax − name is the name of entity. name is the name of entity. SYSTEM is the keyword. SYSTEM is the keyword. URI/URL is the address of the external source enclosed within the double or single quotes. URI/URL is the address of the external source enclosed within the double or single quotes. Types You can refer to an external DTD by either using − System Identifiers − A system identifier enables you to specify the location of an external file containing DTD declarations. As you can see it contains keyword SYSTEM and a URI reference pointing to the document's location. Syntax is as follows − System Identifiers − A system identifier enables you to specify the location of an external file containing DTD declarations. As you can see it contains keyword SYSTEM and a URI reference pointing to the document's location. Syntax is as follows − <!DOCTYPE name SYSTEM "address.dtd" [...]> Public Identifiers − Public identifiers provide a mechanism to locate DTD resources and are written as below − As you can see, it begins with keyword PUBLIC, followed by a specialized identifier. Public identifiers are used to identify an entry in a catalog. Public identifiers can follow any format; however, a commonly used format is called Formal Public Identifiers, or FPIs. Public Identifiers − Public identifiers provide a mechanism to locate DTD resources and are written as below − As you can see, it begins with keyword PUBLIC, followed by a specialized identifier. Public identifiers are used to identify an entry in a catalog. Public identifiers can follow any format; however, a commonly used format is called Formal Public Identifiers, or FPIs. <!DOCTYPE name PUBLIC "-//Beginning XML//DTD Address Example//EN"> Example Let us understand the external entity with the following example − <?xml version = "1.0" encoding = "UTF-8" standalone = "yes"?> <!DOCTYPE address SYSTEM "address.dtd"> <address> <name> Tanmay Patil </name> <company> TutorialsPoint </company> <phone> (011) 123-4567 </phone> </address> Below is the content of the DTD file address.dtd − <!ELEMENT address (name, company, phone)> <!ELEMENT name (#PCDATA)> <!ELEMENT company (#PCDATA)> <!ELEMENT phone (#PCDATA)> All XML parsers must support built-in entities. In general, you can use these entity references anywhere. You can also use normal text within the XML document, such as in element contents and attribute values. There are five built-in entities that play their role in well-formed XML, they are − ampersand: &amp; ampersand: &amp; Single quote: &apos; Single quote: &apos; Greater than: &gt; Greater than: &gt; Less than: &lt; Less than: &lt; Double quote: " Double quote: " Following example demonstrates the built-in entity declaration − <?xml version = "1.0"?> <note> <description>I'm a technical writer & programmer</description> <note> As you can see here the &amp; character is replaced by & whenever the processor encounters this. Character Entities are used to name some of the entities which are symbolic representation of information i.e characters that are difficult or impossible to type can be substituted by Character Entities. Following example demonstrates the character entity declaration − <?xml version = "1.0" encoding = "UTF-8" standalone = "yes"?> <!DOCTYPE author[ <!ELEMENT author (#PCDATA)> <!ENTITY writer "Tanmay patil"> <!ENTITY copyright "&#169;"> ]> <author>&writer;&copyright;</author> You will notice here we have used &#169; as value for copyright character. Save this file as sample.xml and open it in your browser and you will see that copyright is replaced by the character ©. General entities must be declared within the DTD before they can be used within an XML document. Instead of representing only a single character, general entities can represent characters, paragraphs, and even entire documents. To declare a general entity, use a declaration of this general form in your DTD − <!ENTITY ename "text"> Following example demonstrates the general entity declaration − <?xml version = "1.0"?> <!DOCTYPE note [ <!ENTITY source-text "tutorialspoint"> ]> <note> &source-text; </note> Whenever an XML parser encounters a reference to source-text entity, it will supply the replacement text to the application at the point of the reference. The purpose of a parameter entity is to enable you to create reusable sections of replacement text. Following is the syntax for parameter entity declaration − <!ENTITY % ename "entity_value"> entity_value is any character that is not an '&', '%' or ' " '. entity_value is any character that is not an '&', '%' or ' " '. Following example demonstrates the parameter entity declaration. Suppose you have element declarations as below − <!ELEMENT residence (name, street, pincode, city, phone)> <!ELEMENT apartment (name, street, pincode, city, phone)> <!ELEMENT office (name, street, pincode, city, phone)> <!ELEMENT shop (name, street, pincode, city, phone)> Now suppose you want to add additional eleement country, then then you need to add it to all four declarations. Hence we can go for a parameter entity reference. Now using parameter entity reference the above example will be − <!ENTITY % area "name, street, pincode, city"> <!ENTITY % contact "phone"> Parameter entities are dereferenced in the same way as a general entity reference, only with a percent sign instead of an ampersand − <!ELEMENT residence (%area;, %contact;)> <!ELEMENT apartment (%area;, %contact;)> <!ELEMENT office (%area;, %contact;)> <!ELEMENT shop (%area;, %contact;)> When the parser reads these declarations, it substitutes the entity's replacement text for the entity reference. We use DTD to describe precisely the XML document. DTDs check the validity of structure and vocabulary of an XML document against the grammatical rules of the appropriate XML language. Now to check the validity of DTD, following procedures can be used − Using XML DTD validation tools − You can use some IDEs such as XML Spy (not free) and XMLStarlet(opensource) can be used to validate XML files against DTD document. Using XML DTD validation tools − You can use some IDEs such as XML Spy (not free) and XMLStarlet(opensource) can be used to validate XML files against DTD document. Using XML DTD on-line validators − W3C Markup Validation Service is designed to validate Web documents. Use the online validator to check the validaty of your XML DTD here. Using XML DTD on-line validators − W3C Markup Validation Service is designed to validate Web documents. Use the online validator to check the validaty of your XML DTD here. Write your own XML validators with XML DTD validation API − Newer versions of JDK (above 1.4) support XML DTD validation API. You can write your own validator code to check the validity of XML DTD validation. Write your own XML validators with XML DTD validation API − Newer versions of JDK (above 1.4) support XML DTD validation API. You can write your own validator code to check the validity of XML DTD validation. Print Add Notes Bookmark this page
[ { "code": null, "e": 1903, "s": 1666, "text": "XML Document Type Declaration, commonly known as DTD, is a way to describe precisely the XML language. DTDs check the validity of structure and vocabulary of an XML document against the grammatical rules of the appropriate XML language." }, { "code": null, "e": 1939, "s": 1903, "text": "An XML document can be defined as −" }, { "code": null, "e": 2163, "s": 1939, "text": "Well-formed − If the XML document adheres to all the general XML rules such as tags must be properly nested, opening and closing tags must be balanced, and empty tags must end with '/>', then it is called as well-formed.\nOR" }, { "code": null, "e": 2384, "s": 2163, "text": "Well-formed − If the XML document adheres to all the general XML rules such as tags must be properly nested, opening and closing tags must be balanced, and empty tags must end with '/>', then it is called as well-formed." }, { "code": null, "e": 2387, "s": 2384, "text": "OR" }, { "code": null, "e": 2642, "s": 2387, "text": "Valid − An XML document said to be valid when it is not only well-formed, but it also conforms to available DTD that specifies which tags it uses, what attributes those tags can contain, and which tags can occur inside other tags, among other properties." }, { "code": null, "e": 2897, "s": 2642, "text": "Valid − An XML document said to be valid when it is not only well-formed, but it also conforms to available DTD that specifies which tags it uses, what attributes those tags can contain, and which tags can occur inside other tags, among other properties." }, { "code": null, "e": 2981, "s": 2897, "text": "The following diagram represents that a DTD is used to structure the XML document −" }, { "code": null, "e": 3059, "s": 2981, "text": "DTD can be classified on its declaration basis in the XML document, such as −" }, { "code": null, "e": 3072, "s": 3059, "text": "Internal DTD" }, { "code": null, "e": 3085, "s": 3072, "text": "Internal DTD" }, { "code": null, "e": 3098, "s": 3085, "text": "External DTD" }, { "code": null, "e": 3111, "s": 3098, "text": "External DTD" }, { "code": null, "e": 3244, "s": 3111, "text": "When a DTD is declared within the file it is called Internal DTD and if it is declared in a separate file it is called External DTD." }, { "code": null, "e": 3301, "s": 3244, "text": "We will learn more about these in the chapter DTD Syntax" }, { "code": null, "e": 3360, "s": 3301, "text": "Following are some important points that a DTD describes −" }, { "code": null, "e": 3409, "s": 3360, "text": "the elements that can appear in an XML document." }, { "code": null, "e": 3458, "s": 3409, "text": "the elements that can appear in an XML document." }, { "code": null, "e": 3494, "s": 3458, "text": "the order in which they can appear." }, { "code": null, "e": 3530, "s": 3494, "text": "the order in which they can appear." }, { "code": null, "e": 3563, "s": 3530, "text": "optional and mandatory elements." }, { "code": null, "e": 3596, "s": 3563, "text": "optional and mandatory elements." }, { "code": null, "e": 3659, "s": 3596, "text": "element attributes and whether they are optional or mandatory." }, { "code": null, "e": 3722, "s": 3659, "text": "element attributes and whether they are optional or mandatory." }, { "code": null, "e": 3766, "s": 3722, "text": "whether attributes can have default values." }, { "code": null, "e": 3810, "s": 3766, "text": "whether attributes can have default values." }, { "code": null, "e": 3960, "s": 3810, "text": "Documentation − You can define your own format for the XML files. Looking at this document a user/developer can understand the structure of the data." }, { "code": null, "e": 4110, "s": 3960, "text": "Documentation − You can define your own format for the XML files. Looking at this document a user/developer can understand the structure of the data." }, { "code": null, "e": 4364, "s": 4110, "text": "Validation − It gives a way to check the validity of XML files by checking whether the elements appear in the right order, mandatory elements and attributes are in place, the elements and attributes have not been inserted in an incorrect way, and so on." }, { "code": null, "e": 4618, "s": 4364, "text": "Validation − It gives a way to check the validity of XML files by checking whether the elements appear in the right order, mandatory elements and attributes are in place, the elements and attributes have not been inserted in an incorrect way, and so on." }, { "code": null, "e": 4855, "s": 4618, "text": "It does not support the namespaces. Namespace is a mechanism by which element and attribute names can be assigned to groups. However, in a DTD namespaces have to be defined within the DTD, which violates the purpose of using namespaces." }, { "code": null, "e": 5092, "s": 4855, "text": "It does not support the namespaces. Namespace is a mechanism by which element and attribute names can be assigned to groups. However, in a DTD namespaces have to be defined within the DTD, which violates the purpose of using namespaces." }, { "code": null, "e": 5136, "s": 5092, "text": "It supports only the text string data type." }, { "code": null, "e": 5180, "s": 5136, "text": "It supports only the text string data type." }, { "code": null, "e": 5272, "s": 5180, "text": "It is not object oriented. Hence, the concept of inheritance cannot be applied on the DTDs." }, { "code": null, "e": 5364, "s": 5272, "text": "It is not object oriented. Hence, the concept of inheritance cannot be applied on the DTDs." }, { "code": null, "e": 5427, "s": 5364, "text": "Limited possibilities to express the cardinality for elements." }, { "code": null, "e": 5490, "s": 5427, "text": "Limited possibilities to express the cardinality for elements." }, { "code": null, "e": 5654, "s": 5490, "text": "An XML DTD can be either specified inside the document, or it can be kept in a separate document and then the document can be linked to the DTD document to use it." }, { "code": null, "e": 5692, "s": 5654, "text": "Basic syntax of a DTD is as follows −" }, { "code": null, "e": 5774, "s": 5692, "text": "<!DOCTYPE element DTD identifier\n[\n declaration1\n declaration2\n ........\n]>" }, { "code": null, "e": 5796, "s": 5774, "text": "In the above syntax −" }, { "code": null, "e": 5833, "s": 5796, "text": "DTD starts with <!DOCTYPE delimiter." }, { "code": null, "e": 5870, "s": 5833, "text": "DTD starts with <!DOCTYPE delimiter." }, { "code": null, "e": 5953, "s": 5870, "text": "An element tells the parser to parse the document from the specified root element." }, { "code": null, "e": 6036, "s": 5953, "text": "An element tells the parser to parse the document from the specified root element." }, { "code": null, "e": 6253, "s": 6036, "text": "DTD identifier is an identifier for the document type definition, which may be the path to a file on the system or URL to a file on the internet. If the DTD is pointing to external path, it is called external subset." }, { "code": null, "e": 6470, "s": 6253, "text": "DTD identifier is an identifier for the document type definition, which may be the path to a file on the system or URL to a file on the internet. If the DTD is pointing to external path, it is called external subset." }, { "code": null, "e": 6566, "s": 6470, "text": "The square brackets [ ] enclose an optional list of entity declarations called internal subset." }, { "code": null, "e": 6662, "s": 6566, "text": "The square brackets [ ] enclose an optional list of entity declarations called internal subset." }, { "code": null, "e": 6907, "s": 6662, "text": "A DTD is referred to as an internal DTD if elements are declared within the XML files. To reference it as internal DTD, standalone attribute in XML declaration must be set to yes. This means the declaration works independent of external source." }, { "code": null, "e": 6948, "s": 6907, "text": "The syntax of internal DTD is as shown −" }, { "code": null, "e": 6995, "s": 6948, "text": "<!DOCTYPE root-element [element-declarations]>" }, { "code": null, "e": 7102, "s": 6995, "text": "where root-element is the name of root element and element-declarations is where you declare the elements." }, { "code": null, "e": 7150, "s": 7102, "text": "Following is a simple example of internal DTD −" }, { "code": null, "e": 7492, "s": 7150, "text": "<?xml version = \"1.0\" encoding = \"UTF-8\" standalone = \"yes\" ?>\n\n<!DOCTYPE address [\n <!ELEMENT address (name,company,phone)>\n <!ELEMENT name (#PCDATA)>\n <!ELEMENT company (#PCDATA)>\n <!ELEMENT phone (#PCDATA)>\n]>\n\n<address>\n <name>Tanmay Patil</name>\n <company>TutorialsPoint</company>\n <phone>(011) 123-4567</phone>\n</address>" }, { "code": null, "e": 7527, "s": 7492, "text": "Let us go through the above code −" }, { "code": null, "e": 7599, "s": 7527, "text": "Start Declaration − Begin the XML declaration with following statement." }, { "code": null, "e": 7662, "s": 7599, "text": "<?xml version = \"1.0\" encoding = \"UTF-8\" standalone = \"yes\" ?>" }, { "code": null, "e": 7779, "s": 7662, "text": "DTD − Immediately after the XML header, the document type declaration follows, commonly referred to as the DOCTYPE −" }, { "code": null, "e": 7799, "s": 7779, "text": "<!DOCTYPE address [" }, { "code": null, "e": 7965, "s": 7799, "text": "The DOCTYPE declaration has an exclamation mark (!) at the start of the element name. The DOCTYPE informs the parser that a DTD is associated with this XML document." }, { "code": null, "e": 8098, "s": 7965, "text": "DTD Body − The DOCTYPE declaration is followed by body of the DTD, where you declare elements, attributes, entities, and notations −" }, { "code": null, "e": 8223, "s": 8098, "text": "<!ELEMENT address (name,company,phone)>\n<!ELEMENT name (#PCDATA)>\n<!ELEMENT company (#PCDATA)>\n<!ELEMENT phone_no (#PCDATA)>" }, { "code": null, "e": 8427, "s": 8223, "text": "Several elements are declared here that make up the vocabulary of the <name> document. <!ELEMENT name (#PCDATA)> defines the element name to be of type \"#PCDATA\". Here #PCDATA means parse-able text data." }, { "code": null, "e": 8649, "s": 8427, "text": "End Declaration − Finally, the declaration section of the DTD is closed using a closing bracket and a closing angle bracket (]>). This effectively ends the definition, and thereafter, the XML document follows immediately." }, { "code": null, "e": 8811, "s": 8649, "text": "The document type declaration must appear at the start of the document (preceded only by the XML header) - it is not permitted anywhere else within the document." }, { "code": null, "e": 8973, "s": 8811, "text": "The document type declaration must appear at the start of the document (preceded only by the XML header) - it is not permitted anywhere else within the document." }, { "code": null, "e": 9071, "s": 8973, "text": "Similar to the DOCTYPE declaration, the element declarations must start with an exclamation mark." }, { "code": null, "e": 9169, "s": 9071, "text": "Similar to the DOCTYPE declaration, the element declarations must start with an exclamation mark." }, { "code": null, "e": 9260, "s": 9169, "text": "The Name in the document type declaration must match the element type of the root element." }, { "code": null, "e": 9351, "s": 9260, "text": "The Name in the document type declaration must match the element type of the root element." }, { "code": null, "e": 9689, "s": 9351, "text": "In external DTD elements are declared outside the XML file. They are accessed by specifying the system attributes which may be either the legal .dtd file or a valid URL. To reference it as external DTD, standalone attribute in the XML declaration must be set as no. This means, declaration includes information from the external source." }, { "code": null, "e": 9732, "s": 9689, "text": "Following is the syntax for external DTD −" }, { "code": null, "e": 9775, "s": 9732, "text": "<!DOCTYPE root-element SYSTEM \"file-name\">" }, { "code": null, "e": 9824, "s": 9775, "text": "where file-name is the file with .dtd extension." }, { "code": null, "e": 9873, "s": 9824, "text": "The following example shows external DTD usage −" }, { "code": null, "e": 10093, "s": 9873, "text": "<?xml version = \"1.0\" encoding = \"UTF-8\" standalone = \"no\" ?>\n<!DOCTYPE address SYSTEM \"address.dtd\">\n\n<address>\n <name>Tanmay Patil</name>\n <company>TutorialsPoint</company>\n <phone>(011) 123-4567</phone>\n</address>" }, { "code": null, "e": 10148, "s": 10093, "text": "The content of the DTD file address.dtd are as shown −" }, { "code": null, "e": 10270, "s": 10148, "text": "<!ELEMENT address (name,company,phone)>\n<!ELEMENT name (#PCDATA)>\n<!ELEMENT company (#PCDATA)>\n<!ELEMENT phone (#PCDATA)>" }, { "code": null, "e": 10361, "s": 10270, "text": "You can refer to an external DTD by either using system identifiers or public identifiers." }, { "code": null, "e": 10380, "s": 10361, "text": "System Identifiers" }, { "code": null, "e": 10508, "s": 10380, "text": "A system identifier enables you to specify the location of an external file containing DTD declarations. Syntax is as follows −" }, { "code": null, "e": 10551, "s": 10508, "text": "<!DOCTYPE name SYSTEM \"address.dtd\" [...]>" }, { "code": null, "e": 10655, "s": 10551, "text": "As you can see it contains keyword SYSTEM and a URI reference pointing to the location of the document." }, { "code": null, "e": 10674, "s": 10655, "text": "Public Identifiers" }, { "code": null, "e": 10764, "s": 10674, "text": "Public identifiers provide a mechanism to locate DTD resources and are written as below −" }, { "code": null, "e": 10831, "s": 10764, "text": "<!DOCTYPE name PUBLIC \"-//Beginning XML//DTD Address Example//EN\">" }, { "code": null, "e": 11099, "s": 10831, "text": "As you can see, it begins with keyword PUBLIC, followed by a specialized identifier. Public identifiers are used to identify an entry in a catalog. Public identifiers can follow any format, however, a commonly used format is called Formal Public Identifiers, or FPIs." }, { "code": null, "e": 11244, "s": 11099, "text": "This chapter will discuss about XML Components from DTD perspective. A DTD will basically contain declarations of the following XML components −" }, { "code": null, "e": 11252, "s": 11244, "text": "Element" }, { "code": null, "e": 11260, "s": 11252, "text": "Element" }, { "code": null, "e": 11271, "s": 11260, "text": "Attributes" }, { "code": null, "e": 11282, "s": 11271, "text": "Attributes" }, { "code": null, "e": 11291, "s": 11282, "text": "Entities" }, { "code": null, "e": 11300, "s": 11291, "text": "Entities" }, { "code": null, "e": 11467, "s": 11300, "text": "XML elements can be defined as building blocks of an XML document. Elements can behave as a container to hold text, elements, attributes, media objects or mix of all." }, { "code": null, "e": 11608, "s": 11467, "text": "Each XML document contains one or more elements, the boundaries of which are either delimited by start-tags and end-tags, or empty elements." }, { "code": null, "e": 11650, "s": 11608, "text": "Below is a simple example of XML elements" }, { "code": null, "e": 11684, "s": 11650, "text": "<name>\n Tutorials Point\n</name>" }, { "code": null, "e": 11899, "s": 11684, "text": "As you can see we have defined a <name> tag. There's a text between start and end tag of <name>. Elements, when used in an XML-DTD, need to be declared which will be discussed in detail in the chapter DTD Elements." }, { "code": null, "e": 12150, "s": 11899, "text": "Attributes are part of the XML elements. An element can have any number of unique attributes. Attributes give more information about the XML element or more precisely it defines a property of the element. An XML attribute is always a name-value pair." }, { "code": null, "e": 12196, "s": 12150, "text": "Below is a simple example of XML attributes −" }, { "code": null, "e": 12222, "s": 12196, "text": "<img src = \"flower.jpg\"/>" }, { "code": null, "e": 12340, "s": 12222, "text": "Here img is the element name whereas src is an attribute name and flower.jpg is a value given for the attribute src.\n" }, { "code": null, "e": 12472, "s": 12340, "text": "If attributes are used in an XML DTD then these need to be declared which will be discussed in detail in the chapter DTD Attributes" }, { "code": null, "e": 12607, "s": 12472, "text": "Entities are placeholders in XML. These can be declared in the document prolog or in a DTD. Entities can be primarily categorized as −" }, { "code": null, "e": 12625, "s": 12607, "text": "Built-in entities" }, { "code": null, "e": 12643, "s": 12625, "text": "Built-in entities" }, { "code": null, "e": 12662, "s": 12643, "text": "Character entities" }, { "code": null, "e": 12681, "s": 12662, "text": "Character entities" }, { "code": null, "e": 12698, "s": 12681, "text": "General entities" }, { "code": null, "e": 12715, "s": 12698, "text": "General entities" }, { "code": null, "e": 12734, "s": 12715, "text": "Parameter entities" }, { "code": null, "e": 12753, "s": 12734, "text": "Parameter entities" }, { "code": null, "e": 12827, "s": 12753, "text": "There are five built-in entities that play in well-formed XML, they are −" }, { "code": null, "e": 12844, "s": 12827, "text": "ampersand: &amp;" }, { "code": null, "e": 12861, "s": 12844, "text": "ampersand: &amp;" }, { "code": null, "e": 12882, "s": 12861, "text": "Single quote: &apos;" }, { "code": null, "e": 12903, "s": 12882, "text": "Single quote: &apos;" }, { "code": null, "e": 12922, "s": 12903, "text": "Greater than: &gt;" }, { "code": null, "e": 12941, "s": 12922, "text": "Greater than: &gt;" }, { "code": null, "e": 12957, "s": 12941, "text": "Less than: &lt;" }, { "code": null, "e": 12973, "s": 12957, "text": "Less than: &lt;" }, { "code": null, "e": 12989, "s": 12973, "text": "Double quote: \"" }, { "code": null, "e": 13005, "s": 12989, "text": "Double quote: \"" }, { "code": null, "e": 13099, "s": 13005, "text": "We will study more about entity declarations in XML DTD in detail in the chapter DTD Entities" }, { "code": null, "e": 13266, "s": 13099, "text": "XML elements can be defined as building blocks of an XML document. Elements can behave as a container to hold text, elements, attributes, media objects or mix of all." }, { "code": null, "e": 13447, "s": 13266, "text": "A DTD element is declared with an ELEMENT declaration. When an XML file is validated by DTD, parser initially checks for the root element and then the child elements are validated." }, { "code": null, "e": 13501, "s": 13447, "text": "All DTD element declarations have this general form −" }, { "code": null, "e": 13534, "s": 13501, "text": "<!ELEMENT elementname (content)>" }, { "code": null, "e": 13626, "s": 13534, "text": "ELEMENT declaration is used to indicate the parser that you are about to define an element." }, { "code": null, "e": 13718, "s": 13626, "text": "ELEMENT declaration is used to indicate the parser that you are about to define an element." }, { "code": null, "e": 13810, "s": 13718, "text": "elementname is the element name (also called the generic identifier) that you are defining." }, { "code": null, "e": 13902, "s": 13810, "text": "elementname is the element name (also called the generic identifier) that you are defining." }, { "code": null, "e": 13967, "s": 13902, "text": "content defines what content (if any) can go within the element." }, { "code": null, "e": 14032, "s": 13967, "text": "content defines what content (if any) can go within the element." }, { "code": null, "e": 14103, "s": 14032, "text": "Content of elements declaration in a DTD can be categorized as below −" }, { "code": null, "e": 14117, "s": 14103, "text": "Empty content" }, { "code": null, "e": 14131, "s": 14117, "text": "Empty content" }, { "code": null, "e": 14147, "s": 14131, "text": "Element content" }, { "code": null, "e": 14163, "s": 14147, "text": "Element content" }, { "code": null, "e": 14177, "s": 14163, "text": "Mixed content" }, { "code": null, "e": 14191, "s": 14177, "text": "Mixed content" }, { "code": null, "e": 14203, "s": 14191, "text": "Any content" }, { "code": null, "e": 14215, "s": 14203, "text": "Any content" }, { "code": null, "e": 14360, "s": 14215, "text": "This is a special case of element declaration. This element declaration does not contain any content. These are declared with the keyword EMPTY." }, { "code": null, "e": 14367, "s": 14360, "text": "Syntax" }, { "code": null, "e": 14423, "s": 14367, "text": "Following is the syntax for empty element declaration −" }, { "code": null, "e": 14453, "s": 14423, "text": "<!ELEMENT elementname EMPTY >" }, { "code": null, "e": 14475, "s": 14453, "text": "In the above syntax −" }, { "code": null, "e": 14528, "s": 14475, "text": "ELEMENT is the element declaration of category EMPTY" }, { "code": null, "e": 14581, "s": 14528, "text": "ELEMENT is the element declaration of category EMPTY" }, { "code": null, "e": 14623, "s": 14581, "text": "elementname is the name of empty element." }, { "code": null, "e": 14665, "s": 14623, "text": "elementname is the name of empty element." }, { "code": null, "e": 14673, "s": 14665, "text": "Example" }, { "code": null, "e": 14745, "s": 14673, "text": "Following is a simple example demonstrating empty element declaration −" }, { "code": null, "e": 14831, "s": 14745, "text": "<?xml version = \"1.0\"?>\n\n<!DOCTYPE hr[\n <!ELEMENT address EMPTY> \n]>\n<address />" }, { "code": null, "e": 14948, "s": 14831, "text": "In this example address is declared as an empty element. The markup for address element would appear as <address />." }, { "code": null, "e": 15096, "s": 14948, "text": "In element declaration with element content, the content would be allowable elements within parentheses. We can also include more than one element." }, { "code": null, "e": 15103, "s": 15096, "text": "Syntax" }, { "code": null, "e": 15171, "s": 15103, "text": "Following is a syntax of element declaration with element content −" }, { "code": null, "e": 15214, "s": 15171, "text": "<!ELEMENT elementname (child1, child2...)>" }, { "code": null, "e": 15253, "s": 15214, "text": "ELEMENT is the element declaration tag" }, { "code": null, "e": 15292, "s": 15253, "text": "ELEMENT is the element declaration tag" }, { "code": null, "e": 15332, "s": 15292, "text": "elementname is the name of the element." }, { "code": null, "e": 15372, "s": 15332, "text": "elementname is the name of the element." }, { "code": null, "e": 15468, "s": 15372, "text": "child1, child2.. are the elements and each element must have its own definition within the DTD." }, { "code": null, "e": 15564, "s": 15468, "text": "child1, child2.. are the elements and each element must have its own definition within the DTD." }, { "code": null, "e": 15572, "s": 15564, "text": "Example" }, { "code": null, "e": 15663, "s": 15572, "text": "Below example demonstrates a simple example for element declaration with element content −" }, { "code": null, "e": 16005, "s": 15663, "text": "<?xml version = \"1.0\" encoding = \"UTF-8\" standalone = \"yes\" ?>\n\n<!DOCTYPE address [\n <!ELEMENT address (name,company,phone)>\n <!ELEMENT name (#PCDATA)>\n <!ELEMENT company (#PCDATA)>\n <!ELEMENT phone (#PCDATA)>\n]>\n\n<address>\n <name>Tanmay Patil</name>\n <company>TutorialsPoint</company>\n <phone>(011) 123-4567</phone>\n</address>" }, { "code": null, "e": 16112, "s": 16005, "text": "In the above example, address is the parent element and name, company and phone_no are its child elements." }, { "code": null, "e": 16219, "s": 16112, "text": "Below table shows the list of operators and syntax rules which can be applied in defining child elements −" }, { "code": null, "e": 16246, "s": 16219, "text": "<!ELEMENT address (name+)>" }, { "code": null, "e": 16326, "s": 16246, "text": "Child element name can occur one or more times inside the element name address." }, { "code": null, "e": 16353, "s": 16326, "text": "<!ELEMENT address (name*)>" }, { "code": null, "e": 16434, "s": 16353, "text": "Child element name can occur zero or more times inside the element name address." }, { "code": null, "e": 16461, "s": 16434, "text": "<!ELEMENT address (name?)>" }, { "code": null, "e": 16540, "s": 16461, "text": "Child element name can occur zero or one time inside the element name address." }, { "code": null, "e": 16575, "s": 16540, "text": "<!ELEMENT address (name, company)>" }, { "code": null, "e": 16685, "s": 16575, "text": "Sequence of child elements name, company, which must occur in the same order inside the element name address." }, { "code": null, "e": 16721, "s": 16685, "text": "<!ELEMENT address (name | company)>" }, { "code": null, "e": 16845, "s": 16721, "text": "It allows you to choose either of child elements i.e. name or company, which must occur in inside the element name address." }, { "code": null, "e": 16921, "s": 16845, "text": "We need to follow certain rules if there is more than one element content −" }, { "code": null, "e": 17247, "s": 16921, "text": "Sequences − Often the elements within DTD documents must appear in a distinct order. If this is the case, you define the content using a sequence.\nThe declaration indicates that the <address> element must have exactly three children - <name>, <company>, and <phone> - and that they must appear in this order. For example −\n" }, { "code": null, "e": 17396, "s": 17247, "text": "Sequences − Often the elements within DTD documents must appear in a distinct order. If this is the case, you define the content using a sequence." }, { "code": null, "e": 17572, "s": 17396, "text": "The declaration indicates that the <address> element must have exactly three children - <name>, <company>, and <phone> - and that they must appear in this order. For example −" }, { "code": null, "e": 17612, "s": 17572, "text": "<!ELEMENT address (name,company,phone)>" }, { "code": null, "e": 17791, "s": 17612, "text": "Choices − Suppose you need to allow one element or another, but not both. In such cases you must use the pipe (|) character. The pipe functions as an exclusive OR. For example −\n" }, { "code": null, "e": 17969, "s": 17791, "text": "Choices − Suppose you need to allow one element or another, but not both. In such cases you must use the pipe (|) character. The pipe functions as an exclusive OR. For example −" }, { "code": null, "e": 18008, "s": 17969, "text": "<!ELEMENT address (mobile | landline)>" }, { "code": null, "e": 18350, "s": 18008, "text": "This is the combination of (#PCDATA) and children elements. PCDATA stands for parsed character data, that is, text that is not markup. Within mixed content models, text can appear by itself or it can be interspersed between elements. The rules for mixed content models are similar to the element content as discussed in the previous section." }, { "code": null, "e": 18357, "s": 18350, "text": "Syntax" }, { "code": null, "e": 18415, "s": 18357, "text": "Following is a generic syntax for mixed element content −" }, { "code": null, "e": 18463, "s": 18415, "text": "<!ELEMENT elementname (#PCDATA|child1|child2)*>" }, { "code": null, "e": 18503, "s": 18463, "text": "ELEMENT is the element declaration tag." }, { "code": null, "e": 18543, "s": 18503, "text": "ELEMENT is the element declaration tag." }, { "code": null, "e": 18583, "s": 18543, "text": "elementname is the name of the element." }, { "code": null, "e": 18623, "s": 18583, "text": "elementname is the name of the element." }, { "code": null, "e": 18720, "s": 18623, "text": "PCDATA is the text that is not markup. #PCDATA must come first in the mixed content declaration." }, { "code": null, "e": 18817, "s": 18720, "text": "PCDATA is the text that is not markup. #PCDATA must come first in the mixed content declaration." }, { "code": null, "e": 18913, "s": 18817, "text": "child1, child2.. are the elements and each element must have its own definition within the DTD." }, { "code": null, "e": 19009, "s": 18913, "text": "child1, child2.. are the elements and each element must have its own definition within the DTD." }, { "code": null, "e": 19102, "s": 19009, "text": "The operator (*) must follow the mixed content declaration if children elements are included" }, { "code": null, "e": 19195, "s": 19102, "text": "The operator (*) must follow the mixed content declaration if children elements are included" }, { "code": null, "e": 19282, "s": 19195, "text": "The (#PCDATA) and children element declarations must be separated by the (|) operator." }, { "code": null, "e": 19369, "s": 19282, "text": "The (#PCDATA) and children element declarations must be separated by the (|) operator." }, { "code": null, "e": 19377, "s": 19369, "text": "Example" }, { "code": null, "e": 19469, "s": 19377, "text": "Following is a simple example demonstrating the mixed content element declaration in a DTD." }, { "code": null, "e": 19742, "s": 19469, "text": "<?xml version = \"1.0\" encoding = \"UTF-8\" standalone = \"yes\" ?>\n\n<!DOCTYPE address [\n <!ELEMENT address (#PCDATA|name)*>\n <!ELEMENT name (#PCDATA)>\n]>\n\n<address>\n Here's a bit of text mixed up with the child element.\n <name>\n Tanmay Patil\n </name>\n</address>" }, { "code": null, "e": 19944, "s": 19742, "text": "You can declare an element using the ANY keyword in the content. It is most often referred to as mixed category element. ANY is useful when you have yet to decide the allowable contents of the element." }, { "code": null, "e": 19951, "s": 19944, "text": "Syntax" }, { "code": null, "e": 20017, "s": 19951, "text": "Following is the syntax for declaring elements with ANY content −" }, { "code": null, "e": 20044, "s": 20017, "text": "<!ELEMENT elementname ANY>" }, { "code": null, "e": 20353, "s": 20044, "text": "Here, the ANY keyword indicates that text (PCDATA) and/or any elements declared within the DTD can be used within the content of the <elementname> element. They can be used in any order any number of times. However, the ANY keyword does not allow you to include elements that are not declared within the DTD." }, { "code": null, "e": 20361, "s": 20353, "text": "Example" }, { "code": null, "e": 20448, "s": 20361, "text": "Following is a simple example demonstrating the element declaration with ANY content −" }, { "code": null, "e": 20614, "s": 20448, "text": "<?xml version = \"1.0\" encoding = \"UTF-8\" standalone = \"yes\" ?>\n\n<!DOCTYPE address [\n <!ELEMENT address ANY>\n]>\n\n<address>\n Here's a bit of sample text\n</address>" }, { "code": null, "e": 20887, "s": 20614, "text": "In this chapter we will discuss about DTD Attributes. Attribute gives more information about an element or more precisely it defines a property of an element. An XML attribute is always in the form of a name-value pair. An element can have any number of unique attributes." }, { "code": null, "e": 21137, "s": 20887, "text": "Attribute declaration is very much similar to element declarations in many ways except one; instead of declaring allowable content for elements, you declare a list of allowable attributes for each element. These lists are called ATTLIST declaration." }, { "code": null, "e": 21196, "s": 21137, "text": "Basic syntax of DTD attributes declaration is as follows −" }, { "code": null, "e": 21266, "s": 21196, "text": "<!ATTLIST element-name attribute-name attribute-type attribute-value>" }, { "code": null, "e": 21288, "s": 21266, "text": "In the above syntax −" }, { "code": null, "e": 21375, "s": 21288, "text": "The DTD attributes start with <!ATTLIST keyword if the element contains the attribute." }, { "code": null, "e": 21462, "s": 21375, "text": "The DTD attributes start with <!ATTLIST keyword if the element contains the attribute." }, { "code": null, "e": 21541, "s": 21462, "text": "element-name specifies the name of the element to which the attribute applies." }, { "code": null, "e": 21620, "s": 21541, "text": "element-name specifies the name of the element to which the attribute applies." }, { "code": null, "e": 21712, "s": 21620, "text": "attribute-name specifies the name of the attribute which is included with the element-name." }, { "code": null, "e": 21804, "s": 21712, "text": "attribute-name specifies the name of the attribute which is included with the element-name." }, { "code": null, "e": 21907, "s": 21804, "text": "attribute-type defines the type of attributes. We will discuss more on this in the following sections." }, { "code": null, "e": 22010, "s": 21907, "text": "attribute-type defines the type of attributes. We will discuss more on this in the following sections." }, { "code": null, "e": 22135, "s": 22010, "text": "attribute-value takes a fixed value that the attributes must define. We will discuss more on this in the following sections." }, { "code": null, "e": 22260, "s": 22135, "text": "attribute-value takes a fixed value that the attributes must define. We will discuss more on this in the following sections." }, { "code": null, "e": 22321, "s": 22260, "text": "Below is a simple example for attribute declaration in DTD −" }, { "code": null, "e": 22531, "s": 22321, "text": "<?xml version = \"1.0\"?>\n\n<!DOCTYPE address [\n <!ELEMENT address ( name )>\n <!ELEMENT name ( #PCDATA )>\n <!ATTLIST name id CDATA #REQUIRED>\n]>\n\n<address>\n <name id = \"123\">Tanmay Patil</name>\n</address>" }, { "code": null, "e": 22566, "s": 22531, "text": "Let us go through the above code −" }, { "code": null, "e": 22628, "s": 22566, "text": "Begin with the XML declaration with the following statement −" }, { "code": null, "e": 22690, "s": 22628, "text": "Begin with the XML declaration with the following statement −" }, { "code": null, "e": 22714, "s": 22690, "text": "<?xml version = \"1.0\"?>" }, { "code": null, "e": 23004, "s": 22714, "text": "Immediately following the XML header is the document type declaration, commonly referred to as the DOCTYPE as shown below −\nThe DOCTYPE informs the parser that a DTD is associated with this XML document. The DOCTYPE declaration has an exclamation mark (!) at the start of the element name." }, { "code": null, "e": 23128, "s": 23004, "text": "Immediately following the XML header is the document type declaration, commonly referred to as the DOCTYPE as shown below −" }, { "code": null, "e": 23294, "s": 23128, "text": "The DOCTYPE informs the parser that a DTD is associated with this XML document. The DOCTYPE declaration has an exclamation mark (!) at the start of the element name." }, { "code": null, "e": 23314, "s": 23294, "text": "<!DOCTYPE address [" }, { "code": null, "e": 23390, "s": 23314, "text": "Following is the body of DTD. Here we have declared element and attribute −" }, { "code": null, "e": 23466, "s": 23390, "text": "Following is the body of DTD. Here we have declared element and attribute −" }, { "code": null, "e": 23522, "s": 23466, "text": "<!ELEMENT address ( name )>\n<!ELEMENT name ( #PCDATA )>" }, { "code": null, "e": 23641, "s": 23522, "text": "Attribute id for the element name is defined as given below −\nHere attribute type is CDATA and its value is #REQUIRED." }, { "code": null, "e": 23703, "s": 23641, "text": "Attribute id for the element name is defined as given below −" }, { "code": null, "e": 23760, "s": 23703, "text": "Here attribute type is CDATA and its value is #REQUIRED." }, { "code": null, "e": 23795, "s": 23760, "text": "<!ATTLIST name id CDATA #REQUIRED>" }, { "code": null, "e": 23925, "s": 23795, "text": "All attributes used in an XML document must be declared in the Document Type Definition (DTD) using an Attribute-List Declaration" }, { "code": null, "e": 24055, "s": 23925, "text": "All attributes used in an XML document must be declared in the Document Type Definition (DTD) using an Attribute-List Declaration" }, { "code": null, "e": 24106, "s": 24055, "text": "Attributes may only appear in start or empty tags." }, { "code": null, "e": 24157, "s": 24106, "text": "Attributes may only appear in start or empty tags." }, { "code": null, "e": 24199, "s": 24157, "text": "The keyword ATTLIST must be in upper case" }, { "code": null, "e": 24241, "s": 24199, "text": "The keyword ATTLIST must be in upper case" }, { "code": null, "e": 24333, "s": 24241, "text": "No duplicate attribute names will be allowed within the attribute list for a given element." }, { "code": null, "e": 24425, "s": 24333, "text": "No duplicate attribute names will be allowed within the attribute list for a given element." }, { "code": null, "e": 24597, "s": 24425, "text": "When declaring attributes, you can specify how the processor should handle the data that appears in the value. We can categorize attribute types in three main categories −" }, { "code": null, "e": 24609, "s": 24597, "text": "String type" }, { "code": null, "e": 24621, "s": 24609, "text": "String type" }, { "code": null, "e": 24637, "s": 24621, "text": "Tokenized types" }, { "code": null, "e": 24653, "s": 24637, "text": "Tokenized types" }, { "code": null, "e": 24670, "s": 24653, "text": "Enumerated types" }, { "code": null, "e": 24687, "s": 24670, "text": "Enumerated types" }, { "code": null, "e": 24757, "s": 24687, "text": "Following table provides a summary of the different attribute types −" }, { "code": null, "e": 24763, "s": 24757, "text": "CDATA" }, { "code": null, "e": 24842, "s": 24763, "text": "CDATA is character data (text and not markup). It is a String Attribute Type. " }, { "code": null, "e": 24845, "s": 24842, "text": "ID" }, { "code": null, "e": 24960, "s": 24845, "text": "It is a unique identifier of the attribute. It should not appear more than once. It is a Tokenized Attribute Type." }, { "code": null, "e": 24966, "s": 24960, "text": "IDREF" }, { "code": null, "e": 25104, "s": 24966, "text": "It is used to reference an ID of another element. It is used to establish connections between elements. It is a Tokenized Attribute Type." }, { "code": null, "e": 25111, "s": 25104, "text": "IDREFS" }, { "code": null, "e": 25184, "s": 25111, "text": "It is used to reference multiple ID's. It is a Tokenized Attribute Type." }, { "code": null, "e": 25191, "s": 25184, "text": "ENTITY" }, { "code": null, "e": 25275, "s": 25191, "text": "It represents an external entity in the document. It is a Tokenized Attribute Type." }, { "code": null, "e": 25284, "s": 25275, "text": "ENTITIES" }, { "code": null, "e": 25377, "s": 25284, "text": "It represents a list of external entities in the document. It is a Tokenized Attribute Type." }, { "code": null, "e": 25385, "s": 25377, "text": "NMTOKEN" }, { "code": null, "e": 25496, "s": 25385, "text": "It is similar to CDATA and the attribute value consists of a valid XML name. It is a Tokenized Attribute Type." }, { "code": null, "e": 25505, "s": 25496, "text": "NMTOKENS" }, { "code": null, "e": 25621, "s": 25505, "text": "It is similar to CDATA and the attribute value consists a list of valid XML name. It is a Tokenized Attribute Type." }, { "code": null, "e": 25630, "s": 25621, "text": "NOTATION" }, { "code": null, "e": 25740, "s": 25630, "text": "An element will be referenced to a notation declared in the DTD document. It is an Enumerated Attribute Type." }, { "code": null, "e": 25752, "s": 25740, "text": "Enumeration" }, { "code": null, "e": 25869, "s": 25752, "text": "It allows defining a specific list of values where one of the values must match. It is an Enumerated Attribute Type." }, { "code": null, "e": 25998, "s": 25869, "text": "Within each attribute declaration, you must specify how the value will appear in the document. You can specify if an attribute −" }, { "code": null, "e": 26023, "s": 25998, "text": "can have a default value" }, { "code": null, "e": 26048, "s": 26023, "text": "can have a default value" }, { "code": null, "e": 26071, "s": 26048, "text": "can have a fixed value" }, { "code": null, "e": 26094, "s": 26071, "text": "can have a fixed value" }, { "code": null, "e": 26106, "s": 26094, "text": "is required" }, { "code": null, "e": 26118, "s": 26106, "text": "is required" }, { "code": null, "e": 26129, "s": 26118, "text": "is implied" }, { "code": null, "e": 26140, "s": 26129, "text": "is implied" }, { "code": null, "e": 26239, "s": 26140, "text": "It contains the default value. The values can be enclosed in single quotes(') or double quotes(\")." }, { "code": null, "e": 26246, "s": 26239, "text": "Syntax" }, { "code": null, "e": 26281, "s": 26246, "text": "Following is the syntax of value −" }, { "code": null, "e": 26351, "s": 26281, "text": "<!ATTLIST element-name attribute-name attribute-type \"default-value\">" }, { "code": null, "e": 26403, "s": 26351, "text": "where default-value is the attribute value defined." }, { "code": null, "e": 26411, "s": 26403, "text": "Example" }, { "code": null, "e": 26487, "s": 26411, "text": "Following is a simple example of attribute declaration with default value −" }, { "code": null, "e": 26702, "s": 26487, "text": "<?xml version = \"1.0\"?>\n\n<!DOCTYPE address [\n <!ELEMENT address ( name )>\n <!ELEMENT name ( #PCDATA )>\n <!ATTLIST name id CDATA \"0\">\n]>\n\n<address>\n <name id = \"123\">\n Tanmay Patil\n </name>\n</address>" }, { "code": null, "e": 26844, "s": 26702, "text": "In this example we have name element with attribute id whose default value is 0. The default value is been enclosed within the double quotes." }, { "code": null, "e": 27044, "s": 26844, "text": "#FIXED keyword followed by the fixed value is used when you want to specify that the attribute value is constant and cannot be changed. A common use of fixed attributes is specifying version numbers." }, { "code": null, "e": 27051, "s": 27044, "text": "Syntax" }, { "code": null, "e": 27093, "s": 27051, "text": "Following is the syntax of fixed values −" }, { "code": null, "e": 27163, "s": 27093, "text": "<!ATTLIST element-name attribute-name attribute-type #FIXED \"value\" >" }, { "code": null, "e": 27207, "s": 27163, "text": "where #FIXED is an attribute value defined." }, { "code": null, "e": 27215, "s": 27207, "text": "Example" }, { "code": null, "e": 27289, "s": 27215, "text": "Following is a simple example of attribute declaration with FIXED value −" }, { "code": null, "e": 27563, "s": 27289, "text": "<?xml version = \"1.0\"?>\n\n<!DOCTYPE address [\n <!ELEMENT address (company)*>\n <!ELEMENT company (#PCDATA)>\n <!ATTLIST company name NMTOKEN #FIXED \"tutorialspoint\">\n]>\n\n<address>\n <company name = \"tutorialspoint\">we are a free online teaching faculty</company>\n</address>" }, { "code": null, "e": 27789, "s": 27563, "text": "In this example we have used the keyword #FIXED where it indicates that the value \"tutorialspoint\" is the only value for the attribute name of element <company>. If we try to change the attribute value then it gives an error." }, { "code": null, "e": 27819, "s": 27789, "text": "Following is an invalid DTD −" }, { "code": null, "e": 28082, "s": 27819, "text": "<?xml version = \"1.0\"?>\n\n<!DOCTYPE address [\n <!ELEMENT address (company)*>\n <!ELEMENT company (#PCDATA)>\n <!ATTLIST company name NMTOKEN #FIXED \"tutorialspoint\">\n]>\n\n<address>\n <company name = \"abc\">we are a free online teaching faculty</company>\n</address>" }, { "code": null, "e": 28162, "s": 28082, "text": "Whenever you want specify that an attribute is required, use #REQUIRED keyword." }, { "code": null, "e": 28169, "s": 28162, "text": "Syntax" }, { "code": null, "e": 28208, "s": 28169, "text": "Following is the syntax of #REQUIRED −" }, { "code": null, "e": 28272, "s": 28208, "text": "<!ATTLIST element-name attribute-name attribute-type #REQUIRED>" }, { "code": null, "e": 28318, "s": 28272, "text": "where #REQUIRED is an attribute type defined." }, { "code": null, "e": 28326, "s": 28318, "text": "Example" }, { "code": null, "e": 28410, "s": 28326, "text": "Following is a simple example of DTD attribute declaration with #REQUIRED keyword −" }, { "code": null, "e": 28631, "s": 28410, "text": "<?xml version = \"1.0\"?>\n\n<!DOCTYPE address [\n <!ELEMENT address ( name )>\n <!ELEMENT name ( #PCDATA )>\n <!ATTLIST name id CDATA #REQUIRED>\n]>\n\n<address>\n <name id = \"123\">\n Tanmay Patil\n </name>\n</address>" }, { "code": null, "e": 28754, "s": 28631, "text": "In this example we have used #REQUIRED keyword to specify that the attribute id must be provided for the element-name name" }, { "code": null, "e": 29037, "s": 28754, "text": "When declaring attributes you must always specify a value declaration. If the attribute you are declaring has no default value, has no fixed value, and is not required, then you must declare that the attribute as implied. Keyword #IMPLIED is used to specify an attribute as implied." }, { "code": null, "e": 29044, "s": 29037, "text": "Syntax" }, { "code": null, "e": 29082, "s": 29044, "text": "Following is the syntax of #IMPLIED −" }, { "code": null, "e": 29145, "s": 29082, "text": "<!ATTLIST element-name attribute-name attribute-type #IMPLIED>" }, { "code": null, "e": 29190, "s": 29145, "text": "where #IMPLIED is an attribute type defined." }, { "code": null, "e": 29198, "s": 29190, "text": "Example" }, { "code": null, "e": 29240, "s": 29198, "text": "Following is a simple example of #IMPLIED" }, { "code": null, "e": 29421, "s": 29240, "text": "<?xml version = \"1.0\"?>\n\n<!DOCTYPE address [\n <!ELEMENT address ( name )>\n <!ELEMENT name ( #PCDATA )>\n <!ATTLIST name id CDATA #IMPLIED>\n]>\n\n<address>\n <name />\n</address>" }, { "code": null, "e": 29563, "s": 29421, "text": "In this example we have used the keyword #IMPLIED as we do not want to specify any attributes to be included in element name. It is optional." }, { "code": null, "e": 29691, "s": 29563, "text": "Entities are used to define shortcuts to special characters within the XML documents. Entities can be primarily of four types −" }, { "code": null, "e": 29709, "s": 29691, "text": "Built-in entities" }, { "code": null, "e": 29727, "s": 29709, "text": "Built-in entities" }, { "code": null, "e": 29746, "s": 29727, "text": "Character entities" }, { "code": null, "e": 29765, "s": 29746, "text": "Character entities" }, { "code": null, "e": 29782, "s": 29765, "text": "General entities" }, { "code": null, "e": 29799, "s": 29782, "text": "General entities" }, { "code": null, "e": 29818, "s": 29799, "text": "Parameter entities" }, { "code": null, "e": 29837, "s": 29818, "text": "Parameter entities" }, { "code": null, "e": 29962, "s": 29837, "text": "In general, entities can be declared internally or externally. Let us understand each of these and their syntax as follows −" }, { "code": null, "e": 30033, "s": 29962, "text": "If an entity is declared within a DTD it is called as internal entity." }, { "code": null, "e": 30040, "s": 30033, "text": "Syntax" }, { "code": null, "e": 30098, "s": 30040, "text": "Following is the syntax for internal entity declaration −" }, { "code": null, "e": 30135, "s": 30098, "text": "<!ENTITY entity_name \"entity_value\">" }, { "code": null, "e": 30157, "s": 30135, "text": "In the above syntax −" }, { "code": null, "e": 30255, "s": 30157, "text": "entity_name is the name of entity followed by its value within the double quotes or single quote." }, { "code": null, "e": 30353, "s": 30255, "text": "entity_name is the name of entity followed by its value within the double quotes or single quote." }, { "code": null, "e": 30403, "s": 30353, "text": "entity_value holds the value for the entity name." }, { "code": null, "e": 30453, "s": 30403, "text": "entity_value holds the value for the entity name." }, { "code": null, "e": 30569, "s": 30453, "text": "The entity value of the Internal Entity is de-referenced by adding prefix & to the entity name i.e. &entity_name." }, { "code": null, "e": 30685, "s": 30569, "text": "The entity value of the Internal Entity is de-referenced by adding prefix & to the entity name i.e. &entity_name." }, { "code": null, "e": 30693, "s": 30685, "text": "Example" }, { "code": null, "e": 30757, "s": 30693, "text": "Following is a simple example for internal entity declaration −" }, { "code": null, "e": 31044, "s": 30757, "text": "<?xml version = \"1.0\" encoding = \"UTF-8\" standalone = \"yes\"?>\n\n<!DOCTYPE address [\n <!ELEMENT address (#PCDATA)>\n <!ENTITY name \"Tanmay patil\">\n <!ENTITY company \"TutorialsPoint\">\n <!ENTITY phone_no \"(011) 123-4567\">\n]>\n\n<address>\n &name;\n &company;\n &phone_no;\n</address>" }, { "code": null, "e": 31249, "s": 31044, "text": "In the above example, the respective entity names name, company and phone_no are replaced by their values in the XML document. The entity values are de-referenced by adding prefix & to the entity name." }, { "code": null, "e": 31400, "s": 31249, "text": "Save this file as sample.xml and open it in any browser, you will notice that the entity values for name, company, phone_no are replaced respectively." }, { "code": null, "e": 31566, "s": 31400, "text": "If an entity is declared outside a DTD it is called as external entity. You can refer to an external Entity by either using system identifiers or public identifiers." }, { "code": null, "e": 31573, "s": 31566, "text": "Syntax" }, { "code": null, "e": 31631, "s": 31573, "text": "Following is the syntax for External Entity declaration −" }, { "code": null, "e": 31663, "s": 31631, "text": "<!ENTITY name SYSTEM \"URI/URL\">" }, { "code": null, "e": 31685, "s": 31663, "text": "In the above syntax −" }, { "code": null, "e": 31713, "s": 31685, "text": "name is the name of entity." }, { "code": null, "e": 31741, "s": 31713, "text": "name is the name of entity." }, { "code": null, "e": 31764, "s": 31741, "text": "SYSTEM is the keyword." }, { "code": null, "e": 31787, "s": 31764, "text": "SYSTEM is the keyword." }, { "code": null, "e": 31878, "s": 31787, "text": "URI/URL is the address of the external source enclosed within the double or single quotes." }, { "code": null, "e": 31969, "s": 31878, "text": "URI/URL is the address of the external source enclosed within the double or single quotes." }, { "code": null, "e": 31975, "s": 31969, "text": "Types" }, { "code": null, "e": 32026, "s": 31975, "text": "You can refer to an external DTD by either using −" }, { "code": null, "e": 32276, "s": 32026, "text": "System Identifiers − A system identifier enables you to specify the location of an external file containing DTD declarations.\nAs you can see it contains keyword SYSTEM and a URI reference pointing to the document's location. Syntax is as follows −\n" }, { "code": null, "e": 32403, "s": 32276, "text": "System Identifiers − A system identifier enables you to specify the location of an external file containing DTD declarations." }, { "code": null, "e": 32525, "s": 32403, "text": "As you can see it contains keyword SYSTEM and a URI reference pointing to the document's location. Syntax is as follows −" }, { "code": null, "e": 32568, "s": 32525, "text": "<!DOCTYPE name SYSTEM \"address.dtd\" [...]>" }, { "code": null, "e": 32949, "s": 32568, "text": "Public Identifiers − Public identifiers provide a mechanism to locate DTD resources and are written as below −\nAs you can see, it begins with keyword PUBLIC, followed by a specialized identifier. Public identifiers are used to identify an entry in a catalog. Public identifiers can follow any format; however, a commonly used format is called Formal Public Identifiers, or FPIs.\n" }, { "code": null, "e": 33061, "s": 32949, "text": "Public Identifiers − Public identifiers provide a mechanism to locate DTD resources and are written as below −" }, { "code": null, "e": 33329, "s": 33061, "text": "As you can see, it begins with keyword PUBLIC, followed by a specialized identifier. Public identifiers are used to identify an entry in a catalog. Public identifiers can follow any format; however, a commonly used format is called Formal Public Identifiers, or FPIs." }, { "code": null, "e": 33396, "s": 33329, "text": "<!DOCTYPE name PUBLIC \"-//Beginning XML//DTD Address Example//EN\">" }, { "code": null, "e": 33404, "s": 33396, "text": "Example" }, { "code": null, "e": 33471, "s": 33404, "text": "Let us understand the external entity with the following example −" }, { "code": null, "e": 33735, "s": 33471, "text": "<?xml version = \"1.0\" encoding = \"UTF-8\" standalone = \"yes\"?>\n<!DOCTYPE address SYSTEM \"address.dtd\">\n\n<address>\n <name>\n Tanmay Patil\n </name>\n \n <company>\n TutorialsPoint\n </company>\n \n <phone>\n (011) 123-4567\n </phone>\n</address>" }, { "code": null, "e": 33786, "s": 33735, "text": "Below is the content of the DTD file address.dtd −" }, { "code": null, "e": 33910, "s": 33786, "text": "<!ELEMENT address (name, company, phone)>\n<!ELEMENT name (#PCDATA)>\n<!ELEMENT company (#PCDATA)>\n<!ELEMENT phone (#PCDATA)>" }, { "code": null, "e": 34120, "s": 33910, "text": "All XML parsers must support built-in entities. In general, you can use these entity references anywhere. You can also use normal text within the XML document, such as in element contents and attribute values." }, { "code": null, "e": 34205, "s": 34120, "text": "There are five built-in entities that play their role in well-formed XML, they are −" }, { "code": null, "e": 34222, "s": 34205, "text": "ampersand: &amp;" }, { "code": null, "e": 34239, "s": 34222, "text": "ampersand: &amp;" }, { "code": null, "e": 34260, "s": 34239, "text": "Single quote: &apos;" }, { "code": null, "e": 34281, "s": 34260, "text": "Single quote: &apos;" }, { "code": null, "e": 34300, "s": 34281, "text": "Greater than: &gt;" }, { "code": null, "e": 34319, "s": 34300, "text": "Greater than: &gt;" }, { "code": null, "e": 34335, "s": 34319, "text": "Less than: &lt;" }, { "code": null, "e": 34351, "s": 34335, "text": "Less than: &lt;" }, { "code": null, "e": 34367, "s": 34351, "text": "Double quote: \"" }, { "code": null, "e": 34383, "s": 34367, "text": "Double quote: \"" }, { "code": null, "e": 34448, "s": 34383, "text": "Following example demonstrates the built-in entity declaration −" }, { "code": null, "e": 34553, "s": 34448, "text": "<?xml version = \"1.0\"?>\n\n<note>\n <description>I'm a technical writer & programmer</description>\n<note>" }, { "code": null, "e": 34650, "s": 34553, "text": "As you can see here the &amp; character is replaced by & whenever the processor encounters this." }, { "code": null, "e": 34854, "s": 34650, "text": "Character Entities are used to name some of the entities which are symbolic representation of information i.e characters that are difficult or impossible to type can be substituted by Character Entities." }, { "code": null, "e": 34920, "s": 34854, "text": "Following example demonstrates the character entity declaration −" }, { "code": null, "e": 35138, "s": 34920, "text": "<?xml version = \"1.0\" encoding = \"UTF-8\" standalone = \"yes\"?>\n<!DOCTYPE author[\n <!ELEMENT author (#PCDATA)>\n <!ENTITY writer \"Tanmay patil\">\n <!ENTITY copyright \"&#169;\">\n]>\n<author>&writer;&copyright;</author>" }, { "code": null, "e": 35334, "s": 35138, "text": "You will notice here we have used &#169; as value for copyright character. Save this file as sample.xml and open it in your browser and you will see that copyright is replaced by the character ©." }, { "code": null, "e": 35562, "s": 35334, "text": "General entities must be declared within the DTD before they can be used within an XML document. Instead of representing only a single character, general entities can represent characters, paragraphs, and even entire documents." }, { "code": null, "e": 35644, "s": 35562, "text": "To declare a general entity, use a declaration of this general form in your DTD −" }, { "code": null, "e": 35667, "s": 35644, "text": "<!ENTITY ename \"text\">" }, { "code": null, "e": 35731, "s": 35667, "text": "Following example demonstrates the general entity declaration −" }, { "code": null, "e": 35851, "s": 35731, "text": "<?xml version = \"1.0\"?>\n\n<!DOCTYPE note [\n <!ENTITY source-text \"tutorialspoint\">\n]>\n\n<note>\n &source-text;\n</note>" }, { "code": null, "e": 36006, "s": 35851, "text": "Whenever an XML parser encounters a reference to source-text entity, it will supply the replacement text to the application at the point of the reference." }, { "code": null, "e": 36106, "s": 36006, "text": "The purpose of a parameter entity is to enable you to create reusable sections of replacement text." }, { "code": null, "e": 36165, "s": 36106, "text": "Following is the syntax for parameter entity declaration −" }, { "code": null, "e": 36198, "s": 36165, "text": "<!ENTITY % ename \"entity_value\">" }, { "code": null, "e": 36262, "s": 36198, "text": "entity_value is any character that is not an '&', '%' or ' \" '." }, { "code": null, "e": 36326, "s": 36262, "text": "entity_value is any character that is not an '&', '%' or ' \" '." }, { "code": null, "e": 36440, "s": 36326, "text": "Following example demonstrates the parameter entity declaration. Suppose you have element declarations as below −" }, { "code": null, "e": 36664, "s": 36440, "text": "<!ELEMENT residence (name, street, pincode, city, phone)>\n<!ELEMENT apartment (name, street, pincode, city, phone)>\n<!ELEMENT office (name, street, pincode, city, phone)>\n<!ELEMENT shop (name, street, pincode, city, phone)>" }, { "code": null, "e": 36893, "s": 36664, "text": "Now suppose you want to add additional eleement country, then then you need to add it to all four declarations. Hence we can go for a parameter entity reference. Now using parameter entity reference the above example will be −" }, { "code": null, "e": 36968, "s": 36893, "text": "<!ENTITY % area \"name, street, pincode, city\">\n<!ENTITY % contact \"phone\">" }, { "code": null, "e": 37102, "s": 36968, "text": "Parameter entities are dereferenced in the same way as a general entity reference, only with a percent sign instead of an ampersand −" }, { "code": null, "e": 37258, "s": 37102, "text": "<!ELEMENT residence (%area;, %contact;)>\n<!ELEMENT apartment (%area;, %contact;)>\n<!ELEMENT office (%area;, %contact;)>\n<!ELEMENT shop (%area;, %contact;)>" }, { "code": null, "e": 37371, "s": 37258, "text": "When the parser reads these declarations, it substitutes the entity's replacement text for the entity reference." }, { "code": null, "e": 37625, "s": 37371, "text": "We use DTD to describe precisely the XML document. DTDs check the validity of structure and vocabulary of an XML document against the grammatical rules of the appropriate XML language. Now to check the validity of DTD, following procedures can be used −" }, { "code": null, "e": 37791, "s": 37625, "text": "Using XML DTD validation tools − You can use some IDEs such as XML Spy (not free) and XMLStarlet(opensource) can be used to validate XML files against DTD document." }, { "code": null, "e": 37957, "s": 37791, "text": "Using XML DTD validation tools − You can use some IDEs such as XML Spy (not free) and XMLStarlet(opensource) can be used to validate XML files against DTD document." }, { "code": null, "e": 38131, "s": 37957, "text": "Using XML DTD on-line validators − W3C Markup Validation Service is designed to validate Web documents. Use the online validator to check the validaty of your XML DTD here." }, { "code": null, "e": 38305, "s": 38131, "text": "Using XML DTD on-line validators − W3C Markup Validation Service is designed to validate Web documents. Use the online validator to check the validaty of your XML DTD here." }, { "code": null, "e": 38517, "s": 38305, "text": "Write your own XML validators with XML DTD validation API − Newer versions of JDK (above 1.4) support XML DTD validation API. You can write your own validator code to check the validity of XML DTD validation." }, { "code": null, "e": 38729, "s": 38517, "text": "Write your own XML validators with XML DTD validation API − Newer versions of JDK (above 1.4) support XML DTD validation API. You can write your own validator code to check the validity of XML DTD validation." }, { "code": null, "e": 38736, "s": 38729, "text": " Print" }, { "code": null, "e": 38747, "s": 38736, "text": " Add Notes" } ]
How To Handle Map Projections Properly In Python | by Abdishakur | Towards Data Science
If you have ever tried overlaying geospatial data and it turns out that they do not align properly, the chances are that you have encountered the annoying coordinate reference system problem. In this tutorial, we first clarify the concept and terminology of the Coordinate Reference System (CRS) followed by a tutorial on how to handle CRS in Python using Geospatial data. Maps are mostly flat and 2-Dimensional, whether they are on paper or screen. However, the earth is not 2-Dimensional. Therefore, maps always lie — sort of. To represent large parts of the earth, you have to make a trade-off between size, angle, shape or directions. There is no way you can get all of them right. So what is the best way to represent the earth on a flat surface? Well, it depends! That is why we use Mercator projection for most of the web maps today. The Mercator projection preserves all angles in their correct shape, and that means if yo measure the angle using this projection, you get the right direction in the real world — useful in map navigation. However, you can not compare different country sizes in web Mercator as it does not preserve size. The African continent is much larger than it appears and also Canada and Rusia take-up a large surface while in reality, they only occupy 5% of the earth surface. There are two closely related concepts here that need clarification. We have the Geographic Coordinate System, which is mostly used for global mapping. Geographic Coordinate systems usually use Latitude and Longitude. In contrast, there are multiply local projections that bring visual distortions, which is called the Projected Coordinate System. Universal Transverse Mercator coordinate system, State Plane and Robinson projections are the most widely used projections. In Geographic Coordinate systems, the unit of measurement is decimal degrees which help locate places on the earth. However, to measure distances in other units like meters or feet, we need projections. With just a basic understanding of Coordinate reference systems and projections, it is straightforward to handle them properly in Python, thanks to Geopandas. Let us read three different datasets to illustrate the importance of handling projections properly. import geopandas as gpdimport matplotlib.pyplot as plt# Read world Countriesworld = gpd.read_file(gpd.datasets.get_path(“naturalearth_lowres”))# Read world citiescities = gpd.read_file( gpd.datasets.get_path(“naturalearth_cities”))# Read Graticules graticules = gpd.read_file( “ne_110m_graticules_10/ne_110m_graticules_10.shp”) To know which Coordinate Reference System the data, Geopandas has .crs() , which can provide information about the data and its reference system. world.crs Let us see and understand the output of this method. <Geographic 2D CRS: EPSG:4326>Name: WGS 84Axis Info [ellipsoidal]:- Lat[north]: Geodetic latitude (degree)- Lon[east]: Geodetic longitude (degree)Area of Use:- name: World- bounds: (-180.0, -90.0, 180.0, 90.0)Datum: World Geodetic System 1984- Ellipsoid: WGS 84- Prime Meridian: Greenwich First, the data is in Geographic 2D CRS with the World Geodetic System (WGS84). We usually use codes for different coordinate systems. The WGS84 has this code EPSG:4326. You can find these codes from EPSG.io website or search it in the Spatial Reference Organization. We need to check if all the dataset has the same CRS before plotting them together. cities.crs == world.crs == graticules.crs This returns True since all the datasets have the same coordinate systems. So let us go ahead and plot the data on a map. fig, ax = plt.subplots(figsize=(12,10))world.plot(ax=ax, color=”lightgray”)cities.plot(ax=ax, color=”black”, markersize=10, marker =”o”)graticules.plot(ax=ax, color=”lightgray”, linewidth=0.5)ax.set(xlabel=”Longitude(Degrees)”, ylabel=”Latitude(Degrees)”, title=”WGS84 Datum (Degrees)”)plt.show() Notice also the x and y-axis which has decimal degrees. To project any Geographic data, Geopandas has also .to_crs() method which takes a projection code. Let us reproject the data. Let us start with Eckert IV Projection. The Eckert IV projection is an equal-area pseudocylindrical map projection. The length of the polar lines is half that of the equator, and lines of longitude are semiellipses, or portions of ellipses. — Wikepedia world_eckert = world.to_crs(“ESRI:54012”)graticules_eckert = graticules.to_crs(“ESRI:54012”) Now, let us print out the CRS of any of these projected datasets. The world Eckert projected dataset has the following parameters. <Projected CRS: ESRI:54012>Name: World_Eckert_IVAxis Info [cartesian]:- E[east]: Easting (metre)- N[north]: Northing (metre)Area of Use:- name: World- bounds: (-180.0, -90.0, 180.0, 90.0)Coordinate Operation:- name: World_Eckert_IV- method: Eckert IVDatum: World Geodetic System 1984- Ellipsoid: WGS 84- Prime Meridian: Greenwich Notice the difference between the world dataset and world Eckert projected dataset. The later one has Projected CRS while the first had a Geographic 2D CRS. The axis of the first dataset was ellipsoidal with degrees as a unit of measurement, while the later one has cartesian coordinates with a metre as a unit of measurement. Now, let us try to plot these two projected datasets and the unprotected city dataset. Since we will plot these maps several times, let us make a function and plot them. def plot_map(gdf1, gdf2, gdf3, name,unit): fig, ax = plt.subplots(figsize=(12,10)) gdf1.plot(ax=ax, color=”lightgray”) gdf2.plot(ax=ax, color=”black”, markersize=10, marker =”o”) gdf3.plot(ax=ax, color=”lightgray”, linewidth=0.5) ax.set(xlabel=”X Coordinate -”+unit, ylabel=”Y Coordinate -” +unit, title=name )plt.show()plot_map(world_eckert, cities, graticules_eckert, "Eckert IV - Cities not Projected", "Metre") Where are the city points dataset? The cities are clustered in one place. Most of the time, the problem of misaligned layers in the GIS world is due to mismatched CRS and projections. We can fix this by also projecting the cities dataset to Eckert IV projection. cities_eckert = cities.to_crs(“ESRI:54012”)plot_map(world_eckert, cities_eckert, graticules_eckert, “Eckert IV — With projected Cities”, “Metre”) Finally, let us bring out another projection and also show the differences between any of the projections out there. Let us go with Robinson projection. world_robinson = world.to_crs(“ESRI:54030”)graticules_robinson = graticules.to_crs(“ESRI:54030”)cities_robinson = cities.to_crs(“ESRI:54030”)plot_map(world_robinson, cities_robinson, graticules_robinson, "Robinson Projection", "Metre") The above two projections might look like the same from the first glance, but they are different. We can look at overlayed maps of the two projections. Any calculations done on different projections result in different results, for example, area size or distance. In this article, we have explained the basic concepts of Geographic Coordinate Reference System (CRS) and Projected Coordinates. We have also seen how to handle them correctly in Python using Geopandas.
[ { "code": null, "e": 545, "s": 172, "text": "If you have ever tried overlaying geospatial data and it turns out that they do not align properly, the chances are that you have encountered the annoying coordinate reference system problem. In this tutorial, we first clarify the concept and terminology of the Coordinate Reference System (CRS) followed by a tutorial on how to handle CRS in Python using Geospatial data." }, { "code": null, "e": 924, "s": 545, "text": "Maps are mostly flat and 2-Dimensional, whether they are on paper or screen. However, the earth is not 2-Dimensional. Therefore, maps always lie — sort of. To represent large parts of the earth, you have to make a trade-off between size, angle, shape or directions. There is no way you can get all of them right. So what is the best way to represent the earth on a flat surface?" }, { "code": null, "e": 1218, "s": 924, "text": "Well, it depends! That is why we use Mercator projection for most of the web maps today. The Mercator projection preserves all angles in their correct shape, and that means if yo measure the angle using this projection, you get the right direction in the real world — useful in map navigation." }, { "code": null, "e": 1480, "s": 1218, "text": "However, you can not compare different country sizes in web Mercator as it does not preserve size. The African continent is much larger than it appears and also Canada and Rusia take-up a large surface while in reality, they only occupy 5% of the earth surface." }, { "code": null, "e": 1952, "s": 1480, "text": "There are two closely related concepts here that need clarification. We have the Geographic Coordinate System, which is mostly used for global mapping. Geographic Coordinate systems usually use Latitude and Longitude. In contrast, there are multiply local projections that bring visual distortions, which is called the Projected Coordinate System. Universal Transverse Mercator coordinate system, State Plane and Robinson projections are the most widely used projections." }, { "code": null, "e": 2155, "s": 1952, "text": "In Geographic Coordinate systems, the unit of measurement is decimal degrees which help locate places on the earth. However, to measure distances in other units like meters or feet, we need projections." }, { "code": null, "e": 2414, "s": 2155, "text": "With just a basic understanding of Coordinate reference systems and projections, it is straightforward to handle them properly in Python, thanks to Geopandas. Let us read three different datasets to illustrate the importance of handling projections properly." }, { "code": null, "e": 2742, "s": 2414, "text": "import geopandas as gpdimport matplotlib.pyplot as plt# Read world Countriesworld = gpd.read_file(gpd.datasets.get_path(“naturalearth_lowres”))# Read world citiescities = gpd.read_file( gpd.datasets.get_path(“naturalearth_cities”))# Read Graticules graticules = gpd.read_file( “ne_110m_graticules_10/ne_110m_graticules_10.shp”)" }, { "code": null, "e": 2888, "s": 2742, "text": "To know which Coordinate Reference System the data, Geopandas has .crs() , which can provide information about the data and its reference system." }, { "code": null, "e": 2898, "s": 2888, "text": "world.crs" }, { "code": null, "e": 2951, "s": 2898, "text": "Let us see and understand the output of this method." }, { "code": null, "e": 3240, "s": 2951, "text": "<Geographic 2D CRS: EPSG:4326>Name: WGS 84Axis Info [ellipsoidal]:- Lat[north]: Geodetic latitude (degree)- Lon[east]: Geodetic longitude (degree)Area of Use:- name: World- bounds: (-180.0, -90.0, 180.0, 90.0)Datum: World Geodetic System 1984- Ellipsoid: WGS 84- Prime Meridian: Greenwich" }, { "code": null, "e": 3508, "s": 3240, "text": "First, the data is in Geographic 2D CRS with the World Geodetic System (WGS84). We usually use codes for different coordinate systems. The WGS84 has this code EPSG:4326. You can find these codes from EPSG.io website or search it in the Spatial Reference Organization." }, { "code": null, "e": 3592, "s": 3508, "text": "We need to check if all the dataset has the same CRS before plotting them together." }, { "code": null, "e": 3634, "s": 3592, "text": "cities.crs == world.crs == graticules.crs" }, { "code": null, "e": 3756, "s": 3634, "text": "This returns True since all the datasets have the same coordinate systems. So let us go ahead and plot the data on a map." }, { "code": null, "e": 4053, "s": 3756, "text": "fig, ax = plt.subplots(figsize=(12,10))world.plot(ax=ax, color=”lightgray”)cities.plot(ax=ax, color=”black”, markersize=10, marker =”o”)graticules.plot(ax=ax, color=”lightgray”, linewidth=0.5)ax.set(xlabel=”Longitude(Degrees)”, ylabel=”Latitude(Degrees)”, title=”WGS84 Datum (Degrees)”)plt.show()" }, { "code": null, "e": 4109, "s": 4053, "text": "Notice also the x and y-axis which has decimal degrees." }, { "code": null, "e": 4275, "s": 4109, "text": "To project any Geographic data, Geopandas has also .to_crs() method which takes a projection code. Let us reproject the data. Let us start with Eckert IV Projection." }, { "code": null, "e": 4488, "s": 4275, "text": "The Eckert IV projection is an equal-area pseudocylindrical map projection. The length of the polar lines is half that of the equator, and lines of longitude are semiellipses, or portions of ellipses. — Wikepedia" }, { "code": null, "e": 4581, "s": 4488, "text": "world_eckert = world.to_crs(“ESRI:54012”)graticules_eckert = graticules.to_crs(“ESRI:54012”)" }, { "code": null, "e": 4712, "s": 4581, "text": "Now, let us print out the CRS of any of these projected datasets. The world Eckert projected dataset has the following parameters." }, { "code": null, "e": 5042, "s": 4712, "text": "<Projected CRS: ESRI:54012>Name: World_Eckert_IVAxis Info [cartesian]:- E[east]: Easting (metre)- N[north]: Northing (metre)Area of Use:- name: World- bounds: (-180.0, -90.0, 180.0, 90.0)Coordinate Operation:- name: World_Eckert_IV- method: Eckert IVDatum: World Geodetic System 1984- Ellipsoid: WGS 84- Prime Meridian: Greenwich" }, { "code": null, "e": 5369, "s": 5042, "text": "Notice the difference between the world dataset and world Eckert projected dataset. The later one has Projected CRS while the first had a Geographic 2D CRS. The axis of the first dataset was ellipsoidal with degrees as a unit of measurement, while the later one has cartesian coordinates with a metre as a unit of measurement." }, { "code": null, "e": 5539, "s": 5369, "text": "Now, let us try to plot these two projected datasets and the unprotected city dataset. Since we will plot these maps several times, let us make a function and plot them." }, { "code": null, "e": 6007, "s": 5539, "text": "def plot_map(gdf1, gdf2, gdf3, name,unit): fig, ax = plt.subplots(figsize=(12,10)) gdf1.plot(ax=ax, color=”lightgray”) gdf2.plot(ax=ax, color=”black”, markersize=10, marker =”o”) gdf3.plot(ax=ax, color=”lightgray”, linewidth=0.5) ax.set(xlabel=”X Coordinate -”+unit, ylabel=”Y Coordinate -” +unit, title=name )plt.show()plot_map(world_eckert, cities, graticules_eckert, \"Eckert IV - Cities not Projected\", \"Metre\")" }, { "code": null, "e": 6042, "s": 6007, "text": "Where are the city points dataset?" }, { "code": null, "e": 6270, "s": 6042, "text": "The cities are clustered in one place. Most of the time, the problem of misaligned layers in the GIS world is due to mismatched CRS and projections. We can fix this by also projecting the cities dataset to Eckert IV projection." }, { "code": null, "e": 6416, "s": 6270, "text": "cities_eckert = cities.to_crs(“ESRI:54012”)plot_map(world_eckert, cities_eckert, graticules_eckert, “Eckert IV — With projected Cities”, “Metre”)" }, { "code": null, "e": 6569, "s": 6416, "text": "Finally, let us bring out another projection and also show the differences between any of the projections out there. Let us go with Robinson projection." }, { "code": null, "e": 6805, "s": 6569, "text": "world_robinson = world.to_crs(“ESRI:54030”)graticules_robinson = graticules.to_crs(“ESRI:54030”)cities_robinson = cities.to_crs(“ESRI:54030”)plot_map(world_robinson, cities_robinson, graticules_robinson, \"Robinson Projection\", \"Metre\")" }, { "code": null, "e": 6957, "s": 6805, "text": "The above two projections might look like the same from the first glance, but they are different. We can look at overlayed maps of the two projections." }, { "code": null, "e": 7069, "s": 6957, "text": "Any calculations done on different projections result in different results, for example, area size or distance." } ]
How to get currently running function name using JavaScript ? - GeeksforGeeks
17 Dec, 2019 Given a function and the task is to get the name of function that is currently running using JavaScript. Approach 1: Using arguments.callee method: It refers to the currently executing function inside the function body of that function. In this method, we use arguments.callee to refer to the name of the function. So we define a new variable as arguments.callee.toString(). Then we use (variable_name).substr to get the function and then we display it as an alert.Syntax:arguments.callee.toString()You may have to parse the name though, as it will probably include some extra junk.Example 1: This example display currently running function using arguments.callee method.<!DOCTYPE HTML><html> <head> <title> How to get currently running function name using JavaScript ? </title> </head> <body style = "text-align:center;"> <h1 style = "color:green;" > GeeksForGeeks </h1> <script> function GFGs() { var me = arguments.callee.toString(); me = me.substr('function '.length); me = me.substr(0, me.indexOf('(')); alert(me); } GFGs(); </script> </body> </html>Output: Syntax: arguments.callee.toString() You may have to parse the name though, as it will probably include some extra junk. Example 1: This example display currently running function using arguments.callee method. <!DOCTYPE HTML><html> <head> <title> How to get currently running function name using JavaScript ? </title> </head> <body style = "text-align:center;"> <h1 style = "color:green;" > GeeksForGeeks </h1> <script> function GFGs() { var me = arguments.callee.toString(); me = me.substr('function '.length); me = me.substr(0, me.indexOf('(')); alert(me); } GFGs(); </script> </body> </html> Output: Approach 2: With the help of console.log method, we define a new function which returns the name of the function and call it the present function.Syntax:function getFuncName() { return getFuncName.caller.name } function teddy() { console.log(getFuncName()) } teddy()Example 2: This example display currently running function using console.log method.<!DOCTYPE html><html> <head> <title> How to get currently running function name using JavaScript ? </title> </head> <body style = "text-align:center;"> <h1 style = "color:green;" > GeeksForGeeks </h1> <script> function getFuncName() { return getFuncName.caller.name } function teddy() { console.log(getFuncName()) } teddy() </script> </body> </html>Output: Syntax: function getFuncName() { return getFuncName.caller.name } function teddy() { console.log(getFuncName()) } teddy() Example 2: This example display currently running function using console.log method. <!DOCTYPE html><html> <head> <title> How to get currently running function name using JavaScript ? </title> </head> <body style = "text-align:center;"> <h1 style = "color:green;" > GeeksForGeeks </h1> <script> function getFuncName() { return getFuncName.caller.name } function teddy() { console.log(getFuncName()) } teddy() </script> </body> </html> Output: jQuery-Misc Picked JQuery Web Technologies Web technologies Questions Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Form validation using jQuery How to Dynamically Add/Remove Table Rows using jQuery ? Scroll to the top of the page using JavaScript/jQuery How to get the ID of the clicked button using JavaScript / jQuery ? jQuery | children() with Examples Top 10 Front End Developer Skills That You Need in 2022 Installation of Node.js on Linux Top 10 Projects For Beginners To Practice HTML and CSS Skills How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 24712, "s": 24684, "text": "\n17 Dec, 2019" }, { "code": null, "e": 24817, "s": 24712, "text": "Given a function and the task is to get the name of function that is currently running using JavaScript." }, { "code": null, "e": 25939, "s": 24817, "text": "Approach 1: Using arguments.callee method: It refers to the currently executing function inside the function body of that function. In this method, we use arguments.callee to refer to the name of the function. So we define a new variable as arguments.callee.toString(). Then we use (variable_name).substr to get the function and then we display it as an alert.Syntax:arguments.callee.toString()You may have to parse the name though, as it will probably include some extra junk.Example 1: This example display currently running function using arguments.callee method.<!DOCTYPE HTML><html> <head> <title> How to get currently running function name using JavaScript ? </title> </head> <body style = \"text-align:center;\"> <h1 style = \"color:green;\" > GeeksForGeeks </h1> <script> function GFGs() { var me = arguments.callee.toString(); me = me.substr('function '.length); me = me.substr(0, me.indexOf('(')); alert(me); } GFGs(); </script> </body> </html>Output:" }, { "code": null, "e": 25947, "s": 25939, "text": "Syntax:" }, { "code": null, "e": 25975, "s": 25947, "text": "arguments.callee.toString()" }, { "code": null, "e": 26059, "s": 25975, "text": "You may have to parse the name though, as it will probably include some extra junk." }, { "code": null, "e": 26149, "s": 26059, "text": "Example 1: This example display currently running function using arguments.callee method." }, { "code": "<!DOCTYPE HTML><html> <head> <title> How to get currently running function name using JavaScript ? </title> </head> <body style = \"text-align:center;\"> <h1 style = \"color:green;\" > GeeksForGeeks </h1> <script> function GFGs() { var me = arguments.callee.toString(); me = me.substr('function '.length); me = me.substr(0, me.indexOf('(')); alert(me); } GFGs(); </script> </body> </html>", "e": 26698, "s": 26149, "text": null }, { "code": null, "e": 26706, "s": 26698, "text": "Output:" }, { "code": null, "e": 27574, "s": 26706, "text": "Approach 2: With the help of console.log method, we define a new function which returns the name of the function and call it the present function.Syntax:function getFuncName() {\n return getFuncName.caller.name\n}\nfunction teddy() { \n console.log(getFuncName())\n}\nteddy()Example 2: This example display currently running function using console.log method.<!DOCTYPE html><html> <head> <title> How to get currently running function name using JavaScript ? </title> </head> <body style = \"text-align:center;\"> <h1 style = \"color:green;\" > GeeksForGeeks </h1> <script> function getFuncName() { return getFuncName.caller.name } function teddy() { console.log(getFuncName()) } teddy() </script> </body> </html>Output:" }, { "code": null, "e": 27582, "s": 27574, "text": "Syntax:" }, { "code": null, "e": 27705, "s": 27582, "text": "function getFuncName() {\n return getFuncName.caller.name\n}\nfunction teddy() { \n console.log(getFuncName())\n}\nteddy()" }, { "code": null, "e": 27790, "s": 27705, "text": "Example 2: This example display currently running function using console.log method." }, { "code": "<!DOCTYPE html><html> <head> <title> How to get currently running function name using JavaScript ? </title> </head> <body style = \"text-align:center;\"> <h1 style = \"color:green;\" > GeeksForGeeks </h1> <script> function getFuncName() { return getFuncName.caller.name } function teddy() { console.log(getFuncName()) } teddy() </script> </body> </html>", "e": 28292, "s": 27790, "text": null }, { "code": null, "e": 28300, "s": 28292, "text": "Output:" }, { "code": null, "e": 28312, "s": 28300, "text": "jQuery-Misc" }, { "code": null, "e": 28319, "s": 28312, "text": "Picked" }, { "code": null, "e": 28326, "s": 28319, "text": "JQuery" }, { "code": null, "e": 28343, "s": 28326, "text": "Web Technologies" }, { "code": null, "e": 28370, "s": 28343, "text": "Web technologies Questions" }, { "code": null, "e": 28468, "s": 28370, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28477, "s": 28468, "text": "Comments" }, { "code": null, "e": 28490, "s": 28477, "text": "Old Comments" }, { "code": null, "e": 28519, "s": 28490, "text": "Form validation using jQuery" }, { "code": null, "e": 28575, "s": 28519, "text": "How to Dynamically Add/Remove Table Rows using jQuery ?" }, { "code": null, "e": 28629, "s": 28575, "text": "Scroll to the top of the page using JavaScript/jQuery" }, { "code": null, "e": 28697, "s": 28629, "text": "How to get the ID of the clicked button using JavaScript / jQuery ?" }, { "code": null, "e": 28731, "s": 28697, "text": "jQuery | children() with Examples" }, { "code": null, "e": 28787, "s": 28731, "text": "Top 10 Front End Developer Skills That You Need in 2022" }, { "code": null, "e": 28820, "s": 28787, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 28882, "s": 28820, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 28925, "s": 28882, "text": "How to fetch data from an API in ReactJS ?" } ]
How to install Maven on Windows10 - onlinetutorialspoint
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, I am going to show you how to install Maven on Windows10 operating system. Download the Maven latest version from maven downloads. For me it is apache-maven-3.5.2-bin.zip. Extract the downloaded maven .zip file at your preferred location and proceed the below steps. After extracting the apache-maven-3.5.2-bin.zip file, folder consists like below. I have extracted in E:\Softwares\apache-maven-3.5.2 Search for Advanced System Settings in the Search box like below: by selecting the above Advanced System Settings, you can see the below System Properties window where you can find Environment Variables button. Click on Environment Variables > There you can find System variables section. Select the Path variable and click on Edit button. Now opens another window like below: This is a new widow introduced from Windows10. Here click on the new button and add environment variable E:\Softwares\apache-maven-3.5.2\bin (your maven folder location till \bin) like below. And Click on OK. You can check your setup, by firing the below command on your windows command prompt. Type mvn –version and Enter: It will give installed maven version with JAVA_HOME like below. C:\>mvn -version Apache Maven 3.5.2 (138edd61fd100ec658bfa2d307c43b76940a5d7d; 2017-10-18T13:28:13+05:30) Maven home: E:\Softwares\apache-maven-3.5.2\bin\.. Java version: 1.8.0_151, vendor: Oracle Corporation Java home: C:\Program Files\Java\jre1.8.0_151 Default locale: en_US, platform encoding: Cp1252 OS name: "windows 10", version: "10.0", arch: "amd64", family: "windows" Happy Learning 🙂 How to Install Ant on Windows 10 How to install Gradle on Windows 10 How to install Android Studio on Windows 10 How to Install Java8 on Windows 10 Install Docker Desktop on Windows 10 How to set JAVA_HOME on Linux How to install Android SDK Windows 10 Manual Process How to Install Git windows 10 Operating System How to install AWS CLI on Windows 10 How to install Docker Toolbox on Windows 10 How to install RabbitMQ on Windows 10 How to install Maven on Ubuntu 14.x How to install Maven on windows 7 command line How to add OJDBC jar to Maven Repository Java 8 – How to set JAVA_HOME on Windows10 How to Install Ant on Windows 10 How to install Gradle on Windows 10 How to install Android Studio on Windows 10 How to Install Java8 on Windows 10 Install Docker Desktop on Windows 10 How to set JAVA_HOME on Linux How to install Android SDK Windows 10 Manual Process How to Install Git windows 10 Operating System How to install AWS CLI on Windows 10 How to install Docker Toolbox on Windows 10 How to install RabbitMQ on Windows 10 How to install Maven on Ubuntu 14.x How to install Maven on windows 7 command line How to add OJDBC jar to Maven Repository Java 8 – How to set JAVA_HOME on Windows10 Maven user February 22, 2021 at 5:57 am - Reply Thank you. Clear explanation 🙂 hetalben thanki April 6, 2021 at 9:54 pm - Reply thank you Maven user February 22, 2021 at 5:57 am - Reply Thank you. Clear explanation 🙂 Thank you. Clear explanation 🙂 hetalben thanki April 6, 2021 at 9:54 pm - Reply
[ { "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": 491, "s": 398, "text": "In this tutorial, I am going to show you how to install Maven on Windows10 operating system." }, { "code": null, "e": 588, "s": 491, "text": "Download the Maven latest version from maven downloads. For me it is apache-maven-3.5.2-bin.zip." }, { "code": null, "e": 683, "s": 588, "text": "Extract the downloaded maven .zip file at your preferred location and proceed the below steps." }, { "code": null, "e": 817, "s": 683, "text": "After extracting the apache-maven-3.5.2-bin.zip file, folder consists like below. I have extracted in E:\\Softwares\\apache-maven-3.5.2" }, { "code": null, "e": 883, "s": 817, "text": "Search for Advanced System Settings in the Search box like below:" }, { "code": null, "e": 1028, "s": 883, "text": "by selecting the above Advanced System Settings, you can see the below System Properties window where you can find Environment Variables button." }, { "code": null, "e": 1106, "s": 1028, "text": "Click on Environment Variables > There you can find System variables section." }, { "code": null, "e": 1241, "s": 1106, "text": "Select the Path variable and click on Edit button. Now opens another window like below: This is a new widow introduced from Windows10." }, { "code": null, "e": 1386, "s": 1241, "text": "Here click on the new button and add environment variable E:\\Softwares\\apache-maven-3.5.2\\bin (your maven folder location till \\bin) like below." }, { "code": null, "e": 1403, "s": 1386, "text": "And Click on OK." }, { "code": null, "e": 1489, "s": 1403, "text": "You can check your setup, by firing the below command on your windows command prompt." }, { "code": null, "e": 1582, "s": 1489, "text": "Type mvn –version and Enter: It will give installed maven version with JAVA_HOME like below." }, { "code": null, "e": 1959, "s": 1582, "text": "C:\\>mvn -version\nApache Maven 3.5.2 (138edd61fd100ec658bfa2d307c43b76940a5d7d; 2017-10-18T13:28:13+05:30)\nMaven home: E:\\Softwares\\apache-maven-3.5.2\\bin\\..\nJava version: 1.8.0_151, vendor: Oracle Corporation\nJava home: C:\\Program Files\\Java\\jre1.8.0_151\nDefault locale: en_US, platform encoding: Cp1252\nOS name: \"windows 10\", version: \"10.0\", arch: \"amd64\", family: \"windows\"" }, { "code": null, "e": 1976, "s": 1959, "text": "Happy Learning 🙂" }, { "code": null, "e": 2579, "s": 1976, "text": "\nHow to Install Ant on Windows 10\nHow to install Gradle on Windows 10\nHow to install Android Studio on Windows 10\nHow to Install Java8 on Windows 10\nInstall Docker Desktop on Windows 10\nHow to set JAVA_HOME on Linux\nHow to install Android SDK Windows 10 Manual Process\nHow to Install Git windows 10 Operating System\nHow to install AWS CLI on Windows 10\nHow to install Docker Toolbox on Windows 10\nHow to install RabbitMQ on Windows 10\nHow to install Maven on Ubuntu 14.x\nHow to install Maven on windows 7 command line\nHow to add OJDBC jar to Maven Repository\nJava 8 – How to set JAVA_HOME on Windows10\n" }, { "code": null, "e": 2612, "s": 2579, "text": "How to Install Ant on Windows 10" }, { "code": null, "e": 2648, "s": 2612, "text": "How to install Gradle on Windows 10" }, { "code": null, "e": 2692, "s": 2648, "text": "How to install Android Studio on Windows 10" }, { "code": null, "e": 2727, "s": 2692, "text": "How to Install Java8 on Windows 10" }, { "code": null, "e": 2764, "s": 2727, "text": "Install Docker Desktop on Windows 10" }, { "code": null, "e": 2794, "s": 2764, "text": "How to set JAVA_HOME on Linux" }, { "code": null, "e": 2847, "s": 2794, "text": "How to install Android SDK Windows 10 Manual Process" }, { "code": null, "e": 2894, "s": 2847, "text": "How to Install Git windows 10 Operating System" }, { "code": null, "e": 2931, "s": 2894, "text": "How to install AWS CLI on Windows 10" }, { "code": null, "e": 2975, "s": 2931, "text": "How to install Docker Toolbox on Windows 10" }, { "code": null, "e": 3013, "s": 2975, "text": "How to install RabbitMQ on Windows 10" }, { "code": null, "e": 3049, "s": 3013, "text": "How to install Maven on Ubuntu 14.x" }, { "code": null, "e": 3096, "s": 3049, "text": "How to install Maven on windows 7 command line" }, { "code": null, "e": 3137, "s": 3096, "text": "How to add OJDBC jar to Maven Repository" }, { "code": null, "e": 3180, "s": 3137, "text": "Java 8 – How to set JAVA_HOME on Windows10" }, { "code": null, "e": 3342, "s": 3180, "text": "\n\n\n\n\n\nMaven user\nFebruary 22, 2021 at 5:57 am - Reply \n\nThank you. Clear explanation 🙂\n\n\n\n\n\n\n\n\n\nhetalben thanki\nApril 6, 2021 at 9:54 pm - Reply \n\nthank you\n\n\n\n\n" }, { "code": null, "e": 3432, "s": 3342, "text": "\n\n\n\n\nMaven user\nFebruary 22, 2021 at 5:57 am - Reply \n\nThank you. Clear explanation 🙂\n\n\n\n" }, { "code": null, "e": 3463, "s": 3432, "text": "Thank you. Clear explanation 🙂" } ]
Type Hinting in PHP 7
PHP 7 uses two types of hinting in scalar type declaration and return type declaration − Weak type hinting Strict type hinting By default, PHP 7 works in weak type checking mode.Weak type checking will not give any error or fatal error.When a type declaration mismatch occurs it will simply execute the code without throwing any error. By using strict_typesdeclare(), we can control the weak type checking. declare(strict_types=0); //weak type-checking; we should set the strict value = 0 Live Demo <?php $x=10; // integer variable x =10 value $y=20.20; // using floating point number y=20.20 value function add(int $x, int $y){ return $x + $y; } echo add($x, $y); ?> The code will produce the following output − 30 In the above example, we are not using a strict value for a parameter. We used two integer variables, x, and y. For x=10 and y is using the floating number 20.20, but y will not produce any error; it will simply give the output integer value 30. Live Demo <?php function returnadd(int ...$integers){ return array_sum($integers); } var_dump(returnadd(2, '3', 4.1)); ?> The output for the above program will be − int(9) Strict type hinting will give a Fatal Error when a type declaration mismatch occurs. We can say that strict type hinting accepts a variable of the exact type of the type declaration, else it will throw the TypeError mismatch. In the strict type hinting, the first statement in a file must be declared (strict_types=1), otherwise, it will produce a compiler error. It does not affect the other included files which are not specified in files, which means it only affects the specific file it is used. The strict type hinting directive is completely compile-time and cannot be controlled at runtime. Live Demo <?php declare (strict_types=1); function returnadd(float $x , float $y){ return $x+$y; } var_dump(returnadd(3.1,2.1)); //output float(5.2) var_dump(returnadd(3, "2 days")); //fatal error ?> The above strict type hinting program will be − float(5.2) Fatal error: Uncaught TypeError: Argument 2 passed to returnadd() must be of the type float, string given, called in C:\xampp\htdocs\gud.php on line 7 and defined in C:\xampp\htdocs\gud.php:3 Stack trace: #0 C:\xampp\htdocs\gud.php(7): returnadd(3, '2 days') #1 {main} thrown in C:\xampp\htdocs\gud.php on line 3 Live Demo <?php declare(strict_types=1); // strict mode checking $x='1'; // string $y=20; //integer number function add(int $x, int $y){ return $x + $y; } var_dump(add($x, $y)); ?> It will produce the output “fatal error” In the above strict type declaration example, if we declare the strict_type value is 1, the code will give the output “Fatal error: Uncaught TypeError: Argument 1 passed to add() must be of the type int, a string is given”.
[ { "code": null, "e": 1151, "s": 1062, "text": "PHP 7 uses two types of hinting in scalar type declaration and return type declaration −" }, { "code": null, "e": 1169, "s": 1151, "text": "Weak type hinting" }, { "code": null, "e": 1189, "s": 1169, "text": "Strict type hinting" }, { "code": null, "e": 1398, "s": 1189, "text": "By default, PHP 7 works in weak type checking mode.Weak type checking will not give any error or fatal error.When a type declaration mismatch occurs it will simply execute the code without throwing any error." }, { "code": null, "e": 1469, "s": 1398, "text": "By using strict_typesdeclare(), we can control the weak type checking." }, { "code": null, "e": 1551, "s": 1469, "text": "declare(strict_types=0);\n//weak type-checking; we should set the strict value = 0" }, { "code": null, "e": 1561, "s": 1551, "text": "Live Demo" }, { "code": null, "e": 1751, "s": 1561, "text": "<?php\n $x=10; // integer variable x =10 value\n $y=20.20; // using floating point number y=20.20 value\n function add(int $x, int $y){\n return $x + $y;\n }\n echo add($x, $y);\n?>" }, { "code": null, "e": 1796, "s": 1751, "text": "The code will produce the following output −" }, { "code": null, "e": 1799, "s": 1796, "text": "30" }, { "code": null, "e": 2045, "s": 1799, "text": "In the above example, we are not using a strict value for a parameter. We used two integer variables, x, and y. For x=10 and y is using the floating number 20.20, but y will not produce any error; it will simply give the output integer value 30." }, { "code": null, "e": 2055, "s": 2045, "text": "Live Demo" }, { "code": null, "e": 2182, "s": 2055, "text": "<?php\n function returnadd(int ...$integers){\n return array_sum($integers);\n }\n var_dump(returnadd(2, '3', 4.1));\n?>" }, { "code": null, "e": 2225, "s": 2182, "text": "The output for the above program will be −" }, { "code": null, "e": 2232, "s": 2225, "text": "int(9)" }, { "code": null, "e": 2458, "s": 2232, "text": "Strict type hinting will give a Fatal Error when a type declaration mismatch occurs. We can say that strict type hinting accepts a variable of the exact type of the type declaration, else it will throw the TypeError mismatch." }, { "code": null, "e": 2732, "s": 2458, "text": "In the strict type hinting, the first statement in a file must be declared (strict_types=1), otherwise, it will produce a compiler error. It does not affect the other included files which are not specified in files, which means it only affects the specific file it is used." }, { "code": null, "e": 2830, "s": 2732, "text": "The strict type hinting directive is completely compile-time and cannot be controlled at runtime." }, { "code": null, "e": 2840, "s": 2830, "text": "Live Demo" }, { "code": null, "e": 3051, "s": 2840, "text": "<?php\n declare (strict_types=1);\n function returnadd(float $x , float $y){\n return $x+$y;\n }\n var_dump(returnadd(3.1,2.1)); //output float(5.2)\n var_dump(returnadd(3, \"2 days\")); //fatal error\n?>" }, { "code": null, "e": 3099, "s": 3051, "text": "The above strict type hinting program will be −" }, { "code": null, "e": 3423, "s": 3099, "text": "float(5.2)\nFatal error: Uncaught TypeError: Argument 2 passed to returnadd() must be of the type float, string given, called in C:\\xampp\\htdocs\\gud.php on line 7 and defined in C:\\xampp\\htdocs\\gud.php:3 Stack trace: #0 C:\\xampp\\htdocs\\gud.php(7): returnadd(3, '2 days') #1 {main} thrown in C:\\xampp\\htdocs\\gud.php on line 3" }, { "code": null, "e": 3433, "s": 3423, "text": "Live Demo" }, { "code": null, "e": 3628, "s": 3433, "text": "<?php\n declare(strict_types=1); // strict mode checking\n $x='1'; // string\n $y=20; //integer number\n function add(int $x, int $y){\n return $x + $y;\n }\n var_dump(add($x, $y));\n?>" }, { "code": null, "e": 3669, "s": 3628, "text": "It will produce the output “fatal error”" }, { "code": null, "e": 3893, "s": 3669, "text": "In the above strict type declaration example, if we declare the strict_type value is 1, the code will give the output “Fatal error: Uncaught TypeError: Argument 1 passed to add() must be of the type int, a string is given”." } ]
Gamma Function — Intuition, Derivation, and Examples | by Aerin Kim | Towards Data Science
Why should I care? Many probability distributions are defined by using the gamma function — such as Gamma distribution, Beta distribution, Dirichlet distribution, Chi-squared distribution, and Student’s t-distribution, etc.For data scientists, machine learning engineers, researchers, the Gamma function is probably one of the most widely used functions because it is employed in many distributions. These distributions are then used for Bayesian inference, stochastic processes (such as queueing models), generative statistical models (such as Latent Dirichlet Allocation), and variational inference. Therefore, if you understand the Gamma function well, you will have a better understanding of a lot of applications in which it appears! Because we want to generalize the factorial! The factorial function is defined only for discrete points (for positive integers — black dots in the graph above), but we wanted to connect the black dots. We want to extend the factorial function to all complex numbers. The simple formula for the factorial, x! = 1 * 2 * ... * x, cannot be used directly for fractional values because it is only valid when x is a whole number. So mathematicians had been searching for... “What kind of functions will connect these dots smoothly and give us factorials of all real values?” However, they couldn’t find *finite* combinations of sums, products, powers, exponential, or logarithms that could express x! for real numbers until... The formula above is used to find the value of the Gamma function for any real value of z. Let’s say you want to calculate Γ(4.8). How would you solve the integration above? Can you calculate Γ(4.8) by hand? Maybe using the integral by parts? Try it and let me know if you find an interesting way to do so! For me (and many others so far), there is no quick and easy way to evaluate the Gamma function of fractions manually. (If you are interested in solving it by hand, here is a good starting point.) Ok, then, forget about doing it analytically. Can you implement this integral from 0 to infinity — adding the term infinite times programmatically? You can implement this in a few ways. Two of the most often used implementations are Stirling’s approximation and Lanczos approximation. For implementation addicts: the codes of Gamma function (mostly Lanczos approximation) in 60+ different language - C, C++, C#, python, java, etc. Let’s calculate Γ(4.8) using a calculator that is implemented already. We got 17.837. 17.837 falls between 3!(= Γ(4) = 6) and 4!(= Γ(5) = 24) — as we expected. (When z is a natural number, Γ(z) =(z-1)! We are going to prove this shortly.) Unlike the factorial, which takes only the positive integers, we can input any real/complex number into z, including negative numbers. The Gamma function connects the black dots and draws the curve nicely. Confusion-buster: We are integrating over x (NOT z) from 0 to infinity. • x is a helper variable that is being integrated out.• We are NOT plugging 4.8 into x. We are plugging 4.8 into z. If you take a look at the Gamma function, you will notice two things. First, it is definitely an increasing function, with respect to z. Second, when z is a natural number, Γ(z+1) = z! (I promise we’re going to prove this soon!) Therefore, we can expect the Gamma function to connect the factorial. How did the Gamma function end up with current terms x^z and e^-x? I don’t know exactly what Euler’s thought process was, but he is the one who discovered the natural number e, so he must have experimented a lot with multiplying e with other functions to find the current form. As x goes to infinity ∞, the first term (x^z) also goes to infinity ∞, but the second term (e^-x) goes to zero. Then, will the Gamma function converge to finite values? We can rigorously show that it converges using L’Hôpital’s rule. But we can also see its convergence in an effortless way. If you think about it, we are integrating a product of x^z — a polynomially increasing function — and e^-x — an exponentially decreasing function. Because the value of e^-x decreases much more quickly than that of x^z, the Gamma function is pretty likely to converge and have finite values. Let’s plot each graph, since seeing is believing. Let’s look at the case of Γ(4.8). Python code is used to generate the beautiful plots above. Plot it yourself and see how z changes the shape of the Gamma function! ######################### f(x) = exp(-x) graph #########################import matplotlib.pyplot as pltimport numpy as np# Create x and yx = np.linspace(-2, 20, 100)y = np.exp(-x)# Create the plotfig, ax = plt.subplots()plt.plot(x, y, label='f(x) = exp(-x)', linewidth=3, color='palegreen')# Make the x=0, y=0 thickerax.set_aspect('equal')ax.grid(True, which='both')ax.axhline(y=0, color='k')ax.axvline(x=0, color='k')# Add a titleplt.title('f(x) = exp(-x)', fontsize=20)# Add X and y Labelplt.xlabel('x', fontsize=16)plt.ylabel('f(x)', fontsize=16)# Add a gridplt.grid(alpha=.4, linestyle='--')# Show the plotplt.show()##################### f(x) = x^z graph #####################import matplotlib.pyplot as pltimport numpy as np# Create x and yx = np.linspace(0, 2, 100)y1 = x**1.3y2 = x**2.5 y3 = x**3.8# Create the plotfig, ax = plt.subplots()plt.plot(x, y1, label='f(x) = x^1.3', linewidth=3, color='palegreen')plt.plot(x, y2, label='f(x) = x^2.5', linewidth=3, color='yellowgreen')plt.plot(x, y3, label='f(x) = x^3.8', linewidth=3, color='olivedrab')# Make the x=0, y=0 thickerax.set_aspect('equal')ax.grid(True, which='both')ax.axhline(y=0, color='k')ax.axvline(x=0, color='k')# Add a titleplt.title('f(x) = x^z', fontsize=20)# Add X and y Labelplt.xlabel('x', fontsize=16)plt.ylabel('f(x)', fontsize=16)# Add a gridplt.grid(alpha=.4, linestyle='--')# Add a Legendplt.legend(bbox_to_anchor=(1, 1), loc='best', borderaxespad=1, fontsize=12)# Show the plotplt.show()################################ f(x) = x^(3.8)*e^(-x) graph ################################import matplotlib.pyplot as pltimport numpy as np# Create x and yx = np.linspace(0, 20, 100)y = x**3.8 * np.exp(-x)# Create the plotfig, ax = plt.subplots()plt.plot(x, y, label='f(x) = x^(3.8) * np.exp(-x)', linewidth=3, color='palegreen')ax.fill_between(x, 0, y, color='yellowgreen')# Make the x=0, y=0 thickerax.set_aspect('equal')ax.grid(True, which='both')ax.axhline(y=0, color='k')ax.axvline(x=0, color='k')# Add a titleplt.title('f(x) = x^(3.8)*e^(-x) ', fontsize=20)# Add X and y Labelplt.xlabel('x', fontsize=16)plt.ylabel('f(x)' ,fontsize=16)# Add a gridplt.grid(alpha=.4, linestyle='--')# Add a Legendplt.legend(bbox_to_anchor=(1, 1), loc='upper right', borderaxespad=1, fontsize=12)# Show the plotplt.show() The code in ipynb: https://github.com/aerinkim/TowardsDataScience/blob/master/Gamma%20Function.ipynb If you take one thing away from this post, it should be this section. Property 1.given z > 1Γ(z) = (z-1) * Γ(z-1)or you can write it asΓ(z+1) = z * Γ(z) Let’s prove it using integration by parts and the definition of Gamma function. Beautifully proved! Property 2. If n is a positive integerΓ(n) = (n-1)! Let’s prove it using the property 1. What is Γ(1)? Therefore, Γ(n) = (n-1)! You might have also seen the expression Γ(n+1) = n! instead of Γ(n) = (n-1)!.This is just to make the right hand side n!, instead of (n-1)! All we did was to shift n by 1. A quick recap about the Gamma “distribution” (not the Gamma “function”!): Gamma Distribution Intuition and Derivation. Here goes the proof: For the proof addicts: Let’s prove the red arrow above. We’ll use integration by substitution. Beautifully proved again! A few things to note: How old is the Gamma function? How old is the Gamma function? Pretty old. About 300 yrs. (Are you working on something today that will be used 300 years later?;) An interesting side note: Euler became blind at age 64 however he produced almost half of his total works after losing his sight. 2. Some interesting values at points: Γ(1/2) = sqrt(π)Many interesting ways to show this:https://math.stackexchange.com/questions/215352/why-is-gamma-left-frac12-right-sqrt-piΓ(-1/2) = -2 * sqrt(π)Γ(-1) = Γ(-2) = Γ(-3) = infinity ∞ Can you prove these? 3. Here is a quick look at the graph of the Gamma function in real numbers. The Gamma function, Γ(z) in blue, plotted along with Γ(z) + sin(πz) in green. (Notice the intersection at positive integers because sin(πz) is zero!) Both are valid analytic continuations of the factorials to the non-integers. 4. Gamma function also appears in the general formula for the volume of an n-sphere.
[ { "code": null, "e": 191, "s": 172, "text": "Why should I care?" }, { "code": null, "e": 911, "s": 191, "text": "Many probability distributions are defined by using the gamma function — such as Gamma distribution, Beta distribution, Dirichlet distribution, Chi-squared distribution, and Student’s t-distribution, etc.For data scientists, machine learning engineers, researchers, the Gamma function is probably one of the most widely used functions because it is employed in many distributions. These distributions are then used for Bayesian inference, stochastic processes (such as queueing models), generative statistical models (such as Latent Dirichlet Allocation), and variational inference. Therefore, if you understand the Gamma function well, you will have a better understanding of a lot of applications in which it appears!" }, { "code": null, "e": 956, "s": 911, "text": "Because we want to generalize the factorial!" }, { "code": null, "e": 1335, "s": 956, "text": "The factorial function is defined only for discrete points (for positive integers — black dots in the graph above), but we wanted to connect the black dots. We want to extend the factorial function to all complex numbers. The simple formula for the factorial, x! = 1 * 2 * ... * x, cannot be used directly for fractional values because it is only valid when x is a whole number." }, { "code": null, "e": 1379, "s": 1335, "text": "So mathematicians had been searching for..." }, { "code": null, "e": 1480, "s": 1379, "text": "“What kind of functions will connect these dots smoothly and give us factorials of all real values?”" }, { "code": null, "e": 1632, "s": 1480, "text": "However, they couldn’t find *finite* combinations of sums, products, powers, exponential, or logarithms that could express x! for real numbers until..." }, { "code": null, "e": 1723, "s": 1632, "text": "The formula above is used to find the value of the Gamma function for any real value of z." }, { "code": null, "e": 1875, "s": 1723, "text": "Let’s say you want to calculate Γ(4.8). How would you solve the integration above? Can you calculate Γ(4.8) by hand? Maybe using the integral by parts?" }, { "code": null, "e": 2135, "s": 1875, "text": "Try it and let me know if you find an interesting way to do so! For me (and many others so far), there is no quick and easy way to evaluate the Gamma function of fractions manually. (If you are interested in solving it by hand, here is a good starting point.)" }, { "code": null, "e": 2283, "s": 2135, "text": "Ok, then, forget about doing it analytically. Can you implement this integral from 0 to infinity — adding the term infinite times programmatically?" }, { "code": null, "e": 2420, "s": 2283, "text": "You can implement this in a few ways. Two of the most often used implementations are Stirling’s approximation and Lanczos approximation." }, { "code": null, "e": 2566, "s": 2420, "text": "For implementation addicts: the codes of Gamma function (mostly Lanczos approximation) in 60+ different language - C, C++, C#, python, java, etc." }, { "code": null, "e": 2637, "s": 2566, "text": "Let’s calculate Γ(4.8) using a calculator that is implemented already." }, { "code": null, "e": 2652, "s": 2637, "text": "We got 17.837." }, { "code": null, "e": 2726, "s": 2652, "text": "17.837 falls between 3!(= Γ(4) = 6) and 4!(= Γ(5) = 24) — as we expected." }, { "code": null, "e": 2805, "s": 2726, "text": "(When z is a natural number, Γ(z) =(z-1)! We are going to prove this shortly.)" }, { "code": null, "e": 3011, "s": 2805, "text": "Unlike the factorial, which takes only the positive integers, we can input any real/complex number into z, including negative numbers. The Gamma function connects the black dots and draws the curve nicely." }, { "code": null, "e": 3199, "s": 3011, "text": "Confusion-buster: We are integrating over x (NOT z) from 0 to infinity. • x is a helper variable that is being integrated out.• We are NOT plugging 4.8 into x. We are plugging 4.8 into z." }, { "code": null, "e": 3269, "s": 3199, "text": "If you take a look at the Gamma function, you will notice two things." }, { "code": null, "e": 3336, "s": 3269, "text": "First, it is definitely an increasing function, with respect to z." }, { "code": null, "e": 3428, "s": 3336, "text": "Second, when z is a natural number, Γ(z+1) = z! (I promise we’re going to prove this soon!)" }, { "code": null, "e": 3498, "s": 3428, "text": "Therefore, we can expect the Gamma function to connect the factorial." }, { "code": null, "e": 3565, "s": 3498, "text": "How did the Gamma function end up with current terms x^z and e^-x?" }, { "code": null, "e": 3776, "s": 3565, "text": "I don’t know exactly what Euler’s thought process was, but he is the one who discovered the natural number e, so he must have experimented a lot with multiplying e with other functions to find the current form." }, { "code": null, "e": 3888, "s": 3776, "text": "As x goes to infinity ∞, the first term (x^z) also goes to infinity ∞, but the second term (e^-x) goes to zero." }, { "code": null, "e": 3945, "s": 3888, "text": "Then, will the Gamma function converge to finite values?" }, { "code": null, "e": 4360, "s": 3945, "text": "We can rigorously show that it converges using L’Hôpital’s rule. But we can also see its convergence in an effortless way. If you think about it, we are integrating a product of x^z — a polynomially increasing function — and e^-x — an exponentially decreasing function. Because the value of e^-x decreases much more quickly than that of x^z, the Gamma function is pretty likely to converge and have finite values." }, { "code": null, "e": 4410, "s": 4360, "text": "Let’s plot each graph, since seeing is believing." }, { "code": null, "e": 4444, "s": 4410, "text": "Let’s look at the case of Γ(4.8)." }, { "code": null, "e": 4575, "s": 4444, "text": "Python code is used to generate the beautiful plots above. Plot it yourself and see how z changes the shape of the Gamma function!" }, { "code": null, "e": 6858, "s": 4575, "text": "######################### f(x) = exp(-x) graph #########################import matplotlib.pyplot as pltimport numpy as np# Create x and yx = np.linspace(-2, 20, 100)y = np.exp(-x)# Create the plotfig, ax = plt.subplots()plt.plot(x, y, label='f(x) = exp(-x)', linewidth=3, color='palegreen')# Make the x=0, y=0 thickerax.set_aspect('equal')ax.grid(True, which='both')ax.axhline(y=0, color='k')ax.axvline(x=0, color='k')# Add a titleplt.title('f(x) = exp(-x)', fontsize=20)# Add X and y Labelplt.xlabel('x', fontsize=16)plt.ylabel('f(x)', fontsize=16)# Add a gridplt.grid(alpha=.4, linestyle='--')# Show the plotplt.show()##################### f(x) = x^z graph #####################import matplotlib.pyplot as pltimport numpy as np# Create x and yx = np.linspace(0, 2, 100)y1 = x**1.3y2 = x**2.5 y3 = x**3.8# Create the plotfig, ax = plt.subplots()plt.plot(x, y1, label='f(x) = x^1.3', linewidth=3, color='palegreen')plt.plot(x, y2, label='f(x) = x^2.5', linewidth=3, color='yellowgreen')plt.plot(x, y3, label='f(x) = x^3.8', linewidth=3, color='olivedrab')# Make the x=0, y=0 thickerax.set_aspect('equal')ax.grid(True, which='both')ax.axhline(y=0, color='k')ax.axvline(x=0, color='k')# Add a titleplt.title('f(x) = x^z', fontsize=20)# Add X and y Labelplt.xlabel('x', fontsize=16)plt.ylabel('f(x)', fontsize=16)# Add a gridplt.grid(alpha=.4, linestyle='--')# Add a Legendplt.legend(bbox_to_anchor=(1, 1), loc='best', borderaxespad=1, fontsize=12)# Show the plotplt.show()################################ f(x) = x^(3.8)*e^(-x) graph ################################import matplotlib.pyplot as pltimport numpy as np# Create x and yx = np.linspace(0, 20, 100)y = x**3.8 * np.exp(-x)# Create the plotfig, ax = plt.subplots()plt.plot(x, y, label='f(x) = x^(3.8) * np.exp(-x)', linewidth=3, color='palegreen')ax.fill_between(x, 0, y, color='yellowgreen')# Make the x=0, y=0 thickerax.set_aspect('equal')ax.grid(True, which='both')ax.axhline(y=0, color='k')ax.axvline(x=0, color='k')# Add a titleplt.title('f(x) = x^(3.8)*e^(-x) ', fontsize=20)# Add X and y Labelplt.xlabel('x', fontsize=16)plt.ylabel('f(x)' ,fontsize=16)# Add a gridplt.grid(alpha=.4, linestyle='--')# Add a Legendplt.legend(bbox_to_anchor=(1, 1), loc='upper right', borderaxespad=1, fontsize=12)# Show the plotplt.show()" }, { "code": null, "e": 6959, "s": 6858, "text": "The code in ipynb: https://github.com/aerinkim/TowardsDataScience/blob/master/Gamma%20Function.ipynb" }, { "code": null, "e": 7029, "s": 6959, "text": "If you take one thing away from this post, it should be this section." }, { "code": null, "e": 7118, "s": 7029, "text": "Property 1.given z > 1Γ(z) = (z-1) * Γ(z-1)or you can write it asΓ(z+1) = z * Γ(z)" }, { "code": null, "e": 7198, "s": 7118, "text": "Let’s prove it using integration by parts and the definition of Gamma function." }, { "code": null, "e": 7218, "s": 7198, "text": "Beautifully proved!" }, { "code": null, "e": 7270, "s": 7218, "text": "Property 2. If n is a positive integerΓ(n) = (n-1)!" }, { "code": null, "e": 7307, "s": 7270, "text": "Let’s prove it using the property 1." }, { "code": null, "e": 7321, "s": 7307, "text": "What is Γ(1)?" }, { "code": null, "e": 7346, "s": 7321, "text": "Therefore, Γ(n) = (n-1)!" }, { "code": null, "e": 7518, "s": 7346, "text": "You might have also seen the expression Γ(n+1) = n! instead of Γ(n) = (n-1)!.This is just to make the right hand side n!, instead of (n-1)! All we did was to shift n by 1." }, { "code": null, "e": 7637, "s": 7518, "text": "A quick recap about the Gamma “distribution” (not the Gamma “function”!): Gamma Distribution Intuition and Derivation." }, { "code": null, "e": 7658, "s": 7637, "text": "Here goes the proof:" }, { "code": null, "e": 7714, "s": 7658, "text": "For the proof addicts: Let’s prove the red arrow above." }, { "code": null, "e": 7753, "s": 7714, "text": "We’ll use integration by substitution." }, { "code": null, "e": 7779, "s": 7753, "text": "Beautifully proved again!" }, { "code": null, "e": 7801, "s": 7779, "text": "A few things to note:" }, { "code": null, "e": 7832, "s": 7801, "text": "How old is the Gamma function?" }, { "code": null, "e": 7863, "s": 7832, "text": "How old is the Gamma function?" }, { "code": null, "e": 7963, "s": 7863, "text": "Pretty old. About 300 yrs. (Are you working on something today that will be used 300 years later?;)" }, { "code": null, "e": 8093, "s": 7963, "text": "An interesting side note: Euler became blind at age 64 however he produced almost half of his total works after losing his sight." }, { "code": null, "e": 8131, "s": 8093, "text": "2. Some interesting values at points:" }, { "code": null, "e": 8325, "s": 8131, "text": "Γ(1/2) = sqrt(π)Many interesting ways to show this:https://math.stackexchange.com/questions/215352/why-is-gamma-left-frac12-right-sqrt-piΓ(-1/2) = -2 * sqrt(π)Γ(-1) = Γ(-2) = Γ(-3) = infinity ∞" }, { "code": null, "e": 8346, "s": 8325, "text": "Can you prove these?" }, { "code": null, "e": 8422, "s": 8346, "text": "3. Here is a quick look at the graph of the Gamma function in real numbers." }, { "code": null, "e": 8649, "s": 8422, "text": "The Gamma function, Γ(z) in blue, plotted along with Γ(z) + sin(πz) in green. (Notice the intersection at positive integers because sin(πz) is zero!) Both are valid analytic continuations of the factorials to the non-integers." } ]
Batch Script - Copying Registry Keys
Copying from the registry is done via the REG COPY command. Note that in order to copy values from the registry, you need to have sufficient privileges on the system to perform this operation on both the source location and the destination location. REG COPY [\\SourceMachine\][ROOT\]RegKey [\\DestMachine\][ROOT\]RegKey @echo off REG COPY HKEY_CURRENT_USER\Console HKEY_CURRENT_USER\Console\Test REG QUERY HKEY_CURRENT_USER\Console\Test In the above example, the first part is to copy the contents from the location HKEY_CURRENT_USER\Console into the location HKEY_CURRENT_USER\Console\Test on the same machine. The second command is used to query the new location to check if all the values were copied properly. Following is the output of the above program. The first line of the output shows that the ‘Copy’ functionality was successful and the second output shows the values in our copied location. The operation completed successfully. HKEY_CURRENT_USER\Console\Test HistoryNoDup REG_DWORD 0x0 FullScreen REG_DWORD 0x0 ScrollScale REG_DWORD 0x1 ExtendedEditKeyCustom REG_DWORD 0x0 CursorSize REG_DWORD 0x19 FontFamily REG_DWORD 0x0 ScreenColors REG_DWORD 0x7 TrimLeadingZeros REG_DWORD 0x0 WindowSize REG_DWORD 0x190050 LoadConIme REG_DWORD 0x1 PopupColors REG_DWORD 0xf5 QuickEdit REG_DWORD 0x0 WordDelimiters REG_DWORD 0x0 ColorTable10 REG_DWORD 0xff00 ColorTable00 REG_DWORD 0x0 ColorTable11 REG_DWORD 0xffff00 ColorTable01 REG_DWORD 0x800000 ColorTable12 REG_DWORD 0xff Print Add Notes Bookmark this page
[ { "code": null, "e": 2419, "s": 2169, "text": "Copying from the registry is done via the REG COPY command. Note that in order to copy values from the registry, you need to have sufficient privileges on the system to perform this operation on both the source location and the destination location." }, { "code": null, "e": 2491, "s": 2419, "text": "REG COPY [\\\\SourceMachine\\][ROOT\\]RegKey [\\\\DestMachine\\][ROOT\\]RegKey\n" }, { "code": null, "e": 2610, "s": 2491, "text": "@echo off \nREG COPY HKEY_CURRENT_USER\\Console HKEY_CURRENT_USER\\Console\\Test \nREG QUERY HKEY_CURRENT_USER\\Console\\Test" }, { "code": null, "e": 2887, "s": 2610, "text": "In the above example, the first part is to copy the contents from the location HKEY_CURRENT_USER\\Console into the location HKEY_CURRENT_USER\\Console\\Test on the same machine. The second command is used to query the new location to check if all the values were copied properly." }, { "code": null, "e": 3076, "s": 2887, "text": "Following is the output of the above program. The first line of the output shows that the ‘Copy’ functionality was successful and the second output shows the values in our copied location." }, { "code": null, "e": 3707, "s": 3076, "text": "The operation completed successfully.\nHKEY_CURRENT_USER\\Console\\Test\n HistoryNoDup REG_DWORD 0x0\n FullScreen REG_DWORD 0x0\n ScrollScale REG_DWORD 0x1\n ExtendedEditKeyCustom REG_DWORD 0x0\n CursorSize REG_DWORD 0x19\n FontFamily REG_DWORD 0x0\n ScreenColors REG_DWORD 0x7\n TrimLeadingZeros REG_DWORD 0x0\n WindowSize REG_DWORD 0x190050\n LoadConIme REG_DWORD 0x1\n PopupColors REG_DWORD 0xf5\n QuickEdit REG_DWORD 0x0\n WordDelimiters REG_DWORD 0x0\n ColorTable10 REG_DWORD 0xff00\n ColorTable00 REG_DWORD 0x0\n ColorTable11 REG_DWORD 0xffff00\n ColorTable01 REG_DWORD 0x800000\n ColorTable12 REG_DWORD 0xff\n" }, { "code": null, "e": 3714, "s": 3707, "text": " Print" }, { "code": null, "e": 3725, "s": 3714, "text": " Add Notes" } ]
Java String compareTo() Method
❮ String Methods Compare two strings: String myStr1 = "Hello"; String myStr2 = "Hello"; System.out.println(myStr1.compareTo(myStr2)); // Returns 0 because they are equal Try it Yourself » The compareTo() method compares two strings lexicographically. The comparison is based on the Unicode value of each character in the strings. The method returns 0 if the string is equal to the other string. A value less than 0 is returned if the string is less than the other string (less characters) and a value greater than 0 if the string is greater than the other string (more characters). Tip: Use compareToIgnoreCase() to compare two strings lexicographyically, ignoring lower case and upper case differences. Tip: Use the equals() method to compare two strings without consideration of Unicode values. public int compareTo(String string2) public int compareTo(Object object) 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: [email protected] Your message has been sent to W3Schools.
[ { "code": null, "e": 19, "s": 0, "text": "\n❮ String Methods\n" }, { "code": null, "e": 40, "s": 19, "text": "Compare two strings:" }, { "code": null, "e": 172, "s": 40, "text": "String myStr1 = \"Hello\";\nString myStr2 = \"Hello\";\nSystem.out.println(myStr1.compareTo(myStr2)); // Returns 0 because they are equal" }, { "code": null, "e": 192, "s": 172, "text": "\nTry it Yourself »\n" }, { "code": null, "e": 256, "s": 192, "text": "The compareTo() method compares two strings \nlexicographically." }, { "code": null, "e": 336, "s": 256, "text": "The comparison is based on the Unicode value of each character in the \nstrings." }, { "code": null, "e": 596, "s": 336, "text": "The method returns 0 if the string is equal to the other string.\n A value less than 0 is returned if the string is less than the other string \n (less characters) and a value greater than 0 if the string is greater than the other string \n (more characters)." }, { "code": null, "e": 720, "s": 596, "text": "Tip: Use \ncompareToIgnoreCase() to compare two strings lexicographyically, ignoring \nlower case and upper case differences." }, { "code": null, "e": 813, "s": 720, "text": "Tip: Use the equals() method to compare two strings without consideration of Unicode values." }, { "code": null, "e": 887, "s": 813, "text": "public int compareTo(String string2)\npublic int compareTo(Object object)\n" }, { "code": null, "e": 920, "s": 887, "text": "We just launchedW3Schools videos" }, { "code": null, "e": 962, "s": 920, "text": "Get certifiedby completinga course today!" }, { "code": null, "e": 1069, "s": 962, "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": 1088, "s": 1069, "text": "[email protected]" } ]
YAML - Basics
Now that you have an idea about YAML and its features, let us learn its basics with syntax and other operations. Remember that YAML includes a human readable structured format. When you are creating a file in YAML, you should remember the following basic rules − YAML is case sensitive YAML is case sensitive The files should have .yaml as the extension The files should have .yaml as the extension YAML does not allow the use of tabs while creating YAML files; spaces are allowed instead YAML does not allow the use of tabs while creating YAML files; spaces are allowed instead The basic components of YAML are described below − This block format uses hyphen+space to begin a new item in a specified list. Observe the example shown below − --- # Favorite movies - Casablanca - North by Northwest - The Man Who Wasn't There Inline Format Inline format is delimited with comma and space and the items are enclosed in JSON. Observe the example shown below − --- # Shopping list [milk, groceries, eggs, juice, fruits] Folded Text Folded text converts newlines to spaces and removes the leading whitespace. Observe the example shown below − - {name: John Smith, age: 33} - name: Mary Smith age: 27 The structure which follows all the basic conventions of YAML is shown below − men: [John Smith, Bill Jones] women: - Mary Smith - Susan Williams The synopsis of YAML basic elements is given here: Comments in YAML begins with the (#) character. The synopsis of YAML basic elements is given here: Comments in YAML begins with the (#) character. Comments must be separated from other tokens by whitespaces. Comments must be separated from other tokens by whitespaces. Indentation of whitespace is used to denote structure. Indentation of whitespace is used to denote structure. Tabs are not included as indentation for YAML files. Tabs are not included as indentation for YAML files. List members are denoted by a leading hyphen (-). List members are denoted by a leading hyphen (-). List members are enclosed in square brackets and separated by commas. List members are enclosed in square brackets and separated by commas. Associative arrays are represented using colon ( : ) in the format of key value pair. They are enclosed in curly braces {}. Associative arrays are represented using colon ( : ) in the format of key value pair. They are enclosed in curly braces {}. Multiple documents with single streams are separated with 3 hyphens (---). Multiple documents with single streams are separated with 3 hyphens (---). Repeated nodes in each file are initially denoted by an ampersand (&) and by an asterisk (*) mark later. Repeated nodes in each file are initially denoted by an ampersand (&) and by an asterisk (*) mark later. YAML always requires colons and commas used as list separators followed by space with scalar values. YAML always requires colons and commas used as list separators followed by space with scalar values. Nodes should be labelled with an exclamation mark (!) or double exclamation mark (!!), followed by string which can be expanded into an URI or URL. Nodes should be labelled with an exclamation mark (!) or double exclamation mark (!!), followed by string which can be expanded into an URI or URL. 33 Lectures 44 mins Tarun Telang Print Add Notes Bookmark this page
[ { "code": null, "e": 2225, "s": 2048, "text": "Now that you have an idea about YAML and its features, let us learn its basics with syntax and other operations. Remember that YAML includes a human readable structured format." }, { "code": null, "e": 2311, "s": 2225, "text": "When you are creating a file in YAML, you should remember the following basic rules −" }, { "code": null, "e": 2334, "s": 2311, "text": "YAML is case sensitive" }, { "code": null, "e": 2357, "s": 2334, "text": "YAML is case sensitive" }, { "code": null, "e": 2402, "s": 2357, "text": "The files should have .yaml as the extension" }, { "code": null, "e": 2447, "s": 2402, "text": "The files should have .yaml as the extension" }, { "code": null, "e": 2537, "s": 2447, "text": "YAML does not allow the use of tabs while creating YAML files; spaces are allowed instead" }, { "code": null, "e": 2627, "s": 2537, "text": "YAML does not allow the use of tabs while creating YAML files; spaces are allowed instead" }, { "code": null, "e": 2678, "s": 2627, "text": "The basic components of YAML are described below −" }, { "code": null, "e": 2789, "s": 2678, "text": "This block format uses hyphen+space to begin a new item in a specified list. Observe the example shown below −" }, { "code": null, "e": 2876, "s": 2789, "text": "--- # Favorite movies\n - Casablanca\n - North by Northwest\n - The Man Who Wasn't There\n" }, { "code": null, "e": 2890, "s": 2876, "text": "Inline Format" }, { "code": null, "e": 3008, "s": 2890, "text": "Inline format is delimited with comma and space and the items are enclosed in JSON. Observe the example shown below −" }, { "code": null, "e": 3071, "s": 3008, "text": "--- # Shopping list\n [milk, groceries, eggs, juice, fruits]\n" }, { "code": null, "e": 3083, "s": 3071, "text": "Folded Text" }, { "code": null, "e": 3193, "s": 3083, "text": "Folded text converts newlines to spaces and removes the leading whitespace. Observe the example shown below −" }, { "code": null, "e": 3253, "s": 3193, "text": "- {name: John Smith, age: 33}\n- name: Mary Smith\n age: 27\n" }, { "code": null, "e": 3332, "s": 3253, "text": "The structure which follows all the basic conventions of YAML is shown below −" }, { "code": null, "e": 3404, "s": 3332, "text": "men: [John Smith, Bill Jones]\nwomen:\n - Mary Smith\n - Susan Williams\n" }, { "code": null, "e": 3503, "s": 3404, "text": "The synopsis of YAML basic elements is given here: Comments in YAML begins with the (#) character." }, { "code": null, "e": 3602, "s": 3503, "text": "The synopsis of YAML basic elements is given here: Comments in YAML begins with the (#) character." }, { "code": null, "e": 3663, "s": 3602, "text": "Comments must be separated from other tokens by whitespaces." }, { "code": null, "e": 3724, "s": 3663, "text": "Comments must be separated from other tokens by whitespaces." }, { "code": null, "e": 3779, "s": 3724, "text": "Indentation of whitespace is used to denote structure." }, { "code": null, "e": 3834, "s": 3779, "text": "Indentation of whitespace is used to denote structure." }, { "code": null, "e": 3887, "s": 3834, "text": "Tabs are not included as indentation for YAML files." }, { "code": null, "e": 3940, "s": 3887, "text": "Tabs are not included as indentation for YAML files." }, { "code": null, "e": 3990, "s": 3940, "text": "List members are denoted by a leading hyphen (-)." }, { "code": null, "e": 4040, "s": 3990, "text": "List members are denoted by a leading hyphen (-)." }, { "code": null, "e": 4110, "s": 4040, "text": "List members are enclosed in square brackets and separated by commas." }, { "code": null, "e": 4180, "s": 4110, "text": "List members are enclosed in square brackets and separated by commas." }, { "code": null, "e": 4304, "s": 4180, "text": "Associative arrays are represented using colon ( : ) in the format of key value pair. They are enclosed in curly braces {}." }, { "code": null, "e": 4428, "s": 4304, "text": "Associative arrays are represented using colon ( : ) in the format of key value pair. They are enclosed in curly braces {}." }, { "code": null, "e": 4503, "s": 4428, "text": "Multiple documents with single streams are separated with 3 hyphens (---)." }, { "code": null, "e": 4578, "s": 4503, "text": "Multiple documents with single streams are separated with 3 hyphens (---)." }, { "code": null, "e": 4683, "s": 4578, "text": "Repeated nodes in each file are initially denoted by an ampersand (&) and by an asterisk (*) mark later." }, { "code": null, "e": 4788, "s": 4683, "text": "Repeated nodes in each file are initially denoted by an ampersand (&) and by an asterisk (*) mark later." }, { "code": null, "e": 4889, "s": 4788, "text": "YAML always requires colons and commas used as list separators followed by space with scalar values." }, { "code": null, "e": 4990, "s": 4889, "text": "YAML always requires colons and commas used as list separators followed by space with scalar values." }, { "code": null, "e": 5138, "s": 4990, "text": "Nodes should be labelled with an exclamation mark (!) or double exclamation mark (!!), followed by string which can be expanded into an URI or URL." }, { "code": null, "e": 5286, "s": 5138, "text": "Nodes should be labelled with an exclamation mark (!) or double exclamation mark (!!), followed by string which can be expanded into an URI or URL." }, { "code": null, "e": 5318, "s": 5286, "text": "\n 33 Lectures \n 44 mins\n" }, { "code": null, "e": 5332, "s": 5318, "text": " Tarun Telang" }, { "code": null, "e": 5339, "s": 5332, "text": " Print" }, { "code": null, "e": 5350, "s": 5339, "text": " Add Notes" } ]
PostgreSQL - REGEXP_MATCHES Function - GeeksforGeeks
01 Feb, 2021 The PostgreSQL REGEXP_MATCHES() function is used to match a POSIX regular expression against a string and subsequently returns the strings that match the pattern. Syntax:REGEXP_MATCHES(source_string, pattern [, flags]) Let’s analyze the above syntax: The source is a string from which the regular expression matches and returns the substring. The pattern is a POSIX regular expression for matching the source string. The flags argument handles the function when more tha one character matches the pattern. The REGEXP_MATCHES() function returns the queried string based on the matches. Example 1: Suppose, you have a social networking’s post as follows: 'Learning #Geeksforgeeks #geekPower' The following statement allows you to extract the hashtags such as Geeksforgeeks and geekPower: SELECT REGEXP_MATCHES('Learning #Geeksforgeeks #geekPower', '#([A-Za-z0-9_]+)', 'g'); Output: Example 2: This is common for all patterns that can be matched using the Regular Expressions as shown in the below example: SELECT REGEXP_MATCHES('ABC', '^(A)(..)$', 'g'); Output: PostgreSQL-function PostgreSQL-String-function PostgreSQL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments PostgreSQL - Create Auto-increment Column using SERIAL PostgreSQL - Introduction to Stored Procedures PostgreSQL - ARRAY_AGG() Function PostgreSQL - Joins PostgreSQL - GROUP BY clause PostgreSQL - DROP INDEX PostgreSQL - ROW_NUMBER Function PostgreSQL - Rename Table PostgreSQL - Copy Table How to use PostgreSQL Database in Django?
[ { "code": null, "e": 23425, "s": 23397, "text": "\n01 Feb, 2021" }, { "code": null, "e": 23588, "s": 23425, "text": "The PostgreSQL REGEXP_MATCHES() function is used to match a POSIX regular expression against a string and subsequently returns the strings that match the pattern." }, { "code": null, "e": 23646, "s": 23588, "text": "Syntax:REGEXP_MATCHES(source_string, pattern [, flags])\n\n" }, { "code": null, "e": 23678, "s": 23646, "text": "Let’s analyze the above syntax:" }, { "code": null, "e": 23770, "s": 23678, "text": "The source is a string from which the regular expression matches and returns the substring." }, { "code": null, "e": 23844, "s": 23770, "text": "The pattern is a POSIX regular expression for matching the source string." }, { "code": null, "e": 23933, "s": 23844, "text": "The flags argument handles the function when more tha one character matches the pattern." }, { "code": null, "e": 24012, "s": 23933, "text": "The REGEXP_MATCHES() function returns the queried string based on the matches." }, { "code": null, "e": 24023, "s": 24012, "text": "Example 1:" }, { "code": null, "e": 24080, "s": 24023, "text": "Suppose, you have a social networking’s post as follows:" }, { "code": null, "e": 24119, "s": 24080, "text": "'Learning #Geeksforgeeks #geekPower'\n\n" }, { "code": null, "e": 24215, "s": 24119, "text": "The following statement allows you to extract the hashtags such as Geeksforgeeks and geekPower:" }, { "code": null, "e": 24327, "s": 24215, "text": "SELECT \n REGEXP_MATCHES('Learning #Geeksforgeeks #geekPower', \n '#([A-Za-z0-9_]+)', \n 'g');\n\n" }, { "code": null, "e": 24335, "s": 24327, "text": "Output:" }, { "code": null, "e": 24346, "s": 24335, "text": "Example 2:" }, { "code": null, "e": 24459, "s": 24346, "text": "This is common for all patterns that can be matched using the Regular Expressions as shown in the below example:" }, { "code": null, "e": 24509, "s": 24459, "text": "SELECT REGEXP_MATCHES('ABC', '^(A)(..)$', 'g');\n\n" }, { "code": null, "e": 24517, "s": 24509, "text": "Output:" }, { "code": null, "e": 24537, "s": 24517, "text": "PostgreSQL-function" }, { "code": null, "e": 24564, "s": 24537, "text": "PostgreSQL-String-function" }, { "code": null, "e": 24575, "s": 24564, "text": "PostgreSQL" }, { "code": null, "e": 24673, "s": 24575, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 24682, "s": 24673, "text": "Comments" }, { "code": null, "e": 24695, "s": 24682, "text": "Old Comments" }, { "code": null, "e": 24750, "s": 24695, "text": "PostgreSQL - Create Auto-increment Column using SERIAL" }, { "code": null, "e": 24797, "s": 24750, "text": "PostgreSQL - Introduction to Stored Procedures" }, { "code": null, "e": 24831, "s": 24797, "text": "PostgreSQL - ARRAY_AGG() Function" }, { "code": null, "e": 24850, "s": 24831, "text": "PostgreSQL - Joins" }, { "code": null, "e": 24879, "s": 24850, "text": "PostgreSQL - GROUP BY clause" }, { "code": null, "e": 24903, "s": 24879, "text": "PostgreSQL - DROP INDEX" }, { "code": null, "e": 24936, "s": 24903, "text": "PostgreSQL - ROW_NUMBER Function" }, { "code": null, "e": 24962, "s": 24936, "text": "PostgreSQL - Rename Table" }, { "code": null, "e": 24986, "s": 24962, "text": "PostgreSQL - Copy Table" } ]
A Multi-page Interactive Dashboard with Streamlit and Plotly | by Alan Jones | Towards Data Science
The great thing about Streamlit is, not only is it beautiful, but it’s simple, too. A few months ago I wrote about how to write a dashboard using Plotly and Flask — it was an alternative approach to using Dash and I was quite pleased with it. The app consisted of two files, a Python/Flask app of 20-odd lines and an HTML/Javascript file of nearly 30 lines. You can see the article here: towardsdatascience.com Then I decided to have a go at implementing the same thing using Streamlit: the result a single Python file of around a dozen lines. A quarter of the size! And not only was it easy and quick to write, it was better looking, too. So, I thought I’d share my experience of creating, first, a simple interactive Streamlit app with Plotly charts and then developing it into a more sophisticated (but still simple) multi-page app. Along the way I look at how to draw Plotly charts, control layout in Streamlit and navigating with drop-down menus. The first app will be a clone of my Flask app and will look like this: The user selects a country from the drop-down menu on the left and the appropriate graph is drawn on the right. A Streamlit app is just a Python program that uses the Streamlit library and is run using the Streamlit command from a terminal window. e.g. streamlit run myapp.py It will then fire up your browser and run the app there. First things first, though. To use Streamlit you obviously have to install it: pip3 install streamlit Or conda, or whatever other arcane method you use to install Python packages. You start your Python program with something like this: import streamlit as stimport pandas as pdimport plotly.express as px I’m going to use Pandas to store and manipulate the data and Plotly to create the charts. For demonstration purposes I’m using the Gapminder data included in the Plotly package. So, the next bit of code is: df = pd.DataFrame(px.data.gapminder()) This creates a dataframe that holds a table of information about all the countries the world and looks like this: Each country is listed in the table along with data about life expectancy, population and GDP per capita over a few decades. The continent for each country is also given (there are other data, too, but they are not of interest, here). What we are initially going to do is create plots of population and GDP per capita for a selected nation. So, we need a list of country names from which the user can select. This is easily achieved by selecting the country column from the dataframe and creating a list of unique names. clist = df['country'].unique() After running this we have a list of unique names in the variable clist. The drop-down menu is created in a sidebar from clist like this: country = st.sidebar.selectbox("Select a country:",clist) All of the Streamlit functions start with st. st.sidebar creates a sidebar on the left of the screen and .selectbox creates a drop-down from the list using the prompt provided in the first parameter. Next we draw the chart. fig = px.line(df[df['country'] == country], x = "year", y = "gdpPercap", title = country) Here you can see we are creating a line chart in the variable fig by selecting only the rows in the dataframe that correspond to the chosen country. The entire program is shown below and, as I mentioned earlier, it is only around a dozen lines of code. import streamlit as stimport pandas as pdimport plotly.express as pxdf = pd.DataFrame(px.data.gapminder())clist = df['country'].unique()country = st.sidebar.selectbox("Select a country:",clist)st.header("GDP per Capita over time")fig = px.line(df[df['country'] == country], x = "year", y = "gdpPercap", title = country)st.plotly_chart(fig) There a couple of lines that I haven’t covered. st.header("GDP per Capita over time") creates a heading and st.plotly_chart(fig) plots the chart. And when we run the program we get this: Which is, I think, pretty good for such a tiny program. But it gets better. As part of my efforts to persuade myself that I could make apps as easily with Flask and HTML as I could with Dash, I created a simple multi-page app that used the same HTML template for each page but loaded different data into it from Flask. You can see the article here: towardsdatascience.com It’s a different story with Streamlit. There’s no specific support for multiple page and I’m guessing that’s not an omission. Streamlit just isn’t meant for creating whole web sites. But sometimes a little pagination is useful so I wrote a new app that expands on the first, gives more information and runs over two pages. It looks better, too! The aim is to have two pages, one for countries and the other for continents. On each page you can select a country or continent and you’ll get two graphs, one for GDP and the other for population. You can see what the continent page looks like below. Actually, maybe you can’t see it that well, so here is a zoomed in image of the left of the page. On the left is the sidebar with a drop-down menu where you select either country or continent. the main part of the page holds the graphs and has its own drop-down to select which continent (Europe, Asia, etc.) or which country. The country page looks like this. The method is easy. Just use the value returned from the drop-down menu in the sidebar in an if... else... statement and display the appropriate data in the if block or the else block. The code looks like this: page = st.sidebar.selectbox('Select page', ['Country data','Continent data'])if page == 'Country data': # Display the country content hereelse: # Display the continent content here I’m using columns to display the charts side by side and I’ve set the layout to wide to give myself a bit more space. Other than that, the code that replaces those comments is pretty much the same as we have seen in the first example. Here’s the full listing: import streamlit as stimport pandas as pdimport plotly.express as pxst.set_page_config(layout = "wide")df = pd.DataFrame(px.data.gapminder())st.header("National Statistics")page = st.sidebar.selectbox('Select page', ['Country data','Continent data'])if page == 'Country data': ## Countries clist = df['country'].unique() country = st.selectbox("Select a country:",clist) col1, col2 = st.columns(2) fig = px.line(df[df['country'] == country], x = "year", y = "gdpPercap",title = "GDP per Capita") col1.plotly_chart(fig,use_container_width = True) fig = px.line(df[df['country'] == country], x = "year", y = "pop",title = "Population Growth") col2.plotly_chart(fig,use_container_width = True)else: ## Continents contlist = df['continent'].unique() continent = st.selectbox("Select a continent:",contlist) col1,col2 = st.columns(2) fig = px.line(df[df['continent'] == continent], x = "year", y = "gdpPercap", title = "GDP per Capita",color = 'country') col1.plotly_chart(fig) fig = px.line(df[df['continent'] == continent], x = "year", y = "pop", title = "Population",color = 'country') col2.plotly_chart(fig, use_container_width = True) Now, if I were clever, I’d realise that I’ve got a fair amount of very similar code in this app and so would write some functions to reduce this. But I’ll leave it as it is for now. Streamlit is easy to use and produces very nice results but it is only designed for fairly simple apps. Multi-page apps with complex layouts are not really what it is intended for and that is fair enough. Update: I have recently devised a more sophisticated method of creating multiple apps on a single web site in Streamlit. Read about it here: How to Build a Gallery of Streamlit Apps as a Single Web App Streamlit does have some nice layout components (more on that another day) and multi-page apps could be better implemented with Python 3.10 pattern matching (see here and here) — more on that another day, too. As ever thanks for reading and if you would like to know when I publish new articles, please consider signing up for an email alert here. You can get the code for this and other articles on my Github page and see a demo of the final app here. If you are not a Medium subscriber, how about signing up so you can read as many articles as you like for $5 a month. Sign up here and I’ll earn a small commission.
[ { "code": null, "e": 255, "s": 171, "text": "The great thing about Streamlit is, not only is it beautiful, but it’s simple, too." }, { "code": null, "e": 559, "s": 255, "text": "A few months ago I wrote about how to write a dashboard using Plotly and Flask — it was an alternative approach to using Dash and I was quite pleased with it. The app consisted of two files, a Python/Flask app of 20-odd lines and an HTML/Javascript file of nearly 30 lines. You can see the article here:" }, { "code": null, "e": 582, "s": 559, "text": "towardsdatascience.com" }, { "code": null, "e": 811, "s": 582, "text": "Then I decided to have a go at implementing the same thing using Streamlit: the result a single Python file of around a dozen lines. A quarter of the size! And not only was it easy and quick to write, it was better looking, too." }, { "code": null, "e": 1123, "s": 811, "text": "So, I thought I’d share my experience of creating, first, a simple interactive Streamlit app with Plotly charts and then developing it into a more sophisticated (but still simple) multi-page app. Along the way I look at how to draw Plotly charts, control layout in Streamlit and navigating with drop-down menus." }, { "code": null, "e": 1194, "s": 1123, "text": "The first app will be a clone of my Flask app and will look like this:" }, { "code": null, "e": 1306, "s": 1194, "text": "The user selects a country from the drop-down menu on the left and the appropriate graph is drawn on the right." }, { "code": null, "e": 1447, "s": 1306, "text": "A Streamlit app is just a Python program that uses the Streamlit library and is run using the Streamlit command from a terminal window. e.g." }, { "code": null, "e": 1470, "s": 1447, "text": "streamlit run myapp.py" }, { "code": null, "e": 1527, "s": 1470, "text": "It will then fire up your browser and run the app there." }, { "code": null, "e": 1606, "s": 1527, "text": "First things first, though. To use Streamlit you obviously have to install it:" }, { "code": null, "e": 1629, "s": 1606, "text": "pip3 install streamlit" }, { "code": null, "e": 1707, "s": 1629, "text": "Or conda, or whatever other arcane method you use to install Python packages." }, { "code": null, "e": 1763, "s": 1707, "text": "You start your Python program with something like this:" }, { "code": null, "e": 1832, "s": 1763, "text": "import streamlit as stimport pandas as pdimport plotly.express as px" }, { "code": null, "e": 1922, "s": 1832, "text": "I’m going to use Pandas to store and manipulate the data and Plotly to create the charts." }, { "code": null, "e": 2039, "s": 1922, "text": "For demonstration purposes I’m using the Gapminder data included in the Plotly package. So, the next bit of code is:" }, { "code": null, "e": 2078, "s": 2039, "text": "df = pd.DataFrame(px.data.gapminder())" }, { "code": null, "e": 2192, "s": 2078, "text": "This creates a dataframe that holds a table of information about all the countries the world and looks like this:" }, { "code": null, "e": 2427, "s": 2192, "text": "Each country is listed in the table along with data about life expectancy, population and GDP per capita over a few decades. The continent for each country is also given (there are other data, too, but they are not of interest, here)." }, { "code": null, "e": 2713, "s": 2427, "text": "What we are initially going to do is create plots of population and GDP per capita for a selected nation. So, we need a list of country names from which the user can select. This is easily achieved by selecting the country column from the dataframe and creating a list of unique names." }, { "code": null, "e": 2744, "s": 2713, "text": "clist = df['country'].unique()" }, { "code": null, "e": 2817, "s": 2744, "text": "After running this we have a list of unique names in the variable clist." }, { "code": null, "e": 2882, "s": 2817, "text": "The drop-down menu is created in a sidebar from clist like this:" }, { "code": null, "e": 2940, "s": 2882, "text": "country = st.sidebar.selectbox(\"Select a country:\",clist)" }, { "code": null, "e": 3140, "s": 2940, "text": "All of the Streamlit functions start with st. st.sidebar creates a sidebar on the left of the screen and .selectbox creates a drop-down from the list using the prompt provided in the first parameter." }, { "code": null, "e": 3164, "s": 3140, "text": "Next we draw the chart." }, { "code": null, "e": 3258, "s": 3164, "text": "fig = px.line(df[df['country'] == country], x = \"year\", y = \"gdpPercap\", title = country)" }, { "code": null, "e": 3407, "s": 3258, "text": "Here you can see we are creating a line chart in the variable fig by selecting only the rows in the dataframe that correspond to the chosen country." }, { "code": null, "e": 3511, "s": 3407, "text": "The entire program is shown below and, as I mentioned earlier, it is only around a dozen lines of code." }, { "code": null, "e": 3855, "s": 3511, "text": "import streamlit as stimport pandas as pdimport plotly.express as pxdf = pd.DataFrame(px.data.gapminder())clist = df['country'].unique()country = st.sidebar.selectbox(\"Select a country:\",clist)st.header(\"GDP per Capita over time\")fig = px.line(df[df['country'] == country], x = \"year\", y = \"gdpPercap\", title = country)st.plotly_chart(fig)" }, { "code": null, "e": 4001, "s": 3855, "text": "There a couple of lines that I haven’t covered. st.header(\"GDP per Capita over time\") creates a heading and st.plotly_chart(fig) plots the chart." }, { "code": null, "e": 4042, "s": 4001, "text": "And when we run the program we get this:" }, { "code": null, "e": 4098, "s": 4042, "text": "Which is, I think, pretty good for such a tiny program." }, { "code": null, "e": 4118, "s": 4098, "text": "But it gets better." }, { "code": null, "e": 4391, "s": 4118, "text": "As part of my efforts to persuade myself that I could make apps as easily with Flask and HTML as I could with Dash, I created a simple multi-page app that used the same HTML template for each page but loaded different data into it from Flask. You can see the article here:" }, { "code": null, "e": 4414, "s": 4391, "text": "towardsdatascience.com" }, { "code": null, "e": 4597, "s": 4414, "text": "It’s a different story with Streamlit. There’s no specific support for multiple page and I’m guessing that’s not an omission. Streamlit just isn’t meant for creating whole web sites." }, { "code": null, "e": 4759, "s": 4597, "text": "But sometimes a little pagination is useful so I wrote a new app that expands on the first, gives more information and runs over two pages. It looks better, too!" }, { "code": null, "e": 5011, "s": 4759, "text": "The aim is to have two pages, one for countries and the other for continents. On each page you can select a country or continent and you’ll get two graphs, one for GDP and the other for population. You can see what the continent page looks like below." }, { "code": null, "e": 5109, "s": 5011, "text": "Actually, maybe you can’t see it that well, so here is a zoomed in image of the left of the page." }, { "code": null, "e": 5338, "s": 5109, "text": "On the left is the sidebar with a drop-down menu where you select either country or continent. the main part of the page holds the graphs and has its own drop-down to select which continent (Europe, Asia, etc.) or which country." }, { "code": null, "e": 5372, "s": 5338, "text": "The country page looks like this." }, { "code": null, "e": 5583, "s": 5372, "text": "The method is easy. Just use the value returned from the drop-down menu in the sidebar in an if... else... statement and display the appropriate data in the if block or the else block. The code looks like this:" }, { "code": null, "e": 5767, "s": 5583, "text": "page = st.sidebar.selectbox('Select page', ['Country data','Continent data'])if page == 'Country data': # Display the country content hereelse: # Display the continent content here" }, { "code": null, "e": 5885, "s": 5767, "text": "I’m using columns to display the charts side by side and I’ve set the layout to wide to give myself a bit more space." }, { "code": null, "e": 6002, "s": 5885, "text": "Other than that, the code that replaces those comments is pretty much the same as we have seen in the first example." }, { "code": null, "e": 6027, "s": 6002, "text": "Here’s the full listing:" }, { "code": null, "e": 7209, "s": 6027, "text": "import streamlit as stimport pandas as pdimport plotly.express as pxst.set_page_config(layout = \"wide\")df = pd.DataFrame(px.data.gapminder())st.header(\"National Statistics\")page = st.sidebar.selectbox('Select page', ['Country data','Continent data'])if page == 'Country data': ## Countries clist = df['country'].unique() country = st.selectbox(\"Select a country:\",clist) col1, col2 = st.columns(2) fig = px.line(df[df['country'] == country], x = \"year\", y = \"gdpPercap\",title = \"GDP per Capita\") col1.plotly_chart(fig,use_container_width = True) fig = px.line(df[df['country'] == country], x = \"year\", y = \"pop\",title = \"Population Growth\") col2.plotly_chart(fig,use_container_width = True)else: ## Continents contlist = df['continent'].unique() continent = st.selectbox(\"Select a continent:\",contlist) col1,col2 = st.columns(2) fig = px.line(df[df['continent'] == continent], x = \"year\", y = \"gdpPercap\", title = \"GDP per Capita\",color = 'country') col1.plotly_chart(fig) fig = px.line(df[df['continent'] == continent], x = \"year\", y = \"pop\", title = \"Population\",color = 'country') col2.plotly_chart(fig, use_container_width = True)" }, { "code": null, "e": 7391, "s": 7209, "text": "Now, if I were clever, I’d realise that I’ve got a fair amount of very similar code in this app and so would write some functions to reduce this. But I’ll leave it as it is for now." }, { "code": null, "e": 7596, "s": 7391, "text": "Streamlit is easy to use and produces very nice results but it is only designed for fairly simple apps. Multi-page apps with complex layouts are not really what it is intended for and that is fair enough." }, { "code": null, "e": 7798, "s": 7596, "text": "Update: I have recently devised a more sophisticated method of creating multiple apps on a single web site in Streamlit. Read about it here: How to Build a Gallery of Streamlit Apps as a Single Web App" }, { "code": null, "e": 8008, "s": 7798, "text": "Streamlit does have some nice layout components (more on that another day) and multi-page apps could be better implemented with Python 3.10 pattern matching (see here and here) — more on that another day, too." }, { "code": null, "e": 8146, "s": 8008, "text": "As ever thanks for reading and if you would like to know when I publish new articles, please consider signing up for an email alert here." }, { "code": null, "e": 8251, "s": 8146, "text": "You can get the code for this and other articles on my Github page and see a demo of the final app here." } ]
PyQt5 - QRadioButton Widget
A QRadioButton class object presents a selectable button with a text label. The user can select one of many options presented on the form. This class is derived from QAbstractButton class. Radio buttons are autoexclusive by default. Hence, only one of the radio buttons in the parent window can be selected at a time. If one is selected, previously selected button is automatically deselected. Radio buttons can also be put in a QGroupBox or QButtonGroup to create more than one selectable fields on the parent window. The following listed methods of QRadioButton class are most commonly used. setChecked() Changes the state of radio button setText() Sets the label associated with the button text() Retrieves the caption of button isChecked() Checks if the button is selected Default signal associated with QRadioButton object is toggled(), although other signals inherited from QAbstractButton class can also be implemented. Here two mutually exclusive radio buttons are constructed on a top level window. Default state of b1 is set to checked by the statement − Self.b1.setChecked(True) The toggled() signal of both the buttons is connected to btnstate() function. Use of lambda allows the source of signal to be passed to the function as an argument. self.b1.toggled.connect(lambda:self.btnstate(self.b1)) self.b2.toggled.connect(lambda:self.btnstate(self.b2)) The btnstate() function checks state of button emitting toggled() signal. if b.isChecked() == True: print b.text()+" is selected" else: print b.text()+" is deselected" Complete code for QRadioButton example is as below − import sys from PyQt5.QtCore import * from PyQt5.QtGui import * from PyQt5.QtWidgets import * class Radiodemo(QWidget): def __init__(self, parent = None): super(Radiodemo, self).__init__(parent) layout = QHBoxLayout() self.b1 = QRadioButton("Button1") self.b1.setChecked(True) self.b1.toggled.connect(lambda:self.btnstate(self.b1)) layout.addWidget(self.b1) self.b2 = QRadioButton("Button2") self.b2.toggled.connect(lambda:self.btnstate(self.b2)) layout.addWidget(self.b2) self.setLayout(layout) self.setWindowTitle("RadioButton demo") def btnstate(self,b): if b.text() == "Button1": if b.isChecked() == True: print b.text()+" is selected" else: print b.text()+" is deselected" if b.text() == "Button2": if b.isChecked() == True: print b.text()+" is selected" else: print b.text()+" is deselected" def main(): app = QApplication(sys.argv) ex = Radiodemo() ex.show() sys.exit(app.exec_()) if __name__ == '__main__': main() The above code produces the following output − Button1 is deselected Button2 is selected Button2 is deselected Button1 is selected 146 Lectures 22.5 hours ALAA EID Print Add Notes Bookmark this page
[ { "code": null, "e": 2152, "s": 1963, "text": "A QRadioButton class object presents a selectable button with a text label. The user can select one of many options presented on the form. This class is derived from QAbstractButton class." }, { "code": null, "e": 2482, "s": 2152, "text": "Radio buttons are autoexclusive by default. Hence, only one of the radio buttons in the parent window can be selected at a time. If one is selected, previously selected button is automatically deselected. Radio buttons can also be put in a QGroupBox or QButtonGroup to create more than one selectable fields on the parent window." }, { "code": null, "e": 2557, "s": 2482, "text": "The following listed methods of QRadioButton class are most commonly used." }, { "code": null, "e": 2570, "s": 2557, "text": "setChecked()" }, { "code": null, "e": 2604, "s": 2570, "text": "Changes the state of radio button" }, { "code": null, "e": 2614, "s": 2604, "text": "setText()" }, { "code": null, "e": 2656, "s": 2614, "text": "Sets the label associated with the button" }, { "code": null, "e": 2663, "s": 2656, "text": "text()" }, { "code": null, "e": 2695, "s": 2663, "text": "Retrieves the caption of button" }, { "code": null, "e": 2707, "s": 2695, "text": "isChecked()" }, { "code": null, "e": 2740, "s": 2707, "text": "Checks if the button is selected" }, { "code": null, "e": 2890, "s": 2740, "text": "Default signal associated with QRadioButton object is toggled(), although other signals inherited from QAbstractButton class can also be implemented." }, { "code": null, "e": 2971, "s": 2890, "text": "Here two mutually exclusive radio buttons are constructed on a top level window." }, { "code": null, "e": 3028, "s": 2971, "text": "Default state of b1 is set to checked by the statement −" }, { "code": null, "e": 3054, "s": 3028, "text": "Self.b1.setChecked(True)\n" }, { "code": null, "e": 3219, "s": 3054, "text": "The toggled() signal of both the buttons is connected to btnstate() function. Use of lambda allows the source of signal to be passed to the function as an argument." }, { "code": null, "e": 3330, "s": 3219, "text": "self.b1.toggled.connect(lambda:self.btnstate(self.b1))\nself.b2.toggled.connect(lambda:self.btnstate(self.b2))\n" }, { "code": null, "e": 3404, "s": 3330, "text": "The btnstate() function checks state of button emitting toggled() signal." }, { "code": null, "e": 3513, "s": 3404, "text": "if b.isChecked() == True:\n print b.text()+\" is selected\"\n else:\n print b.text()+\" is deselected\"" }, { "code": null, "e": 3566, "s": 3513, "text": "Complete code for QRadioButton example is as below −" }, { "code": null, "e": 4695, "s": 3566, "text": "import sys\nfrom PyQt5.QtCore import *\nfrom PyQt5.QtGui import *\nfrom PyQt5.QtWidgets import *\n\nclass Radiodemo(QWidget):\n def __init__(self, parent = None):\n super(Radiodemo, self).__init__(parent)\n\t\t\n layout = QHBoxLayout()\n self.b1 = QRadioButton(\"Button1\")\n self.b1.setChecked(True)\n self.b1.toggled.connect(lambda:self.btnstate(self.b1))\n layout.addWidget(self.b1)\n\t\t\n self.b2 = QRadioButton(\"Button2\")\n self.b2.toggled.connect(lambda:self.btnstate(self.b2))\n\n layout.addWidget(self.b2)\n self.setLayout(layout)\n self.setWindowTitle(\"RadioButton demo\")\n\t\t\n def btnstate(self,b):\n if b.text() == \"Button1\":\n if b.isChecked() == True:\n print b.text()+\" is selected\"\n else:\n print b.text()+\" is deselected\"\n\t\t\t\t\n if b.text() == \"Button2\":\n if b.isChecked() == True:\n print b.text()+\" is selected\"\n else:\n print b.text()+\" is deselected\"\n\t\t\t\t\ndef main():\n\n app = QApplication(sys.argv)\n ex = Radiodemo()\n ex.show()\n sys.exit(app.exec_())\n\t\nif __name__ == '__main__':\n main()" }, { "code": null, "e": 4742, "s": 4695, "text": "The above code produces the following output −" }, { "code": null, "e": 4827, "s": 4742, "text": "Button1 is deselected\nButton2 is selected\nButton2 is deselected\nButton1 is selected\n" }, { "code": null, "e": 4864, "s": 4827, "text": "\n 146 Lectures \n 22.5 hours \n" }, { "code": null, "e": 4874, "s": 4864, "text": " ALAA EID" }, { "code": null, "e": 4881, "s": 4874, "text": " Print" }, { "code": null, "e": 4892, "s": 4881, "text": " Add Notes" } ]
Equivalent of waitForVisible/waitForElementPresent in Selenium WebDriver tests using Java?
There are equivalent methods for waitForVisible/waitForElementPresent in Selenium webdriver. They are a part of the synchronization concept in Selenium. The implicit and explicit waits are the two types of waits in synchronization. The implicit wait is the wait applied to the webdriver for a specified amount of time for all elements. Once this time has elapsed and an element is still not available, an expectation is thrown. driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS); Code Implementation with implicit wait import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import java.util.concurrent.TimeUnit; public class ImplctWait{ public static void main(String[] args) { System.setProperty("webdriver.chrome.driver", "C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe"); WebDriver driver = new ChromeDriver(); //implicit wait of 5 secs driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS); //URL launch driver.get("https://www.tutorialspoint.com/index.htm"); // identify element WebElement m = driver.findElement(By.tagName("h4")); System.out.println("Element text is: " + m.getText()); driver.quit(); } } The explicit wait is the wait applied to the webdriver for a specified amount of time for an expected condition to be satisfied for an element. Once this time has elapsed and the expected criteria is not satisfied, an exception is thrown. An equivalent to waitForVisible method can be the visibilityOfElementLocated expected condition in explicit wait. Also, an equivalent to waitForElementPresent method can be the presenceOfElementLocated expected condition. WebDriverWait w= (new WebDriverWait(driver,5 )); w.until(ExpectedConditions.presenceOfElementLocated(By.id("txt"))); w.until(ExpectedConditions.visibilityOfElementLocated (By.name("nam-txt"))); import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.WebDriverWait; public class ExplicitWt{ public static void main(String[] args) { System.setProperty("webdriver.chrome.driver", "C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe"); WebDriver driver = new ChromeDriver(); //launch URL driver.get("https://www.tutorialspoint.com/index.htm"); //explicit wait condition - presenceOfElementLocated WebDriverWait w= (new WebDriverWait(driver, 7)); w.until(ExpectedConditions.presenceOfElementLocated(By.xpath("//*[text()='Library']"))); WebElement m = driver.findElement(By.xpath("//*[text()='Library']")); m.click(); //explicit wait condition - visibilityOfElementLocated w.until(ExpectedConditions.visibilityOfElementLocated (By.linkText("Subscribe to Premium"))); WebElement n = driver.findElement(By.linkText("Subscribe to Premium")); String s = n.getText(); System.out.println("Text is: " + s); driver.quit(); } }
[ { "code": null, "e": 1215, "s": 1062, "text": "There are equivalent methods for waitForVisible/waitForElementPresent in Selenium webdriver. They are a part of the synchronization concept in Selenium." }, { "code": null, "e": 1294, "s": 1215, "text": "The implicit and explicit waits are the two types of waits in synchronization." }, { "code": null, "e": 1490, "s": 1294, "text": "The implicit wait is the wait applied to the webdriver for a specified amount of time for all elements. Once this time has elapsed and an element is still not available, an expectation is thrown." }, { "code": null, "e": 1554, "s": 1490, "text": "driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);" }, { "code": null, "e": 1593, "s": 1554, "text": "Code Implementation with implicit wait" }, { "code": null, "e": 2375, "s": 1593, "text": "import org.openqa.selenium.By;\nimport org.openqa.selenium.WebDriver;\nimport org.openqa.selenium.WebElement;\nimport org.openqa.selenium.chrome.ChromeDriver;\nimport java.util.concurrent.TimeUnit;\npublic class ImplctWait{\n public static void main(String[] args) {\n System.setProperty(\"webdriver.chrome.driver\",\n \"C:\\\\Users\\\\ghs6kor\\\\Desktop\\\\Java\\\\chromedriver.exe\");\n WebDriver driver = new ChromeDriver();\n //implicit wait of 5 secs\n driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);\n //URL launch\n driver.get(\"https://www.tutorialspoint.com/index.htm\");\n // identify element\n WebElement m = driver.findElement(By.tagName(\"h4\"));\n System.out.println(\"Element text is: \" + m.getText());\n driver.quit();\n }\n}" }, { "code": null, "e": 2614, "s": 2375, "text": "The explicit wait is the wait applied to the webdriver for a specified amount of time for an expected condition to be satisfied for an element. Once this time has elapsed and the expected criteria is not satisfied, an exception is thrown." }, { "code": null, "e": 2836, "s": 2614, "text": "An equivalent to waitForVisible method can be the visibilityOfElementLocated expected condition in explicit wait. Also, an equivalent to waitForElementPresent method can be the presenceOfElementLocated expected condition." }, { "code": null, "e": 3030, "s": 2836, "text": "WebDriverWait w= (new WebDriverWait(driver,5 ));\nw.until(ExpectedConditions.presenceOfElementLocated(By.id(\"txt\")));\nw.until(ExpectedConditions.visibilityOfElementLocated (By.name(\"nam-txt\")));" }, { "code": null, "e": 4251, "s": 3030, "text": "import org.openqa.selenium.By;\nimport org.openqa.selenium.WebDriver;\nimport org.openqa.selenium.WebElement;\nimport org.openqa.selenium.chrome.ChromeDriver;\nimport org.openqa.selenium.support.ui.ExpectedConditions;\nimport org.openqa.selenium.support.ui.WebDriverWait;\npublic class ExplicitWt{\n public static void main(String[] args) {\n System.setProperty(\"webdriver.chrome.driver\",\n \"C:\\\\Users\\\\ghs6kor\\\\Desktop\\\\Java\\\\chromedriver.exe\");\n WebDriver driver = new ChromeDriver();\n //launch URL\n driver.get(\"https://www.tutorialspoint.com/index.htm\");\n //explicit wait condition - presenceOfElementLocated\n WebDriverWait w= (new WebDriverWait(driver, 7));\n w.until(ExpectedConditions.presenceOfElementLocated(By.xpath(\"//*[text()='Library']\")));\n WebElement m = driver.findElement(By.xpath(\"//*[text()='Library']\"));\n m.click();\n //explicit wait condition - visibilityOfElementLocated\n w.until(ExpectedConditions.visibilityOfElementLocated (By.linkText(\"Subscribe to Premium\")));\n WebElement n = driver.findElement(By.linkText(\"Subscribe to Premium\"));\n String s = n.getText();\n System.out.println(\"Text is: \" + s);\n driver.quit();\n }\n}" } ]
Check for Majority Element in a sorted array - GeeksforGeeks
03 Mar, 2022 Question: Write a C function to find if a given integer x appears more than n/2 times in a sorted array of n integers. Basically, we need to write a function say isMajority() that takes an array (arr[] ), array’s size (n) and a number to be searched (x) as parameters and returns true if x is a majority element (present more than n/2 times). Examples: Input: arr[] = {1, 2, 3, 3, 3, 3, 10}, x = 3 Output: True (x appears more than n/2 times in the given array) Input: arr[] = {1, 1, 2, 4, 4, 4, 6, 6}, x = 4 Output: False (x doesn't appear more than n/2 times in the given array) Input: arr[] = {1, 1, 1, 2, 2}, x = 1 Output: True (x appears more than n/2 times in the given array) METHOD 1 (Using Linear Search) Linearly search for the first occurrence of the element, once you find it (let at index i), check element at index i + n/2. If element is present at i+n/2 then return 1 else return 0. C++ C Java Python3 C# PHP Javascript /* C++ Program to check for majority element in a sorted array */#include<bits/stdc++.h>using namespace std; bool isMajority(int arr[], int n, int x){ int i; /* get last index according to n (even or odd) */ int last_index = n % 2 ? (n / 2 + 1): (n / 2); /* search for first occurrence of x in arr[]*/ for (i = 0; i < last_index; i++) { /* check if x is present and is present more than n/2 times */ if (arr[i] == x && arr[i + n / 2] == x) return 1; } return 0;} /* Driver code */int main(){ int arr[] ={1, 2, 3, 4, 4, 4, 4}; int n = sizeof(arr)/sizeof(arr[0]); int x = 4; if (isMajority(arr, n, x)) cout << x <<" appears more than "<< n/2 << " times in arr[]"<< endl; else cout <<x <<" does not appear more than" << n/2 <<" times in arr[]" << endl; return 0;} // This code is contributed by shivanisinghss2110 /* C Program to check for majority element in a sorted array */# include <stdio.h># include <stdbool.h> bool isMajority(int arr[], int n, int x){ int i; /* get last index according to n (even or odd) */ int last_index = n%2? (n/2+1): (n/2); /* search for first occurrence of x in arr[]*/ for (i = 0; i < last_index; i++) { /* check if x is present and is present more than n/2 times */ if (arr[i] == x && arr[i+n/2] == x) return 1; } return 0;} /* Driver program to check above function */int main(){ int arr[] ={1, 2, 3, 4, 4, 4, 4}; int n = sizeof(arr)/sizeof(arr[0]); int x = 4; if (isMajority(arr, n, x)) printf("%d appears more than %d times in arr[]", x, n/2); else printf("%d does not appear more than %d times in arr[]", x, n/2); return 0;} /* Program to check for majority element in a sorted array */import java.io.*; class Majority { static boolean isMajority(int arr[], int n, int x) { int i, last_index = 0; /* get last index according to n (even or odd) */ last_index = (n%2==0)? n/2: n/2+1; /* search for first occurrence of x in arr[]*/ for (i = 0; i < last_index; i++) { /* check if x is present and is present more than n/2 times */ if (arr[i] == x && arr[i+n/2] == x) return true; } return false; } /* Driver function to check for above functions*/ public static void main (String[] args) { int arr[] = {1, 2, 3, 4, 4, 4, 4}; int n = arr.length; int x = 4; if (isMajority(arr, n, x)==true) System.out.println(x+" appears more than "+ n/2+" times in arr[]"); else System.out.println(x+" does not appear more than "+ n/2+" times in arr[]"); }}/*This article is contributed by Devesh Agrawal*/ '''Python3 Program to check for majority element in a sorted array''' def isMajority(arr, n, x): # get last index according to n (even or odd) */ last_index = (n//2 + 1) if n % 2 == 0 else (n//2) # search for first occurrence of x in arr[]*/ for i in range(last_index): # check if x is present and is present more than n / 2 times */ if arr[i] == x and arr[i + n//2] == x: return 1 # Driver program to check above function */arr = [1, 2, 3, 4, 4, 4, 4]n = len(arr)x = 4if (isMajority(arr, n, x)): print ("% d appears more than % d times in arr[]" %(x, n//2))else: print ("% d does not appear more than % d times in arr[]" %(x, n//2)) # This code is contributed by shreyanshi_arun. // C# Program to check for majority// element in a sorted arrayusing System; class GFG { static bool isMajority(int[] arr, int n, int x) { int i, last_index = 0; // Get last index according to // n (even or odd) last_index = (n % 2 == 0) ? n / 2 : n / 2 + 1; // Search for first occurrence // of x in arr[] for (i = 0; i < last_index; i++) { // Check if x is present and // is present more than n/2 times if (arr[i] == x && arr[i + n / 2] == x) return true; } return false; } // Driver code public static void Main() { int[] arr = { 1, 2, 3, 4, 4, 4, 4 }; int n = arr.Length; int x = 4; if (isMajority(arr, n, x) == true) Console.Write(x + " appears more than " + n / 2 + " times in arr[]"); else Console.Write(x + " does not appear more than " + n / 2 + " times in arr[]"); }} // This code is contributed by Sam007 <?php// PHP Program to check for// majority element in a// sorted array // function returns majority// element in a sorted arrayfunction isMajority($arr, $n, $x){ $i; // get last index according // to n (even or odd) $last_index = $n % 2? ($n / 2 + 1): ($n / 2); // search for first occurrence // of x in arr[] for ($i = 0; $i < $last_index; $i++) { // check if x is present and // is present more than n/2 // times if ($arr[$i] == $x && $arr[$i + $n / 2] == $x) return 1; } return 0;} // Driver Code $arr = array(1, 2, 3, 4, 4, 4, 4); $n = sizeof($arr); $x = 4; if (isMajority($arr, $n, $x)) echo $x, " appears more than " , floor($n / 2), " times in arr[]"; else echo $x, "does not appear more than " , floor($n / 2), "times in arr[]"; // This code is contributed by Ajit?> <script> // Javascript Program to check for majority // element in a sorted array function isMajority(arr, n, x) { let i, last_index = 0; // Get last index according to // n (even or odd) last_index = (n % 2 == 0) ? parseInt(n / 2, 10) : parseInt(n / 2, 10) + 1; // Search for first occurrence // of x in arr[] for (i = 0; i < last_index; i++) { // Check if x is present and // is present more than n/2 times if (arr[i] == x && arr[i + parseInt(n / 2, 10)] == x) return true; } return false; } let arr = [ 1, 2, 3, 4, 4, 4, 4 ]; let n = arr.length; let x = 4; if (isMajority(arr, n, x) == true) document.write(x + " appears more than " + parseInt(n / 2, 10) + " times in arr[]"); else document.write(x + " does not appear more than " + parseInt(n / 2, 10) + " times in arr[]"); </script> Output: 4 appears more than 3 times in arr[] Time Complexity: O(n) Auxiliary Space: O(1) METHOD 2 (Using Binary Search) Use binary search methodology to find the first occurrence of the given number. The criteria for binary search is important here. C++ C Java Python3 C# Javascript // C++ program to check for majority// element in a sorted array#include<bits/stdc++.h>using namespace std; // If x is present in arr[low...high]// then returns the index of first// occurrence of x, otherwise returns -1int _binarySearch(int arr[], int low, int high, int x); // This function returns true if the x// is present more than n/2 times in// arr[] of size nbool isMajority(int arr[], int n, int x){ // Find the index of first occurrence // of x in arr[] int i = _binarySearch(arr, 0, n - 1, x); // If element is not present at all, // return false if (i == -1) return false; // Check if the element is present // more than n/2 times if (((i + n / 2) <= (n - 1)) && arr[i + n / 2] == x) return true; else return false;} // If x is present in arr[low...high] then// returns the index of first occurrence// of x, otherwise returns -1int _binarySearch(int arr[], int low, int high, int x){ if (high >= low) { int mid = (low + high)/2; /*low + (high - low)/2;*/ /* Check if arr[mid] is the first occurrence of x. arr[mid] is first occurrence if x is one of the following is true: (i) mid == 0 and arr[mid] == x (ii) arr[mid-1] < x and arr[mid] == x */ if ((mid == 0 || x > arr[mid - 1]) && (arr[mid] == x) ) return mid; else if (x > arr[mid]) return _binarySearch(arr, (mid + 1), high, x); else return _binarySearch(arr, low, (mid - 1), x); } return -1;} // Driver codeint main(){ int arr[] = { 1, 2, 3, 3, 3, 3, 10 }; int n = sizeof(arr) / sizeof(arr[0]); int x = 3; if (isMajority(arr, n, x)) cout << x << " appears more than " << n / 2 << " times in arr[]" << endl; else cout << x << " does not appear more than" << n / 2 << " times in arr[]" << endl; return 0;} // This code is contributed by shivanisinghss2110 /* C Program to check for majority element in a sorted array */# include <stdio.h># include <stdbool.h> /* If x is present in arr[low...high] then returns the index offirst occurrence of x, otherwise returns -1 */int _binarySearch(int arr[], int low, int high, int x); /* This function returns true if the x is present more than n/2times in arr[] of size n */bool isMajority(int arr[], int n, int x){ /* Find the index of first occurrence of x in arr[] */ int i = _binarySearch(arr, 0, n-1, x); /* If element is not present at all, return false*/ if (i == -1) return false; /* check if the element is present more than n/2 times */ if (((i + n/2) <= (n -1)) && arr[i + n/2] == x) return true; else return false;} /* If x is present in arr[low...high] then returns the index offirst occurrence of x, otherwise returns -1 */int _binarySearch(int arr[], int low, int high, int x){ if (high >= low) { int mid = (low + high)/2; /*low + (high - low)/2;*/ /* Check if arr[mid] is the first occurrence of x. arr[mid] is first occurrence if x is one of the following is true: (i) mid == 0 and arr[mid] == x (ii) arr[mid-1] < x and arr[mid] == x */ if ( (mid == 0 || x > arr[mid-1]) && (arr[mid] == x) ) return mid; else if (x > arr[mid]) return _binarySearch(arr, (mid + 1), high, x); else return _binarySearch(arr, low, (mid -1), x); } return -1;} /* Driver program to check above functions */int main(){ int arr[] = {1, 2, 3, 3, 3, 3, 10}; int n = sizeof(arr)/sizeof(arr[0]); int x = 3; if (isMajority(arr, n, x)) printf("%d appears more than %d times in arr[]", x, n/2); else printf("%d does not appear more than %d times in arr[]", x, n/2); return 0;} /* Java Program to check for majority element in a sorted array */import java.io.*; class Majority { /* If x is present in arr[low...high] then returns the index of first occurrence of x, otherwise returns -1 */ static int _binarySearch(int arr[], int low, int high, int x) { if (high >= low) { int mid = (low + high)/2; /*low + (high - low)/2;*/ /* Check if arr[mid] is the first occurrence of x. arr[mid] is first occurrence if x is one of the following is true: (i) mid == 0 and arr[mid] == x (ii) arr[mid-1] < x and arr[mid] == x */ if ( (mid == 0 || x > arr[mid-1]) && (arr[mid] == x) ) return mid; else if (x > arr[mid]) return _binarySearch(arr, (mid + 1), high, x); else return _binarySearch(arr, low, (mid -1), x); } return -1; } /* This function returns true if the x is present more than n/2 times in arr[] of size n */ static boolean isMajority(int arr[], int n, int x) { /* Find the index of first occurrence of x in arr[] */ int i = _binarySearch(arr, 0, n-1, x); /* If element is not present at all, return false*/ if (i == -1) return false; /* check if the element is present more than n/2 times */ if (((i + n/2) <= (n -1)) && arr[i + n/2] == x) return true; else return false; } /*Driver function to check for above functions*/ public static void main (String[] args) { int arr[] = {1, 2, 3, 3, 3, 3, 10}; int n = arr.length; int x = 3; if (isMajority(arr, n, x)==true) System.out.println(x + " appears more than "+ n/2 + " times in arr[]"); else System.out.println(x + " does not appear more than " + n/2 + " times in arr[]"); }}/*This code is contributed by Devesh Agrawal*/ '''Python3 Program to check for majority element in a sorted array''' # This function returns true if the x is present more than n / 2# times in arr[] of size n */def isMajority(arr, n, x): # Find the index of first occurrence of x in arr[] */ i = _binarySearch(arr, 0, n-1, x) # If element is not present at all, return false*/ if i == -1: return False # check if the element is present more than n / 2 times */ if ((i + n//2) <= (n -1)) and arr[i + n//2] == x: return True else: return False # If x is present in arr[low...high] then returns the index of# first occurrence of x, otherwise returns -1 */def _binarySearch(arr, low, high, x): if high >= low: mid = (low + high)//2 # low + (high - low)//2; ''' Check if arr[mid] is the first occurrence of x. arr[mid] is first occurrence if x is one of the following is true: (i) mid == 0 and arr[mid] == x (ii) arr[mid-1] < x and arr[mid] == x''' if (mid == 0 or x > arr[mid-1]) and (arr[mid] == x): return mid elif x > arr[mid]: return _binarySearch(arr, (mid + 1), high, x) else: return _binarySearch(arr, low, (mid -1), x) return -1 # Driver program to check above functions */arr = [1, 2, 3, 3, 3, 3, 10]n = len(arr)x = 3if (isMajority(arr, n, x)): print ("% d appears more than % d times in arr[]" % (x, n//2))else: print ("% d does not appear more than % d times in arr[]" % (x, n//2)) # This code is contributed by shreyanshi_arun. // C# Program to check for majority// element in a sorted array */using System; class GFG { // If x is present in arr[low...high] // then returns the index of first // occurrence of x, otherwise returns -1 static int _binarySearch(int[] arr, int low, int high, int x) { if (high >= low) { int mid = (low + high) / 2; //low + (high - low)/2; // Check if arr[mid] is the first // occurrence of x. arr[mid] is // first occurrence if x is one of // the following is true: // (i) mid == 0 and arr[mid] == x // (ii) arr[mid-1] < x and arr[mid] == x if ((mid == 0 || x > arr[mid - 1]) && (arr[mid] == x)) return mid; else if (x > arr[mid]) return _binarySearch(arr, (mid + 1), high, x); else return _binarySearch(arr, low, (mid - 1), x); } return -1; } // This function returns true if the x is // present more than n/2 times in arr[] // of size n static bool isMajority(int[] arr, int n, int x) { // Find the index of first occurrence // of x in arr[] int i = _binarySearch(arr, 0, n - 1, x); // If element is not present at all, // return false if (i == -1) return false; // check if the element is present // more than n/2 times if (((i + n / 2) <= (n - 1)) && arr[i + n / 2] == x) return true; else return false; } //Driver code public static void Main() { int[] arr = { 1, 2, 3, 3, 3, 3, 10 }; int n = arr.Length; int x = 3; if (isMajority(arr, n, x) == true) Console.Write(x + " appears more than " + n / 2 + " times in arr[]"); else Console.Write(x + " does not appear more than " + n / 2 + " times in arr[]"); }} // This code is contributed by Sam007 <script> // Javascript Program to check for majority // element in a sorted array */ // If x is present in arr[low...high] // then returns the index of first // occurrence of x, otherwise returns -1 function _binarySearch(arr, low, high, x) { if (high >= low) { let mid = parseInt((low + high) / 2, 10); //low + (high - low)/2; // Check if arr[mid] is the first // occurrence of x. arr[mid] is // first occurrence if x is one of // the following is true: // (i) mid == 0 and arr[mid] == x // (ii) arr[mid-1] < x and arr[mid] == x if ((mid == 0 || x > arr[mid - 1]) && (arr[mid] == x)) return mid; else if (x > arr[mid]) return _binarySearch(arr, (mid + 1), high, x); else return _binarySearch(arr, low, (mid - 1), x); } return -1; } // This function returns true if the x is // present more than n/2 times in arr[] // of size n function isMajority(arr, n, x) { // Find the index of first occurrence // of x in arr[] let i = _binarySearch(arr, 0, n - 1, x); // If element is not present at all, // return false if (i == -1) return false; // check if the element is present // more than n/2 times if (((i + parseInt(n / 2, 10)) <= (n - 1)) && arr[i + parseInt(n / 2, 10)] == x) return true; else return false; } let arr = [ 1, 2, 3, 3, 3, 3, 10 ]; let n = arr.length; let x = 3; if (isMajority(arr, n, x) == true) document.write(x + " appears more than " + parseInt(n / 2, 10) + " times in arr[]"); else document.write(x + " does not appear more than " + parseInt(n / 2, 10) + " times in arr[]"); </script> Output: 3 appears more than 3 times in arr[] Time Complexity: O(Logn) Auxiliary Space: O(1)Algorithmic Paradigm: Divide and Conquer METHOD 3: If it is already given that the array is sorted and there exists a majority element, checking if a particular element is as easy as checking if the middle element of the array is the number we are checking against. Since a majority element occurs more than n/2 times in an array, it will always be the middle element. We can use this logic to check if the given number is the majority element. C++ C Java Python3 C# Javascript #include <iostream>using namespace std; bool isMajorityElement(int arr[], int n, int key){ if (arr[n / 2] == key) return true; else return false;} int main(){ int arr[] = { 1, 2, 3, 3, 3, 3, 10 }; int n = sizeof(arr) / sizeof(arr[0]); int x = 3; if (isMajorityElement(arr, n, x)) cout << x << " appears more than " << n / 2 << " times in arr[]" << endl; else cout << x << " does not appear more than" << n / 2 << " times in arr[]" << endl; return 0;} // This code is contributed by shivanisinghss2110 #include <stdio.h>#include <stdbool.h> bool isMajorityElement(int arr[], int n, int key){ if (arr[n / 2] == key) return true; else return false;} int main(){ int arr[] = { 1, 2, 3, 3, 3, 3, 10 }; int n = sizeof(arr) / sizeof(arr[0]); int x = 3; if (isMajorityElement(arr, n, x)) printf("%d appears more than %d times in arr[]", x, n / 2); else printf("%d does not appear more than %d times in " "arr[]", x, n / 2); return 0;} import java.util.*; class GFG{ static boolean isMajorityElement(int arr[], int n, int key){ if (arr[n / 2] == key) return true; else return false;} // Driver Codepublic static void main(String[] args){ int arr[] = { 1, 2, 3, 3, 3, 3, 10 }; int n = arr.length; int x = 3; if (isMajorityElement(arr, n, x)) System.out.printf("%d appears more than %d " + "times in arr[]", x, n / 2); else System.out.printf("%d does not appear more " + "than %d times in " + "arr[]", x, n / 2);}} // This code is contributed by aashish1995 def isMajorityElement(arr, n, key): if (arr[n // 2] == key): return True return False # Driver codeif __name__ == "__main__": arr = [1, 2, 3, 3, 3, 3, 10] n = len(arr) x = 3 if (isMajorityElement(arr, n, x)): print(x, " appears more than ", n // 2 , " times in arr[]") else: print(x, " does not appear more than", n // 2, " times in arr[]") # This code is contributed by Chitranayal using System;class GFG{ static bool isMajorityElement(int []arr, int n, int key){ if (arr[n / 2] == key) return true; else return false;} // Driver Codepublic static void Main(String[] args){ int []arr = { 1, 2, 3, 3, 3, 3, 10 }; int n = arr.Length; int x = 3; if (isMajorityElement(arr, n, x)) Console.Write(x + " appears more than " + n/2 + " times in []arr"); else Console.Write(x + " does not appear more " + "than " + n/2 + " times in arr[]");}} // This code is contributed by aashish1995 <script> function isMajorityElement(arr, n, key) { if (arr[parseInt(n / 2, 10)] == key) return true; else return false; } let arr = [ 1, 2, 3, 3, 3, 3, 10 ]; let n = arr.length; let x = 3; if (isMajorityElement(arr, n, x)) document.write(x + " appears more than " + parseInt(n/2, 10) + " times in arr[]"); else document.write(x + " does not appear more " + "than " + parseInt(n/2, 10) + " times in arr[]"); </script> 3 appears more than 3 times in arr[] Time complexity: O(1)Auxiliary Space: O(1) Please write comments if you find any bug in the above program/algorithm or a better way to solve the same problem. jit_t _np_ ukasp aashish1995 shivanisinghss2110 rameshtravel07 suresh07 divyeshrabadiya07 rohitsingh07052 Binary Search Arrays Divide and Conquer Arrays Divide and Conquer Binary Search Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Next Greater Element Window Sliding Technique Count pairs with given sum Program to find sum of elements in a given array Reversal algorithm for array rotation QuickSort Merge Sort Binary Search Program for Tower of Hanoi Divide and Conquer Algorithm | Introduction
[ { "code": null, "e": 24429, "s": 24401, "text": "\n03 Mar, 2022" }, { "code": null, "e": 24772, "s": 24429, "text": "Question: Write a C function to find if a given integer x appears more than n/2 times in a sorted array of n integers. Basically, we need to write a function say isMajority() that takes an array (arr[] ), array’s size (n) and a number to be searched (x) as parameters and returns true if x is a majority element (present more than n/2 times)." }, { "code": null, "e": 24783, "s": 24772, "text": "Examples: " }, { "code": null, "e": 25115, "s": 24783, "text": "Input: arr[] = {1, 2, 3, 3, 3, 3, 10}, x = 3\nOutput: True (x appears more than n/2 times in the given array)\n\nInput: arr[] = {1, 1, 2, 4, 4, 4, 6, 6}, x = 4\nOutput: False (x doesn't appear more than n/2 times in the given array)\n\nInput: arr[] = {1, 1, 1, 2, 2}, x = 1\nOutput: True (x appears more than n/2 times in the given array)" }, { "code": null, "e": 25330, "s": 25115, "text": "METHOD 1 (Using Linear Search) Linearly search for the first occurrence of the element, once you find it (let at index i), check element at index i + n/2. If element is present at i+n/2 then return 1 else return 0." }, { "code": null, "e": 25334, "s": 25330, "text": "C++" }, { "code": null, "e": 25336, "s": 25334, "text": "C" }, { "code": null, "e": 25341, "s": 25336, "text": "Java" }, { "code": null, "e": 25349, "s": 25341, "text": "Python3" }, { "code": null, "e": 25352, "s": 25349, "text": "C#" }, { "code": null, "e": 25356, "s": 25352, "text": "PHP" }, { "code": null, "e": 25367, "s": 25356, "text": "Javascript" }, { "code": "/* C++ Program to check for majority element in a sorted array */#include<bits/stdc++.h>using namespace std; bool isMajority(int arr[], int n, int x){ int i; /* get last index according to n (even or odd) */ int last_index = n % 2 ? (n / 2 + 1): (n / 2); /* search for first occurrence of x in arr[]*/ for (i = 0; i < last_index; i++) { /* check if x is present and is present more than n/2 times */ if (arr[i] == x && arr[i + n / 2] == x) return 1; } return 0;} /* Driver code */int main(){ int arr[] ={1, 2, 3, 4, 4, 4, 4}; int n = sizeof(arr)/sizeof(arr[0]); int x = 4; if (isMajority(arr, n, x)) cout << x <<\" appears more than \"<< n/2 << \" times in arr[]\"<< endl; else cout <<x <<\" does not appear more than\" << n/2 <<\" times in arr[]\" << endl; return 0;} // This code is contributed by shivanisinghss2110", "e": 26305, "s": 25367, "text": null }, { "code": "/* C Program to check for majority element in a sorted array */# include <stdio.h># include <stdbool.h> bool isMajority(int arr[], int n, int x){ int i; /* get last index according to n (even or odd) */ int last_index = n%2? (n/2+1): (n/2); /* search for first occurrence of x in arr[]*/ for (i = 0; i < last_index; i++) { /* check if x is present and is present more than n/2 times */ if (arr[i] == x && arr[i+n/2] == x) return 1; } return 0;} /* Driver program to check above function */int main(){ int arr[] ={1, 2, 3, 4, 4, 4, 4}; int n = sizeof(arr)/sizeof(arr[0]); int x = 4; if (isMajority(arr, n, x)) printf(\"%d appears more than %d times in arr[]\", x, n/2); else printf(\"%d does not appear more than %d times in arr[]\", x, n/2); return 0;}", "e": 27181, "s": 26305, "text": null }, { "code": "/* Program to check for majority element in a sorted array */import java.io.*; class Majority { static boolean isMajority(int arr[], int n, int x) { int i, last_index = 0; /* get last index according to n (even or odd) */ last_index = (n%2==0)? n/2: n/2+1; /* search for first occurrence of x in arr[]*/ for (i = 0; i < last_index; i++) { /* check if x is present and is present more than n/2 times */ if (arr[i] == x && arr[i+n/2] == x) return true; } return false; } /* Driver function to check for above functions*/ public static void main (String[] args) { int arr[] = {1, 2, 3, 4, 4, 4, 4}; int n = arr.length; int x = 4; if (isMajority(arr, n, x)==true) System.out.println(x+\" appears more than \"+ n/2+\" times in arr[]\"); else System.out.println(x+\" does not appear more than \"+ n/2+\" times in arr[]\"); }}/*This article is contributed by Devesh Agrawal*/", "e": 28284, "s": 27181, "text": null }, { "code": "'''Python3 Program to check for majority element in a sorted array''' def isMajority(arr, n, x): # get last index according to n (even or odd) */ last_index = (n//2 + 1) if n % 2 == 0 else (n//2) # search for first occurrence of x in arr[]*/ for i in range(last_index): # check if x is present and is present more than n / 2 times */ if arr[i] == x and arr[i + n//2] == x: return 1 # Driver program to check above function */arr = [1, 2, 3, 4, 4, 4, 4]n = len(arr)x = 4if (isMajority(arr, n, x)): print (\"% d appears more than % d times in arr[]\" %(x, n//2))else: print (\"% d does not appear more than % d times in arr[]\" %(x, n//2)) # This code is contributed by shreyanshi_arun.", "e": 29104, "s": 28284, "text": null }, { "code": "// C# Program to check for majority// element in a sorted arrayusing System; class GFG { static bool isMajority(int[] arr, int n, int x) { int i, last_index = 0; // Get last index according to // n (even or odd) last_index = (n % 2 == 0) ? n / 2 : n / 2 + 1; // Search for first occurrence // of x in arr[] for (i = 0; i < last_index; i++) { // Check if x is present and // is present more than n/2 times if (arr[i] == x && arr[i + n / 2] == x) return true; } return false; } // Driver code public static void Main() { int[] arr = { 1, 2, 3, 4, 4, 4, 4 }; int n = arr.Length; int x = 4; if (isMajority(arr, n, x) == true) Console.Write(x + \" appears more than \" + n / 2 + \" times in arr[]\"); else Console.Write(x + \" does not appear more than \" + n / 2 + \" times in arr[]\"); }} // This code is contributed by Sam007", "e": 30229, "s": 29104, "text": null }, { "code": "<?php// PHP Program to check for// majority element in a// sorted array // function returns majority// element in a sorted arrayfunction isMajority($arr, $n, $x){ $i; // get last index according // to n (even or odd) $last_index = $n % 2? ($n / 2 + 1): ($n / 2); // search for first occurrence // of x in arr[] for ($i = 0; $i < $last_index; $i++) { // check if x is present and // is present more than n/2 // times if ($arr[$i] == $x && $arr[$i + $n / 2] == $x) return 1; } return 0;} // Driver Code $arr = array(1, 2, 3, 4, 4, 4, 4); $n = sizeof($arr); $x = 4; if (isMajority($arr, $n, $x)) echo $x, \" appears more than \" , floor($n / 2), \" times in arr[]\"; else echo $x, \"does not appear more than \" , floor($n / 2), \"times in arr[]\"; // This code is contributed by Ajit?>", "e": 31168, "s": 30229, "text": null }, { "code": "<script> // Javascript Program to check for majority // element in a sorted array function isMajority(arr, n, x) { let i, last_index = 0; // Get last index according to // n (even or odd) last_index = (n % 2 == 0) ? parseInt(n / 2, 10) : parseInt(n / 2, 10) + 1; // Search for first occurrence // of x in arr[] for (i = 0; i < last_index; i++) { // Check if x is present and // is present more than n/2 times if (arr[i] == x && arr[i + parseInt(n / 2, 10)] == x) return true; } return false; } let arr = [ 1, 2, 3, 4, 4, 4, 4 ]; let n = arr.length; let x = 4; if (isMajority(arr, n, x) == true) document.write(x + \" appears more than \" + parseInt(n / 2, 10) + \" times in arr[]\"); else document.write(x + \" does not appear more than \" + parseInt(n / 2, 10) + \" times in arr[]\"); </script>", "e": 32181, "s": 31168, "text": null }, { "code": null, "e": 32190, "s": 32181, "text": "Output: " }, { "code": null, "e": 32227, "s": 32190, "text": "4 appears more than 3 times in arr[]" }, { "code": null, "e": 32249, "s": 32227, "text": "Time Complexity: O(n)" }, { "code": null, "e": 32271, "s": 32249, "text": "Auxiliary Space: O(1)" }, { "code": null, "e": 32433, "s": 32271, "text": "METHOD 2 (Using Binary Search) Use binary search methodology to find the first occurrence of the given number. The criteria for binary search is important here. " }, { "code": null, "e": 32437, "s": 32433, "text": "C++" }, { "code": null, "e": 32439, "s": 32437, "text": "C" }, { "code": null, "e": 32444, "s": 32439, "text": "Java" }, { "code": null, "e": 32452, "s": 32444, "text": "Python3" }, { "code": null, "e": 32455, "s": 32452, "text": "C#" }, { "code": null, "e": 32466, "s": 32455, "text": "Javascript" }, { "code": "// C++ program to check for majority// element in a sorted array#include<bits/stdc++.h>using namespace std; // If x is present in arr[low...high]// then returns the index of first// occurrence of x, otherwise returns -1int _binarySearch(int arr[], int low, int high, int x); // This function returns true if the x// is present more than n/2 times in// arr[] of size nbool isMajority(int arr[], int n, int x){ // Find the index of first occurrence // of x in arr[] int i = _binarySearch(arr, 0, n - 1, x); // If element is not present at all, // return false if (i == -1) return false; // Check if the element is present // more than n/2 times if (((i + n / 2) <= (n - 1)) && arr[i + n / 2] == x) return true; else return false;} // If x is present in arr[low...high] then// returns the index of first occurrence// of x, otherwise returns -1int _binarySearch(int arr[], int low, int high, int x){ if (high >= low) { int mid = (low + high)/2; /*low + (high - low)/2;*/ /* Check if arr[mid] is the first occurrence of x. arr[mid] is first occurrence if x is one of the following is true: (i) mid == 0 and arr[mid] == x (ii) arr[mid-1] < x and arr[mid] == x */ if ((mid == 0 || x > arr[mid - 1]) && (arr[mid] == x) ) return mid; else if (x > arr[mid]) return _binarySearch(arr, (mid + 1), high, x); else return _binarySearch(arr, low, (mid - 1), x); } return -1;} // Driver codeint main(){ int arr[] = { 1, 2, 3, 3, 3, 3, 10 }; int n = sizeof(arr) / sizeof(arr[0]); int x = 3; if (isMajority(arr, n, x)) cout << x << \" appears more than \" << n / 2 << \" times in arr[]\" << endl; else cout << x << \" does not appear more than\" << n / 2 << \" times in arr[]\" << endl; return 0;} // This code is contributed by shivanisinghss2110", "e": 34580, "s": 32466, "text": null }, { "code": "/* C Program to check for majority element in a sorted array */# include <stdio.h># include <stdbool.h> /* If x is present in arr[low...high] then returns the index offirst occurrence of x, otherwise returns -1 */int _binarySearch(int arr[], int low, int high, int x); /* This function returns true if the x is present more than n/2times in arr[] of size n */bool isMajority(int arr[], int n, int x){ /* Find the index of first occurrence of x in arr[] */ int i = _binarySearch(arr, 0, n-1, x); /* If element is not present at all, return false*/ if (i == -1) return false; /* check if the element is present more than n/2 times */ if (((i + n/2) <= (n -1)) && arr[i + n/2] == x) return true; else return false;} /* If x is present in arr[low...high] then returns the index offirst occurrence of x, otherwise returns -1 */int _binarySearch(int arr[], int low, int high, int x){ if (high >= low) { int mid = (low + high)/2; /*low + (high - low)/2;*/ /* Check if arr[mid] is the first occurrence of x. arr[mid] is first occurrence if x is one of the following is true: (i) mid == 0 and arr[mid] == x (ii) arr[mid-1] < x and arr[mid] == x */ if ( (mid == 0 || x > arr[mid-1]) && (arr[mid] == x) ) return mid; else if (x > arr[mid]) return _binarySearch(arr, (mid + 1), high, x); else return _binarySearch(arr, low, (mid -1), x); } return -1;} /* Driver program to check above functions */int main(){ int arr[] = {1, 2, 3, 3, 3, 3, 10}; int n = sizeof(arr)/sizeof(arr[0]); int x = 3; if (isMajority(arr, n, x)) printf(\"%d appears more than %d times in arr[]\", x, n/2); else printf(\"%d does not appear more than %d times in arr[]\", x, n/2); return 0;}", "e": 36464, "s": 34580, "text": null }, { "code": "/* Java Program to check for majority element in a sorted array */import java.io.*; class Majority { /* If x is present in arr[low...high] then returns the index of first occurrence of x, otherwise returns -1 */ static int _binarySearch(int arr[], int low, int high, int x) { if (high >= low) { int mid = (low + high)/2; /*low + (high - low)/2;*/ /* Check if arr[mid] is the first occurrence of x. arr[mid] is first occurrence if x is one of the following is true: (i) mid == 0 and arr[mid] == x (ii) arr[mid-1] < x and arr[mid] == x */ if ( (mid == 0 || x > arr[mid-1]) && (arr[mid] == x) ) return mid; else if (x > arr[mid]) return _binarySearch(arr, (mid + 1), high, x); else return _binarySearch(arr, low, (mid -1), x); } return -1; } /* This function returns true if the x is present more than n/2 times in arr[] of size n */ static boolean isMajority(int arr[], int n, int x) { /* Find the index of first occurrence of x in arr[] */ int i = _binarySearch(arr, 0, n-1, x); /* If element is not present at all, return false*/ if (i == -1) return false; /* check if the element is present more than n/2 times */ if (((i + n/2) <= (n -1)) && arr[i + n/2] == x) return true; else return false; } /*Driver function to check for above functions*/ public static void main (String[] args) { int arr[] = {1, 2, 3, 3, 3, 3, 10}; int n = arr.length; int x = 3; if (isMajority(arr, n, x)==true) System.out.println(x + \" appears more than \"+ n/2 + \" times in arr[]\"); else System.out.println(x + \" does not appear more than \" + n/2 + \" times in arr[]\"); }}/*This code is contributed by Devesh Agrawal*/", "e": 38515, "s": 36464, "text": null }, { "code": "'''Python3 Program to check for majority element in a sorted array''' # This function returns true if the x is present more than n / 2# times in arr[] of size n */def isMajority(arr, n, x): # Find the index of first occurrence of x in arr[] */ i = _binarySearch(arr, 0, n-1, x) # If element is not present at all, return false*/ if i == -1: return False # check if the element is present more than n / 2 times */ if ((i + n//2) <= (n -1)) and arr[i + n//2] == x: return True else: return False # If x is present in arr[low...high] then returns the index of# first occurrence of x, otherwise returns -1 */def _binarySearch(arr, low, high, x): if high >= low: mid = (low + high)//2 # low + (high - low)//2; ''' Check if arr[mid] is the first occurrence of x. arr[mid] is first occurrence if x is one of the following is true: (i) mid == 0 and arr[mid] == x (ii) arr[mid-1] < x and arr[mid] == x''' if (mid == 0 or x > arr[mid-1]) and (arr[mid] == x): return mid elif x > arr[mid]: return _binarySearch(arr, (mid + 1), high, x) else: return _binarySearch(arr, low, (mid -1), x) return -1 # Driver program to check above functions */arr = [1, 2, 3, 3, 3, 3, 10]n = len(arr)x = 3if (isMajority(arr, n, x)): print (\"% d appears more than % d times in arr[]\" % (x, n//2))else: print (\"% d does not appear more than % d times in arr[]\" % (x, n//2)) # This code is contributed by shreyanshi_arun.", "e": 40181, "s": 38515, "text": null }, { "code": "// C# Program to check for majority// element in a sorted array */using System; class GFG { // If x is present in arr[low...high] // then returns the index of first // occurrence of x, otherwise returns -1 static int _binarySearch(int[] arr, int low, int high, int x) { if (high >= low) { int mid = (low + high) / 2; //low + (high - low)/2; // Check if arr[mid] is the first // occurrence of x. arr[mid] is // first occurrence if x is one of // the following is true: // (i) mid == 0 and arr[mid] == x // (ii) arr[mid-1] < x and arr[mid] == x if ((mid == 0 || x > arr[mid - 1]) && (arr[mid] == x)) return mid; else if (x > arr[mid]) return _binarySearch(arr, (mid + 1), high, x); else return _binarySearch(arr, low, (mid - 1), x); } return -1; } // This function returns true if the x is // present more than n/2 times in arr[] // of size n static bool isMajority(int[] arr, int n, int x) { // Find the index of first occurrence // of x in arr[] int i = _binarySearch(arr, 0, n - 1, x); // If element is not present at all, // return false if (i == -1) return false; // check if the element is present // more than n/2 times if (((i + n / 2) <= (n - 1)) && arr[i + n / 2] == x) return true; else return false; } //Driver code public static void Main() { int[] arr = { 1, 2, 3, 3, 3, 3, 10 }; int n = arr.Length; int x = 3; if (isMajority(arr, n, x) == true) Console.Write(x + \" appears more than \" + n / 2 + \" times in arr[]\"); else Console.Write(x + \" does not appear more than \" + n / 2 + \" times in arr[]\"); }} // This code is contributed by Sam007", "e": 42387, "s": 40181, "text": null }, { "code": "<script> // Javascript Program to check for majority // element in a sorted array */ // If x is present in arr[low...high] // then returns the index of first // occurrence of x, otherwise returns -1 function _binarySearch(arr, low, high, x) { if (high >= low) { let mid = parseInt((low + high) / 2, 10); //low + (high - low)/2; // Check if arr[mid] is the first // occurrence of x. arr[mid] is // first occurrence if x is one of // the following is true: // (i) mid == 0 and arr[mid] == x // (ii) arr[mid-1] < x and arr[mid] == x if ((mid == 0 || x > arr[mid - 1]) && (arr[mid] == x)) return mid; else if (x > arr[mid]) return _binarySearch(arr, (mid + 1), high, x); else return _binarySearch(arr, low, (mid - 1), x); } return -1; } // This function returns true if the x is // present more than n/2 times in arr[] // of size n function isMajority(arr, n, x) { // Find the index of first occurrence // of x in arr[] let i = _binarySearch(arr, 0, n - 1, x); // If element is not present at all, // return false if (i == -1) return false; // check if the element is present // more than n/2 times if (((i + parseInt(n / 2, 10)) <= (n - 1)) && arr[i + parseInt(n / 2, 10)] == x) return true; else return false; } let arr = [ 1, 2, 3, 3, 3, 3, 10 ]; let n = arr.length; let x = 3; if (isMajority(arr, n, x) == true) document.write(x + \" appears more than \" + parseInt(n / 2, 10) + \" times in arr[]\"); else document.write(x + \" does not appear more than \" + parseInt(n / 2, 10) + \" times in arr[]\"); </script>", "e": 44300, "s": 42387, "text": null }, { "code": null, "e": 44309, "s": 44300, "text": "Output: " }, { "code": null, "e": 44346, "s": 44309, "text": "3 appears more than 3 times in arr[]" }, { "code": null, "e": 44372, "s": 44346, "text": "Time Complexity: O(Logn) " }, { "code": null, "e": 44434, "s": 44372, "text": "Auxiliary Space: O(1)Algorithmic Paradigm: Divide and Conquer" }, { "code": null, "e": 44659, "s": 44434, "text": "METHOD 3: If it is already given that the array is sorted and there exists a majority element, checking if a particular element is as easy as checking if the middle element of the array is the number we are checking against." }, { "code": null, "e": 44838, "s": 44659, "text": "Since a majority element occurs more than n/2 times in an array, it will always be the middle element. We can use this logic to check if the given number is the majority element." }, { "code": null, "e": 44842, "s": 44838, "text": "C++" }, { "code": null, "e": 44844, "s": 44842, "text": "C" }, { "code": null, "e": 44849, "s": 44844, "text": "Java" }, { "code": null, "e": 44857, "s": 44849, "text": "Python3" }, { "code": null, "e": 44860, "s": 44857, "text": "C#" }, { "code": null, "e": 44871, "s": 44860, "text": "Javascript" }, { "code": "#include <iostream>using namespace std; bool isMajorityElement(int arr[], int n, int key){ if (arr[n / 2] == key) return true; else return false;} int main(){ int arr[] = { 1, 2, 3, 3, 3, 3, 10 }; int n = sizeof(arr) / sizeof(arr[0]); int x = 3; if (isMajorityElement(arr, n, x)) cout << x << \" appears more than \" << n / 2 << \" times in arr[]\" << endl; else cout << x << \" does not appear more than\" << n / 2 << \" times in arr[]\" << endl; return 0;} // This code is contributed by shivanisinghss2110", "e": 45464, "s": 44871, "text": null }, { "code": "#include <stdio.h>#include <stdbool.h> bool isMajorityElement(int arr[], int n, int key){ if (arr[n / 2] == key) return true; else return false;} int main(){ int arr[] = { 1, 2, 3, 3, 3, 3, 10 }; int n = sizeof(arr) / sizeof(arr[0]); int x = 3; if (isMajorityElement(arr, n, x)) printf(\"%d appears more than %d times in arr[]\", x, n / 2); else printf(\"%d does not appear more than %d times in \" \"arr[]\", x, n / 2); return 0;}", "e": 45976, "s": 45464, "text": null }, { "code": "import java.util.*; class GFG{ static boolean isMajorityElement(int arr[], int n, int key){ if (arr[n / 2] == key) return true; else return false;} // Driver Codepublic static void main(String[] args){ int arr[] = { 1, 2, 3, 3, 3, 3, 10 }; int n = arr.length; int x = 3; if (isMajorityElement(arr, n, x)) System.out.printf(\"%d appears more than %d \" + \"times in arr[]\", x, n / 2); else System.out.printf(\"%d does not appear more \" + \"than %d times in \" + \"arr[]\", x, n / 2);}} // This code is contributed by aashish1995", "e": 46657, "s": 45976, "text": null }, { "code": "def isMajorityElement(arr, n, key): if (arr[n // 2] == key): return True return False # Driver codeif __name__ == \"__main__\": arr = [1, 2, 3, 3, 3, 3, 10] n = len(arr) x = 3 if (isMajorityElement(arr, n, x)): print(x, \" appears more than \", n // 2 , \" times in arr[]\") else: print(x, \" does not appear more than\", n // 2, \" times in arr[]\") # This code is contributed by Chitranayal", "e": 47149, "s": 46657, "text": null }, { "code": "using System;class GFG{ static bool isMajorityElement(int []arr, int n, int key){ if (arr[n / 2] == key) return true; else return false;} // Driver Codepublic static void Main(String[] args){ int []arr = { 1, 2, 3, 3, 3, 3, 10 }; int n = arr.Length; int x = 3; if (isMajorityElement(arr, n, x)) Console.Write(x + \" appears more than \" + n/2 + \" times in []arr\"); else Console.Write(x + \" does not appear more \" + \"than \" + n/2 + \" times in arr[]\");}} // This code is contributed by aashish1995", "e": 47779, "s": 47149, "text": null }, { "code": "<script> function isMajorityElement(arr, n, key) { if (arr[parseInt(n / 2, 10)] == key) return true; else return false; } let arr = [ 1, 2, 3, 3, 3, 3, 10 ]; let n = arr.length; let x = 3; if (isMajorityElement(arr, n, x)) document.write(x + \" appears more than \" + parseInt(n/2, 10) + \" times in arr[]\"); else document.write(x + \" does not appear more \" + \"than \" + parseInt(n/2, 10) + \" times in arr[]\"); </script>", "e": 48300, "s": 47779, "text": null }, { "code": null, "e": 48337, "s": 48300, "text": "3 appears more than 3 times in arr[]" }, { "code": null, "e": 48380, "s": 48337, "text": "Time complexity: O(1)Auxiliary Space: O(1)" }, { "code": null, "e": 48496, "s": 48380, "text": "Please write comments if you find any bug in the above program/algorithm or a better way to solve the same problem." }, { "code": null, "e": 48502, "s": 48496, "text": "jit_t" }, { "code": null, "e": 48507, "s": 48502, "text": "_np_" }, { "code": null, "e": 48513, "s": 48507, "text": "ukasp" }, { "code": null, "e": 48525, "s": 48513, "text": "aashish1995" }, { "code": null, "e": 48544, "s": 48525, "text": "shivanisinghss2110" }, { "code": null, "e": 48559, "s": 48544, "text": "rameshtravel07" }, { "code": null, "e": 48568, "s": 48559, "text": "suresh07" }, { "code": null, "e": 48586, "s": 48568, "text": "divyeshrabadiya07" }, { "code": null, "e": 48602, "s": 48586, "text": "rohitsingh07052" }, { "code": null, "e": 48616, "s": 48602, "text": "Binary Search" }, { "code": null, "e": 48623, "s": 48616, "text": "Arrays" }, { "code": null, "e": 48642, "s": 48623, "text": "Divide and Conquer" }, { "code": null, "e": 48649, "s": 48642, "text": "Arrays" }, { "code": null, "e": 48668, "s": 48649, "text": "Divide and Conquer" }, { "code": null, "e": 48682, "s": 48668, "text": "Binary Search" }, { "code": null, "e": 48780, "s": 48682, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 48789, "s": 48780, "text": "Comments" }, { "code": null, "e": 48802, "s": 48789, "text": "Old Comments" }, { "code": null, "e": 48823, "s": 48802, "text": "Next Greater Element" }, { "code": null, "e": 48848, "s": 48823, "text": "Window Sliding Technique" }, { "code": null, "e": 48875, "s": 48848, "text": "Count pairs with given sum" }, { "code": null, "e": 48924, "s": 48875, "text": "Program to find sum of elements in a given array" }, { "code": null, "e": 48962, "s": 48924, "text": "Reversal algorithm for array rotation" }, { "code": null, "e": 48972, "s": 48962, "text": "QuickSort" }, { "code": null, "e": 48983, "s": 48972, "text": "Merge Sort" }, { "code": null, "e": 48997, "s": 48983, "text": "Binary Search" }, { "code": null, "e": 49024, "s": 48997, "text": "Program for Tower of Hanoi" } ]
PHP - Sending Emails using PHP
PHP must be configured correctly in the php.ini file with the details of how your system sends email. Open php.ini file available in /etc/ directory and find the section headed [mail function]. Windows users should ensure that two directives are supplied. The first is called SMTP that defines your email server address. The second is called sendmail_from which defines your own email address. The configuration for Windows should look something like this − [mail function] ; For Win32 only. SMTP = smtp.secureserver.net ; For win32 only sendmail_from = [email protected] Linux users simply need to let PHP know the location of their sendmail application. The path and any desired switches should be specified to the sendmail_path directive. The configuration for Linux should look something like this − [mail function] ; For Win32 only. SMTP = ; For win32 only sendmail_from = ; For Unix only sendmail_path = /usr/sbin/sendmail -t -i Now you are ready to go − PHP makes use of mail() function to send an email. This function requires three mandatory arguments that specify the recipient's email address, the subject of the the message and the actual message additionally there are other two optional parameters. mail( to, subject, message, headers, parameters ); Here is the description for each parameters. to Required. Specifies the receiver / receivers of the email subject Required. Specifies the subject of the email. This parameter cannot contain any newline characters message Required. Defines the message to be sent. Each line should be separated with a LF (\n). Lines should not exceed 70 characters headers Optional. Specifies additional headers, like From, Cc, and Bcc. The additional headers should be separated with a CRLF (\r\n) parameters Optional. Specifies an additional parameter to the send mail program As soon as the mail function is called PHP will attempt to send the email then it will return true if successful or false if it is failed. Multiple recipients can be specified as the first argument to the mail() function in a comma separated list. When you send a text message using PHP then all the content will be treated as simple text. Even if you will include HTML tags in a text message, it will be displayed as simple text and HTML tags will not be formatted according to HTML syntax. But PHP provides option to send an HTML message as actual HTML message. While sending an email message you can specify a Mime version, content type and character set to send an HTML email. Following example will send an HTML email message to [email protected] copying it to [email protected]. You can code this program in such a way that it should receive all content from the user and then it should send an email. <html> <head> <title>Sending HTML email using PHP</title> </head> <body> <?php $to = "[email protected]"; $subject = "This is subject"; $message = "<b>This is HTML message.</b>"; $message .= "<h1>This is headline.</h1>"; $header = "From:[email protected] \r\n"; $header .= "Cc:[email protected] \r\n"; $header .= "MIME-Version: 1.0\r\n"; $header .= "Content-type: text/html\r\n"; $retval = mail ($to,$subject,$message,$header); if( $retval == true ) { echo "Message sent successfully..."; }else { echo "Message could not be sent..."; } ?> </body> </html> To send an email with mixed content requires to set Content-type header to multipart/mixed. Then text and attachment sections can be specified within boundaries. A boundary is started with two hyphens followed by a unique number which can not appear in the message part of the email. A PHP function md5() is used to create a 32 digit hexadecimal number to create unique number. A final boundary denoting the email's final section must also end with two hyphens. <?php // request variables // important $from = $_REQUEST["from"]; $emaila = $_REQUEST["emaila"]; $filea = $_REQUEST["filea"]; if ($filea) { function mail_attachment ($from , $to, $subject, $message, $attachment){ $fileatt = $attachment; // Path to the file $fileatt_type = "application/octet-stream"; // File Type $start = strrpos($attachment, '/') == -1 ? strrpos($attachment, '//') : strrpos($attachment, '/')+1; $fileatt_name = substr($attachment, $start, strlen($attachment)); // Filename that will be used for the file as the attachment $email_from = $from; // Who the email is from $subject = "New Attachment Message"; $email_subject = $subject; // The Subject of the email $email_txt = $message; // Message that the email has in it $email_to = $to; // Who the email is to $headers = "From: ".$email_from; $file = fopen($fileatt,'rb'); $data = fread($file,filesize($fileatt)); fclose($file); $msg_txt="\n\n You have recieved a new attachment message from $from"; $semi_rand = md5(time()); $mime_boundary = "==Multipart_Boundary_x{$semi_rand}x"; $headers .= "\nMIME-Version: 1.0\n" . "Content-Type: multipart/mixed;\n" . " boundary=\"{$mime_boundary}\""; $email_txt .= $msg_txt; $email_message .= "This is a multi-part message in MIME format.\n\n" . "--{$mime_boundary}\n" . "Content-Type:text/html; charset = \"iso-8859-1\"\n" . "Content-Transfer-Encoding: 7bit\n\n" . $email_txt . "\n\n"; $data = chunk_split(base64_encode($data)); $email_message .= "--{$mime_boundary}\n" . "Content-Type: {$fileatt_type};\n" . " name = \"{$fileatt_name}\"\n" . //"Content-Disposition: attachment;\n" . //" filename = \"{$fileatt_name}\"\n" . "Content-Transfer-Encoding: base64\n\n" . $data . "\n\n" . "--{$mime_boundary}--\n"; $ok = mail($email_to, $email_subject, $email_message, $headers); if($ok) { echo "File Sent Successfully."; unlink($attachment); // delete a file after attachment sent. }else { die("Sorry but the email could not be sent. Please go back and try again!"); } } move_uploaded_file($_FILES["filea"]["tmp_name"], 'temp/'.basename($_FILES['filea']['name'])); mail_attachment("$from", "[email protected]", "subject", "message", ("temp/".$_FILES["filea"]["name"])); } ?> <html> <head> <script language = "javascript" type = "text/javascript"> function CheckData45() { with(document.filepost) { if(filea.value ! = "") { document.getElementById('one').innerText = "Attaching File ... Please Wait"; } } } </script> </head> <body> <table width = "100%" height = "100%" border = "0" cellpadding = "0" cellspacing = "0"> <tr> <td align = "center"> <form name = "filepost" method = "post" action = "file.php" enctype = "multipart/form-data" id = "file"> <table width = "300" border = "0" cellspacing = "0" cellpadding = "0"> <tr valign = "bottom"> <td height = "20">Your Name:</td> </tr> <tr> <td><input name = "from" type = "text" id = "from" size = "30"></td> </tr> <tr valign = "bottom"> <td height = "20">Your Email Address:</td> </tr> <tr> <td class = "frmtxt2"><input name = "emaila" type = "text" id = "emaila" size = "30"></td> </tr> <tr> <td height = "20" valign = "bottom">Attach File:</td> </tr> <tr valign = "bottom"> <td valign = "bottom"><input name = "filea" type = "file" id = "filea" size = "16"></td> </tr> <tr> <td height = "40" valign = "middle"><input name = "Reset2" type = "reset" id = "Reset2" value = "Reset"> <input name = "Submit2" type = "submit" value = "Submit" onClick = "return CheckData45()"></td> </tr> </table> </form> <center> <table width = "400"> <tr> <td id = "one"> </td> </tr> </table> </center> </td> </tr> </table> </body> </html> 45 Lectures 9 hours Malhar Lathkar 34 Lectures 4 hours Syed Raza 84 Lectures 5.5 hours Frahaan Hussain 17 Lectures 1 hours Nivedita Jain 100 Lectures 34 hours Azaz Patel 43 Lectures 5.5 hours Vijay Kumar Parvatha Reddy Print Add Notes Bookmark this page
[ { "code": null, "e": 2951, "s": 2757, "text": "PHP must be configured correctly in the php.ini file with the details of how your system sends email. Open php.ini file available in /etc/ directory and find the section headed [mail function]." }, { "code": null, "e": 3151, "s": 2951, "text": "Windows users should ensure that two directives are supplied. The first is called SMTP that defines your email server address. The second is called sendmail_from which defines your own email address." }, { "code": null, "e": 3215, "s": 3151, "text": "The configuration for Windows should look something like this −" }, { "code": null, "e": 3342, "s": 3215, "text": "[mail function]\n; For Win32 only.\nSMTP = smtp.secureserver.net\n\n; For win32 only\nsendmail_from = [email protected]\n" }, { "code": null, "e": 3512, "s": 3342, "text": "Linux users simply need to let PHP know the location of their sendmail application. The path and any desired switches should be specified to the sendmail_path directive." }, { "code": null, "e": 3574, "s": 3512, "text": "The configuration for Linux should look something like this −" }, { "code": null, "e": 3710, "s": 3574, "text": "[mail function]\n; For Win32 only.\nSMTP = \n\n; For win32 only\nsendmail_from = \n\n; For Unix only\nsendmail_path = /usr/sbin/sendmail -t -i\n" }, { "code": null, "e": 3736, "s": 3710, "text": "Now you are ready to go −" }, { "code": null, "e": 3988, "s": 3736, "text": "PHP makes use of mail() function to send an email. This function requires three mandatory arguments that specify the recipient's email address, the subject of the the message and the actual message additionally there are other two optional parameters." }, { "code": null, "e": 4039, "s": 3988, "text": "mail( to, subject, message, headers, parameters );" }, { "code": null, "e": 4084, "s": 4039, "text": "Here is the description for each parameters." }, { "code": null, "e": 4087, "s": 4084, "text": "to" }, { "code": null, "e": 4145, "s": 4087, "text": "Required. Specifies the receiver / receivers of the email" }, { "code": null, "e": 4153, "s": 4145, "text": "subject" }, { "code": null, "e": 4252, "s": 4153, "text": "Required. Specifies the subject of the email. This parameter cannot contain any newline characters" }, { "code": null, "e": 4260, "s": 4252, "text": "message" }, { "code": null, "e": 4386, "s": 4260, "text": "Required. Defines the message to be sent. Each line should be separated with a LF (\\n). Lines should not exceed 70 characters" }, { "code": null, "e": 4394, "s": 4386, "text": "headers" }, { "code": null, "e": 4520, "s": 4394, "text": "Optional. Specifies additional headers, like From, Cc, and Bcc. The additional headers should be separated with a CRLF (\\r\\n)" }, { "code": null, "e": 4531, "s": 4520, "text": "parameters" }, { "code": null, "e": 4600, "s": 4531, "text": "Optional. Specifies an additional parameter to the send mail program" }, { "code": null, "e": 4739, "s": 4600, "text": "As soon as the mail function is called PHP will attempt to send the email then it will return true if successful or false if it is failed." }, { "code": null, "e": 4848, "s": 4739, "text": "Multiple recipients can be specified as the first argument to the mail() function in a comma separated list." }, { "code": null, "e": 5164, "s": 4848, "text": "When you send a text message using PHP then all the content will be treated as simple text. Even if you will include HTML tags in a text message, it will be displayed as simple text and HTML tags will not be formatted according to HTML syntax. But PHP provides option to send an HTML message as actual HTML message." }, { "code": null, "e": 5281, "s": 5164, "text": "While sending an email message you can specify a Mime version, content type and character set to send an HTML email." }, { "code": null, "e": 5511, "s": 5281, "text": "Following example will send an HTML email message to [email protected] copying it to [email protected]. You can code this program in such a way that it should receive all content from the user and then it should send an email." }, { "code": null, "e": 6294, "s": 5511, "text": "<html>\n \n <head>\n <title>Sending HTML email using PHP</title>\n </head>\n \n <body>\n \n <?php\n $to = \"[email protected]\";\n $subject = \"This is subject\";\n \n $message = \"<b>This is HTML message.</b>\";\n $message .= \"<h1>This is headline.</h1>\";\n \n $header = \"From:[email protected] \\r\\n\";\n $header .= \"Cc:[email protected] \\r\\n\";\n $header .= \"MIME-Version: 1.0\\r\\n\";\n $header .= \"Content-type: text/html\\r\\n\";\n \n $retval = mail ($to,$subject,$message,$header);\n \n if( $retval == true ) {\n echo \"Message sent successfully...\";\n }else {\n echo \"Message could not be sent...\";\n }\n ?>\n \n </body>\n</html>" }, { "code": null, "e": 6456, "s": 6294, "text": "To send an email with mixed content requires to set Content-type header to multipart/mixed. Then text and attachment sections can be specified within boundaries." }, { "code": null, "e": 6756, "s": 6456, "text": "A boundary is started with two hyphens followed by a unique number which can not appear in the message part of the email. A PHP function md5() is used to create a 32 digit hexadecimal number to create unique number. A final boundary denoting the email's final section must also end with two hyphens." }, { "code": null, "e": 12280, "s": 6756, "text": "<?php\n // request variables // important\n $from = $_REQUEST[\"from\"];\n $emaila = $_REQUEST[\"emaila\"];\n $filea = $_REQUEST[\"filea\"];\n \n if ($filea) {\n function mail_attachment ($from , $to, $subject, $message, $attachment){\n $fileatt = $attachment; // Path to the file\n $fileatt_type = \"application/octet-stream\"; // File Type \n \n $start = strrpos($attachment, '/') == -1 ? \n strrpos($attachment, '//') : strrpos($attachment, '/')+1;\n\t\t\t\t\n $fileatt_name = substr($attachment, $start, \n strlen($attachment)); // Filename that will be used for the \n file as the attachment \n \n $email_from = $from; // Who the email is from\n $subject = \"New Attachment Message\";\n \n $email_subject = $subject; // The Subject of the email \n $email_txt = $message; // Message that the email has in it \n $email_to = $to; // Who the email is to\n \n $headers = \"From: \".$email_from;\n $file = fopen($fileatt,'rb'); \n $data = fread($file,filesize($fileatt)); \n fclose($file); \n \n $msg_txt=\"\\n\\n You have recieved a new attachment message from $from\";\n $semi_rand = md5(time()); \n $mime_boundary = \"==Multipart_Boundary_x{$semi_rand}x\"; \n $headers .= \"\\nMIME-Version: 1.0\\n\" . \"Content-Type: multipart/mixed;\\n\" . \"\n boundary=\\\"{$mime_boundary}\\\"\";\n \n $email_txt .= $msg_txt;\n\t\t\t\n $email_message .= \"This is a multi-part message in MIME format.\\n\\n\" . \n \"--{$mime_boundary}\\n\" . \"Content-Type:text/html; \n charset = \\\"iso-8859-1\\\"\\n\" . \"Content-Transfer-Encoding: 7bit\\n\\n\" . \n $email_txt . \"\\n\\n\";\n\t\t\t\t\n $data = chunk_split(base64_encode($data));\n \n $email_message .= \"--{$mime_boundary}\\n\" . \"Content-Type: {$fileatt_type};\\n\" .\n \" name = \\\"{$fileatt_name}\\\"\\n\" . //\"Content-Disposition: attachment;\\n\" . \n //\" filename = \\\"{$fileatt_name}\\\"\\n\" . \"Content-Transfer-Encoding: \n base64\\n\\n\" . $data . \"\\n\\n\" . \"--{$mime_boundary}--\\n\";\n\t\t\t\t\n $ok = mail($email_to, $email_subject, $email_message, $headers);\n \n if($ok) {\n echo \"File Sent Successfully.\";\n unlink($attachment); // delete a file after attachment sent.\n }else {\n die(\"Sorry but the email could not be sent. Please go back and try again!\");\n }\n }\n move_uploaded_file($_FILES[\"filea\"][\"tmp_name\"],\n 'temp/'.basename($_FILES['filea']['name']));\n\t\t\t\n mail_attachment(\"$from\", \"[email protected]\", \n \"subject\", \"message\", (\"temp/\".$_FILES[\"filea\"][\"name\"]));\n }\n?>\n\n<html>\n <head>\n \n <script language = \"javascript\" type = \"text/javascript\">\n function CheckData45() {\n with(document.filepost) {\n if(filea.value ! = \"\") {\n document.getElementById('one').innerText = \n \"Attaching File ... Please Wait\";\n }\n }\n }\n </script>\n \n </head>\n <body>\n \n <table width = \"100%\" height = \"100%\" border = \"0\" \n cellpadding = \"0\" cellspacing = \"0\">\n <tr>\n <td align = \"center\">\n <form name = \"filepost\" method = \"post\" \n action = \"file.php\" enctype = \"multipart/form-data\" id = \"file\">\n \n <table width = \"300\" border = \"0\" cellspacing = \"0\" \n cellpadding = \"0\">\n\t\t\t\t\t\t\t\n <tr valign = \"bottom\">\n <td height = \"20\">Your Name:</td>\n </tr>\n \n <tr>\n <td><input name = \"from\" type = \"text\" \n id = \"from\" size = \"30\"></td>\n </tr>\n \n <tr valign = \"bottom\">\n <td height = \"20\">Your Email Address:</td>\n </tr>\n \n <tr>\n <td class = \"frmtxt2\"><input name = \"emaila\"\n type = \"text\" id = \"emaila\" size = \"30\"></td>\n </tr>\n \n <tr>\n <td height = \"20\" valign = \"bottom\">Attach File:</td>\n </tr>\n \n <tr valign = \"bottom\">\n <td valign = \"bottom\"><input name = \"filea\" \n type = \"file\" id = \"filea\" size = \"16\"></td>\n </tr>\n \n <tr>\n <td height = \"40\" valign = \"middle\"><input \n name = \"Reset2\" type = \"reset\" id = \"Reset2\" value = \"Reset\">\n <input name = \"Submit2\" type = \"submit\" \n value = \"Submit\" onClick = \"return CheckData45()\"></td>\n </tr>\n </table>\n \n </form>\n \n <center>\n <table width = \"400\">\n \n <tr>\n <td id = \"one\">\n </td>\n </tr>\n \n </table>\n </center>\n \n </td>\n </tr>\n </table>\n \n </body>\n</html>" }, { "code": null, "e": 12313, "s": 12280, "text": "\n 45 Lectures \n 9 hours \n" }, { "code": null, "e": 12329, "s": 12313, "text": " Malhar Lathkar" }, { "code": null, "e": 12362, "s": 12329, "text": "\n 34 Lectures \n 4 hours \n" }, { "code": null, "e": 12373, "s": 12362, "text": " Syed Raza" }, { "code": null, "e": 12408, "s": 12373, "text": "\n 84 Lectures \n 5.5 hours \n" }, { "code": null, "e": 12425, "s": 12408, "text": " Frahaan Hussain" }, { "code": null, "e": 12458, "s": 12425, "text": "\n 17 Lectures \n 1 hours \n" }, { "code": null, "e": 12473, "s": 12458, "text": " Nivedita Jain" }, { "code": null, "e": 12508, "s": 12473, "text": "\n 100 Lectures \n 34 hours \n" }, { "code": null, "e": 12520, "s": 12508, "text": " Azaz Patel" }, { "code": null, "e": 12555, "s": 12520, "text": "\n 43 Lectures \n 5.5 hours \n" }, { "code": null, "e": 12583, "s": 12555, "text": " Vijay Kumar Parvatha Reddy" }, { "code": null, "e": 12590, "s": 12583, "text": " Print" }, { "code": null, "e": 12601, "s": 12590, "text": " Add Notes" } ]
Get only specific values in an array of objects in JavaScript?
Let’s say the following is our array of objects − var details = [{ studentName: "John", studentMarks: 92 }, { studentName: "David", studentMarks: 89 }, { studentName: "Mike", studentMarks: 98 }, ]; To get only specific values in an array of objects in JavaScript, use the concept of filter(). var details = [{ studentName: "John", studentMarks: 92 }, { studentName: "David", studentMarks: 89 }, { studentName: "Mike", studentMarks: 98 }, ]; var specificValuesFromArray = details.filter(obj => obj.studentMarks === 92 || obj.studentMarks === 98); console.log(specificValuesFromArray) To run the above program, you need to use the following command − node fileName.js. Here, my file name is demo177.js. This will produce the following output − PS C:\Users\Amit\javascript-code> node demo177.js [ { studentName: 'John', studentMarks: 92 }, { studentName: 'Mike', studentMarks: 98 } ]
[ { "code": null, "e": 1112, "s": 1062, "text": "Let’s say the following is our array of objects −" }, { "code": null, "e": 1278, "s": 1112, "text": "var details = [{\n studentName: \"John\",\n studentMarks: 92\n},\n{\n studentName: \"David\",\n studentMarks: 89\n},\n{\n studentName: \"Mike\",\n studentMarks: 98\n},\n];" }, { "code": null, "e": 1373, "s": 1278, "text": "To get only specific values in an array of objects in JavaScript, use the concept of filter()." }, { "code": null, "e": 1681, "s": 1373, "text": "var details = [{\n studentName: \"John\",\n studentMarks: 92\n},\n{\n studentName: \"David\",\n studentMarks: 89\n},\n{\n studentName: \"Mike\",\n studentMarks: 98\n},\n];\nvar specificValuesFromArray = details.filter(obj => obj.studentMarks ===\n92 || obj.studentMarks === 98);\nconsole.log(specificValuesFromArray)" }, { "code": null, "e": 1747, "s": 1681, "text": "To run the above program, you need to use the following command −" }, { "code": null, "e": 1765, "s": 1747, "text": "node fileName.js." }, { "code": null, "e": 1799, "s": 1765, "text": "Here, my file name is demo177.js." }, { "code": null, "e": 1840, "s": 1799, "text": "This will produce the following output −" }, { "code": null, "e": 1985, "s": 1840, "text": "PS C:\\Users\\Amit\\javascript-code> node demo177.js\n[\n { studentName: 'John', studentMarks: 92 },\n { studentName: 'Mike', studentMarks: 98 }\n]" } ]
Updating nested document in MongoDB
To update the nested document, use $set. Let us create a collection with documents − > db.demo315.insertOne({ _id :101, ... details: [ ... {Name: 'Chris', subjects: [{id:1001, SubjectName:"MySQL"}]} ... ] ... } ...) { "acknowledged" : true, "insertedId" : 101 } Display all documents from a collection with the help of find() method − > db.demo315.find().pretty(); This will produce the following output − { "_id" : 101, "details" : [ { "Name" : "Chris", "subjects" : [ { "id" : 1001, "SubjectName" : "MySQL" } ] } ] } Following is the query to update the nested document in MongoDB − > db.demo315.update ({_id:101}, { '$set': {"details.0.subjects.1.id" :1004} }) WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 }) Display all documents from a collection with the help of find() method − > db.demo315.find().pretty(); This will produce the following output − { "_id" : 101, "details" : [ { "Name" : "Chris", "subjects" : [ { "id" : 1001, "SubjectName" : "MySQL" }, { "id" : 1004 } ] } ] }
[ { "code": null, "e": 1147, "s": 1062, "text": "To update the nested document, use $set. Let us create a collection with documents −" }, { "code": null, "e": 1330, "s": 1147, "text": "> db.demo315.insertOne({ _id :101,\n... details: [\n... {Name: 'Chris', subjects: [{id:1001, SubjectName:\"MySQL\"}]}\n... ]\n... }\n...)\n{ \"acknowledged\" : true, \"insertedId\" : 101 }" }, { "code": null, "e": 1403, "s": 1330, "text": "Display all documents from a collection with the help of find() method −" }, { "code": null, "e": 1433, "s": 1403, "text": "> db.demo315.find().pretty();" }, { "code": null, "e": 1474, "s": 1433, "text": "This will produce the following output −" }, { "code": null, "e": 1689, "s": 1474, "text": "{\n \"_id\" : 101,\n \"details\" : [\n {\n \"Name\" : \"Chris\",\n \"subjects\" : [\n {\n \"id\" : 1001,\n \"SubjectName\" : \"MySQL\"\n }\n ]\n }\n ]\n}" }, { "code": null, "e": 1755, "s": 1689, "text": "Following is the query to update the nested document in MongoDB −" }, { "code": null, "e": 1900, "s": 1755, "text": "> db.demo315.update ({_id:101}, { '$set': {\"details.0.subjects.1.id\" :1004} })\nWriteResult({ \"nMatched\" : 1, \"nUpserted\" : 0, \"nModified\" : 1 })" }, { "code": null, "e": 1973, "s": 1900, "text": "Display all documents from a collection with the help of find() method −" }, { "code": null, "e": 2003, "s": 1973, "text": "> db.demo315.find().pretty();" }, { "code": null, "e": 2044, "s": 2003, "text": "This will produce the following output −" }, { "code": null, "e": 2315, "s": 2044, "text": "{\n \"_id\" : 101,\n \"details\" : [\n {\n \"Name\" : \"Chris\",\n \"subjects\" : [\n {\n \"id\" : 1001,\n \"SubjectName\" : \"MySQL\"\n },\n {\n \"id\" : 1004\n }\n ]\n }\n ]\n}" } ]
Python 3 - Number sin() Method
The sin() method returns the sine of x, in radians. Following is the syntax for sin() method − sin(x) Note − This function is not accessible directly, so we need to import math module and then we need to call this function using math static object. x − This must be a numeric value. This method returns a numeric value between -1 and 1, which represents the sine of the parameter x. The following example shows the usage of sin() method. #!/usr/bin/python3 import math print ("sin(3) : ", math.sin(3)) print ("sin(-3) : ", math.sin(-3)) print ("sin(0) : ", math.sin(0)) print ("sin(math.pi) : ", math.sin(math.pi)) print ("sin(math.pi/2) : ", math.sin(math.pi/2)) When we run the above program, it produces the following result − sin(3) : 0.14112000806 sin(-3) : -0.14112000806 sin(0) : 0.0 sin(math.pi) : 1.22460635382e-16 sin(math.pi/2) : 1 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": 2392, "s": 2340, "text": "The sin() method returns the sine of x, in radians." }, { "code": null, "e": 2435, "s": 2392, "text": "Following is the syntax for sin() method −" }, { "code": null, "e": 2443, "s": 2435, "text": "sin(x)\n" }, { "code": null, "e": 2590, "s": 2443, "text": "Note − This function is not accessible directly, so we need to import math module and then we need to call this function using math static object." }, { "code": null, "e": 2624, "s": 2590, "text": "x − This must be a numeric value." }, { "code": null, "e": 2724, "s": 2624, "text": "This method returns a numeric value between -1 and 1, which represents the sine of the parameter x." }, { "code": null, "e": 2779, "s": 2724, "text": "The following example shows the usage of sin() method." }, { "code": null, "e": 3011, "s": 2779, "text": "#!/usr/bin/python3\nimport math\n\nprint (\"sin(3) : \", math.sin(3))\nprint (\"sin(-3) : \", math.sin(-3))\nprint (\"sin(0) : \", math.sin(0))\nprint (\"sin(math.pi) : \", math.sin(math.pi))\nprint (\"sin(math.pi/2) : \", math.sin(math.pi/2))" }, { "code": null, "e": 3077, "s": 3011, "text": "When we run the above program, it produces the following result −" }, { "code": null, "e": 3196, "s": 3077, "text": "sin(3) : 0.14112000806\nsin(-3) : -0.14112000806\nsin(0) : 0.0\nsin(math.pi) : 1.22460635382e-16\nsin(math.pi/2) : 1\n" }, { "code": null, "e": 3233, "s": 3196, "text": "\n 187 Lectures \n 17.5 hours \n" }, { "code": null, "e": 3249, "s": 3233, "text": " Malhar Lathkar" }, { "code": null, "e": 3282, "s": 3249, "text": "\n 55 Lectures \n 8 hours \n" }, { "code": null, "e": 3301, "s": 3282, "text": " Arnab Chakraborty" }, { "code": null, "e": 3336, "s": 3301, "text": "\n 136 Lectures \n 11 hours \n" }, { "code": null, "e": 3358, "s": 3336, "text": " In28Minutes Official" }, { "code": null, "e": 3392, "s": 3358, "text": "\n 75 Lectures \n 13 hours \n" }, { "code": null, "e": 3420, "s": 3392, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 3455, "s": 3420, "text": "\n 70 Lectures \n 8.5 hours \n" }, { "code": null, "e": 3469, "s": 3455, "text": " Lets Kode It" }, { "code": null, "e": 3502, "s": 3469, "text": "\n 63 Lectures \n 6 hours \n" }, { "code": null, "e": 3519, "s": 3502, "text": " Abhilash Nelson" }, { "code": null, "e": 3526, "s": 3519, "text": " Print" }, { "code": null, "e": 3537, "s": 3526, "text": " Add Notes" } ]
Tutorial: Linear Regression with Stochastic Gradient Descent | by Raimi Karim | Towards Data Science
You can find the backpropagation demo here. This article should provide you a good start for us to dive deep into deep learning. Let me walk you through the step-by-step calculations for a linear regression task using stochastic gradient descent. Preparation1.1 Data1.2 Model1.3 Define loss function1.4 Minimising loss function Preparation1.1 Data1.2 Model1.3 Define loss function1.4 Minimising loss function 2. Implementation2.1 Forward propagation2.1.1 Initialise weights (one-time)2.1.2 Feed data2.1.3 Compute ŷ2.1.4 Compute loss2.2 Backpropagation2.2.1 Compute partial differentials2.2.2 Update weights We have some data: as we observe the independent variables x1 and x2, we observe the dependent variable (or response variable) y along with it. In our dataset, we have 6 examples (or observations). x1 x2 y1) 4 1 22) 2 8 -143) 1 0 14) 3 2 -15) 1 4 -76) 6 7 -8 The next question to ask: “How are both x1 and x2 related to y?” We believe that they are connected to each other by this equation: Our job today is to find the ‘best’ w and b values. I have used the deep learning conventions w and b, which stand for weights and biases respectively. But note that linear regression is not deep learning. Let’s say at the end of this exercise, we’ve figured out our model to be How do we know if our model is doing well? We simply compare the predicted ŷ and the observed y through a loss function. There are many ways to define the loss function but in this post, we define it as the squared difference between ŷ and y. Generally, the smaller the L, the better. Because we want the difference between ŷ and y to be small, we want to make an effort to minimise it. This is done through stochastic gradient descent optimisation. It is basically iteratively updating the values of w1 and w2 using the value of gradient, as in this equation: This algorithm tries to find the right weights by constantly updating them, bearing in mind that we are seeking values that minimise the loss function. Intuition: stochastic gradient descent You are w and you are on a graph (loss function). Your current value is w=5. You want to move to the lowest point in this graph (minimising the loss function). You also know that, with your current value, your gradient is 2. You somehow must make use of this value to move on with life. From high school math, 2 means you’re on an inclined slope and the only way you can descend is to move left, at this point. If taking 5+2 means you’re going to the right climbing up the slope, then the only way is to take 5–2 which brings you to the left, descending down. So gradient descent is all about subtracting the value of the gradient from its current value. The workflow for training our model is simple: forward propagation (or feed-forward or forward pass) and backpropagation. Definition: trainingTraining just means regularly updating the values of your weights, put simply. Below is the workflow. Click to jump to the section. — — — — — — — — — — — — — 2.1 Forward propagation2.1.1 Initialise weights (one-time)2.1.2 Feed data2.1.3 Compute ŷ2.1.4 Compute loss 2.2 Backpropagation2.2.1 Compute partial differentials2.2.2 Update weights — — — — — — — — — — — — — Let’s get started. To keep track of all the values, we first build a ‘computation graph’ that comprises nodes colour-coded in orange — the placeholders (x1, x2 and y),dark green — the weights and bias (w1, w2 and b),light green — the model (ŷ) connecting w1, w2, b, x1 and x2, andyellow — the loss function (L) connecting the ŷ and y. orange — the placeholders (x1, x2 and y), dark green — the weights and bias (w1, w2 and b), light green — the model (ŷ) connecting w1, w2, b, x1 and x2, and yellow — the loss function (L) connecting the ŷ and y. For forward propagation, you should read this graph from top to bottom and for backpropagation bottom to top. NoteI have adopted the term ‘placeholder’, a nomenclature used in TensorFlow to refer to these ‘data variables’.I will also use the term ‘weights’ to refer to w and b collectively. Since gradient descent is all about updating the weights, we need them to start with some values, known as initialising weights. Here we initialised the weights and bias as follows: These are reflected in the dark green nodes in Fig. 2.1.1 below: There are many ways to initialise weights (zeros, ones, uniform distribution, normal distribution, truncated normal distribution, etc.) but we won’t cover them in this post. In this tutorial, we initialised the weights by using truncated normal distribution and the bias with 0. Next, we set the batch size to be 1 and we feed in this first batch of data. Batch and batch size We can divide our dataset into smaller groups of equal size. Each group is called a batch and consists of a specified number of examples, called batch size. If we multiply these two numbers, we should get back the number of observations in our data. Here, our dataset consists of 6 examples and since we defined the batch size to be 1 in this training, we have 6 batches altogether. Current batch of data used to feed in the model is bolded below: x1 x2 y1) 4 1 22) 2 8 -143) 1 0 14) 3 2 -15) 1 4 -76) 6 7 -8 In Fig. 2.1.2, the orange nodes are where we feed in the current batch of data. Now that we have the values of x1, x2, w1, w2 and b ready, let’s compute ŷ. The value of ŷ (=-0.1) is reflected in the light green node below: How far is our predicted ŷ from the given y data? We compare them by calculating the loss function L as defined earlier. You can see this value in the yellow node in the computation graph. It is a common practice to log the loss during training, together with other information like the epoch, batch and time taken. In my demo, you can see this under the Training progress panel. Before we start adjusting the values of the weights and bias w1, w2 and b, let’s first compute all the partial differentials. These are needed later when we do the weight update. Namely, we compute all possible paths leading to every w and b only, because these are the only variables which we are interested in updating. From Fig. 2.2.1 above, we see that there are 4 edges that we labeled with the partial differentials. Recall the equations for the model and loss function: The partial differentials are as follows: L (yellow) — ŷ (light green): ŷ (light green) — b (dark green): ŷ (light green) — w1 (dark green): ŷ (light green) — w2 (dark green): Note that the values of the partial differentials follow the values from the current batch. For example, in Eqn. 2.2.1C, x1 = 4. Observe the dark green nodes in Fig. 2.2.2 below. We see three things:i) b changes from 0.000 to 0.212ii) w1 changes from -0.017 to 0.829iii) w2 changes from -0.048 to 0.164 Also pay attention to the ‘direction’ of the pathway from the yellow node to the green node. They go from bottom to top. This is stochastic gradient descent — updating the weights using backpropagation, making use of the respective gradient values. Let’s first focus on updating b. The formula for updating b is where b — current value b’ — value after update η —learning rate, set to 0.05 ∂L/∂b — gradient i.e. partial differential of L w.r.t. b To get the gradient, we need to multiply the paths from L leading to b using chain rule: We would require the current batch values of x, y, ŷ and the partial differentials so let’s just place them below for easy reference: Using the stochastic gradient descent equation in Eqn. 2.2.2A and plugging in all the values from Eqn. 2.2.2B-D gives us: That’s it for updating b! Phew! We are left with updating w1 and w2, which we update in a similar fashion. Congrats! That’s it for dealing with the first batch! x1 x2 y1) 4 1 2 ✔2) 2 8 -143) 1 0 14) 3 2 -15) 1 4 -76) 6 7 -8 Now we need to iterate the above-mentioned steps to the other 5 batches, namely examples 2 to 6. We complete 1 epoch when the model has iterated through all the batches once. In practice, we extend the epoch to more than 1. One epoch is when our setup has seen all the observations in our dataset once. But one epoch is almost always never enough for the loss to converge. In practice, this number is manually tuned. At the end of it all, you should get a final model, ready for inference, say: Let’s have a review of the entire workflow in a pseudo-code: initialise_weights()for i in epochs: for j in batches: #forward propagation feed_batch_data() compute_ŷ() compute_loss() #backpropagation compute_partial_differentials() update_weights() One epoch is never enough for a stochastic gradient descent optimisation problems. Remember that in Fig. 4.1, our loss is at 4.48. If we increase the number of epochs, which means just increasing the number of times we update the weights and biases, we can converge it to a satisfactory low. Below are the things you can improve the training: Extend training to more than 1 epoch Increase batch size Change optimiser (see my post on gradient descent optimisation algorithms here) Adjust learning rate (changing the learning rate value or using learning rate schedulers) Hold out a train-val-test set I built an interactive explorable demo on linear regression with gradient descent in JavaScript. Here are the libraries I used: Dagre-D3 (GraphViz + d3.js) for rendering the graphs MathJax for rendering mathematical notations ApexCharts for plotting line charts jQuery Check out the interactive demo here. You might also like to check out A Line-by-Line Layman’s Guide to Linear Regression using TensorFlow below, which focuses on coding linear regression using the TensorFlow library. medium.com colah.github.io Animated RNN, LSTM and GRU Line-by-Line Word2Vec Implementation (on word embeddings) 10 Gradient Descent Optimisation Algorithms + Cheat Sheet Counting No. of Parameters in Deep Learning Models Attn: Illustrated Attention Illustrated: Self-Attention Thanks to Ren Jie and Derek for ideas, suggestions and corrections to this article. Follow me on Twitter @remykarem or LinkedIn. You may also reach out to me via [email protected]. Feel free to visit my website at remykarem.github.io.
[ { "code": null, "e": 216, "s": 172, "text": "You can find the backpropagation demo here." }, { "code": null, "e": 419, "s": 216, "text": "This article should provide you a good start for us to dive deep into deep learning. Let me walk you through the step-by-step calculations for a linear regression task using stochastic gradient descent." }, { "code": null, "e": 500, "s": 419, "text": "Preparation1.1 Data1.2 Model1.3 Define loss function1.4 Minimising loss function" }, { "code": null, "e": 581, "s": 500, "text": "Preparation1.1 Data1.2 Model1.3 Define loss function1.4 Minimising loss function" }, { "code": null, "e": 780, "s": 581, "text": "2. Implementation2.1 Forward propagation2.1.1 Initialise weights (one-time)2.1.2 Feed data2.1.3 Compute ŷ2.1.4 Compute loss2.2 Backpropagation2.2.1 Compute partial differentials2.2.2 Update weights" }, { "code": null, "e": 924, "s": 780, "text": "We have some data: as we observe the independent variables x1 and x2, we observe the dependent variable (or response variable) y along with it." }, { "code": null, "e": 978, "s": 924, "text": "In our dataset, we have 6 examples (or observations)." }, { "code": null, "e": 1070, "s": 978, "text": " x1 x2 y1) 4 1 22) 2 8 -143) 1 0 14) 3 2 -15) 1 4 -76) 6 7 -8" }, { "code": null, "e": 1135, "s": 1070, "text": "The next question to ask: “How are both x1 and x2 related to y?”" }, { "code": null, "e": 1202, "s": 1135, "text": "We believe that they are connected to each other by this equation:" }, { "code": null, "e": 1254, "s": 1202, "text": "Our job today is to find the ‘best’ w and b values." }, { "code": null, "e": 1408, "s": 1254, "text": "I have used the deep learning conventions w and b, which stand for weights and biases respectively. But note that linear regression is not deep learning." }, { "code": null, "e": 1481, "s": 1408, "text": "Let’s say at the end of this exercise, we’ve figured out our model to be" }, { "code": null, "e": 1524, "s": 1481, "text": "How do we know if our model is doing well?" }, { "code": null, "e": 1726, "s": 1524, "text": "We simply compare the predicted ŷ and the observed y through a loss function. There are many ways to define the loss function but in this post, we define it as the squared difference between ŷ and y." }, { "code": null, "e": 1768, "s": 1726, "text": "Generally, the smaller the L, the better." }, { "code": null, "e": 2045, "s": 1768, "text": "Because we want the difference between ŷ and y to be small, we want to make an effort to minimise it. This is done through stochastic gradient descent optimisation. It is basically iteratively updating the values of w1 and w2 using the value of gradient, as in this equation:" }, { "code": null, "e": 2197, "s": 2045, "text": "This algorithm tries to find the right weights by constantly updating them, bearing in mind that we are seeking values that minimise the loss function." }, { "code": null, "e": 2236, "s": 2197, "text": "Intuition: stochastic gradient descent" }, { "code": null, "e": 2396, "s": 2236, "text": "You are w and you are on a graph (loss function). Your current value is w=5. You want to move to the lowest point in this graph (minimising the loss function)." }, { "code": null, "e": 2523, "s": 2396, "text": "You also know that, with your current value, your gradient is 2. You somehow must make use of this value to move on with life." }, { "code": null, "e": 2647, "s": 2523, "text": "From high school math, 2 means you’re on an inclined slope and the only way you can descend is to move left, at this point." }, { "code": null, "e": 2891, "s": 2647, "text": "If taking 5+2 means you’re going to the right climbing up the slope, then the only way is to take 5–2 which brings you to the left, descending down. So gradient descent is all about subtracting the value of the gradient from its current value." }, { "code": null, "e": 3013, "s": 2891, "text": "The workflow for training our model is simple: forward propagation (or feed-forward or forward pass) and backpropagation." }, { "code": null, "e": 3112, "s": 3013, "text": "Definition: trainingTraining just means regularly updating the values of your weights, put simply." }, { "code": null, "e": 3165, "s": 3112, "text": "Below is the workflow. Click to jump to the section." }, { "code": null, "e": 3299, "s": 3165, "text": "— — — — — — — — — — — — — 2.1 Forward propagation2.1.1 Initialise weights (one-time)2.1.2 Feed data2.1.3 Compute ŷ2.1.4 Compute loss" }, { "code": null, "e": 3400, "s": 3299, "text": "2.2 Backpropagation2.2.1 Compute partial differentials2.2.2 Update weights — — — — — — — — — — — — —" }, { "code": null, "e": 3419, "s": 3400, "text": "Let’s get started." }, { "code": null, "e": 3526, "s": 3419, "text": "To keep track of all the values, we first build a ‘computation graph’ that comprises nodes colour-coded in" }, { "code": null, "e": 3737, "s": 3526, "text": "orange — the placeholders (x1, x2 and y),dark green — the weights and bias (w1, w2 and b),light green — the model (ŷ) connecting w1, w2, b, x1 and x2, andyellow — the loss function (L) connecting the ŷ and y." }, { "code": null, "e": 3779, "s": 3737, "text": "orange — the placeholders (x1, x2 and y)," }, { "code": null, "e": 3829, "s": 3779, "text": "dark green — the weights and bias (w1, w2 and b)," }, { "code": null, "e": 3895, "s": 3829, "text": "light green — the model (ŷ) connecting w1, w2, b, x1 and x2, and" }, { "code": null, "e": 3951, "s": 3895, "text": "yellow — the loss function (L) connecting the ŷ and y." }, { "code": null, "e": 4061, "s": 3951, "text": "For forward propagation, you should read this graph from top to bottom and for backpropagation bottom to top." }, { "code": null, "e": 4242, "s": 4061, "text": "NoteI have adopted the term ‘placeholder’, a nomenclature used in TensorFlow to refer to these ‘data variables’.I will also use the term ‘weights’ to refer to w and b collectively." }, { "code": null, "e": 4371, "s": 4242, "text": "Since gradient descent is all about updating the weights, we need them to start with some values, known as initialising weights." }, { "code": null, "e": 4424, "s": 4371, "text": "Here we initialised the weights and bias as follows:" }, { "code": null, "e": 4489, "s": 4424, "text": "These are reflected in the dark green nodes in Fig. 2.1.1 below:" }, { "code": null, "e": 4768, "s": 4489, "text": "There are many ways to initialise weights (zeros, ones, uniform distribution, normal distribution, truncated normal distribution, etc.) but we won’t cover them in this post. In this tutorial, we initialised the weights by using truncated normal distribution and the bias with 0." }, { "code": null, "e": 4845, "s": 4768, "text": "Next, we set the batch size to be 1 and we feed in this first batch of data." }, { "code": null, "e": 4866, "s": 4845, "text": "Batch and batch size" }, { "code": null, "e": 5116, "s": 4866, "text": "We can divide our dataset into smaller groups of equal size. Each group is called a batch and consists of a specified number of examples, called batch size. If we multiply these two numbers, we should get back the number of observations in our data." }, { "code": null, "e": 5249, "s": 5116, "text": "Here, our dataset consists of 6 examples and since we defined the batch size to be 1 in this training, we have 6 batches altogether." }, { "code": null, "e": 5314, "s": 5249, "text": "Current batch of data used to feed in the model is bolded below:" }, { "code": null, "e": 5406, "s": 5314, "text": " x1 x2 y1) 4 1 22) 2 8 -143) 1 0 14) 3 2 -15) 1 4 -76) 6 7 -8" }, { "code": null, "e": 5486, "s": 5406, "text": "In Fig. 2.1.2, the orange nodes are where we feed in the current batch of data." }, { "code": null, "e": 5563, "s": 5486, "text": "Now that we have the values of x1, x2, w1, w2 and b ready, let’s compute ŷ." }, { "code": null, "e": 5631, "s": 5563, "text": "The value of ŷ (=-0.1) is reflected in the light green node below:" }, { "code": null, "e": 5753, "s": 5631, "text": "How far is our predicted ŷ from the given y data? We compare them by calculating the loss function L as defined earlier." }, { "code": null, "e": 5821, "s": 5753, "text": "You can see this value in the yellow node in the computation graph." }, { "code": null, "e": 6012, "s": 5821, "text": "It is a common practice to log the loss during training, together with other information like the epoch, batch and time taken. In my demo, you can see this under the Training progress panel." }, { "code": null, "e": 6191, "s": 6012, "text": "Before we start adjusting the values of the weights and bias w1, w2 and b, let’s first compute all the partial differentials. These are needed later when we do the weight update." }, { "code": null, "e": 6435, "s": 6191, "text": "Namely, we compute all possible paths leading to every w and b only, because these are the only variables which we are interested in updating. From Fig. 2.2.1 above, we see that there are 4 edges that we labeled with the partial differentials." }, { "code": null, "e": 6489, "s": 6435, "text": "Recall the equations for the model and loss function:" }, { "code": null, "e": 6531, "s": 6489, "text": "The partial differentials are as follows:" }, { "code": null, "e": 6562, "s": 6531, "text": "L (yellow) — ŷ (light green):" }, { "code": null, "e": 6597, "s": 6562, "text": "ŷ (light green) — b (dark green):" }, { "code": null, "e": 6633, "s": 6597, "text": "ŷ (light green) — w1 (dark green):" }, { "code": null, "e": 6669, "s": 6633, "text": "ŷ (light green) — w2 (dark green):" }, { "code": null, "e": 6798, "s": 6669, "text": "Note that the values of the partial differentials follow the values from the current batch. For example, in Eqn. 2.2.1C, x1 = 4." }, { "code": null, "e": 6972, "s": 6798, "text": "Observe the dark green nodes in Fig. 2.2.2 below. We see three things:i) b changes from 0.000 to 0.212ii) w1 changes from -0.017 to 0.829iii) w2 changes from -0.048 to 0.164" }, { "code": null, "e": 7093, "s": 6972, "text": "Also pay attention to the ‘direction’ of the pathway from the yellow node to the green node. They go from bottom to top." }, { "code": null, "e": 7221, "s": 7093, "text": "This is stochastic gradient descent — updating the weights using backpropagation, making use of the respective gradient values." }, { "code": null, "e": 7284, "s": 7221, "text": "Let’s first focus on updating b. The formula for updating b is" }, { "code": null, "e": 7290, "s": 7284, "text": "where" }, { "code": null, "e": 7308, "s": 7290, "text": "b — current value" }, { "code": null, "e": 7332, "s": 7308, "text": "b’ — value after update" }, { "code": null, "e": 7362, "s": 7332, "text": "η —learning rate, set to 0.05" }, { "code": null, "e": 7419, "s": 7362, "text": "∂L/∂b — gradient i.e. partial differential of L w.r.t. b" }, { "code": null, "e": 7508, "s": 7419, "text": "To get the gradient, we need to multiply the paths from L leading to b using chain rule:" }, { "code": null, "e": 7643, "s": 7508, "text": "We would require the current batch values of x, y, ŷ and the partial differentials so let’s just place them below for easy reference:" }, { "code": null, "e": 7765, "s": 7643, "text": "Using the stochastic gradient descent equation in Eqn. 2.2.2A and plugging in all the values from Eqn. 2.2.2B-D gives us:" }, { "code": null, "e": 7872, "s": 7765, "text": "That’s it for updating b! Phew! We are left with updating w1 and w2, which we update in a similar fashion." }, { "code": null, "e": 7926, "s": 7872, "text": "Congrats! That’s it for dealing with the first batch!" }, { "code": null, "e": 8021, "s": 7926, "text": " x1 x2 y1) 4 1 2 ✔2) 2 8 -143) 1 0 14) 3 2 -15) 1 4 -76) 6 7 -8" }, { "code": null, "e": 8118, "s": 8021, "text": "Now we need to iterate the above-mentioned steps to the other 5 batches, namely examples 2 to 6." }, { "code": null, "e": 8245, "s": 8118, "text": "We complete 1 epoch when the model has iterated through all the batches once. In practice, we extend the epoch to more than 1." }, { "code": null, "e": 8438, "s": 8245, "text": "One epoch is when our setup has seen all the observations in our dataset once. But one epoch is almost always never enough for the loss to converge. In practice, this number is manually tuned." }, { "code": null, "e": 8516, "s": 8438, "text": "At the end of it all, you should get a final model, ready for inference, say:" }, { "code": null, "e": 8577, "s": 8516, "text": "Let’s have a review of the entire workflow in a pseudo-code:" }, { "code": null, "e": 8817, "s": 8577, "text": "initialise_weights()for i in epochs: for j in batches: #forward propagation feed_batch_data() compute_ŷ() compute_loss() #backpropagation compute_partial_differentials() update_weights()" }, { "code": null, "e": 9109, "s": 8817, "text": "One epoch is never enough for a stochastic gradient descent optimisation problems. Remember that in Fig. 4.1, our loss is at 4.48. If we increase the number of epochs, which means just increasing the number of times we update the weights and biases, we can converge it to a satisfactory low." }, { "code": null, "e": 9160, "s": 9109, "text": "Below are the things you can improve the training:" }, { "code": null, "e": 9197, "s": 9160, "text": "Extend training to more than 1 epoch" }, { "code": null, "e": 9217, "s": 9197, "text": "Increase batch size" }, { "code": null, "e": 9297, "s": 9217, "text": "Change optimiser (see my post on gradient descent optimisation algorithms here)" }, { "code": null, "e": 9387, "s": 9297, "text": "Adjust learning rate (changing the learning rate value or using learning rate schedulers)" }, { "code": null, "e": 9417, "s": 9387, "text": "Hold out a train-val-test set" }, { "code": null, "e": 9545, "s": 9417, "text": "I built an interactive explorable demo on linear regression with gradient descent in JavaScript. Here are the libraries I used:" }, { "code": null, "e": 9598, "s": 9545, "text": "Dagre-D3 (GraphViz + d3.js) for rendering the graphs" }, { "code": null, "e": 9643, "s": 9598, "text": "MathJax for rendering mathematical notations" }, { "code": null, "e": 9679, "s": 9643, "text": "ApexCharts for plotting line charts" }, { "code": null, "e": 9686, "s": 9679, "text": "jQuery" }, { "code": null, "e": 9723, "s": 9686, "text": "Check out the interactive demo here." }, { "code": null, "e": 9903, "s": 9723, "text": "You might also like to check out A Line-by-Line Layman’s Guide to Linear Regression using TensorFlow below, which focuses on coding linear regression using the TensorFlow library." }, { "code": null, "e": 9914, "s": 9903, "text": "medium.com" }, { "code": null, "e": 9930, "s": 9914, "text": "colah.github.io" }, { "code": null, "e": 9957, "s": 9930, "text": "Animated RNN, LSTM and GRU" }, { "code": null, "e": 10015, "s": 9957, "text": "Line-by-Line Word2Vec Implementation (on word embeddings)" }, { "code": null, "e": 10073, "s": 10015, "text": "10 Gradient Descent Optimisation Algorithms + Cheat Sheet" }, { "code": null, "e": 10124, "s": 10073, "text": "Counting No. of Parameters in Deep Learning Models" }, { "code": null, "e": 10152, "s": 10124, "text": "Attn: Illustrated Attention" }, { "code": null, "e": 10180, "s": 10152, "text": "Illustrated: Self-Attention" }, { "code": null, "e": 10264, "s": 10180, "text": "Thanks to Ren Jie and Derek for ideas, suggestions and corrections to this article." } ]
Automating Scrolling using Python-Opencv by Color Detection - GeeksforGeeks
13 Jan, 2021 Prerequisites: Opencv PyAutoGUI It is possible to perform actions without actually giving any input through touchpad or mouse. This article discusses how this can be done using opencv module. Here we will use color detection to scroll screen. When a certain color is detected by the program during execution the screen starts to scroll on its own. Import module Use cv2 to capture video, here to use default webcam use 0, and for any other cam use 1. Read the captured video and store the video frame in a variable Get every color of the frame. Create a mask of the color required to take as input to scroll using their acceptable color ranges. Here it is taken as green. Get contours and hierarchy from mask Pass contours using for loop and calculate the area. Add scroll mechanism when required color is detected(Green here). Show the frame using cv2.imshow()and pass the frame name and the frame variable to show every captured frame, put the frame capture process in a while loop. To come out of the process use a wait key and break statement. Then stop the window of webcam. Below is the implementation. Python3 import cv2import numpy as npimport pyautogui low_green = np.array([25, 52, 72])high_green = np.array([102, 255, 255]) cap = cv2.VideoCapture(0) prev_y = 0 while True: ret, frame = cap.read() hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV) mask = cv2.inRange(hsv, low_green, high_green) contours, hierarchy = cv2.findContours( mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) for i in contours: area = cv2.contourArea(i) if area > 1000: x, y, w, h = cv2.boundingRect(i) cv2.rectangle(frame, (x, y), (x+w, y+h), (0, 255, 0), 2) if y < prev_y: pyautogui.press('space') prev_y = y cv2.imshow('frame', frame) if cv2.waitKey(1) == ord('q'): break cap.release()cap.closeAllWindow() Input: Detecting green color Python-OpenCV Python-projects Technical Scripter 2020 Python Technical Scripter 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 Python | os.path.join() method Defaultdict in Python Selecting rows in pandas DataFrame based on conditions Python | Get unique values from a list Create a directory in Python Python | Pandas dataframe.groupby()
[ { "code": null, "e": 24292, "s": 24264, "text": "\n13 Jan, 2021" }, { "code": null, "e": 24308, "s": 24292, "text": "Prerequisites: " }, { "code": null, "e": 24315, "s": 24308, "text": "Opencv" }, { "code": null, "e": 24325, "s": 24315, "text": "PyAutoGUI" }, { "code": null, "e": 24641, "s": 24325, "text": "It is possible to perform actions without actually giving any input through touchpad or mouse. This article discusses how this can be done using opencv module. Here we will use color detection to scroll screen. When a certain color is detected by the program during execution the screen starts to scroll on its own." }, { "code": null, "e": 24655, "s": 24641, "text": "Import module" }, { "code": null, "e": 24744, "s": 24655, "text": "Use cv2 to capture video, here to use default webcam use 0, and for any other cam use 1." }, { "code": null, "e": 24808, "s": 24744, "text": "Read the captured video and store the video frame in a variable" }, { "code": null, "e": 24838, "s": 24808, "text": "Get every color of the frame." }, { "code": null, "e": 24965, "s": 24838, "text": "Create a mask of the color required to take as input to scroll using their acceptable color ranges. Here it is taken as green." }, { "code": null, "e": 25002, "s": 24965, "text": "Get contours and hierarchy from mask" }, { "code": null, "e": 25055, "s": 25002, "text": "Pass contours using for loop and calculate the area." }, { "code": null, "e": 25121, "s": 25055, "text": "Add scroll mechanism when required color is detected(Green here)." }, { "code": null, "e": 25341, "s": 25121, "text": "Show the frame using cv2.imshow()and pass the frame name and the frame variable to show every captured frame, put the frame capture process in a while loop. To come out of the process use a wait key and break statement." }, { "code": null, "e": 25373, "s": 25341, "text": "Then stop the window of webcam." }, { "code": null, "e": 25402, "s": 25373, "text": "Below is the implementation." }, { "code": null, "e": 25410, "s": 25402, "text": "Python3" }, { "code": "import cv2import numpy as npimport pyautogui low_green = np.array([25, 52, 72])high_green = np.array([102, 255, 255]) cap = cv2.VideoCapture(0) prev_y = 0 while True: ret, frame = cap.read() hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV) mask = cv2.inRange(hsv, low_green, high_green) contours, hierarchy = cv2.findContours( mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) for i in contours: area = cv2.contourArea(i) if area > 1000: x, y, w, h = cv2.boundingRect(i) cv2.rectangle(frame, (x, y), (x+w, y+h), (0, 255, 0), 2) if y < prev_y: pyautogui.press('space') prev_y = y cv2.imshow('frame', frame) if cv2.waitKey(1) == ord('q'): break cap.release()cap.closeAllWindow()", "e": 26198, "s": 25410, "text": null }, { "code": null, "e": 26205, "s": 26198, "text": "Input:" }, { "code": null, "e": 26227, "s": 26205, "text": "Detecting green color" }, { "code": null, "e": 26241, "s": 26227, "text": "Python-OpenCV" }, { "code": null, "e": 26257, "s": 26241, "text": "Python-projects" }, { "code": null, "e": 26281, "s": 26257, "text": "Technical Scripter 2020" }, { "code": null, "e": 26288, "s": 26281, "text": "Python" }, { "code": null, "e": 26307, "s": 26288, "text": "Technical Scripter" }, { "code": null, "e": 26405, "s": 26307, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26437, "s": 26405, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 26479, "s": 26437, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 26535, "s": 26479, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 26577, "s": 26535, "text": "Check if element exists in list in Python" }, { "code": null, "e": 26608, "s": 26577, "text": "Python | os.path.join() method" }, { "code": null, "e": 26630, "s": 26608, "text": "Defaultdict in Python" }, { "code": null, "e": 26685, "s": 26630, "text": "Selecting rows in pandas DataFrame based on conditions" }, { "code": null, "e": 26724, "s": 26685, "text": "Python | Get unique values from a list" }, { "code": null, "e": 26753, "s": 26724, "text": "Create a directory in Python" } ]
Best Ways to Visualize Proportions | by Robert Wood | Towards Data Science
Whatever your application of data analytics & data science, there are proportions everywhere. Proportions are all about understanding the different parts that make up a whole. Proportions are pretty much just a count of something across a given categorical variable. That could be the number of customers across different industries, the number of sales calls in different geographies, the number of activities across various activity types, or the number of ice cream cones sold of various flavors. If you can count it, and break it into groups, then you’ve got proportion data! Whether you’re familiar with the idea of ‘exploratory data analysis’ or not; simple plotting of basic statistics is very helpful to any analysis, especially as you are establishing a foundation of understanding that will inform your more complex analysis. I am going to break down three visualization types for analyzing proportions that will prove very useful: Pie charts, waffle charts, and bar charts (imagine that they’re actually maple bar or candy bar charts for the sake of ‘sweets’ theme) Displaying proportions at angles and offset angles at that; can make pie charts pretty tough to interpret Once you get more then 3–5 classes in a given pie, it is pretty difficult to compare relative proportion — whole purpose here... Ok, let's say yes you can get an idea of the general allotment for any given level or value for your categorical variable... but we often lack precision, or a precise consideration of the disparity between any given set of values. Conversely pie charts are amazing for real estate. Rather than taking up a ton of space, they are small and can include a lot of information in a small space. Depending on your audience, the pie chart can be very easy for uninformed groups to quickly absorb a given idea. From the group up using the mtcars dataset, lets build a pie chart. First things first, install & load up ggplot2 (install.packages(‘ggplot2), then library(ggplot2) and then you’re off to the races) Quick break down of ggplot, you first include the dataframe you’re working with, in this case mtcars then specify aes()-thetics... which is pretty much–where you want different variables to show up on a plot The first here is x, so whatever your categorical variable, your bucket, your container, your ice cream flavor; add it there. From here throw geom_bar() at the bottom to let you know exactly what type of chart you’d like to see. We’ll jump into the syntax, but with ggplot, you effectively create the visualization object, and then tell that object how you want to use it. First to give you a quick idea of the data; below you can see that we’re grouping by the cylinders variable and counting the number of records in each. counts <- mtcars %>% group_by(cyl) %>% summarise(n = n()) Lets throw this into a pie! ggplot(counts, aes(x = 1, y = n, fill = cyl)) + geom_col()+ coord_polar(theta = 'y') Boom! There’s your first pie chart. You’ll see that whatever categorical variable you’re grouping by goes into the color, and the count or n as I’ve written it goes into the y aesthetic. You may also notice the geom_col() command as well as coord_polar() To give an idea of the purpose of coord_polar() I’ll run this with only geom_col() ggplot(counts, aes(x = 1, y = n, fill = cyl)) + geom_col() As you can see, this is a stacked bar with the relative portions included here. Throwing on the coord_polar(theta = 'y') allows us to wrap this bar into a pie chart. Ok so you don’t love pie.... Waffle charts are an excellent alternative. While waffle charts are similar to pie charts, they actually encode each level, class or value of a categorical variable as a proportion of squares. Similar to pie charts, waffle charts can quickly be bogged down with the inclusion of too many classes Definitely don’t try to facet waffle or pie charts.. it does not lend well to making a reasonable comparison of the ‘relative proportion’ which is the whole purpose. To prep your data for a waffle chart, you need to scale values to 1–100 adding up to 100. For this we’ll use dplyr (install.packages('dplyr'), library(dplyr)). What you’ll see below is that we group our dataset by our categorical, then we’ll summarise according to the counts or n(). From there, we then create a new variable called percent using mutate. The big thing here is in our mutate() function, we are creating this scaled to 100 value. We’ll set up the names for case_counts and then we’ll run waffle() count <- mtcars %>% group_by(cyl) %>% summarise(n = n()) %>% mutate(percent = round(n/sum(n)*100))case_counts <- count$percentnames(case_counts) <- count$cylwaffle(case_counts) Ok we’re on our way! For a lot of things, bars just work better at establishing the relative comparability value to value. Lets unroll our pie and throw it into bars. Also take note that this is not a histogram. We are treating the cylinder count as a categorical variable. library(ggplot2)ggplot(mtcars, aes(x = as.factor(cyl))) + geom_bar() best practice for stacked bars: don’t make them in isolation, it’s not nearly as useful after three the key is that the wholes being compared all share the same y axis Something to keep in mind for bars is that anything far beyond three variables will be a lot more difficult to interpret. In order to reorder the bars of your bar chart, you’ll need to make sure the categorical variable is a factor as.factor(), then change the levels into the order you want them displayed Ggplot orders the bars and legend based upon the order it sees the variables in the dataset. To override this, turn the disease column into a factor with the levels in the order we want our plot to use. mtcars %>% factor(levels = c('2', '4', '6')) This can often play a big part in organizing your plots to optimize for interpret-ability Enjoy getting your hands dirty with proportion charts and categorical related data visualization. As you familiarize yourself with different charting techniques it will do you well to think about different charting tools as tools you might use for a given datatype and situation. Happy Data science-ing! And don’t forget to follow my blog to get more blogs related to machine learning, data visualization, data wrangling, and all things data science! datasciencelessons.com.
[ { "code": null, "e": 348, "s": 172, "text": "Whatever your application of data analytics & data science, there are proportions everywhere. Proportions are all about understanding the different parts that make up a whole." }, { "code": null, "e": 752, "s": 348, "text": "Proportions are pretty much just a count of something across a given categorical variable. That could be the number of customers across different industries, the number of sales calls in different geographies, the number of activities across various activity types, or the number of ice cream cones sold of various flavors. If you can count it, and break it into groups, then you’ve got proportion data!" }, { "code": null, "e": 1008, "s": 752, "text": "Whether you’re familiar with the idea of ‘exploratory data analysis’ or not; simple plotting of basic statistics is very helpful to any analysis, especially as you are establishing a foundation of understanding that will inform your more complex analysis." }, { "code": null, "e": 1249, "s": 1008, "text": "I am going to break down three visualization types for analyzing proportions that will prove very useful: Pie charts, waffle charts, and bar charts (imagine that they’re actually maple bar or candy bar charts for the sake of ‘sweets’ theme)" }, { "code": null, "e": 1355, "s": 1249, "text": "Displaying proportions at angles and offset angles at that; can make pie charts pretty tough to interpret" }, { "code": null, "e": 1484, "s": 1355, "text": "Once you get more then 3–5 classes in a given pie, it is pretty difficult to compare relative proportion — whole purpose here..." }, { "code": null, "e": 1715, "s": 1484, "text": "Ok, let's say yes you can get an idea of the general allotment for any given level or value for your categorical variable... but we often lack precision, or a precise consideration of the disparity between any given set of values." }, { "code": null, "e": 1874, "s": 1715, "text": "Conversely pie charts are amazing for real estate. Rather than taking up a ton of space, they are small and can include a lot of information in a small space." }, { "code": null, "e": 1987, "s": 1874, "text": "Depending on your audience, the pie chart can be very easy for uninformed groups to quickly absorb a given idea." }, { "code": null, "e": 2055, "s": 1987, "text": "From the group up using the mtcars dataset, lets build a pie chart." }, { "code": null, "e": 2186, "s": 2055, "text": "First things first, install & load up ggplot2 (install.packages(‘ggplot2), then library(ggplot2) and then you’re off to the races)" }, { "code": null, "e": 2214, "s": 2186, "text": "Quick break down of ggplot," }, { "code": null, "e": 2287, "s": 2214, "text": "you first include the dataframe you’re working with, in this case mtcars" }, { "code": null, "e": 2394, "s": 2287, "text": "then specify aes()-thetics... which is pretty much–where you want different variables to show up on a plot" }, { "code": null, "e": 2520, "s": 2394, "text": "The first here is x, so whatever your categorical variable, your bucket, your container, your ice cream flavor; add it there." }, { "code": null, "e": 2767, "s": 2520, "text": "From here throw geom_bar() at the bottom to let you know exactly what type of chart you’d like to see. We’ll jump into the syntax, but with ggplot, you effectively create the visualization object, and then tell that object how you want to use it." }, { "code": null, "e": 2919, "s": 2767, "text": "First to give you a quick idea of the data; below you can see that we’re grouping by the cylinders variable and counting the number of records in each." }, { "code": null, "e": 2979, "s": 2919, "text": "counts <- mtcars %>% group_by(cyl) %>% summarise(n = n())" }, { "code": null, "e": 3007, "s": 2979, "text": "Lets throw this into a pie!" }, { "code": null, "e": 3094, "s": 3007, "text": "ggplot(counts, aes(x = 1, y = n, fill = cyl)) + geom_col()+ coord_polar(theta = 'y')" }, { "code": null, "e": 3281, "s": 3094, "text": "Boom! There’s your first pie chart. You’ll see that whatever categorical variable you’re grouping by goes into the color, and the count or n as I’ve written it goes into the y aesthetic." }, { "code": null, "e": 3349, "s": 3281, "text": "You may also notice the geom_col() command as well as coord_polar()" }, { "code": null, "e": 3432, "s": 3349, "text": "To give an idea of the purpose of coord_polar() I’ll run this with only geom_col()" }, { "code": null, "e": 3492, "s": 3432, "text": "ggplot(counts, aes(x = 1, y = n, fill = cyl)) + geom_col()" }, { "code": null, "e": 3658, "s": 3492, "text": "As you can see, this is a stacked bar with the relative portions included here. Throwing on the coord_polar(theta = 'y') allows us to wrap this bar into a pie chart." }, { "code": null, "e": 3880, "s": 3658, "text": "Ok so you don’t love pie.... Waffle charts are an excellent alternative. While waffle charts are similar to pie charts, they actually encode each level, class or value of a categorical variable as a proportion of squares." }, { "code": null, "e": 3983, "s": 3880, "text": "Similar to pie charts, waffle charts can quickly be bogged down with the inclusion of too many classes" }, { "code": null, "e": 4149, "s": 3983, "text": "Definitely don’t try to facet waffle or pie charts.. it does not lend well to making a reasonable comparison of the ‘relative proportion’ which is the whole purpose." }, { "code": null, "e": 4309, "s": 4149, "text": "To prep your data for a waffle chart, you need to scale values to 1–100 adding up to 100. For this we’ll use dplyr (install.packages('dplyr'), library(dplyr))." }, { "code": null, "e": 4594, "s": 4309, "text": "What you’ll see below is that we group our dataset by our categorical, then we’ll summarise according to the counts or n(). From there, we then create a new variable called percent using mutate. The big thing here is in our mutate() function, we are creating this scaled to 100 value." }, { "code": null, "e": 4661, "s": 4594, "text": "We’ll set up the names for case_counts and then we’ll run waffle()" }, { "code": null, "e": 4842, "s": 4661, "text": "count <- mtcars %>% group_by(cyl) %>% summarise(n = n()) %>% mutate(percent = round(n/sum(n)*100))case_counts <- count$percentnames(case_counts) <- count$cylwaffle(case_counts)" }, { "code": null, "e": 4863, "s": 4842, "text": "Ok we’re on our way!" }, { "code": null, "e": 5116, "s": 4863, "text": "For a lot of things, bars just work better at establishing the relative comparability value to value. Lets unroll our pie and throw it into bars. Also take note that this is not a histogram. We are treating the cylinder count as a categorical variable." }, { "code": null, "e": 5186, "s": 5116, "text": "library(ggplot2)ggplot(mtcars, aes(x = as.factor(cyl))) + geom_bar()" }, { "code": null, "e": 5286, "s": 5186, "text": "best practice for stacked bars: don’t make them in isolation, it’s not nearly as useful after three" }, { "code": null, "e": 5354, "s": 5286, "text": "the key is that the wholes being compared all share the same y axis" }, { "code": null, "e": 5476, "s": 5354, "text": "Something to keep in mind for bars is that anything far beyond three variables will be a lot more difficult to interpret." }, { "code": null, "e": 5661, "s": 5476, "text": "In order to reorder the bars of your bar chart, you’ll need to make sure the categorical variable is a factor as.factor(), then change the levels into the order you want them displayed" }, { "code": null, "e": 5864, "s": 5661, "text": "Ggplot orders the bars and legend based upon the order it sees the variables in the dataset. To override this, turn the disease column into a factor with the levels in the order we want our plot to use." }, { "code": null, "e": 5910, "s": 5864, "text": "mtcars %>% factor(levels = c('2', '4', '6'))" }, { "code": null, "e": 6000, "s": 5910, "text": "This can often play a big part in organizing your plots to optimize for interpret-ability" }, { "code": null, "e": 6280, "s": 6000, "text": "Enjoy getting your hands dirty with proportion charts and categorical related data visualization. As you familiarize yourself with different charting techniques it will do you well to think about different charting tools as tools you might use for a given datatype and situation." } ]
exit() vs _Exit() in C/C++
The function exit() is used to terminate the calling function immediately without executing further processes. As exit() function calls, it terminates processes. It calls the constructor of class only. It is declared in “stdlib.h” header file in C language. It does not return anything. The following is the syntax of exit() void exit(int status_value); Here, status_value − The value which is returned to parent process. The following is an example of exit() Live Demo #include <stdio.h> #include <stdlib.h> int main() { int x = 10; printf("The value of x : %d\n", x); exit(0); printf("Calling of exit()"); return 0; } The value of x : 10 In the above program, a variable ‘x’ is initialized with a value. The value of variable is printed and exit() function is called. As exit() is called, it exits the execution immediately and it does not print the statement in the printf(). The calling of exit() is as follows − int x = 10; printf("The value of x : %d\n", x); exit(0); The function _Exit() is used to terminate the process normally and it returns the control to host environment. It does not perform any cleanup task. The following is the syntax of _Exit() void _Exit(int status_value); Here, status_value − The value which is returned to parent process. The following is an example of _Exit() #include <stdio.h> #include <stdlib.h> int main() { int x = 10; printf("The value of x : %d\n", x); _Exit(0); printf("Calling of _Exit()"); return 0; } In the above program, neither it will display anything nor it will show error.
[ { "code": null, "e": 1349, "s": 1062, "text": "The function exit() is used to terminate the calling function immediately without executing further processes. As exit() function calls, it terminates processes. It calls the constructor of class only. It is declared in “stdlib.h” header file in C language. It does not return anything." }, { "code": null, "e": 1387, "s": 1349, "text": "The following is the syntax of exit()" }, { "code": null, "e": 1416, "s": 1387, "text": "void exit(int status_value);" }, { "code": null, "e": 1422, "s": 1416, "text": "Here," }, { "code": null, "e": 1484, "s": 1422, "text": "status_value − The value which is returned to parent process." }, { "code": null, "e": 1522, "s": 1484, "text": "The following is an example of exit()" }, { "code": null, "e": 1533, "s": 1522, "text": " Live Demo" }, { "code": null, "e": 1698, "s": 1533, "text": "#include <stdio.h>\n#include <stdlib.h>\nint main() {\n int x = 10;\n printf(\"The value of x : %d\\n\", x);\n exit(0);\n printf(\"Calling of exit()\");\n return 0;\n}" }, { "code": null, "e": 1718, "s": 1698, "text": "The value of x : 10" }, { "code": null, "e": 1995, "s": 1718, "text": "In the above program, a variable ‘x’ is initialized with a value. The value of variable is printed and exit() function is called. As exit() is called, it exits the execution immediately and it does not print the statement in the printf(). The calling of exit() is as follows −" }, { "code": null, "e": 2052, "s": 1995, "text": "int x = 10;\nprintf(\"The value of x : %d\\n\", x);\nexit(0);" }, { "code": null, "e": 2201, "s": 2052, "text": "The function _Exit() is used to terminate the process normally and it returns the control to host environment. It does not perform any cleanup task." }, { "code": null, "e": 2240, "s": 2201, "text": "The following is the syntax of _Exit()" }, { "code": null, "e": 2270, "s": 2240, "text": "void _Exit(int status_value);" }, { "code": null, "e": 2276, "s": 2270, "text": "Here," }, { "code": null, "e": 2338, "s": 2276, "text": "status_value − The value which is returned to parent process." }, { "code": null, "e": 2377, "s": 2338, "text": "The following is an example of _Exit()" }, { "code": null, "e": 2544, "s": 2377, "text": "#include <stdio.h>\n#include <stdlib.h>\nint main() {\n int x = 10;\n printf(\"The value of x : %d\\n\", x);\n _Exit(0);\n printf(\"Calling of _Exit()\");\n return 0;\n}" }, { "code": null, "e": 2623, "s": 2544, "text": "In the above program, neither it will display anything nor it will show error." } ]
Dimensionality Reduction — Does PCA really improve classification outcome? | by Meigarom Lopes | Towards Data Science
I have come across a couple resources about dimensionality reduction techniques. This topic is definitively one of the most interesting ones, it is great to think that there are algorithms able to reduce the number of features by choosing the most important ones that still represent the entire dataset. One of the advantages pointed out by authors is that these algorithms can improve the results of classification task. In this post, I am going to verify this statement using a Principal Component Analysis ( PCA ) to try to improve the classification performance of a neural network over a dataset. Does PCA really improve classification outcome? Let’s check it out. Before go straight ahead to code, let’s talk about dimensionality reduction algorithms. There are two principal algorithms for dimensionality reduction: Linear Discriminant Analysis ( LDA ) and Principal Component Analysis ( PCA ). The basic difference between these two is that LDA uses information of classes to find new features in order to maximize its separability while PCA uses the variance of each feature to do the same. In this context, LDA can be consider a supervised algorithm and PCA an unsupervised algorithm. The idea behind PCA is simply to find a low-dimension set of axes that summarize data. Why do we need to summarize data though? Let’s think about this example: We have a dataset composed by a set of properties from cars. These properties describe each car by its size, color, circularity, compactness, radius, number of seats, number of doors, size of trunk and so on. However, many of these features will measure related properties and so will be redundant. Therefore, we should remove these redundancy and describe each car with less properties. This is exactly what PCA aims to do. For example, think about the number of wheel as a feature of cars and buses, almost every example from both classes have four wheels, hence we can tell that this feature has a low variance ( from four up to six wheels or more in some of rare buses ), so this feature will make bus and cars look the same, but they are actually pretty different from each other. Now, consider the height as a feature, cars and buses have different values for it, the variance has a great range from the lowest car up to the highest bus. Clearly, the height of these vehicle is a good property to separate them. Recall that PCA does not take information of classes into account, it just look at the variance of each feature because is reasonable assumes that features that present high variance are more likely to have a good split between classes. Often, people end up making a mistake in thinking that PCA selects some features out of the dataset and discards others. The algorithm actually constructs new set of properties based on combination of the old ones. Mathematically speaking, PCA performs a linear transformation moving the original set of features to a new space composed by principal component. These new features does not have any real meaning for us, only algebraic, therefore do not think that combining linearly features, you will find new features that you have never thought that it could exist. Many of people still believe that machine learning algorithms are magic, they put a thousands of inputs straight to the algorithm and hope to find all insights and solutions for theirs business. Do not be tricked. It is the job of the data scientist to locate the insights to the business through a well-conducted exploratory analysis of data using machine learning algorithm as a set of tools and not as a magic wand. Keep it in mind. In the new feature space we are looking for some properties that strongly differ across the classes. As I showed in the previous example, some properties that present low variance are not useful, it will make the examples look the same. On the other hand, PCA looks for properties that show as much variation across classes as possible to build the principal component space. The algorithm use the concepts of variance matrix, covariance matrix, eigenvector and eigenvalues pairs to perform PCA, providing a set of eigenvectors and its respectively eigenvalues as a result. How exactly PCA performs is a material for next posts. So, what should we do with eigenvalues and eigenvectors? It is very simple, the eigenvectors represents the new set of axes of the principal component space and the eigenvalues carry the information of quantity of variance that each eigenvector have. So, in order to reduce the dimension of the dataset we are going to choose those eigenvectors that have more variance and discard those with less variance. As we go though the example below, it will be more and more clear how exactly it works. Now, we reached the fun and interesting part of this post. Let’s see if PCA really improves the result of classification task. In order to comprove it, my strategy is to apply a neural network over a dataset and see its initial results. Afterwards, I am going to perform PCA before classification and apply the same neural network over the new dataset and last compare both results. The dataset is originated from UCI machine learning repository called “Statlog ( Vehicle Silhouettes ) dataset”. This dataset stores some measures of four vehicles’s silhouettes with the purpose of classification. It is composed by 946 examples and 18 measures ( attributes ) all numerics values, you can check more details here in this link: https://archive.ics.uci.edu/ml/datasets/Statlog+(Vehicle+Silhouettes). The neural network will be a MultiLayer Perceptron with four hidden nodes and one output node, all with sigmoid function as activation function and PCA functions will coming from a R package. First of all, I am going to prepare the dataset for binary classification. I am going to select examples only from two classes in order to make up a binary classification. The examples will come from “bus” and “saab” classes. The class “saab” will be replace by class 0 and class “bus” will be replaced by class 1. Next step consists in to separate the dataset into training and testing datasets with 60% and 40% of the total class examples, respectively. After previous dataset preparation, let’s model a neural network using all features at once and then to apply the test dataset. # Load librarylibrary( dplyr )# Load datasetdata = read.csv( "../dataset/vehicle.csv", stringsAsFactor = FALSE )# Transform datasetdataset = data %>% filter( class == "bus" | class == "saab" ) %>% transform( class = ifelse( class == "saab", 0, 1 ) )dataset = as.data.frame( sapply( dataset, as.numeric ) )# Spliting training and testing datasetindex = sample( 1:nrow( dataset ), nrow( dataset ) * 0.6, replace = FALSE ) trainset = dataset[ index, ]test = dataset[ -index, ]testset = test %>% select( -class )# Building a neural network (NN)library( neuralnet )n = names( trainset )f = as.formula( paste( "class ~", paste( n[!n %in% "class"], collapse = "+" ) ) )nn = neuralnet( f, trainset, hidden = 4, linear.output = FALSE, threshold = 0.01 )plot( nn, rep = "best" ) # Testing the result outputnn.results = compute( nn, testset )results = data.frame( actual = test$class, prediction = round( nn.results$net.result ) )# Confusion matrixlibrary( caret )t = table( results )print( confusionMatrix( t ) )## Confusion Matrix and Statistics## ## prediction## actual 0 1## 0 79 0## 1 79 16## ## Accuracy : 0.545977 ## 95% CI : (0.4688867, 0.6214742)## No Information Rate : 0.908046 ## P-Value [Acc > NIR] : 1 ## ## Kappa : 0.1553398 ## Mcnemar's Test P-Value : <0.0000000000000002 ## ## Sensitivity : 0.5000000 ## Specificity : 1.0000000 ## Pos Pred Value : 1.0000000 ## Neg Pred Value : 0.1684211 ## Prevalence : 0.9080460 ## Detection Rate : 0.4540230 ## Detection Prevalence : 0.4540230 ## Balanced Accuracy : 0.7500000 ## ## 'Positive' Class : 0 ## It seems we got some results. Firstly, take a look at the confusion matrix. Basically, confusion matrix says how much examples were classified into classes. The main diagonal shows the examples that were classify correctly and secondary diagonal shows misclassification. In this first result, the classifier shows itself very confused, because it classified correctly almost all examples from “saab” class, but it also classified most examples of “bus” class as “saab” class. Reinforcing this results, we can see that the value of accuracy is around 50%, it is a really bad result for classification task. The classifier has essentially a probability of 50% to classify a new example into “car” class and 50% into “bus” classes. Analogically, the neural network is tossing a coin for each new example to choose which class it should classify it in. Now, let’s perform the principal component analysis over the dataset and get the eigenvalues and eigenvectors. In a practical way, you will see that PCA function from R package provides a set of eigenvalues already sorted in descending order, it means that the first component is that one with the highest variance, the second component is the eigenvector with the second highest variance and so on. The code below shows how to chose the eigenvectors looking at the eigenvalues. # PCApca_trainset = trainset %>% select( -class )pca_testset = testsetpca = prcomp( pca_trainset, scale = T )# variancepr_var = ( pca$sdev )^2 # % of varianceprop_varex = pr_var / sum( pr_var )# Plotplot( prop_varex, xlab = "Principal Component", ylab = "Proportion of Variance Explained", type = "b" ) # Scree Plotplot( cumsum( prop_varex ), xlab = "Principal Component", ylab = "Cumulative Proportion of Variance Explained", type = "b" ) The native R function “prcomp” from stats default packages performs PCA, it returns all eigenvalues and eigenvectors needed. The first plot shows the percentage of variance of each feature. You can see that the first component has the highest variance, something value around 50% while the 8th component is around of 0% of variance. So, it indicates that we should pick up the first eight components. The second figure show an another perspective of the variance, though the cumulative sum over all the variance, you can see that the first eight eigenvalues correspond to approximately 98% of the all variance. Indeed, it is a pretty good number, it means that there is just 2% of information being lost. The biggest beneficial is that we are moving from a space with eighteen features to another one with only eight feature losing only 2% of information. That is the power of dimensionality reduction, definitively. Now that we know the number of the features that will compose the new space, let’s create the new dataset and then model the neural network again and check if we get new better outcomes. # Creating a new datasettrain = data.frame( class = trainset$class, pca$x )t = as.data.frame( predict( pca, newdata = pca_testset ) )new_trainset = train[, 1:9]new_testset = t[, 1:8]# Build the neural network (NN)library( neuralnet )n = names( new_trainset )f = as.formula( paste( "class ~", paste( n[!n %in% "class" ], collapse = "+" ) ) )nn = neuralnet( f, new_trainset, hidden = 4, linear.output = FALSE, threshold=0.01 )# Plot the NNplot( nn, rep = "best" ) # Test the resulting outputnn.results = compute( nn, new_testset )# Resultsresults = data.frame( actual = test$class, prediction = round( nn.results$net.result ) )# Confusion Matrixlibrary( caret )t = table( results ) print( confusionMatrix( t ) )## Confusion Matrix and Statistics## ## prediction## actual 0 1## 0 76 3## 1 1 94## ## Accuracy : 0.9770115 ## 95% CI : (0.9421888, 0.9937017)## No Information Rate : 0.5574713 ## P-Value [Acc > NIR] : < 0.00000000000000022 ## ## Kappa : 0.9535318 ## Mcnemar's Test P-Value : 0.6170751 ## ## Sensitivity : 0.9870130 ## Specificity : 0.9690722 ## Pos Pred Value : 0.9620253 ## Neg Pred Value : 0.9894737 ## Prevalence : 0.4425287 ## Detection Rate : 0.4367816 ## Detection Prevalence : 0.4540230 ## Balanced Accuracy : 0.9780426 ## ## 'Positive' Class : 0 ## Well, I guess we got better results now. Let’s to examine it carefully. The confusion matrix shows really good results this time, the neural network is committing less misclassification in both classes, it can be seen though the values of the main diagonal and also the accuracy value is around 95%. It means that the classifier has 95% chance of correctly classifying a new unseen example. For classification problems, it is a not bad result at all. Dimensionality Reduction plays a really important role in machine learning, especially when you are working with thousands of features. Principal Components Analysis are one of the top dimensionality reduction algorithm, it is not hard to understand and use it in real projects. This technique, in addition to making the work of feature manipulation easier, it still helps to improve the results of the classifier, as we saw in this post. Finally, the answer of the initial questioning is yes, indeed Principal Component Analysis helps improve the outcome of a classifier. As I mentioned before there are other dimensionality reduction techniques available, such as Linear Discriminant Analysis, Factor Analysis, Isomap and its variations. The ideia is explore advantages and disadvantages of each one and check its results individually and combined as well. Would LDA combined with PCA improve the classifiers outcome? Well, let’s investigate it in the next posts. The complete code is available on my git hub repository as well as the dataset. ( https://github.com/Meigarom/machine_learning ) Thanks for your time reading this post. I really appreciated, feedbacks are always welcome. See you guys soon.
[ { "code": null, "e": 593, "s": 171, "text": "I have come across a couple resources about dimensionality reduction techniques. This topic is definitively one of the most interesting ones, it is great to think that there are algorithms able to reduce the number of features by choosing the most important ones that still represent the entire dataset. One of the advantages pointed out by authors is that these algorithms can improve the results of classification task." }, { "code": null, "e": 841, "s": 593, "text": "In this post, I am going to verify this statement using a Principal Component Analysis ( PCA ) to try to improve the classification performance of a neural network over a dataset. Does PCA really improve classification outcome? Let’s check it out." }, { "code": null, "e": 1366, "s": 841, "text": "Before go straight ahead to code, let’s talk about dimensionality reduction algorithms. There are two principal algorithms for dimensionality reduction: Linear Discriminant Analysis ( LDA ) and Principal Component Analysis ( PCA ). The basic difference between these two is that LDA uses information of classes to find new features in order to maximize its separability while PCA uses the variance of each feature to do the same. In this context, LDA can be consider a supervised algorithm and PCA an unsupervised algorithm." }, { "code": null, "e": 2781, "s": 1366, "text": "The idea behind PCA is simply to find a low-dimension set of axes that summarize data. Why do we need to summarize data though? Let’s think about this example: We have a dataset composed by a set of properties from cars. These properties describe each car by its size, color, circularity, compactness, radius, number of seats, number of doors, size of trunk and so on. However, many of these features will measure related properties and so will be redundant. Therefore, we should remove these redundancy and describe each car with less properties. This is exactly what PCA aims to do. For example, think about the number of wheel as a feature of cars and buses, almost every example from both classes have four wheels, hence we can tell that this feature has a low variance ( from four up to six wheels or more in some of rare buses ), so this feature will make bus and cars look the same, but they are actually pretty different from each other. Now, consider the height as a feature, cars and buses have different values for it, the variance has a great range from the lowest car up to the highest bus. Clearly, the height of these vehicle is a good property to separate them. Recall that PCA does not take information of classes into account, it just look at the variance of each feature because is reasonable assumes that features that present high variance are more likely to have a good split between classes." }, { "code": null, "e": 3785, "s": 2781, "text": "Often, people end up making a mistake in thinking that PCA selects some features out of the dataset and discards others. The algorithm actually constructs new set of properties based on combination of the old ones. Mathematically speaking, PCA performs a linear transformation moving the original set of features to a new space composed by principal component. These new features does not have any real meaning for us, only algebraic, therefore do not think that combining linearly features, you will find new features that you have never thought that it could exist. Many of people still believe that machine learning algorithms are magic, they put a thousands of inputs straight to the algorithm and hope to find all insights and solutions for theirs business. Do not be tricked. It is the job of the data scientist to locate the insights to the business through a well-conducted exploratory analysis of data using machine learning algorithm as a set of tools and not as a magic wand. Keep it in mind." }, { "code": null, "e": 4414, "s": 3785, "text": "In the new feature space we are looking for some properties that strongly differ across the classes. As I showed in the previous example, some properties that present low variance are not useful, it will make the examples look the same. On the other hand, PCA looks for properties that show as much variation across classes as possible to build the principal component space. The algorithm use the concepts of variance matrix, covariance matrix, eigenvector and eigenvalues pairs to perform PCA, providing a set of eigenvectors and its respectively eigenvalues as a result. How exactly PCA performs is a material for next posts." }, { "code": null, "e": 4909, "s": 4414, "text": "So, what should we do with eigenvalues and eigenvectors? It is very simple, the eigenvectors represents the new set of axes of the principal component space and the eigenvalues carry the information of quantity of variance that each eigenvector have. So, in order to reduce the dimension of the dataset we are going to choose those eigenvectors that have more variance and discard those with less variance. As we go though the example below, it will be more and more clear how exactly it works." }, { "code": null, "e": 5036, "s": 4909, "text": "Now, we reached the fun and interesting part of this post. Let’s see if PCA really improves the result of classification task." }, { "code": null, "e": 5292, "s": 5036, "text": "In order to comprove it, my strategy is to apply a neural network over a dataset and see its initial results. Afterwards, I am going to perform PCA before classification and apply the same neural network over the new dataset and last compare both results." }, { "code": null, "e": 5898, "s": 5292, "text": "The dataset is originated from UCI machine learning repository called “Statlog ( Vehicle Silhouettes ) dataset”. This dataset stores some measures of four vehicles’s silhouettes with the purpose of classification. It is composed by 946 examples and 18 measures ( attributes ) all numerics values, you can check more details here in this link: https://archive.ics.uci.edu/ml/datasets/Statlog+(Vehicle+Silhouettes). The neural network will be a MultiLayer Perceptron with four hidden nodes and one output node, all with sigmoid function as activation function and PCA functions will coming from a R package." }, { "code": null, "e": 5973, "s": 5898, "text": "First of all, I am going to prepare the dataset for binary classification." }, { "code": null, "e": 6354, "s": 5973, "text": "I am going to select examples only from two classes in order to make up a binary classification. The examples will come from “bus” and “saab” classes. The class “saab” will be replace by class 0 and class “bus” will be replaced by class 1. Next step consists in to separate the dataset into training and testing datasets with 60% and 40% of the total class examples, respectively." }, { "code": null, "e": 6482, "s": 6354, "text": "After previous dataset preparation, let’s model a neural network using all features at once and then to apply the test dataset." }, { "code": null, "e": 7274, "s": 6482, "text": "# Load librarylibrary( dplyr )# Load datasetdata = read.csv( \"../dataset/vehicle.csv\", stringsAsFactor = FALSE )# Transform datasetdataset = data %>% filter( class == \"bus\" | class == \"saab\" ) %>% transform( class = ifelse( class == \"saab\", 0, 1 ) )dataset = as.data.frame( sapply( dataset, as.numeric ) )# Spliting training and testing datasetindex = sample( 1:nrow( dataset ), nrow( dataset ) * 0.6, replace = FALSE ) trainset = dataset[ index, ]test = dataset[ -index, ]testset = test %>% select( -class )# Building a neural network (NN)library( neuralnet )n = names( trainset )f = as.formula( paste( \"class ~\", paste( n[!n %in% \"class\"], collapse = \"+\" ) ) )nn = neuralnet( f, trainset, hidden = 4, linear.output = FALSE, threshold = 0.01 )plot( nn, rep = \"best\" )" }, { "code": null, "e": 8580, "s": 7274, "text": "# Testing the result outputnn.results = compute( nn, testset )results = data.frame( actual = test$class, prediction = round( nn.results$net.result ) )# Confusion matrixlibrary( caret )t = table( results )print( confusionMatrix( t ) )## Confusion Matrix and Statistics## ## prediction## actual 0 1## 0 79 0## 1 79 16## ## Accuracy : 0.545977 ## 95% CI : (0.4688867, 0.6214742)## No Information Rate : 0.908046 ## P-Value [Acc > NIR] : 1 ## ## Kappa : 0.1553398 ## Mcnemar's Test P-Value : <0.0000000000000002 ## ## Sensitivity : 0.5000000 ## Specificity : 1.0000000 ## Pos Pred Value : 1.0000000 ## Neg Pred Value : 0.1684211 ## Prevalence : 0.9080460 ## Detection Rate : 0.4540230 ## Detection Prevalence : 0.4540230 ## Balanced Accuracy : 0.7500000 ## ## 'Positive' Class : 0 ##" }, { "code": null, "e": 9429, "s": 8580, "text": "It seems we got some results. Firstly, take a look at the confusion matrix. Basically, confusion matrix says how much examples were classified into classes. The main diagonal shows the examples that were classify correctly and secondary diagonal shows misclassification. In this first result, the classifier shows itself very confused, because it classified correctly almost all examples from “saab” class, but it also classified most examples of “bus” class as “saab” class. Reinforcing this results, we can see that the value of accuracy is around 50%, it is a really bad result for classification task. The classifier has essentially a probability of 50% to classify a new example into “car” class and 50% into “bus” classes. Analogically, the neural network is tossing a coin for each new example to choose which class it should classify it in." }, { "code": null, "e": 9908, "s": 9429, "text": "Now, let’s perform the principal component analysis over the dataset and get the eigenvalues and eigenvectors. In a practical way, you will see that PCA function from R package provides a set of eigenvalues already sorted in descending order, it means that the first component is that one with the highest variance, the second component is the eigenvector with the second highest variance and so on. The code below shows how to chose the eigenvectors looking at the eigenvalues." }, { "code": null, "e": 10229, "s": 9908, "text": "# PCApca_trainset = trainset %>% select( -class )pca_testset = testsetpca = prcomp( pca_trainset, scale = T )# variancepr_var = ( pca$sdev )^2 # % of varianceprop_varex = pr_var / sum( pr_var )# Plotplot( prop_varex, xlab = \"Principal Component\", ylab = \"Proportion of Variance Explained\", type = \"b\" )" }, { "code": null, "e": 10394, "s": 10229, "text": "# Scree Plotplot( cumsum( prop_varex ), xlab = \"Principal Component\", ylab = \"Cumulative Proportion of Variance Explained\", type = \"b\" )" }, { "code": null, "e": 11311, "s": 10394, "text": "The native R function “prcomp” from stats default packages performs PCA, it returns all eigenvalues and eigenvectors needed. The first plot shows the percentage of variance of each feature. You can see that the first component has the highest variance, something value around 50% while the 8th component is around of 0% of variance. So, it indicates that we should pick up the first eight components. The second figure show an another perspective of the variance, though the cumulative sum over all the variance, you can see that the first eight eigenvalues correspond to approximately 98% of the all variance. Indeed, it is a pretty good number, it means that there is just 2% of information being lost. The biggest beneficial is that we are moving from a space with eighteen features to another one with only eight feature losing only 2% of information. That is the power of dimensionality reduction, definitively." }, { "code": null, "e": 11498, "s": 11311, "text": "Now that we know the number of the features that will compose the new space, let’s create the new dataset and then model the neural network again and check if we get new better outcomes." }, { "code": null, "e": 11961, "s": 11498, "text": "# Creating a new datasettrain = data.frame( class = trainset$class, pca$x )t = as.data.frame( predict( pca, newdata = pca_testset ) )new_trainset = train[, 1:9]new_testset = t[, 1:8]# Build the neural network (NN)library( neuralnet )n = names( new_trainset )f = as.formula( paste( \"class ~\", paste( n[!n %in% \"class\" ], collapse = \"+\" ) ) )nn = neuralnet( f, new_trainset, hidden = 4, linear.output = FALSE, threshold=0.01 )# Plot the NNplot( nn, rep = \"best\" )" }, { "code": null, "e": 13303, "s": 11961, "text": "# Test the resulting outputnn.results = compute( nn, new_testset )# Resultsresults = data.frame( actual = test$class, prediction = round( nn.results$net.result ) )# Confusion Matrixlibrary( caret )t = table( results ) print( confusionMatrix( t ) )## Confusion Matrix and Statistics## ## prediction## actual 0 1## 0 76 3## 1 1 94## ## Accuracy : 0.9770115 ## 95% CI : (0.9421888, 0.9937017)## No Information Rate : 0.5574713 ## P-Value [Acc > NIR] : < 0.00000000000000022 ## ## Kappa : 0.9535318 ## Mcnemar's Test P-Value : 0.6170751 ## ## Sensitivity : 0.9870130 ## Specificity : 0.9690722 ## Pos Pred Value : 0.9620253 ## Neg Pred Value : 0.9894737 ## Prevalence : 0.4425287 ## Detection Rate : 0.4367816 ## Detection Prevalence : 0.4540230 ## Balanced Accuracy : 0.9780426 ## ## 'Positive' Class : 0 ##" }, { "code": null, "e": 13375, "s": 13303, "text": "Well, I guess we got better results now. Let’s to examine it carefully." }, { "code": null, "e": 13754, "s": 13375, "text": "The confusion matrix shows really good results this time, the neural network is committing less misclassification in both classes, it can be seen though the values of the main diagonal and also the accuracy value is around 95%. It means that the classifier has 95% chance of correctly classifying a new unseen example. For classification problems, it is a not bad result at all." }, { "code": null, "e": 14193, "s": 13754, "text": "Dimensionality Reduction plays a really important role in machine learning, especially when you are working with thousands of features. Principal Components Analysis are one of the top dimensionality reduction algorithm, it is not hard to understand and use it in real projects. This technique, in addition to making the work of feature manipulation easier, it still helps to improve the results of the classifier, as we saw in this post." }, { "code": null, "e": 14327, "s": 14193, "text": "Finally, the answer of the initial questioning is yes, indeed Principal Component Analysis helps improve the outcome of a classifier." }, { "code": null, "e": 14720, "s": 14327, "text": "As I mentioned before there are other dimensionality reduction techniques available, such as Linear Discriminant Analysis, Factor Analysis, Isomap and its variations. The ideia is explore advantages and disadvantages of each one and check its results individually and combined as well. Would LDA combined with PCA improve the classifiers outcome? Well, let’s investigate it in the next posts." }, { "code": null, "e": 14849, "s": 14720, "text": "The complete code is available on my git hub repository as well as the dataset. ( https://github.com/Meigarom/machine_learning )" }, { "code": null, "e": 14941, "s": 14849, "text": "Thanks for your time reading this post. I really appreciated, feedbacks are always welcome." } ]
DateTime.Add() Method in C# - GeeksforGeeks
18 Jan, 2019 This method is used to return a new DateTime that adds the value of the specified TimeSpan to the value of this instance. Syntax: public DateTime Add (TimeSpan value); Here, value is a positive or negative time interval. Return Value: This method returns an object whose value is the sum of the date and time represented by this instance and the time interval represented by value. Exceptions: This method will give ArgumentOutOfRangeException if the resulting DateTime is less than MinValue or greater than MaxValue. Below programs illustrate the use of DateTime.Add(TimeSpan) Method: Example 1: // C# program to demonstrate the// DateTime.Add(TimeSpan) Methodusing System;using System.Globalization; class GFG { // Main Method public static void Main() { try { // creating object of DateTime DateTime date1 = new DateTime(2010, 1, 1, 8, 0, 15); // creating object of TimeSpan TimeSpan duration = new TimeSpan(36, 0, 0, 0); // adding the TimeSpan of 36 days // using Add() method; DateTime date2 = date1.Add(duration); // Display the date1 System.Console.WriteLine("DateTime before "+ "operation: {0:y} {0:dd}", date1); // Display the date2 System.Console.WriteLine("\nDateTime after"+ " operation: {0:y} {0:dd}", date2); } catch (ArgumentOutOfRangeException e) { Console.Write("Exception Thrown: "); Console.Write("{0}", e.GetType(), e.Message); } }} DateTime before operation: 2010 January 01 DateTime after operation: 2010 February 06 Example 2: For ArgumentOutOfRangeException // C# program to demonstrate the// DateTime.Add(TimeSpan) Methodusing System;using System.Globalization; class GFG { // Main Method public static void Main() { try { // creating object of DateTime // and initialize with MinValue DateTime date1 = DateTime.MinValue; // Display the date1 Console.WriteLine("DateTime before "+ "operation: {0:y} {0:dd}", date1); // creating object of TimeSpan TimeSpan duration = new TimeSpan(-36, 0, 0, 0); // adding the TimeSpan of 36 days // using Add() method; DateTime date2 = date1.Add(duration); // Display the date2 Console.WriteLine("\nDateTime after"+ " operation: {0:y} {0:dd}", date2); } catch (ArgumentOutOfRangeException e) { Console.WriteLine("\nThe resulting DateTime"+ " is less than the MinValue "); Console.Write("Exception Thrown: "); Console.Write("{0}", e.GetType(), e.Message); } }} DateTime before operation: 0001 January 01 The resulting DateTime is less than the MinValue Exception Thrown: System.ArgumentOutOfRangeException Note: The Add method takes into account leap years and the number of days in a month when performing date arithmetic. This method does not change the value of this DateTime. Instead, it returns a new DateTime whose value is the result of this operation. Reference: https://docs.microsoft.com/en-us/dotnet/api/system.datetime.add?view=netframework-4.7.2 CSharp DateTime Struct CSharp-method C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. C# | Method Overriding C# Dictionary with examples Destructors in C# Difference between Ref and Out keywords in C# C# | Delegates C# | Constructors Extension Method in C# C# | String.IndexOf( ) Method | Set - 1 C# | Class and Object Introduction to .NET Framework
[ { "code": null, "e": 24010, "s": 23982, "text": "\n18 Jan, 2019" }, { "code": null, "e": 24132, "s": 24010, "text": "This method is used to return a new DateTime that adds the value of the specified TimeSpan to the value of this instance." }, { "code": null, "e": 24140, "s": 24132, "text": "Syntax:" }, { "code": null, "e": 24178, "s": 24140, "text": "public DateTime Add (TimeSpan value);" }, { "code": null, "e": 24231, "s": 24178, "text": "Here, value is a positive or negative time interval." }, { "code": null, "e": 24392, "s": 24231, "text": "Return Value: This method returns an object whose value is the sum of the date and time represented by this instance and the time interval represented by value." }, { "code": null, "e": 24528, "s": 24392, "text": "Exceptions: This method will give ArgumentOutOfRangeException if the resulting DateTime is less than MinValue or greater than MaxValue." }, { "code": null, "e": 24596, "s": 24528, "text": "Below programs illustrate the use of DateTime.Add(TimeSpan) Method:" }, { "code": null, "e": 24607, "s": 24596, "text": "Example 1:" }, { "code": "// C# program to demonstrate the// DateTime.Add(TimeSpan) Methodusing System;using System.Globalization; class GFG { // Main Method public static void Main() { try { // creating object of DateTime DateTime date1 = new DateTime(2010, 1, 1, 8, 0, 15); // creating object of TimeSpan TimeSpan duration = new TimeSpan(36, 0, 0, 0); // adding the TimeSpan of 36 days // using Add() method; DateTime date2 = date1.Add(duration); // Display the date1 System.Console.WriteLine(\"DateTime before \"+ \"operation: {0:y} {0:dd}\", date1); // Display the date2 System.Console.WriteLine(\"\\nDateTime after\"+ \" operation: {0:y} {0:dd}\", date2); } catch (ArgumentOutOfRangeException e) { Console.Write(\"Exception Thrown: \"); Console.Write(\"{0}\", e.GetType(), e.Message); } }}", "e": 25650, "s": 24607, "text": null }, { "code": null, "e": 25738, "s": 25650, "text": "DateTime before operation: 2010 January 01\n\nDateTime after operation: 2010 February 06\n" }, { "code": null, "e": 25781, "s": 25738, "text": "Example 2: For ArgumentOutOfRangeException" }, { "code": "// C# program to demonstrate the// DateTime.Add(TimeSpan) Methodusing System;using System.Globalization; class GFG { // Main Method public static void Main() { try { // creating object of DateTime // and initialize with MinValue DateTime date1 = DateTime.MinValue; // Display the date1 Console.WriteLine(\"DateTime before \"+ \"operation: {0:y} {0:dd}\", date1); // creating object of TimeSpan TimeSpan duration = new TimeSpan(-36, 0, 0, 0); // adding the TimeSpan of 36 days // using Add() method; DateTime date2 = date1.Add(duration); // Display the date2 Console.WriteLine(\"\\nDateTime after\"+ \" operation: {0:y} {0:dd}\", date2); } catch (ArgumentOutOfRangeException e) { Console.WriteLine(\"\\nThe resulting DateTime\"+ \" is less than the MinValue \"); Console.Write(\"Exception Thrown: \"); Console.Write(\"{0}\", e.GetType(), e.Message); } }}", "e": 26896, "s": 25781, "text": null }, { "code": null, "e": 27044, "s": 26896, "text": "DateTime before operation: 0001 January 01\n\nThe resulting DateTime is less than the MinValue \nException Thrown: System.ArgumentOutOfRangeException\n" }, { "code": null, "e": 27050, "s": 27044, "text": "Note:" }, { "code": null, "e": 27162, "s": 27050, "text": "The Add method takes into account leap years and the number of days in a month when performing date arithmetic." }, { "code": null, "e": 27298, "s": 27162, "text": "This method does not change the value of this DateTime. Instead, it returns a new DateTime whose value is the result of this operation." }, { "code": null, "e": 27309, "s": 27298, "text": "Reference:" }, { "code": null, "e": 27397, "s": 27309, "text": "https://docs.microsoft.com/en-us/dotnet/api/system.datetime.add?view=netframework-4.7.2" }, { "code": null, "e": 27420, "s": 27397, "text": "CSharp DateTime Struct" }, { "code": null, "e": 27434, "s": 27420, "text": "CSharp-method" }, { "code": null, "e": 27437, "s": 27434, "text": "C#" }, { "code": null, "e": 27535, "s": 27437, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27558, "s": 27535, "text": "C# | Method Overriding" }, { "code": null, "e": 27586, "s": 27558, "text": "C# Dictionary with examples" }, { "code": null, "e": 27604, "s": 27586, "text": "Destructors in C#" }, { "code": null, "e": 27650, "s": 27604, "text": "Difference between Ref and Out keywords in C#" }, { "code": null, "e": 27665, "s": 27650, "text": "C# | Delegates" }, { "code": null, "e": 27683, "s": 27665, "text": "C# | Constructors" }, { "code": null, "e": 27706, "s": 27683, "text": "Extension Method in C#" }, { "code": null, "e": 27746, "s": 27706, "text": "C# | String.IndexOf( ) Method | Set - 1" }, { "code": null, "e": 27768, "s": 27746, "text": "C# | Class and Object" } ]
A Simple Guide to Beautiful Visualizations in Python | by Frank Andrade | Towards Data Science
You’re in the middle of a project and suddenly you need to make a plot to analyze the data or present the insights found. You don’t have too much time, but you definitely don’t want to create a plot that looks like this. However you also don’t want to get too technical and waste more time on something that isn’t the main goal of your project, so what should you do? I can’t tell how many times that happened to me in the past, but by using Matplotlib & Seaborn conveniently, I came up with a simple, yet powerful way to create nice-looking and readable visualizations in Python. Forget those blue bar plots, histograms, boxplots, scatterplots, and pie charts with tiny labels, in this article I’ll show you how to give them a better appearance without getting too technical and wasting a lot of time. Table of Contents1. Globally Setting: Graph style and Font size2. Customization of Plots - Color Palettes - Figure size, figure appearance, title, and axes labels3. The Dataset4. Bar Plot5. Histogram6. Boxplot7. Scatterplot8. Piechart + Subplots - Single Piechart - Piechart side by side (subplots)9. Line Plot One of the things that gave me more headaches was setting font sizes in plots individually. That’s why it’s better to globally set them first before we start making plots. First, let’s import the necessary libraries we’ll use in this article. import matplotlib.pyplot as pltimport seaborn as snsimport pandas as pd Note: If you don’t have those libraries installed in Python, you can easily install them by writing pip install name_of_libraryon your terminal or command prompt for each library you wish to install (e.g. pip install matplotlib) Now we can easily globally set the graph style and font size with the following code. sns.set_style('darkgrid') # darkgrid, white grid, dark, white and ticksplt.rc('axes', titlesize=18) # fontsize of the axes titleplt.rc('axes', labelsize=14) # fontsize of the x and y labelsplt.rc('xtick', labelsize=13) # fontsize of the tick labelsplt.rc('ytick', labelsize=13) # fontsize of the tick labelsplt.rc('legend', fontsize=13) # legend fontsizeplt.rc('font', size=13) # controls default text sizes First, we use sns.set_style() to set the graph style. This will make Matplotlib and Seaborn graphs look better by default. Then we use plt.rc() to customize the font size of the text displayed in the plots. My personal choice is 18 for the title, 14 for the text in the axes, and 13 for the rest. Feel free to edit them as you want. That’s it! You only need to do this once to get adequate font sizes and a nice graph style. Matplotlib colors by default are ugly but we can easily make them prettier by using Seaborn palettes. These are some of the palettes Seaborn has and we’ll use in this article. sns.color_palette(‘deep’) sns.color_palette(‘pastel’) sns.color_palette(‘Set2’) These palettes have the form of a list, so instead of using the classical ‘b’ to obtain the blue color, you can extract the color from these palettes by doing sns.color_palette('deep')[0]. If you execute this code, you’ll obtain an RGB code like this (0.298, 0.447, 0.690), which is accepted in the color parameter in Matplotlib’s plots. We’ll check this better when creating the plots. In the seaborn documentation, you can find a list of palettes available. Choose the one you like to start making nice-looking graphs. When creating plots most of the time we’ll need to make some tweaks, so anyone would easily understand our visualizations. The following methods will be used repeatedly throughout the plots presented in this article, so let’s get used to them. How to adjust figure size? To adjust the figure size we use plt.figure(figsize). We’ll also use tight_layout=True to clean up the padding in a plot or between subplots. plt.figure(figsize=(8,4), tight_layout=True) How to edit the figure appearance? Some of the basic tweaks we’ll make to the plot are the color and the linewidth. They are included as extra parameters when plotting. # matplotlibplt.hist(..., color=sns.color_palette('Set2')[2], linewidth=2)# seabornax = sns.histplot(..., palette='Set2', linewidth=2) # seaborn will have either the color or palette parameters available (it depends on the plot) How to add subplots (side-by-side plots)? We’ll need plt.subplots() to make side-by-side plots. #subplotsfig, ax = plt.subplots(nrows=1,ncols=2, figsize=(12, 5), tight_layout=True) After creating subplots, we’ll use either one-dimensional ax[0] or two-dimensional axes ax[0][0] How to add label and title to the plot? Adding labels to axes and setting title names is similar between Matplotlib plt.xlabel() and Seaborn ax.set_xlabel(), but I prefer to use the ax.set() variant in Seaborn because it takes care of most parameters in one line. # matplotlibplt.xlabel('Nationality')plt.ylabel('Average Rating')plt.title('Barplot')#seabornax.set(title='Barplot', xlabel='Nationality', ylabel='Average Rating') To make meaningful graphs, we need to use a dataset. To make things simple, I chose a clean dataset available in Kaggle that you can also find on my Github. This is a Fifa players dataset that will help us compare non-traditional football nations like the USA and Canada with big football nations such as England, Brazil, and Argentina. Hopefully, at the end of this article, we’ll better understand what makes football different in those countries. For the following sections, we’ll work with a dataframe named df_country that will include only the countries in question. The code below will take care of that. df_fifa21 = pd.read_csv('players_20.csv')country = ['United States', 'Canada', 'England', 'Brazil', 'Argentina']df_country = df_fifa21[df_fifa21[‘nationality’].isin(country)] Now let’s create nice-looking visualizations! Bar plots can be easily created with both MatplotLib and Seaborn with some slight differences. A barplot will display categorical data with rectangular bars with heights or lengths proportional to the values that they represent. It’ll be interesting to see the average rating of football player by nationality The code below shows the extra preprocessing necessary only for this plot. # Preprocessingbarplot = df_country.groupby(['nationality'], as_index=False).mean()[['nationality', 'overall']] The output looks like this: nationality overall Argentina 69.118510Brazil 71.143894 Canada 62.855072 England 63.253293 United States 64.538682 MatplotLib’s plt.bar() needs two arguments — the name of the categorical variable (nationality) and their lengths (overall ratings). plt.figure(figsize=(8,4), tight_layout=True)colors = sns.color_palette('pastel')plt.bar(barplot['nationality'], barplot['overall'], color=colors[:5])plt.xlabel('Nationality')plt.ylabel('Average Rating')plt.title('Barplot')plt.show() As we mentioned before, to make bar plots more appealing we’ll use Seaborn color palette. In this case, we used thepastel palette. Apparently, there’s no big difference between the rating of an average player from Canada, the USA, and England. However, average players don’t make it to the national teams, but only the top players in each country do it, so if we get the average rating of the top 20 players, the plot would change. Let’s check this with seaborn. To get the top 20 players of each country we need to do some preprocessing # preprocessingnew_df = pd.concat([df_country[df_country['nationality']=='Argentina'][:20], df_country[df_country['nationality']=='Brazil'][:20], df_country[df_country['nationality']=='England'][:20], df_country[df_country['nationality']=='Canada'][:20], df_country[df_country['nationality']=='United States'][:20]])barplot = new_df.groupby(['nationality'], as_index=False).mean()[['nationality', 'overall']] Now the data is ready to be plotted. We’ll use sns.barplot() to do so. plt.figure(figsize=(8,4), tight_layout=True)ax = sns.barplot(x=barplot['nationality'], y=barplot['overall'], palette='pastel', ci=None)ax.set(title='Barplot', xlabel='Nationality', ylabel='Average Rating')plt.show() The difference in ratings between top players is evident. This reveals why the USA and Canada aren’t big football nations yet, but that’s not everything let’s dig deeper. Now let’s see how many players play in the top football leagues. To do so, we need to group the data by nationality and league (we’ll leave out the Premier League since most England players play in this competition) # Preprocessingbarplot = df_country[df_country['league_name'].isin(['Spain Primera Division', 'Italian Serie A', 'German 1. Bundesliga'])]barplot = barplot.groupby(['nationality', 'league_name'], as_index=False).count() Now that the data is ready, we could plot it with Matplolib or Seaborn; however, to keep things simple and avoid writing more lines of code we’ll use Seaborn. Data grouped by “n” variables can be easily plotted by adding the hue=‘’ parameter. plt.figure(figsize=(12, 6), tight_layout=True)ax = sns.barplot(x=barplot['nationality'], y=barplot['sofifa_id'], hue=barplot['league_name'], palette='pastel')ax.set(title='No of Players outside of domestic league' ,xlabel='Country', ylabel='Count')ax.legend(title='League', title_fontsize='13', loc='upper right')plt.show() We took care of the legend options individually with ax.legend() and obtained the following plot. As we can see, most Argentine and Brazilian footballers play in the top leagues while Canadians and Americans don’t. Players in top leagues make an impact on the national team's success in competitions, so this explains why Brazil and Argentina are big football nations. A histogram represents the distribution of numerical data. Let’s look at the height distribution of football players and analyze its relevance in this sport. MatplotLib’s plt.hist() and Seaborn’s sns.histplot()work the same. Both need two arguments — the name of the numerical variable (height) and the number or list of bins. In this case, we made a list of bins called bins that will be displayed on the x-axis. plt.figure(figsize=(10,6), tight_layout=True)bins = [160, 165, 170, 175, 180, 185, 190, 195, 200]# matplotlibplt.hist(df_country['height_cm'], bins=bins, color=sns.color_palette('Set2')[2], linewidth=2)plt.title('Histogram')plt.xlabel('Height (cm)')plt.ylabel('Count')# seabornax = sns.histplot(data=df_country, x='height_cm', bins=bins, color=sns.color_palette('Set2')[2], linewidth=2)ax.set(title='Histogram', xlabel='Height (cm)', ylabel='Count')plt.show() The histogram reveals that most players’ height is between 175-185 cm, so it seems that being taller than 185cm isn’t so important in football. Let’s check the distribution of height in players from different nations with boxplots. Boxplots display the distribution of data based on the minimum value, first quartile (Q1), median, third quartile (Q3), and maximum value. In this case, we’ll make a boxplot showing the height distribution in players from the 5 countries. Boxplots of multiple categorical variables can be plotted on Matplotlib but it needs some extra preprocessing, so to keep things simple we’ll use Seaborn’s sns.boxplot(). When making boxplots with multiple categorical variables we need two arguments — the name of the categorical variable (nationality) and the name of the numerical variable (height_cm) plt.figure(figsize=(10,6), tight_layout=True)ax = sns.boxplot(data=df_country, x='nationality', y='height_cm', palette='Set2', linewidth=2.5)ax.set(title='Boxplot', xlabel='', ylabel='Height (cm)')plt.show() Now the boxplot reveals that a national team doesn’t need many tall football players to succeed in competitions since the median of Argentina and Brazil is lower than in the rest of the countries. Argentina even presents the shortest football players among the five countries represented by the long bottom whisker. A scatter plot displays and shows the relation between two numerical variables in a dataset. In this case, we’ll see the relationship between the height and weight of players. plt.figure(figsize=(10,6), tight_layout=True)ax = sns.scatterplot(data=df_country, x='height_cm', y='weight_kg', hue='nationality', palette='Set2', s=60)ax.set(xlabel='Height (cm)', ylabel='Weight (kg)')ax.legend(title='Country', title_fontsize = 12) plt.show() In this plot, we added the sto control the dot size and also hue to differentiate the nationality From this scatterplot, we can see that weight and height distribution fit a simple linear regression. We’re going to make a piechart that displays the value of players. In this example, we’ll pick the most valuable player in the USMNT (Pullisic) and see how valuable he is in his club. # Preprocessingpiechart = df_fifa21[df_fifa21['club_name']=='Chelsea']piechart = piechart.sort_values('value_eur', ascending=False)[['short_name', 'value_eur']]piechart = piechart[:11] Now that the data is ready we can make a piechart with Matplolib’s plt.pie() Apart from the parameters we usually add, we’ll also consider autopct to round the numbers, explode to highlight a specific player, pctdistance to adjust the distance of the labels and shadow=True to give the chart a solid appearance. colors = sns.color_palette('pastel')plt.figure(figsize=(7, 6), tight_layout=True)explode_list = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.2]plt.pie(piechart['value_eur'], labels=piechart['short_name'], autopct='%.0f %%', explode=explode_list, pctdistance=.7, colors=colors, shadow=True)plt.title('Chelsea', weight='bold')plt.show() The piechart shows that Pullisic isn’t the most valuable player in his club, but at least he’s in the top 11. Now let’s plot 2 piecharts side by side to see the impact of this player on his club and national team. To do so, we’ll use plt.subplots(nrows, ncols). Here the rows and the columns determine the number of plots we’re going to create so nrow=1 and ncols=2 means 1 plot per column (2 in total). #subplotsfig, ax = plt.subplots(1,2, figsize=(12, 5), tight_layout=True) Also, we need to create a second piechart frame piechart2, apart from the piechart we created before. # Preprocessingpiechart2 = df_fifa21[df_fifa21['nationality']=='United States']piechart2 = piechart2[:10].sort_values('value_eur')[['short_name', 'value_eur']] Now we can plot the 2 piecharts side by side. Now we can verify that Pullisic is by far the most valuable American player, but in his club, there are other skillful players ahead. We’ll plot the ratings of the top football players to see how the rating evolved over the past 5 years. To do so, we have to read the Fifa dataset from 2017 and wrangle the data. The code above gives a dataset ready to be plotted. Making a line plot it’s as easy as typing plt.plot() on Matplotlib, but we’ll do some simple customization to make it look better. plt.figure(figsize=(10,6), tight_layout=True)#plottingplt.plot(lineplot, 'o-', linewidth=2)#customizationplt.xticks([2017, 2018, 2019, 2020, 2021])plt.xlabel('Years')plt.ylabel('Ratings')plt.title('Rating troughtout the years')plt.legend(title='Players', title_fontsize = 13, labels=['L. Messi', 'Cristiano Ronaldo', 'K. De Bruyne', 'V. van Dijk', 'K. Mbappé'])plt.show() With the code above, we generate the following graph. We can also easily make this plot with seaborn. plt.figure(figsize=(10, 5))ax = sns.lineplot(data=lineplot, linewidth=2.5)ax.set(xlabel='Year', ylabel='Ratings', title='Rating troughtout the years', xticks=[2017, 2018, 2019, 2020, 2021])ax.legend(title='Players', title_fontsize = 13)plt.show() After running this code, we should obtain a plot similar to the one above. That’s it! In this article, we learned how to make beautiful plots with Matplotlib and Seaborn. All the code is available on my Github. Thanks for reading this article! In the articles below, I show the code to make heatplots, wordclouds, and also how to make interactive visualization without coding at all. towardsdatascience.com towardsdatascience.com towardsdatascience.com Join my email list with 3k+ people to get my Python for Data Science Cheat Sheet I use in all my tutorials (Free PDF)
[ { "code": null, "e": 392, "s": 171, "text": "You’re in the middle of a project and suddenly you need to make a plot to analyze the data or present the insights found. You don’t have too much time, but you definitely don’t want to create a plot that looks like this." }, { "code": null, "e": 539, "s": 392, "text": "However you also don’t want to get too technical and waste more time on something that isn’t the main goal of your project, so what should you do?" }, { "code": null, "e": 974, "s": 539, "text": "I can’t tell how many times that happened to me in the past, but by using Matplotlib & Seaborn conveniently, I came up with a simple, yet powerful way to create nice-looking and readable visualizations in Python. Forget those blue bar plots, histograms, boxplots, scatterplots, and pie charts with tiny labels, in this article I’ll show you how to give them a better appearance without getting too technical and wasting a lot of time." }, { "code": null, "e": 1285, "s": 974, "text": "Table of Contents1. Globally Setting: Graph style and Font size2. Customization of Plots - Color Palettes - Figure size, figure appearance, title, and axes labels3. The Dataset4. Bar Plot5. Histogram6. Boxplot7. Scatterplot8. Piechart + Subplots - Single Piechart - Piechart side by side (subplots)9. Line Plot" }, { "code": null, "e": 1528, "s": 1285, "text": "One of the things that gave me more headaches was setting font sizes in plots individually. That’s why it’s better to globally set them first before we start making plots. First, let’s import the necessary libraries we’ll use in this article." }, { "code": null, "e": 1600, "s": 1528, "text": "import matplotlib.pyplot as pltimport seaborn as snsimport pandas as pd" }, { "code": null, "e": 1829, "s": 1600, "text": "Note: If you don’t have those libraries installed in Python, you can easily install them by writing pip install name_of_libraryon your terminal or command prompt for each library you wish to install (e.g. pip install matplotlib)" }, { "code": null, "e": 1915, "s": 1829, "text": "Now we can easily globally set the graph style and font size with the following code." }, { "code": null, "e": 2348, "s": 1915, "text": "sns.set_style('darkgrid') # darkgrid, white grid, dark, white and ticksplt.rc('axes', titlesize=18) # fontsize of the axes titleplt.rc('axes', labelsize=14) # fontsize of the x and y labelsplt.rc('xtick', labelsize=13) # fontsize of the tick labelsplt.rc('ytick', labelsize=13) # fontsize of the tick labelsplt.rc('legend', fontsize=13) # legend fontsizeplt.rc('font', size=13) # controls default text sizes" }, { "code": null, "e": 2681, "s": 2348, "text": "First, we use sns.set_style() to set the graph style. This will make Matplotlib and Seaborn graphs look better by default. Then we use plt.rc() to customize the font size of the text displayed in the plots. My personal choice is 18 for the title, 14 for the text in the axes, and 13 for the rest. Feel free to edit them as you want." }, { "code": null, "e": 2773, "s": 2681, "text": "That’s it! You only need to do this once to get adequate font sizes and a nice graph style." }, { "code": null, "e": 2949, "s": 2773, "text": "Matplotlib colors by default are ugly but we can easily make them prettier by using Seaborn palettes. These are some of the palettes Seaborn has and we’ll use in this article." }, { "code": null, "e": 2975, "s": 2949, "text": "sns.color_palette(‘deep’)" }, { "code": null, "e": 3003, "s": 2975, "text": "sns.color_palette(‘pastel’)" }, { "code": null, "e": 3029, "s": 3003, "text": "sns.color_palette(‘Set2’)" }, { "code": null, "e": 3416, "s": 3029, "text": "These palettes have the form of a list, so instead of using the classical ‘b’ to obtain the blue color, you can extract the color from these palettes by doing sns.color_palette('deep')[0]. If you execute this code, you’ll obtain an RGB code like this (0.298, 0.447, 0.690), which is accepted in the color parameter in Matplotlib’s plots. We’ll check this better when creating the plots." }, { "code": null, "e": 3550, "s": 3416, "text": "In the seaborn documentation, you can find a list of palettes available. Choose the one you like to start making nice-looking graphs." }, { "code": null, "e": 3794, "s": 3550, "text": "When creating plots most of the time we’ll need to make some tweaks, so anyone would easily understand our visualizations. The following methods will be used repeatedly throughout the plots presented in this article, so let’s get used to them." }, { "code": null, "e": 3963, "s": 3794, "text": "How to adjust figure size? To adjust the figure size we use plt.figure(figsize). We’ll also use tight_layout=True to clean up the padding in a plot or between subplots." }, { "code": null, "e": 4008, "s": 3963, "text": "plt.figure(figsize=(8,4), tight_layout=True)" }, { "code": null, "e": 4177, "s": 4008, "text": "How to edit the figure appearance? Some of the basic tweaks we’ll make to the plot are the color and the linewidth. They are included as extra parameters when plotting." }, { "code": null, "e": 4406, "s": 4177, "text": "# matplotlibplt.hist(..., color=sns.color_palette('Set2')[2], linewidth=2)# seabornax = sns.histplot(..., palette='Set2', linewidth=2) # seaborn will have either the color or palette parameters available (it depends on the plot)" }, { "code": null, "e": 4502, "s": 4406, "text": "How to add subplots (side-by-side plots)? We’ll need plt.subplots() to make side-by-side plots." }, { "code": null, "e": 4587, "s": 4502, "text": "#subplotsfig, ax = plt.subplots(nrows=1,ncols=2, figsize=(12, 5), tight_layout=True)" }, { "code": null, "e": 4684, "s": 4587, "text": "After creating subplots, we’ll use either one-dimensional ax[0] or two-dimensional axes ax[0][0]" }, { "code": null, "e": 4948, "s": 4684, "text": "How to add label and title to the plot? Adding labels to axes and setting title names is similar between Matplotlib plt.xlabel() and Seaborn ax.set_xlabel(), but I prefer to use the ax.set() variant in Seaborn because it takes care of most parameters in one line." }, { "code": null, "e": 5112, "s": 4948, "text": "# matplotlibplt.xlabel('Nationality')plt.ylabel('Average Rating')plt.title('Barplot')#seabornax.set(title='Barplot', xlabel='Nationality', ylabel='Average Rating')" }, { "code": null, "e": 5562, "s": 5112, "text": "To make meaningful graphs, we need to use a dataset. To make things simple, I chose a clean dataset available in Kaggle that you can also find on my Github. This is a Fifa players dataset that will help us compare non-traditional football nations like the USA and Canada with big football nations such as England, Brazil, and Argentina. Hopefully, at the end of this article, we’ll better understand what makes football different in those countries." }, { "code": null, "e": 5724, "s": 5562, "text": "For the following sections, we’ll work with a dataframe named df_country that will include only the countries in question. The code below will take care of that." }, { "code": null, "e": 5899, "s": 5724, "text": "df_fifa21 = pd.read_csv('players_20.csv')country = ['United States', 'Canada', 'England', 'Brazil', 'Argentina']df_country = df_fifa21[df_fifa21[‘nationality’].isin(country)]" }, { "code": null, "e": 5945, "s": 5899, "text": "Now let’s create nice-looking visualizations!" }, { "code": null, "e": 6255, "s": 5945, "text": "Bar plots can be easily created with both MatplotLib and Seaborn with some slight differences. A barplot will display categorical data with rectangular bars with heights or lengths proportional to the values that they represent. It’ll be interesting to see the average rating of football player by nationality" }, { "code": null, "e": 6330, "s": 6255, "text": "The code below shows the extra preprocessing necessary only for this plot." }, { "code": null, "e": 6442, "s": 6330, "text": "# Preprocessingbarplot = df_country.groupby(['nationality'], as_index=False).mean()[['nationality', 'overall']]" }, { "code": null, "e": 6470, "s": 6442, "text": "The output looks like this:" }, { "code": null, "e": 6627, "s": 6470, "text": "nationality overall Argentina 69.118510Brazil 71.143894 Canada 62.855072 England 63.253293 United States 64.538682" }, { "code": null, "e": 6760, "s": 6627, "text": "MatplotLib’s plt.bar() needs two arguments — the name of the categorical variable (nationality) and their lengths (overall ratings)." }, { "code": null, "e": 6993, "s": 6760, "text": "plt.figure(figsize=(8,4), tight_layout=True)colors = sns.color_palette('pastel')plt.bar(barplot['nationality'], barplot['overall'], color=colors[:5])plt.xlabel('Nationality')plt.ylabel('Average Rating')plt.title('Barplot')plt.show()" }, { "code": null, "e": 7124, "s": 6993, "text": "As we mentioned before, to make bar plots more appealing we’ll use Seaborn color palette. In this case, we used thepastel palette." }, { "code": null, "e": 7456, "s": 7124, "text": "Apparently, there’s no big difference between the rating of an average player from Canada, the USA, and England. However, average players don’t make it to the national teams, but only the top players in each country do it, so if we get the average rating of the top 20 players, the plot would change. Let’s check this with seaborn." }, { "code": null, "e": 7531, "s": 7456, "text": "To get the top 20 players of each country we need to do some preprocessing" }, { "code": null, "e": 7944, "s": 7531, "text": "# preprocessingnew_df = pd.concat([df_country[df_country['nationality']=='Argentina'][:20], df_country[df_country['nationality']=='Brazil'][:20], df_country[df_country['nationality']=='England'][:20], df_country[df_country['nationality']=='Canada'][:20], df_country[df_country['nationality']=='United States'][:20]])barplot = new_df.groupby(['nationality'], as_index=False).mean()[['nationality', 'overall']]" }, { "code": null, "e": 8015, "s": 7944, "text": "Now the data is ready to be plotted. We’ll use sns.barplot() to do so." }, { "code": null, "e": 8231, "s": 8015, "text": "plt.figure(figsize=(8,4), tight_layout=True)ax = sns.barplot(x=barplot['nationality'], y=barplot['overall'], palette='pastel', ci=None)ax.set(title='Barplot', xlabel='Nationality', ylabel='Average Rating')plt.show()" }, { "code": null, "e": 8402, "s": 8231, "text": "The difference in ratings between top players is evident. This reveals why the USA and Canada aren’t big football nations yet, but that’s not everything let’s dig deeper." }, { "code": null, "e": 8618, "s": 8402, "text": "Now let’s see how many players play in the top football leagues. To do so, we need to group the data by nationality and league (we’ll leave out the Premier League since most England players play in this competition)" }, { "code": null, "e": 8838, "s": 8618, "text": "# Preprocessingbarplot = df_country[df_country['league_name'].isin(['Spain Primera Division', 'Italian Serie A', 'German 1. Bundesliga'])]barplot = barplot.groupby(['nationality', 'league_name'], as_index=False).count()" }, { "code": null, "e": 9081, "s": 8838, "text": "Now that the data is ready, we could plot it with Matplolib or Seaborn; however, to keep things simple and avoid writing more lines of code we’ll use Seaborn. Data grouped by “n” variables can be easily plotted by adding the hue=‘’ parameter." }, { "code": null, "e": 9405, "s": 9081, "text": "plt.figure(figsize=(12, 6), tight_layout=True)ax = sns.barplot(x=barplot['nationality'], y=barplot['sofifa_id'], hue=barplot['league_name'], palette='pastel')ax.set(title='No of Players outside of domestic league' ,xlabel='Country', ylabel='Count')ax.legend(title='League', title_fontsize='13', loc='upper right')plt.show()" }, { "code": null, "e": 9503, "s": 9405, "text": "We took care of the legend options individually with ax.legend() and obtained the following plot." }, { "code": null, "e": 9774, "s": 9503, "text": "As we can see, most Argentine and Brazilian footballers play in the top leagues while Canadians and Americans don’t. Players in top leagues make an impact on the national team's success in competitions, so this explains why Brazil and Argentina are big football nations." }, { "code": null, "e": 9932, "s": 9774, "text": "A histogram represents the distribution of numerical data. Let’s look at the height distribution of football players and analyze its relevance in this sport." }, { "code": null, "e": 10188, "s": 9932, "text": "MatplotLib’s plt.hist() and Seaborn’s sns.histplot()work the same. Both need two arguments — the name of the numerical variable (height) and the number or list of bins. In this case, we made a list of bins called bins that will be displayed on the x-axis." }, { "code": null, "e": 10648, "s": 10188, "text": "plt.figure(figsize=(10,6), tight_layout=True)bins = [160, 165, 170, 175, 180, 185, 190, 195, 200]# matplotlibplt.hist(df_country['height_cm'], bins=bins, color=sns.color_palette('Set2')[2], linewidth=2)plt.title('Histogram')plt.xlabel('Height (cm)')plt.ylabel('Count')# seabornax = sns.histplot(data=df_country, x='height_cm', bins=bins, color=sns.color_palette('Set2')[2], linewidth=2)ax.set(title='Histogram', xlabel='Height (cm)', ylabel='Count')plt.show()" }, { "code": null, "e": 10880, "s": 10648, "text": "The histogram reveals that most players’ height is between 175-185 cm, so it seems that being taller than 185cm isn’t so important in football. Let’s check the distribution of height in players from different nations with boxplots." }, { "code": null, "e": 11119, "s": 10880, "text": "Boxplots display the distribution of data based on the minimum value, first quartile (Q1), median, third quartile (Q3), and maximum value. In this case, we’ll make a boxplot showing the height distribution in players from the 5 countries." }, { "code": null, "e": 11473, "s": 11119, "text": "Boxplots of multiple categorical variables can be plotted on Matplotlib but it needs some extra preprocessing, so to keep things simple we’ll use Seaborn’s sns.boxplot(). When making boxplots with multiple categorical variables we need two arguments — the name of the categorical variable (nationality) and the name of the numerical variable (height_cm)" }, { "code": null, "e": 11681, "s": 11473, "text": "plt.figure(figsize=(10,6), tight_layout=True)ax = sns.boxplot(data=df_country, x='nationality', y='height_cm', palette='Set2', linewidth=2.5)ax.set(title='Boxplot', xlabel='', ylabel='Height (cm)')plt.show()" }, { "code": null, "e": 11997, "s": 11681, "text": "Now the boxplot reveals that a national team doesn’t need many tall football players to succeed in competitions since the median of Argentina and Brazil is lower than in the rest of the countries. Argentina even presents the shortest football players among the five countries represented by the long bottom whisker." }, { "code": null, "e": 12173, "s": 11997, "text": "A scatter plot displays and shows the relation between two numerical variables in a dataset. In this case, we’ll see the relationship between the height and weight of players." }, { "code": null, "e": 12437, "s": 12173, "text": "plt.figure(figsize=(10,6), tight_layout=True)ax = sns.scatterplot(data=df_country, x='height_cm', y='weight_kg', hue='nationality', palette='Set2', s=60)ax.set(xlabel='Height (cm)', ylabel='Weight (kg)')ax.legend(title='Country', title_fontsize = 12) plt.show()" }, { "code": null, "e": 12535, "s": 12437, "text": "In this plot, we added the sto control the dot size and also hue to differentiate the nationality" }, { "code": null, "e": 12637, "s": 12535, "text": "From this scatterplot, we can see that weight and height distribution fit a simple linear regression." }, { "code": null, "e": 12821, "s": 12637, "text": "We’re going to make a piechart that displays the value of players. In this example, we’ll pick the most valuable player in the USMNT (Pullisic) and see how valuable he is in his club." }, { "code": null, "e": 13006, "s": 12821, "text": "# Preprocessingpiechart = df_fifa21[df_fifa21['club_name']=='Chelsea']piechart = piechart.sort_values('value_eur', ascending=False)[['short_name', 'value_eur']]piechart = piechart[:11]" }, { "code": null, "e": 13318, "s": 13006, "text": "Now that the data is ready we can make a piechart with Matplolib’s plt.pie() Apart from the parameters we usually add, we’ll also consider autopct to round the numbers, explode to highlight a specific player, pctdistance to adjust the distance of the labels and shadow=True to give the chart a solid appearance." }, { "code": null, "e": 13650, "s": 13318, "text": "colors = sns.color_palette('pastel')plt.figure(figsize=(7, 6), tight_layout=True)explode_list = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.2]plt.pie(piechart['value_eur'], labels=piechart['short_name'], autopct='%.0f %%', explode=explode_list, pctdistance=.7, colors=colors, shadow=True)plt.title('Chelsea', weight='bold')plt.show()" }, { "code": null, "e": 13760, "s": 13650, "text": "The piechart shows that Pullisic isn’t the most valuable player in his club, but at least he’s in the top 11." }, { "code": null, "e": 14054, "s": 13760, "text": "Now let’s plot 2 piecharts side by side to see the impact of this player on his club and national team. To do so, we’ll use plt.subplots(nrows, ncols). Here the rows and the columns determine the number of plots we’re going to create so nrow=1 and ncols=2 means 1 plot per column (2 in total)." }, { "code": null, "e": 14127, "s": 14054, "text": "#subplotsfig, ax = plt.subplots(1,2, figsize=(12, 5), tight_layout=True)" }, { "code": null, "e": 14229, "s": 14127, "text": "Also, we need to create a second piechart frame piechart2, apart from the piechart we created before." }, { "code": null, "e": 14389, "s": 14229, "text": "# Preprocessingpiechart2 = df_fifa21[df_fifa21['nationality']=='United States']piechart2 = piechart2[:10].sort_values('value_eur')[['short_name', 'value_eur']]" }, { "code": null, "e": 14435, "s": 14389, "text": "Now we can plot the 2 piecharts side by side." }, { "code": null, "e": 14569, "s": 14435, "text": "Now we can verify that Pullisic is by far the most valuable American player, but in his club, there are other skillful players ahead." }, { "code": null, "e": 14748, "s": 14569, "text": "We’ll plot the ratings of the top football players to see how the rating evolved over the past 5 years. To do so, we have to read the Fifa dataset from 2017 and wrangle the data." }, { "code": null, "e": 14800, "s": 14748, "text": "The code above gives a dataset ready to be plotted." }, { "code": null, "e": 14931, "s": 14800, "text": "Making a line plot it’s as easy as typing plt.plot() on Matplotlib, but we’ll do some simple customization to make it look better." }, { "code": null, "e": 15304, "s": 14931, "text": "plt.figure(figsize=(10,6), tight_layout=True)#plottingplt.plot(lineplot, 'o-', linewidth=2)#customizationplt.xticks([2017, 2018, 2019, 2020, 2021])plt.xlabel('Years')plt.ylabel('Ratings')plt.title('Rating troughtout the years')plt.legend(title='Players', title_fontsize = 13, labels=['L. Messi', 'Cristiano Ronaldo', 'K. De Bruyne', 'V. van Dijk', 'K. Mbappé'])plt.show()" }, { "code": null, "e": 15358, "s": 15304, "text": "With the code above, we generate the following graph." }, { "code": null, "e": 15406, "s": 15358, "text": "We can also easily make this plot with seaborn." }, { "code": null, "e": 15653, "s": 15406, "text": "plt.figure(figsize=(10, 5))ax = sns.lineplot(data=lineplot, linewidth=2.5)ax.set(xlabel='Year', ylabel='Ratings', title='Rating troughtout the years', xticks=[2017, 2018, 2019, 2020, 2021])ax.legend(title='Players', title_fontsize = 13)plt.show()" }, { "code": null, "e": 15728, "s": 15653, "text": "After running this code, we should obtain a plot similar to the one above." }, { "code": null, "e": 15864, "s": 15728, "text": "That’s it! In this article, we learned how to make beautiful plots with Matplotlib and Seaborn. All the code is available on my Github." }, { "code": null, "e": 16037, "s": 15864, "text": "Thanks for reading this article! In the articles below, I show the code to make heatplots, wordclouds, and also how to make interactive visualization without coding at all." }, { "code": null, "e": 16060, "s": 16037, "text": "towardsdatascience.com" }, { "code": null, "e": 16083, "s": 16060, "text": "towardsdatascience.com" }, { "code": null, "e": 16106, "s": 16083, "text": "towardsdatascience.com" } ]
SAP Scripts - Print Preview of a Document
In SAP Script, it is also possible to preview a document before printing. To perform Print Preview of the document, go to Text → Print Preview. We have opened a document with the following text − Signed Enclosures Prepared Approved Confirmed Receipts Expenditures &uline(130)& &rfcash-anzsb(Z)& &Rfcash-anzhb(Z)& When you go to Text → Print Preview, it will show you the printing format of the document. You can select various Print Preview options. You can select a particular page for Print Preview or printing. When Print Preview is selected from the option, you can see a preview of the existing document as seen in the following screenshot. 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": 2667, "s": 2523, "text": "In SAP Script, it is also possible to preview a document before printing. To perform Print Preview of the document, go to Text → Print Preview." }, { "code": null, "e": 2719, "s": 2667, "text": "We have opened a document with the following text −" }, { "code": null, "e": 2942, "s": 2719, "text": " Signed \nEnclosures \nPrepared Approved Confirmed \nReceipts Expenditures \n&uline(130)& \n\n&rfcash-anzsb(Z)& &Rfcash-anzhb(Z)& \n" }, { "code": null, "e": 3079, "s": 2942, "text": "When you go to Text → Print Preview, it will show you the printing format of the document. You can select various Print Preview options." }, { "code": null, "e": 3275, "s": 3079, "text": "You can select a particular page for Print Preview or printing. When Print Preview is selected from the option, you can see a preview of the existing document as seen in the following screenshot." }, { "code": null, "e": 3308, "s": 3275, "text": "\n 25 Lectures \n 6 hours \n" }, { "code": null, "e": 3322, "s": 3308, "text": " Sanjo Thomas" }, { "code": null, "e": 3355, "s": 3322, "text": "\n 26 Lectures \n 2 hours \n" }, { "code": null, "e": 3367, "s": 3355, "text": " Neha Gupta" }, { "code": null, "e": 3402, "s": 3367, "text": "\n 30 Lectures \n 2.5 hours \n" }, { "code": null, "e": 3417, "s": 3402, "text": " Sumit Agarwal" }, { "code": null, "e": 3450, "s": 3417, "text": "\n 30 Lectures \n 4 hours \n" }, { "code": null, "e": 3465, "s": 3450, "text": " Sumit Agarwal" }, { "code": null, "e": 3500, "s": 3465, "text": "\n 14 Lectures \n 1.5 hours \n" }, { "code": null, "e": 3512, "s": 3500, "text": " Neha Malik" }, { "code": null, "e": 3547, "s": 3512, "text": "\n 13 Lectures \n 1.5 hours \n" }, { "code": null, "e": 3559, "s": 3547, "text": " Neha Malik" }, { "code": null, "e": 3566, "s": 3559, "text": " Print" }, { "code": null, "e": 3577, "s": 3566, "text": " Add Notes" } ]
Write a function to delete a Linked List in C++ Programming
Here, we will create a function that will delete all elements of a linked list one by one. In c/c++, there is no specific function to perform this task but in java, the automatic garbage collection is done to ease deleting linked list. Now, let’s see the implementation of this program, Live Demo #include <iostream> using namespace std; class Node{ public: int data; Node* next; }; void deleteLinkedList(Node** head_ref){ Node* current = *head_ref; Node* next; while (current != NULL){ cout<<current->data<<"\t"; next = current->next; free(current); current = next; } *head_ref = NULL; } void push(Node** head_ref, int new_data){ Node* new_node = new Node(); new_node->data = new_data; new_node->next = (*head_ref); (*head_ref) = new_node; } int main(){ Node* head = NULL; push(&head, 25); push(&head, 10); push(&head, 5); push(&head, 90); push(&head, 68); cout<<"Elements of linked list : "; deleteLinkedList(&head); cout << "\nLinked list deleted"; } Elements of linked list : 68 90 5 10 25 Linked list deleted
[ { "code": null, "e": 1153, "s": 1062, "text": "Here, we will create a function that will delete all elements of a linked list one by one." }, { "code": null, "e": 1298, "s": 1153, "text": "In c/c++, there is no specific function to perform this task but in java, the automatic garbage collection is done to ease deleting linked list." }, { "code": null, "e": 1349, "s": 1298, "text": "Now, let’s see the implementation of this program," }, { "code": null, "e": 1360, "s": 1349, "text": " Live Demo" }, { "code": null, "e": 2104, "s": 1360, "text": "#include <iostream>\nusing namespace std;\nclass Node{\n public:\n int data;\n Node* next;\n};\nvoid deleteLinkedList(Node** head_ref){\n Node* current = *head_ref;\n Node* next;\n while (current != NULL){\n cout<<current->data<<\"\\t\";\n next = current->next;\n free(current);\n current = next;\n }\n *head_ref = NULL;\n}\nvoid push(Node** head_ref, int new_data){\n Node* new_node = new Node();\n new_node->data = new_data;\n new_node->next = (*head_ref);\n (*head_ref) = new_node;\n}\nint main(){\n Node* head = NULL;\n push(&head, 25);\n push(&head, 10);\n push(&head, 5);\n push(&head, 90);\n push(&head, 68);\n cout<<\"Elements of linked list : \";\n deleteLinkedList(&head);\n cout << \"\\nLinked list deleted\";\n}" }, { "code": null, "e": 2164, "s": 2104, "text": "Elements of linked list : 68 90 5 10 25\nLinked list deleted" } ]
PHP Autoloading Classes
In order to use class defined in another PHP script, we can incorporate it with include or require statements. However, PHP's autoloading feature doesn't need such explicit inclusion. Instead, when a class is used (for declaring its object etc.) PHP parser loads it automatically, if it is registered with spl_autoload_register() function. Any number of classes can thus be registered. This way PHP parser gets a laast chance to load class/interface before emitting error. spl_autoload_register(function ($class_name) { include $class_name . '.php'; }); The class will be loaded from its corresponding .php file when it comes in use for first time This example shows how a Class is registered for autoloading <?php spl_autoload_register(function ($class_name) { include $class_name . '.php'; }); $obj = new test1(); $obj2 = new test2(); echo "objects of test1 and test2 class created successfully"; ?> This will produce following result. − objects of test1 and test2 class created successfully However, if corresponding .php file having clas definition is not found, following error will be displayed. Warning: include(): Failed opening 'test10.php' for inclusion (include_path='C:\xampp\php\PEAR') in line 4 PHP Fatal error: Uncaught Error: Class 'test10' not found Live Demo <?php spl_autoload_register(function($className) { $file = $className . '.php'; if (file_exists($file)) { echo "$file included\n"; include $file; } else { throw new Exception("Unable to load $className."); } }); try { $obj1 = new test1(); $obj2 = new test10(); } catch (Exception $e) { echo $e->getMessage(), "\n"; } ?> This will produce following result. − Unable to load test1.
[ { "code": null, "e": 1535, "s": 1062, "text": "In order to use class defined in another PHP script, we can incorporate it with include or require statements. However, PHP's autoloading feature doesn't need such explicit inclusion. Instead, when a class is used (for declaring its object etc.) PHP parser loads it automatically, if it is registered with spl_autoload_register() function. Any number of classes can thus be registered. This way PHP parser gets a laast chance to load class/interface before emitting error." }, { "code": null, "e": 1619, "s": 1535, "text": "spl_autoload_register(function ($class_name) {\n include $class_name . '.php';\n});" }, { "code": null, "e": 1713, "s": 1619, "text": "The class will be loaded from its corresponding .php file when it comes in use for first time" }, { "code": null, "e": 1774, "s": 1713, "text": "This example shows how a Class is registered for autoloading" }, { "code": null, "e": 1970, "s": 1774, "text": "<?php\nspl_autoload_register(function ($class_name) {\n include $class_name . '.php';\n});\n$obj = new test1();\n$obj2 = new test2();\necho \"objects of test1 and test2 class created successfully\";\n?>" }, { "code": null, "e": 2008, "s": 1970, "text": "This will produce following result. −" }, { "code": null, "e": 2062, "s": 2008, "text": "objects of test1 and test2 class created successfully" }, { "code": null, "e": 2170, "s": 2062, "text": "However, if corresponding .php file having clas definition is not found, following error will be displayed." }, { "code": null, "e": 2335, "s": 2170, "text": "Warning: include(): Failed opening 'test10.php' for inclusion (include_path='C:\\xampp\\php\\PEAR') in line 4\nPHP Fatal error: Uncaught Error: Class 'test10' not found" }, { "code": null, "e": 2346, "s": 2335, "text": " Live Demo" }, { "code": null, "e": 2705, "s": 2346, "text": "<?php\nspl_autoload_register(function($className) {\n $file = $className . '.php';\n if (file_exists($file)) {\n echo \"$file included\\n\";\n include $file;\n } else {\n throw new Exception(\"Unable to load $className.\");\n }\n});\ntry {\n $obj1 = new test1();\n $obj2 = new test10();\n} catch (Exception $e) {\n echo $e->getMessage(), \"\\n\";\n}\n?>" }, { "code": null, "e": 2743, "s": 2705, "text": "This will produce following result. −" }, { "code": null, "e": 2765, "s": 2743, "text": "Unable to load test1." } ]
JSTL - fn:escapeXml() Function
The fn:escapeXml() function escapes characters that can be interpreted as XML markup. The fn:escapeXml() function has the following syntax − java.lang.String escapeXml(java.lang.String) Following is the example to explain the functionality of the fn:escapeXml() function − <%@ taglib uri = "http://java.sun.com/jsp/jstl/core" prefix = "c" %> <%@ taglib uri = "http://java.sun.com/jsp/jstl/functions" prefix = "fn" %> <html> <head> <title>Using JSTL Functions</title> </head> <body> <c:set var = "string1" value = "This is first String."/> <c:set var = "string2" value = "This <abc>is second String.</abc>"/> <p>With escapeXml() Function:</p> <p>string (1) : ${fn:escapeXml(string1)}</p> <p>string (2) : ${fn:escapeXml(string2)}</p> <p>Without escapeXml() Function:</p> <p>string (1) : ${string1}</p> <p>string (2) : ${string2}</p> </body> </html> You will receive the following result − With escapeXml() Function: string (1) : This is first String. string (2) : This <abc>is second String.</abc> Without escapeXml() Function − string (1) : This is first String. string (2) : This is second String. 108 Lectures 11 hours Chaand Sheikh 517 Lectures 57 hours Chaand Sheikh 41 Lectures 4.5 hours Karthikeya T 42 Lectures 5.5 hours TELCOMA Global 15 Lectures 3 hours TELCOMA Global 44 Lectures 15 hours Uplatz Print Add Notes Bookmark this page
[ { "code": null, "e": 2325, "s": 2239, "text": "The fn:escapeXml() function escapes characters that can be interpreted as XML markup." }, { "code": null, "e": 2380, "s": 2325, "text": "The fn:escapeXml() function has the following syntax −" }, { "code": null, "e": 2426, "s": 2380, "text": "java.lang.String escapeXml(java.lang.String)\n" }, { "code": null, "e": 2513, "s": 2426, "text": "Following is the example to explain the functionality of the fn:escapeXml() function −" }, { "code": null, "e": 3158, "s": 2513, "text": "<%@ taglib uri = \"http://java.sun.com/jsp/jstl/core\" prefix = \"c\" %>\n<%@ taglib uri = \"http://java.sun.com/jsp/jstl/functions\" prefix = \"fn\" %>\n\n<html>\n <head>\n <title>Using JSTL Functions</title>\n </head>\n\n <body>\n <c:set var = \"string1\" value = \"This is first String.\"/>\n <c:set var = \"string2\" value = \"This <abc>is second String.</abc>\"/>\n\n <p>With escapeXml() Function:</p>\n <p>string (1) : ${fn:escapeXml(string1)}</p>\n <p>string (2) : ${fn:escapeXml(string2)}</p>\n\n <p>Without escapeXml() Function:</p>\n <p>string (1) : ${string1}</p>\n <p>string (2) : ${string2}</p>\n\n </body>\n</html>" }, { "code": null, "e": 3198, "s": 3158, "text": "You will receive the following result −" }, { "code": null, "e": 3412, "s": 3198, "text": "With escapeXml() Function:\nstring (1) : This is first String.\nstring (2) : This <abc>is second String.</abc>\n \nWithout escapeXml() Function −\nstring (1) : This is first String.\nstring (2) : This is second String.\n" }, { "code": null, "e": 3447, "s": 3412, "text": "\n 108 Lectures \n 11 hours \n" }, { "code": null, "e": 3462, "s": 3447, "text": " Chaand Sheikh" }, { "code": null, "e": 3497, "s": 3462, "text": "\n 517 Lectures \n 57 hours \n" }, { "code": null, "e": 3512, "s": 3497, "text": " Chaand Sheikh" }, { "code": null, "e": 3547, "s": 3512, "text": "\n 41 Lectures \n 4.5 hours \n" }, { "code": null, "e": 3561, "s": 3547, "text": " Karthikeya T" }, { "code": null, "e": 3596, "s": 3561, "text": "\n 42 Lectures \n 5.5 hours \n" }, { "code": null, "e": 3612, "s": 3596, "text": " TELCOMA Global" }, { "code": null, "e": 3645, "s": 3612, "text": "\n 15 Lectures \n 3 hours \n" }, { "code": null, "e": 3661, "s": 3645, "text": " TELCOMA Global" }, { "code": null, "e": 3695, "s": 3661, "text": "\n 44 Lectures \n 15 hours \n" }, { "code": null, "e": 3703, "s": 3695, "text": " Uplatz" }, { "code": null, "e": 3710, "s": 3703, "text": " Print" }, { "code": null, "e": 3721, "s": 3710, "text": " Add Notes" } ]
MLOps with MLFlow and Amazon SageMaker Pipelines | by Sofian Hamiti | Towards Data Science
Earlier this year, I published a step-by-step guide to deploying MLflow on AWS Fargate, and using it with Amazon SageMaker. This can help streamline the experimental phase of an ML project. In this post, we will go a step further and automate an end-to-end ML lifecycle using MLflow and Amazon SageMaker Pipelines. SageMaker Pipelines combines ML workflow orchestration, model registry, and CI/CD into one umbrella so you can quickly get your models into production. We will create an MLOps project for model building, training, and deployment to train an example Random Forest model and deploy it into a SageMaker Endpoint. We will update the modelBuild side of the project so it can log models into the MLflow model registry, and the modelDeploy side so it can ship them to production. We will tackle this in 3 steps: We will first deploy MLflow on AWS and launch an MLOps project in SageMaker. Then we will update the modelBuild pipeline so we can log models into our MLflow model registry. Finally, I will show how you can deploy the MLflow models into production with the modelDeploy pipeline. Below is the architecture overview for the project: To go through this example, make sure you have the following: Visited Introducing Amazon SageMaker Pipelines if SageMaker Pipelines sound new to you.Familiarity with Managing your machine learning lifecycle with MLflow and Amazon SageMaker and its example lab.Access to an Amazon SageMaker Studio environment and be familiar with the Studio user interface.Docker to build and push the MLFlow inference container image to ECR.This GitHub repository cloned into your studio environment Visited Introducing Amazon SageMaker Pipelines if SageMaker Pipelines sound new to you. Familiarity with Managing your machine learning lifecycle with MLflow and Amazon SageMaker and its example lab. Access to an Amazon SageMaker Studio environment and be familiar with the Studio user interface. Docker to build and push the MLFlow inference container image to ECR. This GitHub repository cloned into your studio environment First, we need to set up a central MLflow tracking server so we can use it in our MLOps project. If you don’t have one, you can follow instructions and blog explanations to deploy the open source version of MLflow on AWS Fargate. Now, we need to launch a SageMaker project based on the MLOps template for model building, training, and deployment. You can follow Julien Simon’s walk through video to do this: The project template will create 2 CodeCommit repos for modelBuild and modelDeploy, 2 CodePipeline pipelines for CI and CD, CodeBuild projects for packaging and testing artifacts, and other resources to run the project. We use Amazon S3 as artifact store for MLflow and you will need to update the MLOps project role, so it can access the MLflow S3 bucket. The role is called AmazonSageMakerServiceCatalogProductsUseRole and you can update its permissions like I did below: After cloning the modelBuild repository into your environment you can update the code with the one from the model_build folder. You can find the example ML pipeline in pipeline.py. It has 2 simple steps: PrepareData gets the dataset from sklearn and splits it into train/test sets TrainEvaluateRegister trains a Random Forest model, logs parameters, metrics, and the model into MLflow. At line 22 of pipeline.py, make sure you add your MLflow load balancer URI to the pipeline parameter. It will be passed to TrainEvaluateRegister so it knows where to point to find MLflow. You can now push the updated code to the main branch of the repo. From now on, the pipeline will register a new model version in MLflow at each execution. To further automate, you can schedule the pipeline with Amazon EventBridge, or use other type of triggers with the start_pipeline_execution method. We can now bring new model versions to the MLflow model registry, and will use the modelDeploy side of the MLOps project to deploy them into production. Alongside the ML model, we need a container image to handle the inference in our SageMaker Endpoint. Let’s push the one provided by MLflow into ECR. Make sure this is done in the same AWS region as your MLOps project is in. In my case, I push it from my laptop using the following commands: pip install -q mlflow==1.23.1mlflow sagemaker build-and-push-container Next, you can update the modelDeploy repo with the code from this folder. In buildspec.yml, you can define the model version to deploy into production. You will also need to input your MLflow load balancer URI, and Inference container URI. I updated build.py to get the chosen model version binary from MLflow, and upload its model.tar.gz to S3. This is done by mlflow_handler.py, which also transitions model stages in MLflow, as models go through the modelDeploy Pipeline. You can now push the code to the main branch of the repo, which will trigger the modelDeploy pipeline in CodePipeline. Once testing is successful in staging, you can navigate to the CodePipeline console and manually approve the endpoint to go to production. When deploying a new version, the pipeline will archive the previous one. And you can see your SageMaker Endpoints ready to generate predictions. Amazon SageMaker Pipelines brings MLOps tooling into one umbrella to reduce the effort of running end-to-end MLOps projects. In this post, we used a SageMaker MLOps project and the MLflow model registry to automate an end-to-end ML lifecycle. To go further, you can also learn how to deploy a Serverless Inference Service Using Amazon SageMaker Pipelines.
[ { "code": null, "e": 362, "s": 172, "text": "Earlier this year, I published a step-by-step guide to deploying MLflow on AWS Fargate, and using it with Amazon SageMaker. This can help streamline the experimental phase of an ML project." }, { "code": null, "e": 487, "s": 362, "text": "In this post, we will go a step further and automate an end-to-end ML lifecycle using MLflow and Amazon SageMaker Pipelines." }, { "code": null, "e": 639, "s": 487, "text": "SageMaker Pipelines combines ML workflow orchestration, model registry, and CI/CD into one umbrella so you can quickly get your models into production." }, { "code": null, "e": 960, "s": 639, "text": "We will create an MLOps project for model building, training, and deployment to train an example Random Forest model and deploy it into a SageMaker Endpoint. We will update the modelBuild side of the project so it can log models into the MLflow model registry, and the modelDeploy side so it can ship them to production." }, { "code": null, "e": 992, "s": 960, "text": "We will tackle this in 3 steps:" }, { "code": null, "e": 1069, "s": 992, "text": "We will first deploy MLflow on AWS and launch an MLOps project in SageMaker." }, { "code": null, "e": 1166, "s": 1069, "text": "Then we will update the modelBuild pipeline so we can log models into our MLflow model registry." }, { "code": null, "e": 1271, "s": 1166, "text": "Finally, I will show how you can deploy the MLflow models into production with the modelDeploy pipeline." }, { "code": null, "e": 1323, "s": 1271, "text": "Below is the architecture overview for the project:" }, { "code": null, "e": 1385, "s": 1323, "text": "To go through this example, make sure you have the following:" }, { "code": null, "e": 1807, "s": 1385, "text": "Visited Introducing Amazon SageMaker Pipelines if SageMaker Pipelines sound new to you.Familiarity with Managing your machine learning lifecycle with MLflow and Amazon SageMaker and its example lab.Access to an Amazon SageMaker Studio environment and be familiar with the Studio user interface.Docker to build and push the MLFlow inference container image to ECR.This GitHub repository cloned into your studio environment" }, { "code": null, "e": 1895, "s": 1807, "text": "Visited Introducing Amazon SageMaker Pipelines if SageMaker Pipelines sound new to you." }, { "code": null, "e": 2007, "s": 1895, "text": "Familiarity with Managing your machine learning lifecycle with MLflow and Amazon SageMaker and its example lab." }, { "code": null, "e": 2104, "s": 2007, "text": "Access to an Amazon SageMaker Studio environment and be familiar with the Studio user interface." }, { "code": null, "e": 2174, "s": 2104, "text": "Docker to build and push the MLFlow inference container image to ECR." }, { "code": null, "e": 2233, "s": 2174, "text": "This GitHub repository cloned into your studio environment" }, { "code": null, "e": 2330, "s": 2233, "text": "First, we need to set up a central MLflow tracking server so we can use it in our MLOps project." }, { "code": null, "e": 2463, "s": 2330, "text": "If you don’t have one, you can follow instructions and blog explanations to deploy the open source version of MLflow on AWS Fargate." }, { "code": null, "e": 2580, "s": 2463, "text": "Now, we need to launch a SageMaker project based on the MLOps template for model building, training, and deployment." }, { "code": null, "e": 2641, "s": 2580, "text": "You can follow Julien Simon’s walk through video to do this:" }, { "code": null, "e": 2861, "s": 2641, "text": "The project template will create 2 CodeCommit repos for modelBuild and modelDeploy, 2 CodePipeline pipelines for CI and CD, CodeBuild projects for packaging and testing artifacts, and other resources to run the project." }, { "code": null, "e": 2998, "s": 2861, "text": "We use Amazon S3 as artifact store for MLflow and you will need to update the MLOps project role, so it can access the MLflow S3 bucket." }, { "code": null, "e": 3115, "s": 2998, "text": "The role is called AmazonSageMakerServiceCatalogProductsUseRole and you can update its permissions like I did below:" }, { "code": null, "e": 3243, "s": 3115, "text": "After cloning the modelBuild repository into your environment you can update the code with the one from the model_build folder." }, { "code": null, "e": 3319, "s": 3243, "text": "You can find the example ML pipeline in pipeline.py. It has 2 simple steps:" }, { "code": null, "e": 3396, "s": 3319, "text": "PrepareData gets the dataset from sklearn and splits it into train/test sets" }, { "code": null, "e": 3501, "s": 3396, "text": "TrainEvaluateRegister trains a Random Forest model, logs parameters, metrics, and the model into MLflow." }, { "code": null, "e": 3689, "s": 3501, "text": "At line 22 of pipeline.py, make sure you add your MLflow load balancer URI to the pipeline parameter. It will be passed to TrainEvaluateRegister so it knows where to point to find MLflow." }, { "code": null, "e": 3755, "s": 3689, "text": "You can now push the updated code to the main branch of the repo." }, { "code": null, "e": 3844, "s": 3755, "text": "From now on, the pipeline will register a new model version in MLflow at each execution." }, { "code": null, "e": 3992, "s": 3844, "text": "To further automate, you can schedule the pipeline with Amazon EventBridge, or use other type of triggers with the start_pipeline_execution method." }, { "code": null, "e": 4145, "s": 3992, "text": "We can now bring new model versions to the MLflow model registry, and will use the modelDeploy side of the MLOps project to deploy them into production." }, { "code": null, "e": 4369, "s": 4145, "text": "Alongside the ML model, we need a container image to handle the inference in our SageMaker Endpoint. Let’s push the one provided by MLflow into ECR. Make sure this is done in the same AWS region as your MLOps project is in." }, { "code": null, "e": 4436, "s": 4369, "text": "In my case, I push it from my laptop using the following commands:" }, { "code": null, "e": 4507, "s": 4436, "text": "pip install -q mlflow==1.23.1mlflow sagemaker build-and-push-container" }, { "code": null, "e": 4581, "s": 4507, "text": "Next, you can update the modelDeploy repo with the code from this folder." }, { "code": null, "e": 4747, "s": 4581, "text": "In buildspec.yml, you can define the model version to deploy into production. You will also need to input your MLflow load balancer URI, and Inference container URI." }, { "code": null, "e": 4853, "s": 4747, "text": "I updated build.py to get the chosen model version binary from MLflow, and upload its model.tar.gz to S3." }, { "code": null, "e": 4982, "s": 4853, "text": "This is done by mlflow_handler.py, which also transitions model stages in MLflow, as models go through the modelDeploy Pipeline." }, { "code": null, "e": 5240, "s": 4982, "text": "You can now push the code to the main branch of the repo, which will trigger the modelDeploy pipeline in CodePipeline. Once testing is successful in staging, you can navigate to the CodePipeline console and manually approve the endpoint to go to production." }, { "code": null, "e": 5314, "s": 5240, "text": "When deploying a new version, the pipeline will archive the previous one." }, { "code": null, "e": 5386, "s": 5314, "text": "And you can see your SageMaker Endpoints ready to generate predictions." }, { "code": null, "e": 5511, "s": 5386, "text": "Amazon SageMaker Pipelines brings MLOps tooling into one umbrella to reduce the effort of running end-to-end MLOps projects." }, { "code": null, "e": 5629, "s": 5511, "text": "In this post, we used a SageMaker MLOps project and the MLflow model registry to automate an end-to-end ML lifecycle." } ]
How to Deploy Docker Containers to The Cloud | Towards Data Science
Docker containers are brilliant little things. They are essentially self-contained applications that can run across any OS. Imagine you have a Python application, you bundle it, along with everything you need to run it into a Docker container — that container can now be run on any Windows, Linux, or macOS system, without installing anything! Another great benefit of Docker is the level of support for containers on Cloud platforms, such as Google Cloud (GCP), which we will be using in this article. We can quickly build an application, package it into a container with Docker, and deploy it across the globe with GCP. That is what we will do in this article. We will take a simple Python API, package it with Docker, and deploy it with GCP, covering: > Project Setup> Dockerfile - FROM - WORKDIR and COPY - RUN - CMD> Building the Docker Image> Deploy with Google Cloud Platform - GCloud SDK - Cloud Build and Container Registry - Cloud Run We won’t be focusing on the Python code simply because that is not the purpose of the article. Instead, bring-your-own-code — or, here’s something I made earlier. We store our code in a directory called gcp-api (call this anything you like) under the name app.py. Alongside our script, we need: A Dockerfile — the instruction manual for Docker requirements.txt — a set of Python modules for our Dockerfile to install Of course, we’re using Docker, so; we need Docker too. It can be installed from here. If you have any OS-specific issues installing Docker, the 1:46:21 mark in this video explains Windows installation, followed by the 1:53:22 mark for macOS. The Dockerfile is our container building blueprint. It tells Docker exactly how to rearrange our scripts and files in a way that produces a self-contained application. It’s like building a house. Our scripts and files are raw materials (timber, bricks, etc.). We create a set of instructions for what we want our house to be like (the Dockerfile), which we then give to our architect (Docker), who then does all the technical stuff to produce a house blueprint (the image). Later, we will also give the blueprint to our builder (Google Build), who will construct the house (container) for us — but not yet. So, our Dockerfile. It looks like this: FROM python:3.6-slim-busterWORKDIR /appCOPY . .RUN pip install -r requirements.txtCMD exec gunicorn --bind :$PORT --workers 1 --threads 8 --timeout 0 app:app Initially, it may look confusing — but it’s incredibly simple. The very first line of our Dockerfile initializes our container image with another pre-built Docker image. This pre-built image is, in essence, nothing more than a lightweight Linux OS containing Python 3.6. But why ‘slim-buster’? Well, buster is the codename for all version 10 variations of Debian (a Linux Distribution). As for why they chose the word ‘buster’ — I think someone opens a dictionary and picks the first word they see. Slim, on the other hand, does make sense. As you may have guessed, it means Debian 10.x — but trimmed down, resulting in a smaller package size. A full list of official Python images is available here. Warning: It’s also worth noting that we’re using Python 3.6 here; you don’t need to stick to this unless you will be using Google Firebase (which we won’t be using here, but it’s good to be aware of this). If you do happen to use Google Firebase with Python, you will likely use the python-firebase module, which contains an import called async. Unfortunately, Python 3.7 introduced that exact word as a keyword. We avoid the resultant SyntaxError by sticking with Python 3.6. Next up is WORKDIR and COPY. We use WORKDIR to set the active directory inside our image (the construction site of our container) to /app. From now on, . outside of our image refers to our current directory (eg /gcp-api) and . inside our image refers to /app. After WORKDIR , we COPY everything from our local directory /gcp-api to our internal active directory /app. The reason we copy app.py to /app inside our image is because this is the structure that our Google Cloud instance will expect. We can change this, but this is what we will use here. Now, we have our pip install instructions. We use RUN to tell Docker to run the following command. That following command is pip install -r requirements.txt. By writing pip install -r requirements.txt we are telling Docker to run pip install recursively -r over every line contained within requirements.txt. So what does requirements.txt look like? pandas==1.1.1gunicorn==20.0.4flask==1.1.2flask-api==2.0 When that is fed into our recursive pip install instruction, it is translated into: pip install pandas==1.1.1pip install gunicorn==20.0.4pip install flask==1.1.2pip install flask-api==2.0 Which I’m sure is something everyone recognizes. Our final instruction is, depending on our app, not necessarily required. In this case, it is used to host our API using the gunicorn Python package. Nonetheless, the CMD instruction is the equivalent to opening our computer’s command-line interface CLI and typing whatever commands we provide, in this case exec gunicorn — bind :$PORT --workers 1 --threads 8 --timeout 0 app:app. Earlier in the article, we described the house building metaphor for Docker containers. So far, we’ve acquired our raw materials (scripts and files) and written a set of instructions explaining what we want our house to be like (the Dockerfile). Now, it’s time to create our blueprint — the Docker image. We can create this by executing the command: docker build -t gcp-api . Here, the Docker image build command is docker build Next, we use the -t flag to specify our image name — gcp-api Finally, we tell Docker to include everything from the current directory with . At this point, we have our blueprint, and all we need now is our builder, the Cloud — so let’s begin setting it up. There are three steps we need to take to deploy our container to the Cloud. First we: Download the Google Cloud SDK, which we will use to — Build our container with Cloud Build. Upload the container to GCP’s Container Registry. Deploy it with Cloud Run. We can find the SDK installer here. Once it’s installed, we need to authenticate our GCloud SDK by opening CMD prompt (or your equivalent CLI) and typing: gcloud auth login This command opens our web browser and allows us to log in to Google Cloud as usual. We configure Docker to used our GCP credentials with: gcloud auth configure-docker Finally, set the active project to your project ID (mine is medium-286319) with: gcloud config set project medium-286319 Google’s Container Registry (GCR) service allows us to store Docker containers, which we can use as a launchpad for our deployments. Before we can use GCR (or any other GCP services), we need to create a project. We can do this by navigating to the project selector page in the GCP console and clicking Create Project. All we need to do here is give our project a name. I use medium. Now we have our project setup; we should be able to access Container Registry. Here, we should be able to see the name of our newly created project in the top bar. To use GCR, we need to click Enable Container Registry API in the center of the console window. Finally, we can upload our container to GCR by submitting it to Cloud Build — the GCP service that builds Docker containers. To do this, we open our CLI in our project directory (gcp-api) and type: gcloud builds submit --tag gcr.io/[PROJECT-ID]/gcp-api gcloud builds submit submits the Docker image attached to our current directory to Cloud Build — where it will be packaged into a container. Our Container Registry location is provided to the --tag flag, where: gcr.io is the GCR hostname. [PROJECT-ID] is our project ID; we saw this when creating our project — for me, it is medium-286319. gcp-api is our image name. If we go back to our GCR window, we should be able to see our newly uploaded Docker image. If it isn’t there yet, it’s likely still in the build process — which we can find in our Cloud Build dashboard. Now we have our Docker container ready; we can deploy it with Cloud Run. In the Cloud Run interface, we deploy by (1) clicking Create Service, (2) configuring our deployment, (3–4) selecting the container, and (5) creating our deployment! We will see the deployment status in the Cloud Run console, which should take no longer than a few minutes. Once complete, we will see a green tick next to our deployment name and our deployment URL next to that. That’s it, we’ve taken our Python app, packaged it into a Docker container, and deployed it to the web with Google Cloud! Thanks to some brilliant tools — namely Docker and GCP — the process is painless and (typically) results in flawless deployments time after time. Now, more than ever before in the history of humanity. We can take the ideas and concepts in our minds and give them a tangible presence in the real world — which can result in some genuinely awe-inspiring creations. I hope this article will help some of you out there — if you have any questions, feedback, or ideas, feel free to reach out via Twitter or in the comments below. Thanks for reading! Interested in learning about SQL on the Cloud? Try Google’s brilliant MySQL, PostgreSQL, and SQL Server database services:
[ { "code": null, "e": 296, "s": 172, "text": "Docker containers are brilliant little things. They are essentially self-contained applications that can run across any OS." }, { "code": null, "e": 516, "s": 296, "text": "Imagine you have a Python application, you bundle it, along with everything you need to run it into a Docker container — that container can now be run on any Windows, Linux, or macOS system, without installing anything!" }, { "code": null, "e": 675, "s": 516, "text": "Another great benefit of Docker is the level of support for containers on Cloud platforms, such as Google Cloud (GCP), which we will be using in this article." }, { "code": null, "e": 794, "s": 675, "text": "We can quickly build an application, package it into a container with Docker, and deploy it across the globe with GCP." }, { "code": null, "e": 927, "s": 794, "text": "That is what we will do in this article. We will take a simple Python API, package it with Docker, and deploy it with GCP, covering:" }, { "code": null, "e": 1124, "s": 927, "text": "> Project Setup> Dockerfile - FROM - WORKDIR and COPY - RUN - CMD> Building the Docker Image> Deploy with Google Cloud Platform - GCloud SDK - Cloud Build and Container Registry - Cloud Run" }, { "code": null, "e": 1287, "s": 1124, "text": "We won’t be focusing on the Python code simply because that is not the purpose of the article. Instead, bring-your-own-code — or, here’s something I made earlier." }, { "code": null, "e": 1419, "s": 1287, "text": "We store our code in a directory called gcp-api (call this anything you like) under the name app.py. Alongside our script, we need:" }, { "code": null, "e": 1468, "s": 1419, "text": "A Dockerfile — the instruction manual for Docker" }, { "code": null, "e": 1541, "s": 1468, "text": "requirements.txt — a set of Python modules for our Dockerfile to install" }, { "code": null, "e": 1627, "s": 1541, "text": "Of course, we’re using Docker, so; we need Docker too. It can be installed from here." }, { "code": null, "e": 1783, "s": 1627, "text": "If you have any OS-specific issues installing Docker, the 1:46:21 mark in this video explains Windows installation, followed by the 1:53:22 mark for macOS." }, { "code": null, "e": 1951, "s": 1783, "text": "The Dockerfile is our container building blueprint. It tells Docker exactly how to rearrange our scripts and files in a way that produces a self-contained application." }, { "code": null, "e": 1979, "s": 1951, "text": "It’s like building a house." }, { "code": null, "e": 2257, "s": 1979, "text": "Our scripts and files are raw materials (timber, bricks, etc.). We create a set of instructions for what we want our house to be like (the Dockerfile), which we then give to our architect (Docker), who then does all the technical stuff to produce a house blueprint (the image)." }, { "code": null, "e": 2390, "s": 2257, "text": "Later, we will also give the blueprint to our builder (Google Build), who will construct the house (container) for us — but not yet." }, { "code": null, "e": 2430, "s": 2390, "text": "So, our Dockerfile. It looks like this:" }, { "code": null, "e": 2588, "s": 2430, "text": "FROM python:3.6-slim-busterWORKDIR /appCOPY . .RUN pip install -r requirements.txtCMD exec gunicorn --bind :$PORT --workers 1 --threads 8 --timeout 0 app:app" }, { "code": null, "e": 2651, "s": 2588, "text": "Initially, it may look confusing — but it’s incredibly simple." }, { "code": null, "e": 2758, "s": 2651, "text": "The very first line of our Dockerfile initializes our container image with another pre-built Docker image." }, { "code": null, "e": 2859, "s": 2758, "text": "This pre-built image is, in essence, nothing more than a lightweight Linux OS containing Python 3.6." }, { "code": null, "e": 2975, "s": 2859, "text": "But why ‘slim-buster’? Well, buster is the codename for all version 10 variations of Debian (a Linux Distribution)." }, { "code": null, "e": 3087, "s": 2975, "text": "As for why they chose the word ‘buster’ — I think someone opens a dictionary and picks the first word they see." }, { "code": null, "e": 3232, "s": 3087, "text": "Slim, on the other hand, does make sense. As you may have guessed, it means Debian 10.x — but trimmed down, resulting in a smaller package size." }, { "code": null, "e": 3289, "s": 3232, "text": "A full list of official Python images is available here." }, { "code": null, "e": 3495, "s": 3289, "text": "Warning: It’s also worth noting that we’re using Python 3.6 here; you don’t need to stick to this unless you will be using Google Firebase (which we won’t be using here, but it’s good to be aware of this)." }, { "code": null, "e": 3635, "s": 3495, "text": "If you do happen to use Google Firebase with Python, you will likely use the python-firebase module, which contains an import called async." }, { "code": null, "e": 3766, "s": 3635, "text": "Unfortunately, Python 3.7 introduced that exact word as a keyword. We avoid the resultant SyntaxError by sticking with Python 3.6." }, { "code": null, "e": 3795, "s": 3766, "text": "Next up is WORKDIR and COPY." }, { "code": null, "e": 4026, "s": 3795, "text": "We use WORKDIR to set the active directory inside our image (the construction site of our container) to /app. From now on, . outside of our image refers to our current directory (eg /gcp-api) and . inside our image refers to /app." }, { "code": null, "e": 4134, "s": 4026, "text": "After WORKDIR , we COPY everything from our local directory /gcp-api to our internal active directory /app." }, { "code": null, "e": 4317, "s": 4134, "text": "The reason we copy app.py to /app inside our image is because this is the structure that our Google Cloud instance will expect. We can change this, but this is what we will use here." }, { "code": null, "e": 4475, "s": 4317, "text": "Now, we have our pip install instructions. We use RUN to tell Docker to run the following command. That following command is pip install -r requirements.txt." }, { "code": null, "e": 4625, "s": 4475, "text": "By writing pip install -r requirements.txt we are telling Docker to run pip install recursively -r over every line contained within requirements.txt." }, { "code": null, "e": 4666, "s": 4625, "text": "So what does requirements.txt look like?" }, { "code": null, "e": 4722, "s": 4666, "text": "pandas==1.1.1gunicorn==20.0.4flask==1.1.2flask-api==2.0" }, { "code": null, "e": 4806, "s": 4722, "text": "When that is fed into our recursive pip install instruction, it is translated into:" }, { "code": null, "e": 4910, "s": 4806, "text": "pip install pandas==1.1.1pip install gunicorn==20.0.4pip install flask==1.1.2pip install flask-api==2.0" }, { "code": null, "e": 4959, "s": 4910, "text": "Which I’m sure is something everyone recognizes." }, { "code": null, "e": 5109, "s": 4959, "text": "Our final instruction is, depending on our app, not necessarily required. In this case, it is used to host our API using the gunicorn Python package." }, { "code": null, "e": 5340, "s": 5109, "text": "Nonetheless, the CMD instruction is the equivalent to opening our computer’s command-line interface CLI and typing whatever commands we provide, in this case exec gunicorn — bind :$PORT --workers 1 --threads 8 --timeout 0 app:app." }, { "code": null, "e": 5586, "s": 5340, "text": "Earlier in the article, we described the house building metaphor for Docker containers. So far, we’ve acquired our raw materials (scripts and files) and written a set of instructions explaining what we want our house to be like (the Dockerfile)." }, { "code": null, "e": 5645, "s": 5586, "text": "Now, it’s time to create our blueprint — the Docker image." }, { "code": null, "e": 5690, "s": 5645, "text": "We can create this by executing the command:" }, { "code": null, "e": 5716, "s": 5690, "text": "docker build -t gcp-api ." }, { "code": null, "e": 5769, "s": 5716, "text": "Here, the Docker image build command is docker build" }, { "code": null, "e": 5830, "s": 5769, "text": "Next, we use the -t flag to specify our image name — gcp-api" }, { "code": null, "e": 5910, "s": 5830, "text": "Finally, we tell Docker to include everything from the current directory with ." }, { "code": null, "e": 6026, "s": 5910, "text": "At this point, we have our blueprint, and all we need now is our builder, the Cloud — so let’s begin setting it up." }, { "code": null, "e": 6112, "s": 6026, "text": "There are three steps we need to take to deploy our container to the Cloud. First we:" }, { "code": null, "e": 6166, "s": 6112, "text": "Download the Google Cloud SDK, which we will use to —" }, { "code": null, "e": 6204, "s": 6166, "text": "Build our container with Cloud Build." }, { "code": null, "e": 6254, "s": 6204, "text": "Upload the container to GCP’s Container Registry." }, { "code": null, "e": 6280, "s": 6254, "text": "Deploy it with Cloud Run." }, { "code": null, "e": 6435, "s": 6280, "text": "We can find the SDK installer here. Once it’s installed, we need to authenticate our GCloud SDK by opening CMD prompt (or your equivalent CLI) and typing:" }, { "code": null, "e": 6453, "s": 6435, "text": "gcloud auth login" }, { "code": null, "e": 6592, "s": 6453, "text": "This command opens our web browser and allows us to log in to Google Cloud as usual. We configure Docker to used our GCP credentials with:" }, { "code": null, "e": 6621, "s": 6592, "text": "gcloud auth configure-docker" }, { "code": null, "e": 6702, "s": 6621, "text": "Finally, set the active project to your project ID (mine is medium-286319) with:" }, { "code": null, "e": 6742, "s": 6702, "text": "gcloud config set project medium-286319" }, { "code": null, "e": 6875, "s": 6742, "text": "Google’s Container Registry (GCR) service allows us to store Docker containers, which we can use as a launchpad for our deployments." }, { "code": null, "e": 7061, "s": 6875, "text": "Before we can use GCR (or any other GCP services), we need to create a project. We can do this by navigating to the project selector page in the GCP console and clicking Create Project." }, { "code": null, "e": 7126, "s": 7061, "text": "All we need to do here is give our project a name. I use medium." }, { "code": null, "e": 7290, "s": 7126, "text": "Now we have our project setup; we should be able to access Container Registry. Here, we should be able to see the name of our newly created project in the top bar." }, { "code": null, "e": 7386, "s": 7290, "text": "To use GCR, we need to click Enable Container Registry API in the center of the console window." }, { "code": null, "e": 7511, "s": 7386, "text": "Finally, we can upload our container to GCR by submitting it to Cloud Build — the GCP service that builds Docker containers." }, { "code": null, "e": 7584, "s": 7511, "text": "To do this, we open our CLI in our project directory (gcp-api) and type:" }, { "code": null, "e": 7639, "s": 7584, "text": "gcloud builds submit --tag gcr.io/[PROJECT-ID]/gcp-api" }, { "code": null, "e": 7780, "s": 7639, "text": "gcloud builds submit submits the Docker image attached to our current directory to Cloud Build — where it will be packaged into a container." }, { "code": null, "e": 7850, "s": 7780, "text": "Our Container Registry location is provided to the --tag flag, where:" }, { "code": null, "e": 7878, "s": 7850, "text": "gcr.io is the GCR hostname." }, { "code": null, "e": 7979, "s": 7878, "text": "[PROJECT-ID] is our project ID; we saw this when creating our project — for me, it is medium-286319." }, { "code": null, "e": 8006, "s": 7979, "text": "gcp-api is our image name." }, { "code": null, "e": 8209, "s": 8006, "text": "If we go back to our GCR window, we should be able to see our newly uploaded Docker image. If it isn’t there yet, it’s likely still in the build process — which we can find in our Cloud Build dashboard." }, { "code": null, "e": 8282, "s": 8209, "text": "Now we have our Docker container ready; we can deploy it with Cloud Run." }, { "code": null, "e": 8448, "s": 8282, "text": "In the Cloud Run interface, we deploy by (1) clicking Create Service, (2) configuring our deployment, (3–4) selecting the container, and (5) creating our deployment!" }, { "code": null, "e": 8556, "s": 8448, "text": "We will see the deployment status in the Cloud Run console, which should take no longer than a few minutes." }, { "code": null, "e": 8661, "s": 8556, "text": "Once complete, we will see a green tick next to our deployment name and our deployment URL next to that." }, { "code": null, "e": 8783, "s": 8661, "text": "That’s it, we’ve taken our Python app, packaged it into a Docker container, and deployed it to the web with Google Cloud!" }, { "code": null, "e": 8929, "s": 8783, "text": "Thanks to some brilliant tools — namely Docker and GCP — the process is painless and (typically) results in flawless deployments time after time." }, { "code": null, "e": 9146, "s": 8929, "text": "Now, more than ever before in the history of humanity. We can take the ideas and concepts in our minds and give them a tangible presence in the real world — which can result in some genuinely awe-inspiring creations." }, { "code": null, "e": 9328, "s": 9146, "text": "I hope this article will help some of you out there — if you have any questions, feedback, or ideas, feel free to reach out via Twitter or in the comments below. Thanks for reading!" } ]
How to add metadata to a DataFrame or Series with Pandas in Python? - GeeksforGeeks
22 Jul, 2021 Metadata, also known as data about the data. Metadata can give us data description, summary, storage in memory, and datatype of that particular data. We are going to display and create metadata. Scenario: We can get metadata simply by using info() command We can add metadata to the existing data and can view the metadata of the created data. Steps: Create a data frame View the metadata which is already existing Create the metadata and view the metadata. Here, we are going to create a data frame, and we can view and create metadata on the created data frame View existing Metadata methods: dataframe_name.info() – It will return the data types null values and memory usage in tabular format dataframe_name.columns() – It will return an array which includes all the column names in the data frame dataframe_name.describe() – It will give the descriptive statistics of the given numeric data frame column like mean, median, standard deviation etc. Create Metadata We can create the metadata for the particular data frame using dataframe.scale() and dataframe.offset() methods. They are used to represent the metadata. Syntax: dataframe_name.scale=value dataframe_name.offset=value Below are some examples which depict how to add metadata to a DataFrame or Series: Example 1 Initially create and display a dataframe. Python3 # import required modulesimport pandas as pd # initialise data of lists using dictionarydata = {'Name': ['Sravan', 'Deepak', 'Radha', 'Vani'], 'College': ['vignan', 'vignan Lara', 'vignan', 'vignan'], 'Department': ['CSE', 'IT', 'IT', 'CSE'], 'Profession': ['Student', 'Assistant Professor', 'Programmer & ass. Proff', 'Programmer & Scholar'], 'Age': [22, 32, 45, 37] } # create dataframedf = pd.DataFrame(data) # print dataframedf Output: Then check dataframe attributes and description. Python3 # data informationdf.info() # data columns descriptiondf.columns # describing columnsdf.describe() Output: Initialize offset and scale of the dataframe. Python3 # initializing scale and offset# for creating meta datadf.scale = 0.1df.offset = 15 # display scale and and offsetprint('Scale:', df.scale)print('Offset:', df.offset) Output: We are storing data in hdf5 file format, and then we will display the dataframe along with its stored metadata. Python3 # store in hdf5 file formatstoredata = pd.HDFStore('college_data.hdf5') # datastoredata.put('data_01', df) # including metadatametadata = {'scale': 0.1, 'offset': 15} # getting attributesstoredata.get_storer('data_01').attrs.metadata = metadata # closing the storedatastoredata.close() # getting datawith pd.HDFStore('college_data.hdf5') as storedata: data = storedata['data_01'] metadata = storedata.get_storer('data_01').attrs.metadata # display dataprint('\nDataframe:\n', data) # display stored dataprint('\nStored Data:\n', storedata) # display metadataprint('\nMetadata:\n', metadata) Output: Example 2 Series data structure in pandas will not support info and all methods. So we directly create metadata and display. Python3 # import required moduleimport pandas as pd # initialise data of lists using dictionary.data = {'Name': ['Sravan', 'Deepak', 'Radha', 'Vani'], 'College': ['vignan', 'vignan Lara', 'vignan', 'vignan'], 'Department': ['CSE', 'IT', 'IT', 'CSE'], 'Profession': ['Student', 'Assistant Professor', 'Programmer & ass. Proff', 'Programmer & Scholar'], 'Age': [22, 32, 45, 37] } # Create seriesser = pd.Series(data) # display dataser Output: Now we will store the metadata and then display it. Python3 # storing data in hdf5 file formatstoredata = pd.HDFStore('college_data.hdf5') # datastoredata.put('data_01', ser) # mentioning scale and offsetmetadata = {'scale': 0.1, 'offset': 15} storedata.get_storer('data_01').attrs.metadata = metadata # storing closestoredata.close() # getting attributeswith pd.HDFStore('college_data.hdf5') as storedata: data = storedata['data_01'] metadata = storedata.get_storer('data_01').attrs.metadata # display dataprint('\nData:\n', data) # display stored dataprint('\nStored Data:\n', storedata) # display Metadataprint('\nMetadata:\n', metadata) Output: anikakapoor Python pandas-dataFrame Python pandas-series Python-pandas Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Python Dictionary Read a file line by line in Python Enumerate() in Python How to Install PIP on Windows ? Iterate over a list in Python Different ways to create Pandas Dataframe Python String | replace() Python program to convert a list to string Reading and Writing to text files in Python sum() function in Python
[ { "code": null, "e": 24401, "s": 24373, "text": "\n22 Jul, 2021" }, { "code": null, "e": 24596, "s": 24401, "text": "Metadata, also known as data about the data. Metadata can give us data description, summary, storage in memory, and datatype of that particular data. We are going to display and create metadata." }, { "code": null, "e": 24606, "s": 24596, "text": "Scenario:" }, { "code": null, "e": 24657, "s": 24606, "text": "We can get metadata simply by using info() command" }, { "code": null, "e": 24745, "s": 24657, "text": "We can add metadata to the existing data and can view the metadata of the created data." }, { "code": null, "e": 24752, "s": 24745, "text": "Steps:" }, { "code": null, "e": 24772, "s": 24752, "text": "Create a data frame" }, { "code": null, "e": 24816, "s": 24772, "text": "View the metadata which is already existing" }, { "code": null, "e": 24859, "s": 24816, "text": "Create the metadata and view the metadata." }, { "code": null, "e": 24964, "s": 24859, "text": "Here, we are going to create a data frame, and we can view and create metadata on the created data frame" }, { "code": null, "e": 24996, "s": 24964, "text": "View existing Metadata methods:" }, { "code": null, "e": 25097, "s": 24996, "text": "dataframe_name.info() – It will return the data types null values and memory usage in tabular format" }, { "code": null, "e": 25202, "s": 25097, "text": "dataframe_name.columns() – It will return an array which includes all the column names in the data frame" }, { "code": null, "e": 25352, "s": 25202, "text": "dataframe_name.describe() – It will give the descriptive statistics of the given numeric data frame column like mean, median, standard deviation etc." }, { "code": null, "e": 25368, "s": 25352, "text": "Create Metadata" }, { "code": null, "e": 25522, "s": 25368, "text": "We can create the metadata for the particular data frame using dataframe.scale() and dataframe.offset() methods. They are used to represent the metadata." }, { "code": null, "e": 25530, "s": 25522, "text": "Syntax:" }, { "code": null, "e": 25557, "s": 25530, "text": "dataframe_name.scale=value" }, { "code": null, "e": 25585, "s": 25557, "text": "dataframe_name.offset=value" }, { "code": null, "e": 25668, "s": 25585, "text": "Below are some examples which depict how to add metadata to a DataFrame or Series:" }, { "code": null, "e": 25678, "s": 25668, "text": "Example 1" }, { "code": null, "e": 25720, "s": 25678, "text": "Initially create and display a dataframe." }, { "code": null, "e": 25728, "s": 25720, "text": "Python3" }, { "code": "# import required modulesimport pandas as pd # initialise data of lists using dictionarydata = {'Name': ['Sravan', 'Deepak', 'Radha', 'Vani'], 'College': ['vignan', 'vignan Lara', 'vignan', 'vignan'], 'Department': ['CSE', 'IT', 'IT', 'CSE'], 'Profession': ['Student', 'Assistant Professor', 'Programmer & ass. Proff', 'Programmer & Scholar'], 'Age': [22, 32, 45, 37] } # create dataframedf = pd.DataFrame(data) # print dataframedf", "e": 26239, "s": 25728, "text": null }, { "code": null, "e": 26247, "s": 26239, "text": "Output:" }, { "code": null, "e": 26296, "s": 26247, "text": "Then check dataframe attributes and description." }, { "code": null, "e": 26304, "s": 26296, "text": "Python3" }, { "code": "# data informationdf.info() # data columns descriptiondf.columns # describing columnsdf.describe()", "e": 26403, "s": 26304, "text": null }, { "code": null, "e": 26411, "s": 26403, "text": "Output:" }, { "code": null, "e": 26457, "s": 26411, "text": "Initialize offset and scale of the dataframe." }, { "code": null, "e": 26465, "s": 26457, "text": "Python3" }, { "code": "# initializing scale and offset# for creating meta datadf.scale = 0.1df.offset = 15 # display scale and and offsetprint('Scale:', df.scale)print('Offset:', df.offset)", "e": 26632, "s": 26465, "text": null }, { "code": null, "e": 26640, "s": 26632, "text": "Output:" }, { "code": null, "e": 26753, "s": 26640, "text": "We are storing data in hdf5 file format, and then we will display the dataframe along with its stored metadata. " }, { "code": null, "e": 26761, "s": 26753, "text": "Python3" }, { "code": "# store in hdf5 file formatstoredata = pd.HDFStore('college_data.hdf5') # datastoredata.put('data_01', df) # including metadatametadata = {'scale': 0.1, 'offset': 15} # getting attributesstoredata.get_storer('data_01').attrs.metadata = metadata # closing the storedatastoredata.close() # getting datawith pd.HDFStore('college_data.hdf5') as storedata: data = storedata['data_01'] metadata = storedata.get_storer('data_01').attrs.metadata # display dataprint('\\nDataframe:\\n', data) # display stored dataprint('\\nStored Data:\\n', storedata) # display metadataprint('\\nMetadata:\\n', metadata)", "e": 27358, "s": 26761, "text": null }, { "code": null, "e": 27366, "s": 27358, "text": "Output:" }, { "code": null, "e": 27376, "s": 27366, "text": "Example 2" }, { "code": null, "e": 27491, "s": 27376, "text": "Series data structure in pandas will not support info and all methods. So we directly create metadata and display." }, { "code": null, "e": 27499, "s": 27491, "text": "Python3" }, { "code": "# import required moduleimport pandas as pd # initialise data of lists using dictionary.data = {'Name': ['Sravan', 'Deepak', 'Radha', 'Vani'], 'College': ['vignan', 'vignan Lara', 'vignan', 'vignan'], 'Department': ['CSE', 'IT', 'IT', 'CSE'], 'Profession': ['Student', 'Assistant Professor', 'Programmer & ass. Proff', 'Programmer & Scholar'], 'Age': [22, 32, 45, 37] } # Create seriesser = pd.Series(data) # display dataser", "e": 28003, "s": 27499, "text": null }, { "code": null, "e": 28011, "s": 28003, "text": "Output:" }, { "code": null, "e": 28063, "s": 28011, "text": "Now we will store the metadata and then display it." }, { "code": null, "e": 28071, "s": 28063, "text": "Python3" }, { "code": "# storing data in hdf5 file formatstoredata = pd.HDFStore('college_data.hdf5') # datastoredata.put('data_01', ser) # mentioning scale and offsetmetadata = {'scale': 0.1, 'offset': 15} storedata.get_storer('data_01').attrs.metadata = metadata # storing closestoredata.close() # getting attributeswith pd.HDFStore('college_data.hdf5') as storedata: data = storedata['data_01'] metadata = storedata.get_storer('data_01').attrs.metadata # display dataprint('\\nData:\\n', data) # display stored dataprint('\\nStored Data:\\n', storedata) # display Metadataprint('\\nMetadata:\\n', metadata)", "e": 28658, "s": 28071, "text": null }, { "code": null, "e": 28666, "s": 28658, "text": "Output:" }, { "code": null, "e": 28678, "s": 28666, "text": "anikakapoor" }, { "code": null, "e": 28702, "s": 28678, "text": "Python pandas-dataFrame" }, { "code": null, "e": 28723, "s": 28702, "text": "Python pandas-series" }, { "code": null, "e": 28737, "s": 28723, "text": "Python-pandas" }, { "code": null, "e": 28744, "s": 28737, "text": "Python" }, { "code": null, "e": 28842, "s": 28744, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28851, "s": 28842, "text": "Comments" }, { "code": null, "e": 28864, "s": 28851, "text": "Old Comments" }, { "code": null, "e": 28882, "s": 28864, "text": "Python Dictionary" }, { "code": null, "e": 28917, "s": 28882, "text": "Read a file line by line in Python" }, { "code": null, "e": 28939, "s": 28917, "text": "Enumerate() in Python" }, { "code": null, "e": 28971, "s": 28939, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 29001, "s": 28971, "text": "Iterate over a list in Python" }, { "code": null, "e": 29043, "s": 29001, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 29069, "s": 29043, "text": "Python String | replace()" }, { "code": null, "e": 29112, "s": 29069, "text": "Python program to convert a list to string" }, { "code": null, "e": 29156, "s": 29112, "text": "Reading and Writing to text files in Python" } ]
CSS Minifier & Compressor
Editable CSS Code 12345678#fileUpload { white-space:nowrap;position:relative;color:#575765;z-index:999}#uploadmenu a{ color:#424242; text-decoration:none; padding:0px;}#uploadmenu div{ width:290px;}#uploadmenu div{ margin:0px 2px 0px 0px; padding:4px 5px 5px 5px; text-align:center; float:none; list-style:none; line-height:24px; border-bottom: 1px dashed #BCBCBC; }#uploadmenu div:last-child{ border-bottom:none;}#uploadmenu div a { font-size:13px; color:#424242; text-decoration:none; }#uploadmenu div a:hover {color:#aaa; text-decoration:none; }X Privacy Policy Cookies Policy Terms of Use
[ { "code": null, "e": 18, "s": 0, "text": "Editable CSS Code" }, { "code": null, "e": 550, "s": 18, "text": "12345678#fileUpload { white-space:nowrap;position:relative;color:#575765;z-index:999}#uploadmenu a{ color:#424242; text-decoration:none; padding:0px;}#uploadmenu div{ width:290px;}#uploadmenu div{ margin:0px 2px 0px 0px; padding:4px 5px 5px 5px; text-align:center; float:none; list-style:none; line-height:24px; border-bottom: 1px dashed #BCBCBC; }#uploadmenu div:last-child{ border-bottom:none;}#uploadmenu div a { font-size:13px; color:#424242; text-decoration:none; }#uploadmenu div a:hover {color:#aaa; text-decoration:none; }X" }, { "code": null, "e": 565, "s": 550, "text": "Privacy Policy" }, { "code": null, "e": 580, "s": 565, "text": "Cookies Policy" } ]
Angular7 - Services
We might come across a situation where we need some code to be used everywhere on the page. For example, it can be for data connection that needs to be shared across components. This is achieved with the help of Services. With services, we can access methods and properties across other components in the entire project. To create a service, we need to make use of the command line as given below − ng g service myservice C:\projectA7\angular7-app>ng g service myservice CREATE src/app/myservice.service.spec.ts (348 bytes) CREATE src/app/myservice.service.ts (138 bytes) The files created in app folder are as follows − Following are the files created which are shown at the bottom ― myservice.service.specs.ts and myservice.service.ts. myservice.service.ts import { Injectable } from '@angular/core'; @Injectable({ providedIn: 'root' }) export class MyserviceService { constructor() { } } Here, the injectable module is imported from the @angular/core. It contains the @Injectable method and a class called MyserviceService. We will create our service function in this class. Before creating a new service, we need to include the service created in the main parent app.module.ts. import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { AppRoutingModule , RoutingComponent} from './app-routing.module'; import { AppComponent } from './app.component'; import { NewCmpComponent } from './new-cmp/new-cmp.component'; import { ChangeTextDirective } from './change-text.directive'; import { SqrtPipe } from './app.sqrt'; import { MyserviceService } from './myservice.service'; @NgModule({ declarations: [ SqrtPipe, AppComponent, NewCmpComponent, ChangeTextDirective, RoutingComponent ], imports: [ BrowserModule, AppRoutingModule ], providers: [MyserviceService], bootstrap: [AppComponent] }) export class AppModule { } We have imported the Service with the class name, and the same class is used in the providers. Let us now switch back to the service class and create a service function. In the service class, we will create a function which will display today’s date. We can use the same function in the main parent component app.component.ts and also in the new component new-cmp.component.ts that we created in the previous chapter. Let us now see how the function looks in the service and how to use it in components. import { Injectable } from '@angular/core'; @Injectable({ providedIn: 'root' }) export class MyserviceService { constructor() { } showTodayDate() { let ndate = new Date(); return ndate; } } In the above service file, we have created a function showTodayDate. Now we will return the new Date () created. Let us see how we can access this function in the component class. app.component.ts import { Component } from '@angular/core'; import { MyserviceService } from './myservice.service'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { title = 'Angular 7 Project!'; todaydate; constructor(private myservice: MyserviceService) {} ngOnInit() { this.todaydate = this.myservice.showTodayDate(); } } The ngOnInit function gets called by default in any component created. The date is fetched from the service as shown above. To fetch more details of the service, we need to first include the service in the component ts file. We will display the date in the .html file as shown below − app.component.html {{todaydate}} <app-new-cmp></app-new-cmp> Let us now see how to use the service in the new component created. new-cmp.component.ts import { Component, OnInit } from '@angular/core'; import { MyserviceService } from './../myservice.service'; @Component({ selector: 'app-new-cmp', templateUrl: './new-cmp.component.html', styleUrls: ['./new-cmp.component.css'] }) export class NewCmpComponent implements OnInit { newcomponent = "Entered in new component created"; todaydate; constructor(private myservice: MyserviceService) { } ngOnInit() { this.todaydate = this.myservice.showTodayDate(); } } In the new component that we have created, we need to first import the service that we want and access the methods and properties of the same. Check the code highlighted. todaydate is displayed in the component html as follows − new-cmp.component.html <p> {{newcomponent}} </p> <p> Today's Date : {{todaydate}} </p> The selector of the new component is used in the app.component.html file. The contents from the above html file will be displayed in the browser as shown below − If you change the property of the service in any component, the same is changed in other components too. Let us now see how this works. We will define one variable in the service and use it in the parent and the new component. We will again change the property in the parent component and will see if the same is changed in the new component or not. In myservice.service.ts, we have created a property and used the same in other parent and new component. import { Injectable } from '@angular/core'; @Injectable({ providedIn: 'root' }) export class MyserviceService { serviceproperty = "Service Created"; constructor() { } showTodayDate() { let ndate = new Date(); return ndate; } } Let us now use the serviceproperty variable in other components. In app.component.ts, we are accessing the variable as follows − import { Component } from '@angular/core'; import { MyserviceService } from './myservice.service'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { title = 'Angular 7 Project!'; todaydate; componentproperty; constructor(private myservice: MyserviceService) {} ngOnInit() { this.todaydate = this.myservice.showTodayDate(); console.log(this.myservice.serviceproperty); this.myservice.serviceproperty = "component created"; // value is changed. this.componentproperty = this.myservice.serviceproperty; } } We will now fetch the variable and work on the console.log. In the next line, we will change the value of the variable to “component created”. We will do the same in new-cmp.component.ts. import { Component, OnInit } from '@angular/core'; import { MyserviceService } from './../myservice.service'; @Component({ selector: 'app-new-cmp', templateUrl: './new-cmp.component.html', styleUrls: ['./new-cmp.component.css'] }) export class NewCmpComponent implements OnInit { todaydate; newcomponentproperty; newcomponent = "Entered in newcomponent"; constructor(private myservice: MyserviceService) {} ngOnInit() { this.todaydate = this.myservice.showTodayDate(); this.newcomponentproperty = this.myservice.serviceproperty; } } In the above component, we are not changing anything but directly assigning the property to the component property. Now when you execute it in the browser, the service property will be changed since the value of it is changed in app.component.ts and the same will be displayed for the new-cmp.component.ts. Also check the value in the console before it is changed. Here is the app.component.html and new-cmp.component.html files − app.component.html <h3>{{todaydate}}>/h3> <h3> Service Property : {{componentproperty}} </h3> <app-new-cmp></app-new-cmp> new-cmp.component.html <h3>{{newcomponent}} </h3> <h3> Service Property : {{newcomponentproperty}} </h3> <h3> Today's Date : {{todaydate}} </h3> 16 Lectures 1.5 hours Anadi Sharma 28 Lectures 2.5 hours Anadi Sharma 11 Lectures 7.5 hours SHIVPRASAD KOIRALA 16 Lectures 2.5 hours Frahaan Hussain 69 Lectures 5 hours Senol Atac 53 Lectures 3.5 hours Senol Atac Print Add Notes Bookmark this page
[ { "code": null, "e": 2382, "s": 2061, "text": "We might come across a situation where we need some code to be used everywhere on the page. For example, it can be for data connection that needs to be shared across components. This is achieved with the help of Services. With services, we can access methods and properties across other components in the entire project." }, { "code": null, "e": 2460, "s": 2382, "text": "To create a service, we need to make use of the command line as given below −" }, { "code": null, "e": 2484, "s": 2460, "text": "ng g service myservice\n" }, { "code": null, "e": 2637, "s": 2484, "text": "C:\\projectA7\\angular7-app>ng g service myservice \nCREATE src/app/myservice.service.spec.ts (348 bytes) \nCREATE src/app/myservice.service.ts (138 bytes)\n" }, { "code": null, "e": 2686, "s": 2637, "text": "The files created in app folder are as follows −" }, { "code": null, "e": 2803, "s": 2686, "text": "Following are the files created which are shown at the bottom ― myservice.service.specs.ts and myservice.service.ts." }, { "code": null, "e": 2824, "s": 2803, "text": "myservice.service.ts" }, { "code": null, "e": 2964, "s": 2824, "text": "import { Injectable } from '@angular/core';\n@Injectable({\n providedIn: 'root' \n}) \nexport class MyserviceService {\n constructor() { }\n}" }, { "code": null, "e": 3151, "s": 2964, "text": "Here, the injectable module is imported from the @angular/core. It contains the @Injectable method and a class called MyserviceService. We will create our service function in this class." }, { "code": null, "e": 3255, "s": 3151, "text": "Before creating a new service, we need to include the service created in the main parent app.module.ts." }, { "code": null, "e": 4022, "s": 3255, "text": "import { BrowserModule } from '@angular/platform-browser'; \nimport { NgModule } from '@angular/core';\nimport { AppRoutingModule , RoutingComponent} from './app-routing.module'; \nimport { AppComponent } from './app.component'; \nimport { NewCmpComponent } from './new-cmp/new-cmp.component'; \nimport { ChangeTextDirective } from './change-text.directive'; \nimport { SqrtPipe } from './app.sqrt'; \nimport { MyserviceService } from './myservice.service';\n\n@NgModule({ \n declarations: [\n SqrtPipe, \n AppComponent, \n NewCmpComponent, \n ChangeTextDirective, \n RoutingComponent \n ], \n imports: [ \n BrowserModule, \n AppRoutingModule\n ], \n providers: [MyserviceService], \n bootstrap: [AppComponent] \n})\nexport class AppModule { }" }, { "code": null, "e": 4192, "s": 4022, "text": "We have imported the Service with the class name, and the same class is used in the providers. Let us now switch back to the service class and create a service function." }, { "code": null, "e": 4440, "s": 4192, "text": "In the service class, we will create a function which will display today’s date. We can use the same function in the main parent component app.component.ts and also in the new component new-cmp.component.ts that we created in the previous chapter." }, { "code": null, "e": 4526, "s": 4440, "text": "Let us now see how the function looks in the service and how to use it in components." }, { "code": null, "e": 4750, "s": 4526, "text": "import { Injectable } from '@angular/core';\n@Injectable({ \n providedIn: 'root' \n}) \nexport class MyserviceService { \n constructor() { } \n showTodayDate() { \n let ndate = new Date(); \n return ndate; \n } \n}" }, { "code": null, "e": 4930, "s": 4750, "text": "In the above service file, we have created a function showTodayDate. Now we will return the new Date () created. Let us see how we can access this function in the component class." }, { "code": null, "e": 4947, "s": 4930, "text": "app.component.ts" }, { "code": null, "e": 5378, "s": 4947, "text": "import { Component } from '@angular/core'; \nimport { MyserviceService } from './myservice.service';\n@Component({ selector: 'app-root', \n templateUrl: './app.component.html',\n styleUrls: ['./app.component.css'] \n})\nexport class AppComponent { \n title = 'Angular 7 Project!'; \n todaydate;\n constructor(private myservice: MyserviceService) {}\n ngOnInit() { \n this.todaydate = this.myservice.showTodayDate(); \n } \n}" }, { "code": null, "e": 5603, "s": 5378, "text": "The ngOnInit function gets called by default in any component created. The date is fetched from the service as shown above. To fetch more details of the service, we need to first include the service in the component ts file." }, { "code": null, "e": 5663, "s": 5603, "text": "We will display the date in the .html file as shown below −" }, { "code": null, "e": 5682, "s": 5663, "text": "app.component.html" }, { "code": null, "e": 5726, "s": 5682, "text": "{{todaydate}} \n<app-new-cmp></app-new-cmp>\n" }, { "code": null, "e": 5794, "s": 5726, "text": "Let us now see how to use the service in the new component created." }, { "code": null, "e": 5815, "s": 5794, "text": "new-cmp.component.ts" }, { "code": null, "e": 6319, "s": 5815, "text": "import { Component, OnInit } from '@angular/core'; \nimport { MyserviceService } from './../myservice.service';\n\n@Component({ \n selector: 'app-new-cmp', \n templateUrl: './new-cmp.component.html', \n styleUrls: ['./new-cmp.component.css'] \n}) \nexport class NewCmpComponent implements OnInit { \n newcomponent = \"Entered in new component created\"; \n todaydate; \n constructor(private myservice: MyserviceService) { }\n ngOnInit() { \n this.todaydate = this.myservice.showTodayDate(); \n } \n}" }, { "code": null, "e": 6548, "s": 6319, "text": "In the new component that we have created, we need to first import the service that we want and access the methods and properties of the same. Check the code highlighted. todaydate is displayed in the component html as follows −" }, { "code": null, "e": 6571, "s": 6548, "text": "new-cmp.component.html" }, { "code": null, "e": 6647, "s": 6571, "text": "<p> \n {{newcomponent}} \n</p> \n<p> \n Today's Date : {{todaydate}} \n</p>\n" }, { "code": null, "e": 6809, "s": 6647, "text": "The selector of the new component is used in the app.component.html file. The contents from the above html file will be displayed in the browser as shown below −" }, { "code": null, "e": 6945, "s": 6809, "text": "If you change the property of the service in any component, the same is changed in other components too. Let us now see how this works." }, { "code": null, "e": 7159, "s": 6945, "text": "We will define one variable in the service and use it in the parent and the new component. We will again change the property in the parent component and will see if the same is changed in the new component or not." }, { "code": null, "e": 7264, "s": 7159, "text": "In myservice.service.ts, we have created a property and used the same in other parent and new component." }, { "code": null, "e": 7528, "s": 7264, "text": "import { Injectable } from '@angular/core';\n@Injectable({ \n providedIn: 'root' \n}) \nexport class MyserviceService { \n serviceproperty = \"Service Created\"; \n constructor() { } \n showTodayDate() { \n let ndate = new Date(); \n return ndate; \n } \n}" }, { "code": null, "e": 7657, "s": 7528, "text": "Let us now use the serviceproperty variable in other components. In app.component.ts, we are accessing the variable as follows −" }, { "code": null, "e": 8322, "s": 7657, "text": "import { Component } from '@angular/core'; \nimport { MyserviceService } from './myservice.service';\n@Component({\n selector: 'app-root', \n templateUrl: './app.component.html', \n styleUrls: ['./app.component.css'] \n})\nexport class AppComponent { \n title = 'Angular 7 Project!'; \n todaydate; \n componentproperty; \n constructor(private myservice: MyserviceService) {} \n ngOnInit() { \n this.todaydate = this.myservice.showTodayDate(); \n console.log(this.myservice.serviceproperty); \n this.myservice.serviceproperty = \"component created\"; \n // value is changed. this.componentproperty = \n this.myservice.serviceproperty; \n } \n}" }, { "code": null, "e": 8510, "s": 8322, "text": "We will now fetch the variable and work on the console.log. In the next line, we will change the value of the variable to “component created”. We will do the same in new-cmp.component.ts." }, { "code": null, "e": 9102, "s": 8510, "text": "import { Component, OnInit } from '@angular/core'; \nimport { MyserviceService } from './../myservice.service';\n@Component({ \n selector: 'app-new-cmp', \n templateUrl: './new-cmp.component.html', \n styleUrls: ['./new-cmp.component.css'] \n})\nexport class NewCmpComponent implements OnInit { \n todaydate;\n newcomponentproperty; newcomponent = \"Entered in \n newcomponent\"; constructor(private myservice: \n MyserviceService) {} \n ngOnInit() { \n this.todaydate = this.myservice.showTodayDate(); \n this.newcomponentproperty = \n this.myservice.serviceproperty; \n } \n}" }, { "code": null, "e": 9218, "s": 9102, "text": "In the above component, we are not changing anything but directly assigning the property to the component property." }, { "code": null, "e": 9409, "s": 9218, "text": "Now when you execute it in the browser, the service property will be changed since the value of it is changed in app.component.ts and the same will be displayed for the new-cmp.component.ts." }, { "code": null, "e": 9467, "s": 9409, "text": "Also check the value in the console before it is changed." }, { "code": null, "e": 9533, "s": 9467, "text": "Here is the app.component.html and new-cmp.component.html files −" }, { "code": null, "e": 9552, "s": 9533, "text": "app.component.html" }, { "code": null, "e": 9658, "s": 9552, "text": "<h3>{{todaydate}}>/h3> \n<h3> Service Property : {{componentproperty}} </h3> \n<app-new-cmp></app-new-cmp>\n" }, { "code": null, "e": 9681, "s": 9658, "text": "new-cmp.component.html" }, { "code": null, "e": 9805, "s": 9681, "text": "<h3>{{newcomponent}} </h3> \n<h3> Service Property : {{newcomponentproperty}} </h3> \n<h3> Today's Date : {{todaydate}} </h3>" }, { "code": null, "e": 9840, "s": 9805, "text": "\n 16 Lectures \n 1.5 hours \n" }, { "code": null, "e": 9854, "s": 9840, "text": " Anadi Sharma" }, { "code": null, "e": 9889, "s": 9854, "text": "\n 28 Lectures \n 2.5 hours \n" }, { "code": null, "e": 9903, "s": 9889, "text": " Anadi Sharma" }, { "code": null, "e": 9938, "s": 9903, "text": "\n 11 Lectures \n 7.5 hours \n" }, { "code": null, "e": 9958, "s": 9938, "text": " SHIVPRASAD KOIRALA" }, { "code": null, "e": 9993, "s": 9958, "text": "\n 16 Lectures \n 2.5 hours \n" }, { "code": null, "e": 10010, "s": 9993, "text": " Frahaan Hussain" }, { "code": null, "e": 10043, "s": 10010, "text": "\n 69 Lectures \n 5 hours \n" }, { "code": null, "e": 10055, "s": 10043, "text": " Senol Atac" }, { "code": null, "e": 10090, "s": 10055, "text": "\n 53 Lectures \n 3.5 hours \n" }, { "code": null, "e": 10102, "s": 10090, "text": " Senol Atac" }, { "code": null, "e": 10109, "s": 10102, "text": " Print" }, { "code": null, "e": 10120, "s": 10109, "text": " Add Notes" } ]
MySQL - Using Joins
In the previous chapters, we were getting data from one table at a time. This is good enough for simple takes, but in most of the real world MySQL usages, you will often need to get data from multiple tables in a single query. You can use multiple tables in your single SQL query. The act of joining in MySQL refers to smashing two or more tables into a single table. You can use JOINS in the SELECT, UPDATE and DELETE statements to join the MySQL tables. We will see an example of the LEFT JOIN also which is different from the simple MySQL JOIN. Assume we have two tables tcount_tbl and tutorials_tbl, in TUTORIALS. Now take a look at the examples given below − The following examples − root@host# mysql -u root -p password; Enter password:******* mysql> use TUTORIALS; Database changed mysql> SELECT * FROM tcount_tbl; +-----------------+----------------+ | tutorial_author | tutorial_count | +-----------------+----------------+ | mahran | 20 | | mahnaz | NULL | | Jen | NULL | | Gill | 20 | | John Poul | 1 | | Sanjay | 1 | +-----------------+----------------+ 6 rows in set (0.01 sec) mysql> SELECT * from tutorials_tbl; +-------------+----------------+-----------------+-----------------+ | tutorial_id | tutorial_title | tutorial_author | submission_date | +-------------+----------------+-----------------+-----------------+ | 1 | Learn PHP | John Poul | 2007-05-24 | | 2 | Learn MySQL | Abdul S | 2007-05-24 | | 3 | JAVA Tutorial | Sanjay | 2007-05-06 | +-------------+----------------+-----------------+-----------------+ 3 rows in set (0.00 sec) mysql> Now we can write an SQL query to join these two tables. This query will select all the authors from table tutorials_tbl and will pick up the corresponding number of tutorials from the tcount_tbl. mysql> SELECT a.tutorial_id, a.tutorial_author, b.tutorial_count -> FROM tutorials_tbl a, tcount_tbl b -> WHERE a.tutorial_author = b.tutorial_author; +-------------+-----------------+----------------+ | tutorial_id | tutorial_author | tutorial_count | +-------------+-----------------+----------------+ | 1 | John Poul | 1 | | 3 | Sanjay | 1 | +-------------+-----------------+----------------+ 2 rows in set (0.01 sec) mysql> PHP uses mysqli query() or mysql_query() function to get records from a MySQL tables using Joins. This function takes two parameters and returns TRUE on success or FALSE on failure. $mysqli->query($sql,$resultmode) $sql Required - SQL query to get records from multiple tables using Join. $resultmode Optional - Either the constant MYSQLI_USE_RESULT or MYSQLI_STORE_RESULT depending on the desired behavior. By default, MYSQLI_STORE_RESULT is used. First create a table in MySQL using following script and insert two records. create table tcount_tbl( tutorial_author VARCHAR(40) NOT NULL, tutorial_count int ); insert into tcount_tbl values('Mahesh', 3); insert into tcount_tbl values('Suresh', 1); Try the following example to get records from a two tables using Join. − Copy and paste the following example as mysql_example.php − <html> <head> <title>Using joins on MySQL Tables</title> </head> <body> <?php $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 />'); $sql = 'SELECT a.tutorial_id, a.tutorial_author, b.tutorial_count FROM tutorials_tbl a, tcount_tbl b WHERE a.tutorial_author = b.tutorial_author'; $result = $mysqli->query($sql); if ($result->num_rows > 0) { while($row = $result->fetch_assoc()) { printf("Id: %s, Author: %s, Count: %d <br />", $row["tutorial_id"], $row["tutorial_author"], $row["tutorial_count"]); } } else { printf('No record found.<br />'); } mysqli_free_result($result); $mysqli->close(); ?> </body> </html> Access the mysql_example.php deployed on apache web server and verify the output. Connected successfully. Id: 1, Author: Mahesh, Count: 3 Id: 2, Author: Mahesh, Count: 3 Id: 3, Author: Mahesh, Count: 3 Id: 5, Author: Suresh, Count: 1 A MySQL left join is different from a simple join. A MySQL LEFT JOIN gives some extra consideration to the table that is on the left. If I do a LEFT JOIN, I get all the records that match in the same way and IN ADDITION I get an extra record for each unmatched record in the left table of the join: thus ensuring (in my example) that every AUTHOR gets a mention. Try the following example to understand the LEFT JOIN. root@host# mysql -u root -p password; Enter password:******* mysql> use TUTORIALS; Database changed mysql> SELECT a.tutorial_id, a.tutorial_author, b.tutorial_count -> FROM tutorials_tbl a LEFT JOIN tcount_tbl b -> ON a.tutorial_author = b.tutorial_author; +-------------+-----------------+----------------+ | tutorial_id | tutorial_author | tutorial_count | +-------------+-----------------+----------------+ | 1 | John Poul | 1 | | 2 | Abdul S | NULL | | 3 | Sanjay | 1 | +-------------+-----------------+----------------+ 3 rows in set (0.02 sec) You would need to do more practice to become familiar with JOINS. This is slightly a bit complex concept in MySQL/SQL and will become more clear while doing real examples. 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": 2560, "s": 2333, "text": "In the previous chapters, we were getting data from one table at a time. This is good enough for simple takes, but in most of the real world MySQL usages, you will often need to get data from multiple tables in a single query." }, { "code": null, "e": 2701, "s": 2560, "text": "You can use multiple tables in your single SQL query. The act of joining in MySQL refers to smashing two or more tables into a single table." }, { "code": null, "e": 2881, "s": 2701, "text": "You can use JOINS in the SELECT, UPDATE and DELETE statements to join the MySQL tables. We will see an example of the LEFT JOIN also which is different from the simple MySQL JOIN." }, { "code": null, "e": 2997, "s": 2881, "text": "Assume we have two tables tcount_tbl and tutorials_tbl, in TUTORIALS. Now take a look at the examples given below −" }, { "code": null, "e": 3022, "s": 2997, "text": "The following examples −" }, { "code": null, "e": 4157, "s": 3022, "text": "root@host# mysql -u root -p password;\nEnter password:*******\nmysql> use TUTORIALS;\nDatabase changed\nmysql> SELECT * FROM tcount_tbl;\n+-----------------+----------------+\n| tutorial_author | tutorial_count |\n+-----------------+----------------+\n| mahran | 20 | \n| mahnaz | NULL | \n| Jen | NULL | \n| Gill | 20 | \n| John Poul | 1 | \n| Sanjay | 1 | \n+-----------------+----------------+\n6 rows in set (0.01 sec)\nmysql> SELECT * from tutorials_tbl;\n+-------------+----------------+-----------------+-----------------+\n| tutorial_id | tutorial_title | tutorial_author | submission_date |\n+-------------+----------------+-----------------+-----------------+\n| 1 | Learn PHP | John Poul | 2007-05-24 | \n| 2 | Learn MySQL | Abdul S | 2007-05-24 | \n| 3 | JAVA Tutorial | Sanjay | 2007-05-06 | \n+-------------+----------------+-----------------+-----------------+\n3 rows in set (0.00 sec)\nmysql>" }, { "code": null, "e": 4353, "s": 4157, "text": "Now we can write an SQL query to join these two tables. This query will select all the authors from table tutorials_tbl and will pick up the corresponding number of tutorials from the tcount_tbl." }, { "code": null, "e": 4848, "s": 4353, "text": "mysql> SELECT a.tutorial_id, a.tutorial_author, b.tutorial_count\n -> FROM tutorials_tbl a, tcount_tbl b\n -> WHERE a.tutorial_author = b.tutorial_author;\n+-------------+-----------------+----------------+\n| tutorial_id | tutorial_author | tutorial_count |\n+-------------+-----------------+----------------+\n| 1 | John Poul | 1 |\n| 3 | Sanjay | 1 |\n+-------------+-----------------+----------------+\n2 rows in set (0.01 sec)\nmysql>" }, { "code": null, "e": 5030, "s": 4848, "text": "PHP uses mysqli query() or mysql_query() function to get records from a MySQL tables using Joins. This function takes two parameters and returns TRUE on success or FALSE on failure." }, { "code": null, "e": 5064, "s": 5030, "text": "$mysqli->query($sql,$resultmode)\n" }, { "code": null, "e": 5069, "s": 5064, "text": "$sql" }, { "code": null, "e": 5138, "s": 5069, "text": "Required - SQL query to get records from multiple tables using Join." }, { "code": null, "e": 5150, "s": 5138, "text": "$resultmode" }, { "code": null, "e": 5298, "s": 5150, "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": 5375, "s": 5298, "text": "First create a table in MySQL using following script and insert two records." }, { "code": null, "e": 5555, "s": 5375, "text": "create table tcount_tbl(\n tutorial_author VARCHAR(40) NOT NULL,\n tutorial_count int\n);\n\ninsert into tcount_tbl values('Mahesh', 3);\ninsert into tcount_tbl values('Suresh', 1);" }, { "code": null, "e": 5628, "s": 5555, "text": "Try the following example to get records from a two tables using Join. −" }, { "code": null, "e": 5688, "s": 5628, "text": "Copy and paste the following example as mysql_example.php −" }, { "code": null, "e": 6883, "s": 5688, "text": "<html>\n <head>\n <title>Using joins on MySQL Tables</title>\n </head>\n <body>\n <?php\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 $sql = 'SELECT a.tutorial_id, a.tutorial_author, b.tutorial_count\n FROM tutorials_tbl a, tcount_tbl b WHERE a.tutorial_author = b.tutorial_author';\n\t\t \n $result = $mysqli->query($sql);\n \n if ($result->num_rows > 0) {\n while($row = $result->fetch_assoc()) {\n printf(\"Id: %s, Author: %s, Count: %d <br />\", \n $row[\"tutorial_id\"], \n $row[\"tutorial_author\"], \n $row[\"tutorial_count\"]); \n }\n } else {\n printf('No record found.<br />');\n }\n mysqli_free_result($result);\n $mysqli->close();\n ?>\n </body>\n</html>" }, { "code": null, "e": 6965, "s": 6883, "text": "Access the mysql_example.php deployed on apache web server and verify the output." }, { "code": null, "e": 7118, "s": 6965, "text": "Connected successfully.\nId: 1, Author: Mahesh, Count: 3\nId: 2, Author: Mahesh, Count: 3\nId: 3, Author: Mahesh, Count: 3\nId: 5, Author: Suresh, Count: 1\n" }, { "code": null, "e": 7252, "s": 7118, "text": "A MySQL left join is different from a simple join. A MySQL LEFT JOIN gives some extra consideration to the table that is on the left." }, { "code": null, "e": 7481, "s": 7252, "text": "If I do a LEFT JOIN, I get all the records that match in the same way and IN ADDITION I get an extra record for each unmatched record in the left table of the join: thus ensuring (in my example) that every AUTHOR gets a mention." }, { "code": null, "e": 7536, "s": 7481, "text": "Try the following example to understand the LEFT JOIN." }, { "code": null, "e": 8181, "s": 7536, "text": "root@host# mysql -u root -p password;\nEnter password:*******\nmysql> use TUTORIALS;\nDatabase changed\nmysql> SELECT a.tutorial_id, a.tutorial_author, b.tutorial_count\n -> FROM tutorials_tbl a LEFT JOIN tcount_tbl b\n -> ON a.tutorial_author = b.tutorial_author;\n+-------------+-----------------+----------------+\n| tutorial_id | tutorial_author | tutorial_count |\n+-------------+-----------------+----------------+\n| 1 | John Poul | 1 |\n| 2 | Abdul S | NULL |\n| 3 | Sanjay | 1 |\n+-------------+-----------------+----------------+\n3 rows in set (0.02 sec)" }, { "code": null, "e": 8353, "s": 8181, "text": "You would need to do more practice to become familiar with JOINS. This is slightly a bit complex concept in MySQL/SQL and will become more clear while doing real examples." }, { "code": null, "e": 8386, "s": 8353, "text": "\n 31 Lectures \n 6 hours \n" }, { "code": null, "e": 8414, "s": 8386, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 8449, "s": 8414, "text": "\n 84 Lectures \n 5.5 hours \n" }, { "code": null, "e": 8466, "s": 8449, "text": " Frahaan Hussain" }, { "code": null, "e": 8500, "s": 8466, "text": "\n 6 Lectures \n 3.5 hours \n" }, { "code": null, "e": 8535, "s": 8500, "text": " DATAhill Solutions Srinivas Reddy" }, { "code": null, "e": 8569, "s": 8535, "text": "\n 60 Lectures \n 10 hours \n" }, { "code": null, "e": 8597, "s": 8569, "text": " Vijay Kumar Parvatha Reddy" }, { "code": null, "e": 8630, "s": 8597, "text": "\n 10 Lectures \n 1 hours \n" }, { "code": null, "e": 8650, "s": 8630, "text": " Harshit Srivastava" }, { "code": null, "e": 8683, "s": 8650, "text": "\n 25 Lectures \n 4 hours \n" }, { "code": null, "e": 8701, "s": 8683, "text": " Trevoir Williams" }, { "code": null, "e": 8708, "s": 8701, "text": " Print" }, { "code": null, "e": 8719, "s": 8708, "text": " Add Notes" } ]
Print N-bit binary numbers having more 1s than 0s | Practice | GeeksforGeeks
Given a positive integer N, the task is to find all the N bit binary numbers having more than or equal 1’s than 0’s for any prefix of the number. Example 1: Input: N = 2 Output: 11 10 Explanation: 11 and 10 have more than or equal 1's than 0's Example 2: Input: N = 3 Output: 111 110 101 Explanation: 111, 110 and 101 have more than or equal 1's than 0's User Task: Your task is to complete the function NBitBinary() which takes a single number as input and returns the list of strings in decreasing order. You need not take any input or print anything. Expected Time Complexity: O(|2N|) Expected Auxiliary Space: O(2N) Constraints: 1 <= N <= 20 +1 bokonist4 days ago 0.14s C++ solution. Approach is very similar to generate paranthesis question with some added conditions to not generate prefixes . . void generateBinary(int n,vector<string> &ans, int onecount, int zerocount, string curStr) { if(onecount >= zerocount && onecount+zerocount==n) ans.push_back(curStr); if(onecount+zerocount < n) { generateBinary(n, ans, onecount+1, zerocount, curStr+"1"); if(onecount>zerocount) // to meet the prefix condition generateBinary(n, ans, onecount, zerocount+1, curStr+"0"); } } vector<string> NBitBinary(int N) { // Your code goes here vector<string> ans; generateBinary(N, ans, 1,0,"1"); return ans; } 0 premranjan880461 week ago C++ solution; vector<string>v; void solve(int N, string curr, int one, int zero) { if(N==0) { v.push_back(curr); return; } solve(N-1,curr+"1",one+1,zero); if(one>zero) solve(N-1,curr+"0",one,zero+1); } vector<string> NBitBinary(int N){ solve(N,"",0,0); return v;} 0 amanasati11 month ago Python class Solution: def solve(self,n,curr,ones,zeroes,s): if zeroes<=ones and n==ones+zeroes: s.append(curr) return else: if ones+zeroes<n: self.solve(n,curr+"1",ones+1,zeroes,s) if ones>zeroes: self.solve(n,curr+"0",ones,zeroes+1,s) def NBitBinary(self, N): # code here ones=0 zeroes=0 S=[] self.solve(N,"",ones,zeroes,S) return S 0 shrustis1761 month ago C++ solution class Solution{public: void solve(int one, int zero, int n, string op, vector<string> &v){ if(n==0) { v.push_back(op); return; } string op1=op; op1.push_back('1'); solve(one+1, zero, n-1, op1, v); if(one>zero) { string op2=op; op2.push_back('0'); solve( one, zero+1, n-1, op2, v); } return;} vector<string> NBitBinary(int N){ // Your code goes here string op=""; int one=0, zero=0; vector<string> v; solve(one, zero, N, op, v); return v;}}; 0 praveenshakya1 month ago C++ Solution Total Time Taken: 0.2/1.2 void helper(int one, int zero, int n, vector<string>&binary, string output){ if(n == 0){ binary.push_back(output); return; } string op1 = output; op1.push_back('1'); helper(one+1, zero, n-1, binary, op1); if(one > zero){ string op2 = output; op2.push_back('0'); helper(one, zero+1, n-1, binary, op2); } return; } vector<string> NBitBinary(int N){ // Your code goes here int one = 0; int zero = 0; vector<string>binary; string output = ""; helper(one, zero, N, binary, output); return binary;} 0 praveenshakya1 month ago C++ Solution Total Time Taken: 0.2/1.2 void helper(int one, int zero, int n, vector<string>&binary, string output){ if(n == 0){ binary.push_back(output); return; } string op1 = output; op1.push_back('1'); helper(one+1, zero, n-1, binary, op1); if(one > zero){ string op2 = output; op2.push_back('0'); helper(one, zero+1, n-1, binary, op2); } return; } vector<string> NBitBinary(int N){ // Your code goes here int one = 0, zero = 0; vector<string>binary; string output = ""; helper(one, zero, N, binary, output); return binary;} 0 sk77887752 months ago class Solution { ArrayList<String> NBitBinary(int n) { // code here ArrayList<String> res=new ArrayList<>(); solve(res,"",n,0,-1); return res; } void solve(ArrayList<String> res,String str,int n,int n_1,int n_0) { if(n==0) { res.add(str); return; } solve(res,str+"1",n-1,n_1+1,n_0); if(n_1-n_0>1) solve(res,str+"0",n-1,n_1,n_0+1); } } 0 swapnilroy22Premium2 months ago Simply soln using recurssion and observation class Solution { ArrayList<String> NBitBinary(int N) { // code here int count_one=0,count_zero=0; ArrayList<String>res=new ArrayList<>(); generateNBitBinary("",count_one,count_zero,N,res); return res; } public void generateNBitBinary(String op,int c1,int c0,int N,ArrayList<String>ans){ if(c1+c0==N) { ans.add(op); return; } if(c1<N){ generateNBitBinary(op+"1",c1+1,c0,N,ans); } if(c1>c0) { generateNBitBinary(op+"0",c1,c0+1,N,ans); } } } 0 abro3 months ago class Solution{public: void find(int o, int z,int N,string ans,vector<string>&v ){ if(N==0) { v.push_back(ans); return; } if(o==z) { string op1; op1=ans; op1.push_back('1'); find(o+1,z,N-1,op1,v); } if(o>z) { string op1,op2; op1=ans; op2=ans; op1.push_back('1'); op2.push_back('0'); find(o+1,z,N-1,op1,v); find(o,z+1,N-1,op2,v); } } vector<string> NBitBinary(int N){ // Your code goes here vector<string>v; string ans=""; int o=0; int z=0; find(o,z,N,ans,v); return v;}}; 0 kittusingh04243 months ago void Binary(int N,int one,int zero,string ans,vector<string> &v) { if(N==0) { v.push_back(ans); return; } string op=ans; op.push_back('1'); Binary(N-1,one+1,zero,op,v); if(one>zero) { string op1=ans; op1.push_back('0'); Binary(N-1,one,zero+1,op1,v); } } vector<string> NBitBinary(int N) { // Your code goes here vector<string> v; if(N==0) return v; string ans; int one=0; int zero=0; Binary(N,one,zero,ans,v); return v; } 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": 385, "s": 238, "text": "Given a positive integer N, the task is to find all the N bit binary numbers having more than or equal 1’s than 0’s for any prefix of the number. " }, { "code": null, "e": 396, "s": 385, "text": "Example 1:" }, { "code": null, "e": 486, "s": 396, "text": "Input: N = 2\nOutput: 11 10\nExplanation: 11 and 10 have more than \nor equal 1's than 0's\n" }, { "code": null, "e": 497, "s": 486, "text": "Example 2:" }, { "code": null, "e": 600, "s": 497, "text": "Input: N = 3\nOutput: 111 110 101\nExplanation: 111, 110 and 101 have more \nthan or equal 1's than 0's\n" }, { "code": null, "e": 799, "s": 600, "text": "User Task:\nYour task is to complete the function NBitBinary() which takes a single number as input and returns the list of strings in decreasing order. You need not take any input or print anything." }, { "code": null, "e": 865, "s": 799, "text": "Expected Time Complexity: O(|2N|)\nExpected Auxiliary Space: O(2N)" }, { "code": null, "e": 891, "s": 865, "text": "Constraints:\n1 <= N <= 20" }, { "code": null, "e": 894, "s": 891, "text": "+1" }, { "code": null, "e": 913, "s": 894, "text": "bokonist4 days ago" }, { "code": null, "e": 1043, "s": 913, "text": "0.14s C++ solution. Approach is very similar to generate paranthesis question with some added conditions to not generate prefixes" }, { "code": null, "e": 1045, "s": 1043, "text": "." }, { "code": null, "e": 1047, "s": 1045, "text": "." }, { "code": null, "e": 1618, "s": 1047, "text": "void generateBinary(int n,vector<string> &ans, int onecount, int zerocount, string curStr)\n{\n if(onecount >= zerocount && onecount+zerocount==n)\n ans.push_back(curStr);\n \n if(onecount+zerocount < n)\n {\n generateBinary(n, ans, onecount+1, zerocount, curStr+\"1\");\n if(onecount>zerocount) // to meet the prefix condition\n generateBinary(n, ans, onecount, zerocount+1, curStr+\"0\");\n }\n}\nvector<string> NBitBinary(int N)\n{\n // Your code goes here\n vector<string> ans;\n generateBinary(N, ans, 1,0,\"1\");\n return ans;\n}" }, { "code": null, "e": 1620, "s": 1618, "text": "0" }, { "code": null, "e": 1646, "s": 1620, "text": "premranjan880461 week ago" }, { "code": null, "e": 1660, "s": 1646, "text": "C++ solution;" }, { "code": null, "e": 1992, "s": 1662, "text": " vector<string>v; void solve(int N, string curr, int one, int zero) { if(N==0) { v.push_back(curr); return; } solve(N-1,curr+\"1\",one+1,zero); if(one>zero) solve(N-1,curr+\"0\",one,zero+1); } vector<string> NBitBinary(int N){ solve(N,\"\",0,0); return v;}" }, { "code": null, "e": 1994, "s": 1992, "text": "0" }, { "code": null, "e": 2016, "s": 1994, "text": "amanasati11 month ago" }, { "code": null, "e": 2023, "s": 2016, "text": "Python" }, { "code": null, "e": 2504, "s": 2023, "text": "class Solution:\n def solve(self,n,curr,ones,zeroes,s):\n if zeroes<=ones and n==ones+zeroes:\n s.append(curr)\n return \n else:\n if ones+zeroes<n:\n self.solve(n,curr+\"1\",ones+1,zeroes,s)\n if ones>zeroes:\n self.solve(n,curr+\"0\",ones,zeroes+1,s)\n \n\tdef NBitBinary(self, N):\n\t\t# code here\n ones=0\n zeroes=0\n S=[]\n self.solve(N,\"\",ones,zeroes,S)\n return S" }, { "code": null, "e": 2506, "s": 2504, "text": "0" }, { "code": null, "e": 2529, "s": 2506, "text": "shrustis1761 month ago" }, { "code": null, "e": 2542, "s": 2529, "text": "C++ solution" }, { "code": null, "e": 2567, "s": 2544, "text": "class Solution{public:" }, { "code": null, "e": 2895, "s": 2567, "text": "void solve(int one, int zero, int n, string op, vector<string> &v){ if(n==0) { v.push_back(op); return; } string op1=op; op1.push_back('1'); solve(one+1, zero, n-1, op1, v); if(one>zero) { string op2=op; op2.push_back('0'); solve( one, zero+1, n-1, op2, v); } return;}" }, { "code": null, "e": 3070, "s": 2895, "text": "vector<string> NBitBinary(int N){ // Your code goes here string op=\"\"; int one=0, zero=0; vector<string> v; solve(one, zero, N, op, v); return v;}};" }, { "code": null, "e": 3072, "s": 3070, "text": "0" }, { "code": null, "e": 3097, "s": 3072, "text": "praveenshakya1 month ago" }, { "code": null, "e": 3110, "s": 3097, "text": "C++ Solution" }, { "code": null, "e": 3128, "s": 3110, "text": "Total Time Taken:" }, { "code": null, "e": 3136, "s": 3128, "text": "0.2/1.2" }, { "code": null, "e": 3564, "s": 3136, "text": " void helper(int one, int zero, int n, vector<string>&binary, string output){ if(n == 0){ binary.push_back(output); return; } string op1 = output; op1.push_back('1'); helper(one+1, zero, n-1, binary, op1); if(one > zero){ string op2 = output; op2.push_back('0'); helper(one, zero+1, n-1, binary, op2); } return; }" }, { "code": null, "e": 3773, "s": 3564, "text": "vector<string> NBitBinary(int N){ // Your code goes here int one = 0; int zero = 0; vector<string>binary; string output = \"\"; helper(one, zero, N, binary, output); return binary;}" }, { "code": null, "e": 3775, "s": 3773, "text": "0" }, { "code": null, "e": 3800, "s": 3775, "text": "praveenshakya1 month ago" }, { "code": null, "e": 3813, "s": 3800, "text": "C++ Solution" }, { "code": null, "e": 3831, "s": 3813, "text": "Total Time Taken:" }, { "code": null, "e": 3839, "s": 3831, "text": "0.2/1.2" }, { "code": null, "e": 4477, "s": 3839, "text": "void helper(int one, int zero, int n, vector<string>&binary, string output){ if(n == 0){ binary.push_back(output); return; } string op1 = output; op1.push_back('1'); helper(one+1, zero, n-1, binary, op1); if(one > zero){ string op2 = output; op2.push_back('0'); helper(one, zero+1, n-1, binary, op2); } return; } vector<string> NBitBinary(int N){ // Your code goes here int one = 0, zero = 0; vector<string>binary; string output = \"\"; helper(one, zero, N, binary, output); return binary;}" }, { "code": null, "e": 4479, "s": 4477, "text": "0" }, { "code": null, "e": 4501, "s": 4479, "text": "sk77887752 months ago" }, { "code": null, "e": 4957, "s": 4501, "text": "class Solution {\n ArrayList<String> NBitBinary(int n) {\n // code here\n ArrayList<String> res=new ArrayList<>();\n solve(res,\"\",n,0,-1);\n return res;\n }\n \n void solve(ArrayList<String> res,String str,int n,int n_1,int n_0) {\n if(n==0) {\n res.add(str);\n return;\n }\n solve(res,str+\"1\",n-1,n_1+1,n_0);\n if(n_1-n_0>1)\n solve(res,str+\"0\",n-1,n_1,n_0+1);\n }\n}" }, { "code": null, "e": 4959, "s": 4957, "text": "0" }, { "code": null, "e": 4991, "s": 4959, "text": "swapnilroy22Premium2 months ago" }, { "code": null, "e": 5643, "s": 4991, "text": "Simply soln using recurssion and observation\nclass Solution {\n ArrayList<String> NBitBinary(int N) {\n // code here\n int count_one=0,count_zero=0;\n ArrayList<String>res=new ArrayList<>();\n generateNBitBinary(\"\",count_one,count_zero,N,res);\n return res;\n }\n public void generateNBitBinary(String op,int c1,int c0,int N,ArrayList<String>ans){\n if(c1+c0==N)\n {\n ans.add(op);\n return;\n }\n if(c1<N){\n generateNBitBinary(op+\"1\",c1+1,c0,N,ans);\n }\n if(c1>c0)\n {\n generateNBitBinary(op+\"0\",c1,c0+1,N,ans);\n }\n }\n}" }, { "code": null, "e": 5645, "s": 5643, "text": "0" }, { "code": null, "e": 5662, "s": 5645, "text": "abro3 months ago" }, { "code": null, "e": 5685, "s": 5662, "text": "class Solution{public:" }, { "code": null, "e": 6185, "s": 5685, "text": " void find(int o, int z,int N,string ans,vector<string>&v ){ if(N==0) { v.push_back(ans); return; } if(o==z) { string op1; op1=ans; op1.push_back('1'); find(o+1,z,N-1,op1,v); } if(o>z) { string op1,op2; op1=ans; op2=ans; op1.push_back('1'); op2.push_back('0'); find(o+1,z,N-1,op1,v); find(o,z+1,N-1,op2,v); } }" }, { "code": null, "e": 6345, "s": 6185, "text": "vector<string> NBitBinary(int N){ // Your code goes here vector<string>v; string ans=\"\"; int o=0; int z=0; find(o,z,N,ans,v); return v;}};" }, { "code": null, "e": 6347, "s": 6345, "text": "0" }, { "code": null, "e": 6374, "s": 6347, "text": "kittusingh04243 months ago" }, { "code": null, "e": 7001, "s": 6374, "text": " void Binary(int N,int one,int zero,string ans,vector<string> &v)\n {\n if(N==0)\n {\n v.push_back(ans);\n return;\n }\n string op=ans;\n op.push_back('1');\n Binary(N-1,one+1,zero,op,v);\n if(one>zero)\n {\n string op1=ans;\n op1.push_back('0');\n Binary(N-1,one,zero+1,op1,v);\n }\n \n }\n\tvector<string> NBitBinary(int N)\n\t{\n\t // Your code goes here\n\t vector<string> v;\n\t if(N==0) return v;\n\t string ans;\n\t int one=0;\n\t int zero=0;\n\t Binary(N,one,zero,ans,v);\n\t return v;\n\t \n\t}" }, { "code": null, "e": 7147, "s": 7001, "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": 7183, "s": 7147, "text": " Login to access your submissions. " }, { "code": null, "e": 7193, "s": 7183, "text": "\nProblem\n" }, { "code": null, "e": 7203, "s": 7193, "text": "\nContest\n" }, { "code": null, "e": 7266, "s": 7203, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 7414, "s": 7266, "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": 7622, "s": 7414, "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": 7728, "s": 7622, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
I can print out each element of an array by iterating through all values, but can't get a specific element in MongoDB
To fetch a specific element, iterate with forEach(). Let us create a collection with documents − > db.demo742.insertOne({ "userDetails": [ { "userName":"Robert", "CountryName":"UK" }, { "userName":"David", "CountryName":"AUS" } ]} ); { "acknowledged" : true, "insertedId" : ObjectId("5ead790b57bb72a10bcf0677") } Display all documents from a collection with the help of find() method − > db.demo742.find().pretty(); This will produce the following output − { "_id" : ObjectId("5ead790b57bb72a10bcf0677"), "userDetails" : [ { "userName" : "Robert", "CountryName" : "UK" }, { "userName" : "David", "CountryName" : "AUS" } ] } Following is the query to get element from an array − > var ListOfCountryName= {}; > db.demo742.find({}).forEach(function(doc) { ... doc.userDetails.forEach(function (d){ ... ListOfCountryName[d.CountryName] =d.CountryName; ... }); ... } ... ) > printjson(ListOfCountryName); This will produce the following output − { "UK" : "UK", "AUS" : "AUS" }
[ { "code": null, "e": 1159, "s": 1062, "text": "To fetch a specific element, iterate with forEach(). Let us create a collection with documents −" }, { "code": null, "e": 1381, "s": 1159, "text": "> db.demo742.insertOne({ \"userDetails\": [ { \"userName\":\"Robert\", \"CountryName\":\"UK\" }, { \"userName\":\"David\", \"CountryName\":\"AUS\" } ]} );\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5ead790b57bb72a10bcf0677\")\n}" }, { "code": null, "e": 1454, "s": 1381, "text": "Display all documents from a collection with the help of find() method −" }, { "code": null, "e": 1484, "s": 1454, "text": "> db.demo742.find().pretty();" }, { "code": null, "e": 1525, "s": 1484, "text": "This will produce the following output −" }, { "code": null, "e": 1761, "s": 1525, "text": "{\n \"_id\" : ObjectId(\"5ead790b57bb72a10bcf0677\"),\n \"userDetails\" : [\n {\n \"userName\" : \"Robert\",\n \"CountryName\" : \"UK\"\n },\n {\n \"userName\" : \"David\",\n \"CountryName\" : \"AUS\"\n }\n ]\n}" }, { "code": null, "e": 1815, "s": 1761, "text": "Following is the query to get element from an array −" }, { "code": null, "e": 2049, "s": 1815, "text": "> var ListOfCountryName= {};\n> db.demo742.find({}).forEach(function(doc) {\n... doc.userDetails.forEach(function (d){\n... ListOfCountryName[d.CountryName] =d.CountryName;\n... });\n... }\n... )\n> printjson(ListOfCountryName);" }, { "code": null, "e": 2090, "s": 2049, "text": "This will produce the following output −" }, { "code": null, "e": 2121, "s": 2090, "text": "{ \"UK\" : \"UK\", \"AUS\" : \"AUS\" }" } ]
Superior Feature Selection By Combining Multiple Models | Towards Data Science
There are many feature selection methods in Machine Learning. Each one may give different results depending on how you use them, so it is hard to trust a single method entirely. Wouldn’t it be cool to have multiple methods cast their own vote on whether we should keep a feature or not? It would be just like the Random Forests algorithm, where it combines the predictions of multiple weak learners to form a strong one. It turns out, Sklearn has already given us the tools to make such a feature selector on our own. Together, using those tools, we will build a feature selector that accepts an arbitrary number of Sklearn models. All these models will give votes on which features we should keep, and we make decisions by gathering all the votes across models (democracy). Before we move on to building the selector, let’s brush up on some of the topics required. Firstly, almost all Sklearn estimators that yield predictions have either .coef_ and .feature_importances_ attributes after being fitted to the training data. .coef_ attribute mostly occurs in models given under sklearn.linear_model submodule: As the name suggests, the above are coefficients calculated by fitting the line of best fit for Linear Regression. Other models follow a similar pattern and yield the coefficients of their internal equation: Models in sklearn.tree and sklearn.ensemble work differently, and they compute the importance or weight of each feature under .feature_importances_ attribute: Unlike the coefficients of linear models, the weights add up to 1: np.sum(dt.feature_importances_)1.0 Regardless of the model, the feature contributes less and less to the overall prediction as its weight or coefficient decreases. This means that we can drop features with close to 0 coefficients or weights. Recursive Feature Elimination (RFE) is a popular feature selection algorithm. It automatically finds the best number of features to keep to achieve the best performance for a given model. Below is a simple example: The above code is used to find the smallest number of features to achieve the best performance for the Lasso Regression model. After fitting to the training data, RFECV has .support_ attribute which gives a boolean mask, with True values for the features that should be kept: We can then use this mask to subset the original data: X.loc[:, rfecv.support_] The core of the custom feature selector will be this RFECV class. I didn't go into detail about how it works, but my previous article focused on it. I recommend reading it before continuing: towardsdatascience.com We will be using the Ansur Male dataset mainly because it contains many features (98 numeric) about body measurements of 6000 US Army Personnel: We will be trying to predict weight in pounds, and to do that, we need to reduce model complexity — i. e., create a model with as much predictive power as possible using as few features. Currently, there are 98, and we will be trying to decrease that number. Also, we will be dropping the column which records weight in kilograms. ansur.drop("weightkg", axis=1, inplace=True) Our first model will be Lasso Regressor, and we will plug it into RFECV: We are storing the boolean mask generated from the Lasso in lasso_mask, and you are going to see why in a bit. Next, we will do the same for two more models: Linear Regression and GradientBoostingRegressor: Now, we have the votes as boolean masks in three arrays: lasso_mask, gb_mask and lr_mask. Since True/False values represent 1 and 0s, we can add the three arrays: The result will be an array with counts of how many times all models chose each feature. Now, we can set a threshold of votes to decide whether we will keep the feature or not. This threshold depends on how conservative we want to be. We can set a strict threshold where we want the feature to have been chosen by all 3, or we can choose 1 as a threshold to be safe: Now, the final_mask is a boolean array with True values if all of the 3 estimators chose a feature. We can use it to subset the original data: >>> X.loc[:, final_mask].shape(4082, 39) As you can see, the final mask chose 39 columns to keep out of 98. You can use this subset of the dataset to create a less complex model. For example, we will choose a Linear Regression model because we can expect body measurements to be linearly correlated: Even though it takes some work to get to the final results, it will be worth it because the combined power of multiple models can surpass any other feature selection method. We only chose 3 models in the examples, but you can include as many models as you wish to make the results more robust and trustworthy. At this point, a logical step is to wrap all this code in a function or even a custom Sklearn transformer, but custom transformers are a topic for another article. To reinforce the ideas above and give you an outline, let’s review the steps we have taken: Choose an arbitrary number of Sklearn estimators that have either .coef_ or .feature_importnances_ attributes. The more estimators, the more robust the results will be. However, multiple models come at a cost - as RFECV uses cross-validation under the hood, the training times will be computationally expensive for ensemble models and large datasets. Also, make sure to choose estimators depending on the type of the problem - remember to pass either classification or regression-only estimators for RFECV to work.Plug all chosen models into RFECV class and make sure to save each round's boolean mask (accessed via .support_). To speed things up, you can tweak the step parameter so that an arbitrary number of features are dropped in each elimination round.Sum up the masks from all estimators.Set a threshold for the vote count. This threshold depends on how conservative you want to be. Convert the votes array into a boolean mask using this threshold.Subset the original data using the final mask for final model evaluation. Choose an arbitrary number of Sklearn estimators that have either .coef_ or .feature_importnances_ attributes. The more estimators, the more robust the results will be. However, multiple models come at a cost - as RFECV uses cross-validation under the hood, the training times will be computationally expensive for ensemble models and large datasets. Also, make sure to choose estimators depending on the type of the problem - remember to pass either classification or regression-only estimators for RFECV to work. Plug all chosen models into RFECV class and make sure to save each round's boolean mask (accessed via .support_). To speed things up, you can tweak the step parameter so that an arbitrary number of features are dropped in each elimination round. Sum up the masks from all estimators. Set a threshold for the vote count. This threshold depends on how conservative you want to be. Convert the votes array into a boolean mask using this threshold. Subset the original data using the final mask for final model evaluation. How to Use Variance Thresholding For Robust Feature Selection How to Use Pairwise Correlation For Robust Feature Selection Powerful Feature Selection With Recursive Feature Elimination RFECV Sklearn documentation Sklearn Official Feature Selection User Guide Intro to Object-Oriented-Programming For Data Scientists My 6-Part Powerful EDA Template That Speaks of Ultimate Skill How to Use Sklearn Pipelines For Ridiculously Neat Code
[ { "code": null, "e": 690, "s": 172, "text": "There are many feature selection methods in Machine Learning. Each one may give different results depending on how you use them, so it is hard to trust a single method entirely. Wouldn’t it be cool to have multiple methods cast their own vote on whether we should keep a feature or not? It would be just like the Random Forests algorithm, where it combines the predictions of multiple weak learners to form a strong one. It turns out, Sklearn has already given us the tools to make such a feature selector on our own." }, { "code": null, "e": 947, "s": 690, "text": "Together, using those tools, we will build a feature selector that accepts an arbitrary number of Sklearn models. All these models will give votes on which features we should keep, and we make decisions by gathering all the votes across models (democracy)." }, { "code": null, "e": 1197, "s": 947, "text": "Before we move on to building the selector, let’s brush up on some of the topics required. Firstly, almost all Sklearn estimators that yield predictions have either .coef_ and .feature_importances_ attributes after being fitted to the training data." }, { "code": null, "e": 1282, "s": 1197, "text": ".coef_ attribute mostly occurs in models given under sklearn.linear_model submodule:" }, { "code": null, "e": 1490, "s": 1282, "text": "As the name suggests, the above are coefficients calculated by fitting the line of best fit for Linear Regression. Other models follow a similar pattern and yield the coefficients of their internal equation:" }, { "code": null, "e": 1649, "s": 1490, "text": "Models in sklearn.tree and sklearn.ensemble work differently, and they compute the importance or weight of each feature under .feature_importances_ attribute:" }, { "code": null, "e": 1716, "s": 1649, "text": "Unlike the coefficients of linear models, the weights add up to 1:" }, { "code": null, "e": 1751, "s": 1716, "text": "np.sum(dt.feature_importances_)1.0" }, { "code": null, "e": 1958, "s": 1751, "text": "Regardless of the model, the feature contributes less and less to the overall prediction as its weight or coefficient decreases. This means that we can drop features with close to 0 coefficients or weights." }, { "code": null, "e": 2173, "s": 1958, "text": "Recursive Feature Elimination (RFE) is a popular feature selection algorithm. It automatically finds the best number of features to keep to achieve the best performance for a given model. Below is a simple example:" }, { "code": null, "e": 2300, "s": 2173, "text": "The above code is used to find the smallest number of features to achieve the best performance for the Lasso Regression model." }, { "code": null, "e": 2449, "s": 2300, "text": "After fitting to the training data, RFECV has .support_ attribute which gives a boolean mask, with True values for the features that should be kept:" }, { "code": null, "e": 2504, "s": 2449, "text": "We can then use this mask to subset the original data:" }, { "code": null, "e": 2529, "s": 2504, "text": "X.loc[:, rfecv.support_]" }, { "code": null, "e": 2720, "s": 2529, "text": "The core of the custom feature selector will be this RFECV class. I didn't go into detail about how it works, but my previous article focused on it. I recommend reading it before continuing:" }, { "code": null, "e": 2743, "s": 2720, "text": "towardsdatascience.com" }, { "code": null, "e": 2888, "s": 2743, "text": "We will be using the Ansur Male dataset mainly because it contains many features (98 numeric) about body measurements of 6000 US Army Personnel:" }, { "code": null, "e": 3219, "s": 2888, "text": "We will be trying to predict weight in pounds, and to do that, we need to reduce model complexity — i. e., create a model with as much predictive power as possible using as few features. Currently, there are 98, and we will be trying to decrease that number. Also, we will be dropping the column which records weight in kilograms." }, { "code": null, "e": 3264, "s": 3219, "text": "ansur.drop(\"weightkg\", axis=1, inplace=True)" }, { "code": null, "e": 3337, "s": 3264, "text": "Our first model will be Lasso Regressor, and we will plug it into RFECV:" }, { "code": null, "e": 3448, "s": 3337, "text": "We are storing the boolean mask generated from the Lasso in lasso_mask, and you are going to see why in a bit." }, { "code": null, "e": 3544, "s": 3448, "text": "Next, we will do the same for two more models: Linear Regression and GradientBoostingRegressor:" }, { "code": null, "e": 3707, "s": 3544, "text": "Now, we have the votes as boolean masks in three arrays: lasso_mask, gb_mask and lr_mask. Since True/False values represent 1 and 0s, we can add the three arrays:" }, { "code": null, "e": 4074, "s": 3707, "text": "The result will be an array with counts of how many times all models chose each feature. Now, we can set a threshold of votes to decide whether we will keep the feature or not. This threshold depends on how conservative we want to be. We can set a strict threshold where we want the feature to have been chosen by all 3, or we can choose 1 as a threshold to be safe:" }, { "code": null, "e": 4217, "s": 4074, "text": "Now, the final_mask is a boolean array with True values if all of the 3 estimators chose a feature. We can use it to subset the original data:" }, { "code": null, "e": 4258, "s": 4217, "text": ">>> X.loc[:, final_mask].shape(4082, 39)" }, { "code": null, "e": 4517, "s": 4258, "text": "As you can see, the final mask chose 39 columns to keep out of 98. You can use this subset of the dataset to create a less complex model. For example, we will choose a Linear Regression model because we can expect body measurements to be linearly correlated:" }, { "code": null, "e": 4691, "s": 4517, "text": "Even though it takes some work to get to the final results, it will be worth it because the combined power of multiple models can surpass any other feature selection method." }, { "code": null, "e": 4827, "s": 4691, "text": "We only chose 3 models in the examples, but you can include as many models as you wish to make the results more robust and trustworthy." }, { "code": null, "e": 5083, "s": 4827, "text": "At this point, a logical step is to wrap all this code in a function or even a custom Sklearn transformer, but custom transformers are a topic for another article. To reinforce the ideas above and give you an outline, let’s review the steps we have taken:" }, { "code": null, "e": 6113, "s": 5083, "text": "Choose an arbitrary number of Sklearn estimators that have either .coef_ or .feature_importnances_ attributes. The more estimators, the more robust the results will be. However, multiple models come at a cost - as RFECV uses cross-validation under the hood, the training times will be computationally expensive for ensemble models and large datasets. Also, make sure to choose estimators depending on the type of the problem - remember to pass either classification or regression-only estimators for RFECV to work.Plug all chosen models into RFECV class and make sure to save each round's boolean mask (accessed via .support_). To speed things up, you can tweak the step parameter so that an arbitrary number of features are dropped in each elimination round.Sum up the masks from all estimators.Set a threshold for the vote count. This threshold depends on how conservative you want to be. Convert the votes array into a boolean mask using this threshold.Subset the original data using the final mask for final model evaluation." }, { "code": null, "e": 6628, "s": 6113, "text": "Choose an arbitrary number of Sklearn estimators that have either .coef_ or .feature_importnances_ attributes. The more estimators, the more robust the results will be. However, multiple models come at a cost - as RFECV uses cross-validation under the hood, the training times will be computationally expensive for ensemble models and large datasets. Also, make sure to choose estimators depending on the type of the problem - remember to pass either classification or regression-only estimators for RFECV to work." }, { "code": null, "e": 6874, "s": 6628, "text": "Plug all chosen models into RFECV class and make sure to save each round's boolean mask (accessed via .support_). To speed things up, you can tweak the step parameter so that an arbitrary number of features are dropped in each elimination round." }, { "code": null, "e": 6912, "s": 6874, "text": "Sum up the masks from all estimators." }, { "code": null, "e": 7073, "s": 6912, "text": "Set a threshold for the vote count. This threshold depends on how conservative you want to be. Convert the votes array into a boolean mask using this threshold." }, { "code": null, "e": 7147, "s": 7073, "text": "Subset the original data using the final mask for final model evaluation." }, { "code": null, "e": 7209, "s": 7147, "text": "How to Use Variance Thresholding For Robust Feature Selection" }, { "code": null, "e": 7270, "s": 7209, "text": "How to Use Pairwise Correlation For Robust Feature Selection" }, { "code": null, "e": 7332, "s": 7270, "text": "Powerful Feature Selection With Recursive Feature Elimination" }, { "code": null, "e": 7360, "s": 7332, "text": "RFECV Sklearn documentation" }, { "code": null, "e": 7406, "s": 7360, "text": "Sklearn Official Feature Selection User Guide" }, { "code": null, "e": 7463, "s": 7406, "text": "Intro to Object-Oriented-Programming For Data Scientists" }, { "code": null, "e": 7525, "s": 7463, "text": "My 6-Part Powerful EDA Template That Speaks of Ultimate Skill" } ]
Kibana - Dev Tools
We can use Dev Tools to upload data in Elasticsearch, without using Logstash. We can post, put, delete, search the data we want in Kibana using Dev Tools. To create new index in Kibana we can use following command in dev tools − The command to create index is as shown here − PUT /usersdata?pretty Once you execute this, an empty index userdata is created. We are done with the index creation. Now will add the data in the index − You can add data to an index as follows − We will add one more record in usersdata index − So we have 2 records in usersdata index. We can get the details of record 1 as follows − You can get all records as follows − Thus, we can get all the records from usersdata as shown above. To update the record, you can do as follows − We have changed the name from “Ervin Howell” to “Clementine Bauch”. Now we can get all records from the index and see the updated record as follows − You can delete the record as shown here − Now if you see the total records we will have only one record − We can delete the index created as follows − Now if you check the indices available we will not have usersdata index in it as deleted the index. Print Add Notes Bookmark this page
[ { "code": null, "e": 2260, "s": 2105, "text": "We can use Dev Tools to upload data in Elasticsearch, without using Logstash. We can post, put, delete, search the data we want in Kibana using Dev Tools." }, { "code": null, "e": 2334, "s": 2260, "text": "To create new index in Kibana we can use following command in dev tools −" }, { "code": null, "e": 2381, "s": 2334, "text": "The command to create index is as shown here −" }, { "code": null, "e": 2404, "s": 2381, "text": "PUT /usersdata?pretty\n" }, { "code": null, "e": 2463, "s": 2404, "text": "Once you execute this, an empty index userdata is created." }, { "code": null, "e": 2537, "s": 2463, "text": "We are done with the index creation. Now will add the data in the index −" }, { "code": null, "e": 2579, "s": 2537, "text": "You can add data to an index as follows −" }, { "code": null, "e": 2628, "s": 2579, "text": "We will add one more record in usersdata index −" }, { "code": null, "e": 2669, "s": 2628, "text": "So we have 2 records in usersdata index." }, { "code": null, "e": 2717, "s": 2669, "text": "We can get the details of record 1 as follows −" }, { "code": null, "e": 2754, "s": 2717, "text": "You can get all records as follows −" }, { "code": null, "e": 2818, "s": 2754, "text": "Thus, we can get all the records from usersdata as shown above." }, { "code": null, "e": 2864, "s": 2818, "text": "To update the record, you can do as follows −" }, { "code": null, "e": 3014, "s": 2864, "text": "We have changed the name from “Ervin Howell” to “Clementine Bauch”. Now we can get all records from the index and see the updated record as follows −" }, { "code": null, "e": 3056, "s": 3014, "text": "You can delete the record as shown here −" }, { "code": null, "e": 3120, "s": 3056, "text": "Now if you see the total records we will have only one record −" }, { "code": null, "e": 3165, "s": 3120, "text": "We can delete the index created as follows −" }, { "code": null, "e": 3265, "s": 3165, "text": "Now if you check the indices available we will not have usersdata index in it as deleted the index." }, { "code": null, "e": 3272, "s": 3265, "text": " Print" }, { "code": null, "e": 3283, "s": 3272, "text": " Add Notes" } ]
Compute the condition number of a given matrix using NumPy
29 Aug, 2020 In this article, we will use the cond() function of the NumPy package to calculate the condition number of a given matrix. cond() is a function of linear algebra module in NumPy package. Syntax: numpy.linalg.cond(x, p=None) Example 1: Condition Number of 2X2 matrix Python3 # Importing libraryimport numpy as np # Creating a 2X2 matrixmatrix = np.array([[4, 2], [3, 1]]) print("Original matrix:")print(matrix) # Outputresult = np.linalg.cond(matrix) print("Condition number of the matrix:")print(result) Output: Original matrix: [[4 2] [3 1]] Condition number of the matrix: 14.933034373659256 Example 2: Condition Number of 3X3 matrix Python3 # Importing libraryimport numpy as np # Creating a 3X3 matrixmatrix = np.array([[4, 2, 0], [3, 1, 2], [1, 6, 4]]) print("Original matrix:")print(matrix) # Outputresult = np.linalg.cond(matrix) print("Condition number of the matrix:")print(result) Output: Original matrix: [[4 2 0] [3 1 2] [1 6 4]] Condition number of the matrix: 5.347703616656448 Example 3: Condition Number of 4X4 matrix Python3 # Importing libraryimport numpy as np # Creating a 4X4 matrixmatrix = np.array([[4, 1, 4, 2], [3, 1, 2, 0], [3, 5, 7 ,1], [0, 6, 8, 4]]) print("Original matrix:")print(matrix) # Outputresult = np.linalg.cond(matrix) print("Condition number of the matrix:")print(result) Output: Original matrix: [[4 1 4 2] [3 1 2 0] [3 5 7 1] [0 6 8 4]] Condition number of the matrix: 57.34043866386226 Python numpy-Linear Algebra Python-numpy Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n29 Aug, 2020" }, { "code": null, "e": 215, "s": 28, "text": "In this article, we will use the cond() function of the NumPy package to calculate the condition number of a given matrix. cond() is a function of linear algebra module in NumPy package." }, { "code": null, "e": 224, "s": 215, "text": "Syntax: " }, { "code": null, "e": 253, "s": 224, "text": "numpy.linalg.cond(x, p=None)" }, { "code": null, "e": 295, "s": 253, "text": "Example 1: Condition Number of 2X2 matrix" }, { "code": null, "e": 303, "s": 295, "text": "Python3" }, { "code": "# Importing libraryimport numpy as np # Creating a 2X2 matrixmatrix = np.array([[4, 2], [3, 1]]) print(\"Original matrix:\")print(matrix) # Outputresult = np.linalg.cond(matrix) print(\"Condition number of the matrix:\")print(result)", "e": 538, "s": 303, "text": null }, { "code": null, "e": 546, "s": 538, "text": "Output:" }, { "code": null, "e": 630, "s": 546, "text": "Original matrix:\n[[4 2]\n [3 1]]\nCondition number of the matrix:\n14.933034373659256\n" }, { "code": null, "e": 672, "s": 630, "text": "Example 2: Condition Number of 3X3 matrix" }, { "code": null, "e": 680, "s": 672, "text": "Python3" }, { "code": "# Importing libraryimport numpy as np # Creating a 3X3 matrixmatrix = np.array([[4, 2, 0], [3, 1, 2], [1, 6, 4]]) print(\"Original matrix:\")print(matrix) # Outputresult = np.linalg.cond(matrix) print(\"Condition number of the matrix:\")print(result)", "e": 932, "s": 680, "text": null }, { "code": null, "e": 940, "s": 932, "text": "Output:" }, { "code": null, "e": 1036, "s": 940, "text": "Original matrix:\n[[4 2 0]\n [3 1 2]\n [1 6 4]]\nCondition number of the matrix:\n5.347703616656448\n" }, { "code": null, "e": 1078, "s": 1036, "text": "Example 3: Condition Number of 4X4 matrix" }, { "code": null, "e": 1086, "s": 1078, "text": "Python3" }, { "code": "# Importing libraryimport numpy as np # Creating a 4X4 matrixmatrix = np.array([[4, 1, 4, 2], [3, 1, 2, 0], [3, 5, 7 ,1], [0, 6, 8, 4]]) print(\"Original matrix:\")print(matrix) # Outputresult = np.linalg.cond(matrix) print(\"Condition number of the matrix:\")print(result)", "e": 1380, "s": 1086, "text": null }, { "code": null, "e": 1388, "s": 1380, "text": "Output:" }, { "code": null, "e": 1501, "s": 1388, "text": "Original matrix:\n[[4 1 4 2]\n [3 1 2 0]\n [3 5 7 1]\n [0 6 8 4]]\nCondition number of the matrix:\n57.34043866386226\n" }, { "code": null, "e": 1529, "s": 1501, "text": "Python numpy-Linear Algebra" }, { "code": null, "e": 1542, "s": 1529, "text": "Python-numpy" }, { "code": null, "e": 1549, "s": 1542, "text": "Python" } ]
Method Class | getParameterTypes() Method in Java
28 Oct, 2019 Prerequisite : Java.lang.Class class in Java | Set 1, Java.lang.Class class in Java | Set 2 java.lang.reflectMethod class help us to get information of a single method on a class or interface. This class also provides access to the methods of classes and invoke them at runtime. getParameterTypes() method of Method class:For creating methods, many times parameters are needed for those method to work properly. The getParameterTypes() method of Method class returns an array of Class objects that represents the parameter types, declared in method at time of coding. The getParameterTypes() returns an array of length 0 if the method object takes no parameters. Syntax: public Class[] getParameterTypes() Parameters: The method does not take any parameters. Return Value: The method returns an array of Class object that represents the formal parameter types of the method object, in declaration order. Below programs illustrate the getParameterTypes() method of Method class: Program 1: Below program is going to print the details for array of Class objects that represent the formal parameter types of the method object defined in program. /** Program Demonstrate how to apply getParameterTypes() method* of Method Class.*/import java.lang.reflect.Method;public class GFG { // Main method public static void main(String[] args) { try { // Create class object Class classobj = GFG.class; // Get Method Object Method[] methods = classobj.getMethods(); // Iterate through methods for (Method method : methods) { // We are only taking method defined in the demo class // We are not taking other methods of the object class if (method.getName().equals("setValue") || method.getName().equals("getValue") || method.getName().equals("setManyValues")) { // Apply getGenericParameterTypes() method Class[] parameters = method.getParameterTypes(); // Print parameter Types of method Object System.out.println("\nMethod Name : " + method.getName()); System.out.println("No of Parameters : " + parameters.length); System.out.println("Parameter object details:"); for (Class classobject : parameters) { System.out.println(classobject.getName()); } } } } catch (Exception e) { e.printStackTrace(); } } // Method containing two parameter public void setValue(String value1, String value2) { System.out.println("setValue"); } // Method containing no parameter public String getValue() { System.out.println("getValue"); return "getValue"; } // Method containing many parameter public void setManyValues(int value1, double value2, String value3) { System.out.println("setManyValues"); }} Method Name : setManyValues No of Parameters : 3 Parameter object details: int double java.lang.String Method Name : getValue No of Parameters : 0 Parameter object details: Method Name : setValue No of Parameters : 2 Parameter object details: java.lang.String java.lang.String Program 2: We are giving a parameter class object as input and below program going to count number of those type parameter if the Method object contains parameter otherwise program returns 0. /** Program Demonstrate how to apply getParameterTypes() method* of Method Class.*/import java.lang.reflect.Method;import java.lang.reflect.Type; public class GFG3 { // Main method public static void main(String[] args) { try { // Create class object Class classobj = sample.class; Method[] methods = classobj.getMethods(); /* Check whether setManyValues() method contains int parameter or not and print no of string parameter it contains*/ for (Method method : methods) { if (method.getName().equals("setValue")) { int count = containsParameter(method, (Class)java.lang.String.class); System.out.println("No of String "+ "Parameters in setValue(): " + count); } } /* Check whether setManyValues() method contains int parameter or not and print no of string parameter it contains */ for (Method method : methods) { if (method.getName().equals("setManyValues")) { int count = containsParameter(method, (Class) int.class); System.out.println("No of int Parameters"+ " in setManyValues(): " + count); } } } catch (Exception e) { e.printStackTrace(); } } // Count no of parameters contain by method same as passed to method private static int containsParameter(Method method, Class parameterName) { int count = 0; // Get all parameter class objects using getParameterTypes() Class parameters[] = method.getParameterTypes(); for (int i = 0; i < parameters.length; i++) { // Check contains parameter or not if (parameters[i] == parameterName) { count++; } } return count; }}// A simple classclass sample { // Method containing two parameter public void setValue(String value1, String value2) { System.out.println("setValue"); } // Method containing many parameter public void setManyValues(int value1, double value2, String value3) { System.out.println("setManyValues"); }} No of String Parameters in setValue(): 2 No of int Parameters in setManyValues(): 1 Reference:Oracle Doc for getParameterTypes() Akanksha_Rai Java-Functions Java-lang package java-lang-reflect-package Java-Method Class Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to iterate any Map in Java Interfaces in Java HashMap in Java with Examples ArrayList in Java Stream In Java Collections in Java Multidimensional Arrays in Java Singleton Class in Java Stack Class in Java Set in Java
[ { "code": null, "e": 28, "s": 0, "text": "\n28 Oct, 2019" }, { "code": null, "e": 120, "s": 28, "text": "Prerequisite : Java.lang.Class class in Java | Set 1, Java.lang.Class class in Java | Set 2" }, { "code": null, "e": 307, "s": 120, "text": "java.lang.reflectMethod class help us to get information of a single method on a class or interface. This class also provides access to the methods of classes and invoke them at runtime." }, { "code": null, "e": 691, "s": 307, "text": "getParameterTypes() method of Method class:For creating methods, many times parameters are needed for those method to work properly. The getParameterTypes() method of Method class returns an array of Class objects that represents the parameter types, declared in method at time of coding. The getParameterTypes() returns an array of length 0 if the method object takes no parameters." }, { "code": null, "e": 699, "s": 691, "text": "Syntax:" }, { "code": null, "e": 734, "s": 699, "text": "public Class[] getParameterTypes()" }, { "code": null, "e": 787, "s": 734, "text": "Parameters: The method does not take any parameters." }, { "code": null, "e": 932, "s": 787, "text": "Return Value: The method returns an array of Class object that represents the formal parameter types of the method object, in declaration order." }, { "code": null, "e": 1006, "s": 932, "text": "Below programs illustrate the getParameterTypes() method of Method class:" }, { "code": null, "e": 1171, "s": 1006, "text": "Program 1: Below program is going to print the details for array of Class objects that represent the formal parameter types of the method object defined in program." }, { "code": "/** Program Demonstrate how to apply getParameterTypes() method* of Method Class.*/import java.lang.reflect.Method;public class GFG { // Main method public static void main(String[] args) { try { // Create class object Class classobj = GFG.class; // Get Method Object Method[] methods = classobj.getMethods(); // Iterate through methods for (Method method : methods) { // We are only taking method defined in the demo class // We are not taking other methods of the object class if (method.getName().equals(\"setValue\") || method.getName().equals(\"getValue\") || method.getName().equals(\"setManyValues\")) { // Apply getGenericParameterTypes() method Class[] parameters = method.getParameterTypes(); // Print parameter Types of method Object System.out.println(\"\\nMethod Name : \" + method.getName()); System.out.println(\"No of Parameters : \" + parameters.length); System.out.println(\"Parameter object details:\"); for (Class classobject : parameters) { System.out.println(classobject.getName()); } } } } catch (Exception e) { e.printStackTrace(); } } // Method containing two parameter public void setValue(String value1, String value2) { System.out.println(\"setValue\"); } // Method containing no parameter public String getValue() { System.out.println(\"getValue\"); return \"getValue\"; } // Method containing many parameter public void setManyValues(int value1, double value2, String value3) { System.out.println(\"setManyValues\"); }}", "e": 3155, "s": 1171, "text": null }, { "code": null, "e": 3435, "s": 3155, "text": "Method Name : setManyValues\nNo of Parameters : 3\nParameter object details:\nint\ndouble\njava.lang.String\n\nMethod Name : getValue\nNo of Parameters : 0\nParameter object details:\n\nMethod Name : setValue\nNo of Parameters : 2\nParameter object details:\njava.lang.String\njava.lang.String\n" }, { "code": null, "e": 3627, "s": 3435, "text": "Program 2: We are giving a parameter class object as input and below program going to count number of those type parameter if the Method object contains parameter otherwise program returns 0." }, { "code": "/** Program Demonstrate how to apply getParameterTypes() method* of Method Class.*/import java.lang.reflect.Method;import java.lang.reflect.Type; public class GFG3 { // Main method public static void main(String[] args) { try { // Create class object Class classobj = sample.class; Method[] methods = classobj.getMethods(); /* Check whether setManyValues() method contains int parameter or not and print no of string parameter it contains*/ for (Method method : methods) { if (method.getName().equals(\"setValue\")) { int count = containsParameter(method, (Class)java.lang.String.class); System.out.println(\"No of String \"+ \"Parameters in setValue(): \" + count); } } /* Check whether setManyValues() method contains int parameter or not and print no of string parameter it contains */ for (Method method : methods) { if (method.getName().equals(\"setManyValues\")) { int count = containsParameter(method, (Class) int.class); System.out.println(\"No of int Parameters\"+ \" in setManyValues(): \" + count); } } } catch (Exception e) { e.printStackTrace(); } } // Count no of parameters contain by method same as passed to method private static int containsParameter(Method method, Class parameterName) { int count = 0; // Get all parameter class objects using getParameterTypes() Class parameters[] = method.getParameterTypes(); for (int i = 0; i < parameters.length; i++) { // Check contains parameter or not if (parameters[i] == parameterName) { count++; } } return count; }}// A simple classclass sample { // Method containing two parameter public void setValue(String value1, String value2) { System.out.println(\"setValue\"); } // Method containing many parameter public void setManyValues(int value1, double value2, String value3) { System.out.println(\"setManyValues\"); }}", "e": 6047, "s": 3627, "text": null }, { "code": null, "e": 6132, "s": 6047, "text": "No of String Parameters in setValue(): 2\nNo of int Parameters in setManyValues(): 1\n" }, { "code": null, "e": 6177, "s": 6132, "text": "Reference:Oracle Doc for getParameterTypes()" }, { "code": null, "e": 6190, "s": 6177, "text": "Akanksha_Rai" }, { "code": null, "e": 6205, "s": 6190, "text": "Java-Functions" }, { "code": null, "e": 6223, "s": 6205, "text": "Java-lang package" }, { "code": null, "e": 6249, "s": 6223, "text": "java-lang-reflect-package" }, { "code": null, "e": 6267, "s": 6249, "text": "Java-Method Class" }, { "code": null, "e": 6272, "s": 6267, "text": "Java" }, { "code": null, "e": 6277, "s": 6272, "text": "Java" }, { "code": null, "e": 6375, "s": 6277, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 6406, "s": 6375, "text": "How to iterate any Map in Java" }, { "code": null, "e": 6425, "s": 6406, "text": "Interfaces in Java" }, { "code": null, "e": 6455, "s": 6425, "text": "HashMap in Java with Examples" }, { "code": null, "e": 6473, "s": 6455, "text": "ArrayList in Java" }, { "code": null, "e": 6488, "s": 6473, "text": "Stream In Java" }, { "code": null, "e": 6508, "s": 6488, "text": "Collections in Java" }, { "code": null, "e": 6540, "s": 6508, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 6564, "s": 6540, "text": "Singleton Class in Java" }, { "code": null, "e": 6584, "s": 6564, "text": "Stack Class in Java" } ]
What is Dynamic Memory Allocation?
09 Jun, 2021 Resources are always a premium. We have strived to achieve better utilization of resources at all times; that is the premise of our progress. Related to this pursuit, is the concept of memory allocation.Memory has to be allocated to the variables that we create, so that actual variables can be brought to existence. Now there is a constraint as how we think it happens, and how it actually happens.How computer creates a variable? When we think of creating something, we think of creating something from the very scratch, while this isn’t what actually happens when a computer creates a variable ‘X’; to the computer, is more like an allocation, the computer just assigns a memory cell from a lot of pre-existing memory cells to X. It’s like someone named ‘RAJESH’ being allocated to a hotel room from a lot of free or empty pre-existing rooms. This example probably made it very clear as how the computer does the allocation of memory.Now, what is Static Memory Allocation? When we declare variables, we actually are preparing all the variables that will be used, so that the compiler knows that the variable being used is actually an important part of the program that the user wants and not just a rogue symbol floating around. So, when we declare variables, what the compiler actually does is allocate those variables to their rooms (refer to the hotel analogy earlier). Now, if you see, this is being done before the program executes, you can’t allocate variables by this method while the program is executing. CPP // All the variables in below program// are statically allocated.void fun(){ int a;}int main(){ int b; int c[10]} Why do we need to introduce another allocation method if this just gets the job done? Why would we need to allocate memory while the program is executing? Because, even though it isn’t blatantly visible, not being able to allocate memory during run time precludes flexibility and compromises with space efficiency. Specially, those cases where the input isn’t known beforehand, we suffer in terms of inefficient storage use and lack or excess of slots to enter data (given an array or similar data structures to store entries). So, here we define Dynamic Memory Allocation: The mechanism by which storage/memory/cells can be allocated to variables during the run time is called Dynamic Memory Allocation (not to be confused with DMA). So, as we have been going through it all, we can tell that it allocates the memory during the run time which enables us to use as much storage as we want, without worrying about any wastage. Dynamic memory allocation is the process of assigning the memory space during the execution time or the run time. Reasons and Advantage of allocating memory dynamically: When we do not know how much amount of memory would be needed for the program beforehand.When we want data structures without any upper limit of memory space.When you want to use your memory space more efficiently.Example: If you have allocated memory space for a 1D array as array[20] and you end up using only 10 memory spaces then the remaining 10 memory spaces would be wasted and this wasted memory cannot even be utilized by other program variables.Dynamically created lists insertions and deletions can be done very easily just by the manipulation of addresses whereas in case of statically allocated memory insertions and deletions lead to more movements and wastage of memory.When you want you to use the concept of structures and linked list in programming, dynamic memory allocation is a must. When we do not know how much amount of memory would be needed for the program beforehand. When we want data structures without any upper limit of memory space. When you want to use your memory space more efficiently.Example: If you have allocated memory space for a 1D array as array[20] and you end up using only 10 memory spaces then the remaining 10 memory spaces would be wasted and this wasted memory cannot even be utilized by other program variables. Dynamically created lists insertions and deletions can be done very easily just by the manipulation of addresses whereas in case of statically allocated memory insertions and deletions lead to more movements and wastage of memory. When you want you to use the concept of structures and linked list in programming, dynamic memory allocation is a must. CPP int main(){ // Below variables are allocated memory // dynamically. int *ptr1 = new int; int *ptr2 = new int[10]; // Dynamically allocated memory is // deallocated delete ptr1; delete [] ptr2;} There are two types of available memories- stack and heap. Static memory allocation can only be done on stack whereas dynamic memory allocation can be done on both stack and heap. An example of dynamic allocation to be done on the stack is recursion where the functions are put into call stack in order of their occurrence and popped off one by one on reaching the base case. Example of dynamic memory allocation on the heap is: CPP int main(){ // Below variables are allocated memory // dynamically on heap. int *ptr1 = new int; int *ptr2 = new int[10]; // Dynamically allocated memory is // deallocated delete ptr1; delete [] ptr2;} While allocating memory on heap we need to delete the memory manually as memory is not freed(deallocated) by the compiler itself even if the scope of allocated memory finishes(as in case of stack).To conclude the above topic, static memory is something that the compiler allocates in advance. While dynamic memory is something that is controlled by the program during execution. The program may ask more of it or may delete some allocated. Rupali Chawla BabisSarantoglou sunilkannur98 joelmathewv0819 cpp-pointer C++ CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Sorting a vector in C++ Polymorphism in C++ Friend class and function in C++ std::string class in C++ Pair in C++ Standard Template Library (STL) Queue in C++ Standard Template Library (STL) Unordered Sets in C++ Standard Template Library List in C++ Standard Template Library (STL) std::find in C++ Inline Functions in C++
[ { "code": null, "e": 54, "s": 26, "text": "\n09 Jun, 2021" }, { "code": null, "e": 1573, "s": 54, "text": "Resources are always a premium. We have strived to achieve better utilization of resources at all times; that is the premise of our progress. Related to this pursuit, is the concept of memory allocation.Memory has to be allocated to the variables that we create, so that actual variables can be brought to existence. Now there is a constraint as how we think it happens, and how it actually happens.How computer creates a variable? When we think of creating something, we think of creating something from the very scratch, while this isn’t what actually happens when a computer creates a variable ‘X’; to the computer, is more like an allocation, the computer just assigns a memory cell from a lot of pre-existing memory cells to X. It’s like someone named ‘RAJESH’ being allocated to a hotel room from a lot of free or empty pre-existing rooms. This example probably made it very clear as how the computer does the allocation of memory.Now, what is Static Memory Allocation? When we declare variables, we actually are preparing all the variables that will be used, so that the compiler knows that the variable being used is actually an important part of the program that the user wants and not just a rogue symbol floating around. So, when we declare variables, what the compiler actually does is allocate those variables to their rooms (refer to the hotel analogy earlier). Now, if you see, this is being done before the program executes, you can’t allocate variables by this method while the program is executing. " }, { "code": null, "e": 1577, "s": 1573, "text": "CPP" }, { "code": "// All the variables in below program// are statically allocated.void fun(){ int a;}int main(){ int b; int c[10]}", "e": 1697, "s": 1577, "text": null }, { "code": null, "e": 2624, "s": 1697, "text": "Why do we need to introduce another allocation method if this just gets the job done? Why would we need to allocate memory while the program is executing? Because, even though it isn’t blatantly visible, not being able to allocate memory during run time precludes flexibility and compromises with space efficiency. Specially, those cases where the input isn’t known beforehand, we suffer in terms of inefficient storage use and lack or excess of slots to enter data (given an array or similar data structures to store entries). So, here we define Dynamic Memory Allocation: The mechanism by which storage/memory/cells can be allocated to variables during the run time is called Dynamic Memory Allocation (not to be confused with DMA). So, as we have been going through it all, we can tell that it allocates the memory during the run time which enables us to use as much storage as we want, without worrying about any wastage. " }, { "code": null, "e": 2738, "s": 2624, "text": "Dynamic memory allocation is the process of assigning the memory space during the execution time or the run time." }, { "code": null, "e": 2796, "s": 2738, "text": "Reasons and Advantage of allocating memory dynamically: " }, { "code": null, "e": 3601, "s": 2796, "text": "When we do not know how much amount of memory would be needed for the program beforehand.When we want data structures without any upper limit of memory space.When you want to use your memory space more efficiently.Example: If you have allocated memory space for a 1D array as array[20] and you end up using only 10 memory spaces then the remaining 10 memory spaces would be wasted and this wasted memory cannot even be utilized by other program variables.Dynamically created lists insertions and deletions can be done very easily just by the manipulation of addresses whereas in case of statically allocated memory insertions and deletions lead to more movements and wastage of memory.When you want you to use the concept of structures and linked list in programming, dynamic memory allocation is a must." }, { "code": null, "e": 3691, "s": 3601, "text": "When we do not know how much amount of memory would be needed for the program beforehand." }, { "code": null, "e": 3761, "s": 3691, "text": "When we want data structures without any upper limit of memory space." }, { "code": null, "e": 4059, "s": 3761, "text": "When you want to use your memory space more efficiently.Example: If you have allocated memory space for a 1D array as array[20] and you end up using only 10 memory spaces then the remaining 10 memory spaces would be wasted and this wasted memory cannot even be utilized by other program variables." }, { "code": null, "e": 4290, "s": 4059, "text": "Dynamically created lists insertions and deletions can be done very easily just by the manipulation of addresses whereas in case of statically allocated memory insertions and deletions lead to more movements and wastage of memory." }, { "code": null, "e": 4410, "s": 4290, "text": "When you want you to use the concept of structures and linked list in programming, dynamic memory allocation is a must." }, { "code": null, "e": 4416, "s": 4412, "text": "CPP" }, { "code": "int main(){ // Below variables are allocated memory // dynamically. int *ptr1 = new int; int *ptr2 = new int[10]; // Dynamically allocated memory is // deallocated delete ptr1; delete [] ptr2;}", "e": 4627, "s": 4416, "text": null }, { "code": null, "e": 5058, "s": 4627, "text": "There are two types of available memories- stack and heap. Static memory allocation can only be done on stack whereas dynamic memory allocation can be done on both stack and heap. An example of dynamic allocation to be done on the stack is recursion where the functions are put into call stack in order of their occurrence and popped off one by one on reaching the base case. Example of dynamic memory allocation on the heap is: " }, { "code": null, "e": 5062, "s": 5058, "text": "CPP" }, { "code": "int main(){ // Below variables are allocated memory // dynamically on heap. int *ptr1 = new int; int *ptr2 = new int[10]; // Dynamically allocated memory is // deallocated delete ptr1; delete [] ptr2;}", "e": 5281, "s": 5062, "text": null }, { "code": null, "e": 5722, "s": 5281, "text": "While allocating memory on heap we need to delete the memory manually as memory is not freed(deallocated) by the compiler itself even if the scope of allocated memory finishes(as in case of stack).To conclude the above topic, static memory is something that the compiler allocates in advance. While dynamic memory is something that is controlled by the program during execution. The program may ask more of it or may delete some allocated. " }, { "code": null, "e": 5736, "s": 5722, "text": "Rupali Chawla" }, { "code": null, "e": 5753, "s": 5736, "text": "BabisSarantoglou" }, { "code": null, "e": 5767, "s": 5753, "text": "sunilkannur98" }, { "code": null, "e": 5783, "s": 5767, "text": "joelmathewv0819" }, { "code": null, "e": 5795, "s": 5783, "text": "cpp-pointer" }, { "code": null, "e": 5799, "s": 5795, "text": "C++" }, { "code": null, "e": 5803, "s": 5799, "text": "CPP" }, { "code": null, "e": 5901, "s": 5803, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 5925, "s": 5901, "text": "Sorting a vector in C++" }, { "code": null, "e": 5945, "s": 5925, "text": "Polymorphism in C++" }, { "code": null, "e": 5978, "s": 5945, "text": "Friend class and function in C++" }, { "code": null, "e": 6003, "s": 5978, "text": "std::string class in C++" }, { "code": null, "e": 6047, "s": 6003, "text": "Pair in C++ Standard Template Library (STL)" }, { "code": null, "e": 6092, "s": 6047, "text": "Queue in C++ Standard Template Library (STL)" }, { "code": null, "e": 6140, "s": 6092, "text": "Unordered Sets in C++ Standard Template Library" }, { "code": null, "e": 6184, "s": 6140, "text": "List in C++ Standard Template Library (STL)" }, { "code": null, "e": 6201, "s": 6184, "text": "std::find in C++" } ]
JSON with Perl
This chapter covers how to encode and decode JSON objects using Perl programming language. Let's start with preparing the environment to start our programming with Perl for JSON. Before you start encoding and decoding JSON using Perl, you need to install JSON module, which can be obtained from CPAN. Once you downloaded JSON-2.53.tar.gz or any other latest version, follow the steps mentioned below − $tar xvfz JSON-2.53.tar.gz $cd JSON-2.53 $perl Makefile.PL $make $make install Perl encode_json() function converts the given Perl data structure to a UTF-8 encoded, binary string. $json_text = encode_json ($perl_scalar ); or $json_text = JSON->new->utf8->encode($perl_scalar); The following example shows arrays under JSON with Perl − #!/usr/bin/perl use JSON; my %rec_hash = ('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5); my $json = encode_json \%rec_hash; print "$json\n"; While executing, this will produce the following result − {"e":5,"c":3,"a":1,"b":2,"d":4} The following example shows how Perl objects can be converted into JSON − #!/usr/bin/perl package Emp; sub new { my $class = shift; my $self = { name => shift, hobbies => shift, birthdate => shift, }; bless $self, $class; return $self; } sub TO_JSON { return { %{ shift() } }; } package main; use JSON; my $JSON = JSON->new->utf8; $JSON->convert_blessed(1); $e = new Emp( "sachin", "sports", "8/5/1974 12:20:03 pm"); $json = $JSON->encode($e); print "$json\n"; On executing, it will produce the following result − {"birthdate":"8/5/1974 12:20:03 pm","name":"sachin","hobbies":"sports"} Perl decode_json() function is used for decoding JSON in Perl. This function returns the value decoded from json to an appropriate Perl type. $perl_scalar = decode_json $json_text or $perl_scalar = JSON->new->utf8->decode($json_text) The following example shows how Perl can be used to decode JSON objects. Here you will need to install Data::Dumper module if you already do not have it on your machine. #!/usr/bin/perl use JSON; use Data::Dumper; $json = '{"a":1,"b":2,"c":3,"d":4,"e":5}'; $text = decode_json($json); print Dumper($text); On executing, it will produce following result − $VAR1 = { 'e' => 5, 'c' => 3, 'a' => 1, 'b' => 2, 'd' => 4
[ { "code": null, "e": 2093, "s": 1914, "text": "This chapter covers how to encode and decode JSON objects using Perl programming language. Let's start with preparing the environment to start our programming with Perl for JSON." }, { "code": null, "e": 2316, "s": 2093, "text": "Before you start encoding and decoding JSON using Perl, you need to install JSON module, which can be obtained from CPAN. Once you downloaded JSON-2.53.tar.gz or any other latest version, follow the steps mentioned below −" }, { "code": null, "e": 2396, "s": 2316, "text": "$tar xvfz JSON-2.53.tar.gz\n$cd JSON-2.53\n$perl Makefile.PL\n$make\n$make install\n" }, { "code": null, "e": 2498, "s": 2396, "text": "Perl encode_json() function converts the given Perl data structure to a UTF-8 encoded, binary string." }, { "code": null, "e": 2596, "s": 2498, "text": "$json_text = encode_json ($perl_scalar );\nor\n$json_text = JSON->new->utf8->encode($perl_scalar);\n" }, { "code": null, "e": 2654, "s": 2596, "text": "The following example shows arrays under JSON with Perl −" }, { "code": null, "e": 2800, "s": 2654, "text": "#!/usr/bin/perl\nuse JSON;\n\nmy %rec_hash = ('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5);\nmy $json = encode_json \\%rec_hash;\nprint \"$json\\n\";" }, { "code": null, "e": 2858, "s": 2800, "text": "While executing, this will produce the following result −" }, { "code": null, "e": 2891, "s": 2858, "text": "{\"e\":5,\"c\":3,\"a\":1,\"b\":2,\"d\":4}\n" }, { "code": null, "e": 2965, "s": 2891, "text": "The following example shows how Perl objects can be converted into JSON −" }, { "code": null, "e": 3396, "s": 2965, "text": "#!/usr/bin/perl\n\npackage Emp;\nsub new {\n my $class = shift;\n\t\n my $self = {\n name => shift,\n hobbies => shift,\n birthdate => shift,\n };\n\t\n bless $self, $class;\n return $self;\n}\n\nsub TO_JSON { return { %{ shift() } }; }\n\npackage main;\nuse JSON;\n\nmy $JSON = JSON->new->utf8;\n$JSON->convert_blessed(1);\n\n$e = new Emp( \"sachin\", \"sports\", \"8/5/1974 12:20:03 pm\");\n$json = $JSON->encode($e);\nprint \"$json\\n\";" }, { "code": null, "e": 3449, "s": 3396, "text": "On executing, it will produce the following result −" }, { "code": null, "e": 3522, "s": 3449, "text": "{\"birthdate\":\"8/5/1974 12:20:03 pm\",\"name\":\"sachin\",\"hobbies\":\"sports\"}\n" }, { "code": null, "e": 3664, "s": 3522, "text": "Perl decode_json() function is used for decoding JSON in Perl. This function returns the value decoded from json to an appropriate Perl type." }, { "code": null, "e": 3757, "s": 3664, "text": "$perl_scalar = decode_json $json_text\nor\n$perl_scalar = JSON->new->utf8->decode($json_text)\n" }, { "code": null, "e": 3927, "s": 3757, "text": "The following example shows how Perl can be used to decode JSON objects. Here you will need to install Data::Dumper module if you already do not have it on your machine." }, { "code": null, "e": 4066, "s": 3927, "text": "#!/usr/bin/perl\nuse JSON;\nuse Data::Dumper;\n\n$json = '{\"a\":1,\"b\":2,\"c\":3,\"d\":4,\"e\":5}';\n\n$text = decode_json($json);\nprint Dumper($text);" }, { "code": null, "e": 4115, "s": 4066, "text": "On executing, it will produce following result −" } ]
Shadows in Bootstrap with Examples
22 Jun, 2020 Bootstrap Shadow is a property that provides shadow to an element with box-shadow utilities, the intensity can vary from user to user. The shadow property can be very much useful when the user needs to highlight something specifically on the web page. Example 1: The below example represents 4 different shadow intensities from no shadow effect to a high shadow effect. It is implemented using .shadow class within the div element. <!DOCTYPE html><html lang="en"> <head> <!-- Meta tags --> <meta charset="utf-8"> <meta name="viewport" content= "width=device-width, initial-scale=1, shrink-to-fit=no"> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css"> <title>Bootstrap 4 Shadow</title></head> <body bgcolor> <div class="container"> <h2>Shadow</h2> <div class="shadow-none p-3 mb-5 bg-light rounded">No shadow</div> <div class="shadow-sm p-3 mb-5 bg-white rounded">Small shadow</div> <div class="shadow p-3 mb-5 bg-white rounded">Regular shadow</div> <div class="shadow-lg p-3 mb-5 bg-white rounded">Larger shadow</div> </div> <!-- jQuery first, then Popper.js, then Bootstrap JS --> <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"> </script> <!-- Popper --> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"> </script> <!-- Latest compiled and minified Bootstrap JavaScript --> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"> </script></body> </html> Output: Example 2: The below example represents a hover over shadow box i.e. it shows the shadow when the cursor points on the box and when the cursor is removed from the box the shadow disappears. The intensity of the shadow in this example is high. <!DOCTYPE html><html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content= "width=device-width, initial-scale=1"> <title>Bootstrap Shadow</title> <!-- Bootstrap --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous"> <style> .box-shadow-hover:hover { box-shadow: 0 2px 5px 0 rgba(0, 0, 0, 0.5), 0 2px 10px 0 rgba(0, 0, 0, 1); } .pointer { cursor: pointer; } img { width: auto; max-height: 100px; } </style></head> <body> <div class="container"> <div class="row"> <div class="col-md-4 col-sm-6 col-xl-4 my-3"> <div class="card d-block h-100 box-shadow-hover pointer"> <div class="pt-3 h-75p align-items-center d-flex justify-content-center"> <img class="img-fluid w-xs-120p" src="https://media.geeksforgeeks.org/wp-content/uploads/geeksforgeeks-6.png" alt="valkyrie ship image"> </div> <div class="card-body p-4"> <hr> <p> Bootstrap Shadow is a property that provides shadow to an element with box-shadow utilities, the intensity can vary from user to user. The shadow property can be very much useful when the user needs to highlight something specifically on the web page. </p> <p> Bootstrap Shadow is a property that provides shadow to an element with box-shadow utilities, the intensity can vary from user to user. The shadow property can be very much useful when the user needs to highlight something specifically on the web page. </p> </div> </div> </div> </div> </div> <!-- jQuery (necessary for Bootstrap's JavaScript plugins) --> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"> </script> <!-- Include all compiled plugins (below), or include individual files as needed --> <script src="//maxcdn.bootstrapcdn.com/bootstrap/3.3.1/js/bootstrap.min.js"> </script></body> </html> Output: Bootstrap-4 Bootstrap-Misc Picked Bootstrap Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Show Images on Click using HTML ? How to Use Bootstrap with React? How to set vertical alignment in Bootstrap ? Tailwind CSS vs Bootstrap How to toggle password visibility in forms using Bootstrap-icons ? Installation of Node.js on Linux Top 10 Projects For Beginners To Practice HTML and CSS Skills Difference between var, let and const keywords in JavaScript How to insert spaces/tabs in text using HTML/CSS? How to fetch data from an API in ReactJS ?
[ { "code": null, "e": 28, "s": 0, "text": "\n22 Jun, 2020" }, { "code": null, "e": 280, "s": 28, "text": "Bootstrap Shadow is a property that provides shadow to an element with box-shadow utilities, the intensity can vary from user to user. The shadow property can be very much useful when the user needs to highlight something specifically on the web page." }, { "code": null, "e": 460, "s": 280, "text": "Example 1: The below example represents 4 different shadow intensities from no shadow effect to a high shadow effect. It is implemented using .shadow class within the div element." }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <!-- Meta tags --> <meta charset=\"utf-8\"> <meta name=\"viewport\" content= \"width=device-width, initial-scale=1, shrink-to-fit=no\"> <!-- Bootstrap CSS --> <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css\"> <title>Bootstrap 4 Shadow</title></head> <body bgcolor> <div class=\"container\"> <h2>Shadow</h2> <div class=\"shadow-none p-3 mb-5 bg-light rounded\">No shadow</div> <div class=\"shadow-sm p-3 mb-5 bg-white rounded\">Small shadow</div> <div class=\"shadow p-3 mb-5 bg-white rounded\">Regular shadow</div> <div class=\"shadow-lg p-3 mb-5 bg-white rounded\">Larger shadow</div> </div> <!-- jQuery first, then Popper.js, then Bootstrap JS --> <script src=\"https://code.jquery.com/jquery-3.2.1.slim.min.js\" integrity=\"sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN\" crossorigin=\"anonymous\"> </script> <!-- Popper --> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js\" integrity=\"sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q\" crossorigin=\"anonymous\"> </script> <!-- Latest compiled and minified Bootstrap JavaScript --> <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js\" integrity=\"sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl\" crossorigin=\"anonymous\"> </script></body> </html>", "e": 2091, "s": 460, "text": null }, { "code": null, "e": 2099, "s": 2091, "text": "Output:" }, { "code": null, "e": 2342, "s": 2099, "text": "Example 2: The below example represents a hover over shadow box i.e. it shows the shadow when the cursor points on the box and when the cursor is removed from the box the shadow disappears. The intensity of the shadow in this example is high." }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"utf-8\"> <meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\"> <meta name=\"viewport\" content= \"width=device-width, initial-scale=1\"> <title>Bootstrap Shadow</title> <!-- Bootstrap --> <link rel=\"stylesheet\" href=\"https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css\" integrity=\"sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO\" crossorigin=\"anonymous\"> <style> .box-shadow-hover:hover { box-shadow: 0 2px 5px 0 rgba(0, 0, 0, 0.5), 0 2px 10px 0 rgba(0, 0, 0, 1); } .pointer { cursor: pointer; } img { width: auto; max-height: 100px; } </style></head> <body> <div class=\"container\"> <div class=\"row\"> <div class=\"col-md-4 col-sm-6 col-xl-4 my-3\"> <div class=\"card d-block h-100 box-shadow-hover pointer\"> <div class=\"pt-3 h-75p align-items-center d-flex justify-content-center\"> <img class=\"img-fluid w-xs-120p\" src=\"https://media.geeksforgeeks.org/wp-content/uploads/geeksforgeeks-6.png\" alt=\"valkyrie ship image\"> </div> <div class=\"card-body p-4\"> <hr> <p> Bootstrap Shadow is a property that provides shadow to an element with box-shadow utilities, the intensity can vary from user to user. The shadow property can be very much useful when the user needs to highlight something specifically on the web page. </p> <p> Bootstrap Shadow is a property that provides shadow to an element with box-shadow utilities, the intensity can vary from user to user. The shadow property can be very much useful when the user needs to highlight something specifically on the web page. </p> </div> </div> </div> </div> </div> <!-- jQuery (necessary for Bootstrap's JavaScript plugins) --> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js\"> </script> <!-- Include all compiled plugins (below), or include individual files as needed --> <script src=\"//maxcdn.bootstrapcdn.com/bootstrap/3.3.1/js/bootstrap.min.js\"> </script></body> </html>", "e": 5445, "s": 2342, "text": null }, { "code": null, "e": 5453, "s": 5445, "text": "Output:" }, { "code": null, "e": 5465, "s": 5453, "text": "Bootstrap-4" }, { "code": null, "e": 5480, "s": 5465, "text": "Bootstrap-Misc" }, { "code": null, "e": 5487, "s": 5480, "text": "Picked" }, { "code": null, "e": 5497, "s": 5487, "text": "Bootstrap" }, { "code": null, "e": 5514, "s": 5497, "text": "Web Technologies" }, { "code": null, "e": 5612, "s": 5514, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 5653, "s": 5612, "text": "How to Show Images on Click using HTML ?" }, { "code": null, "e": 5686, "s": 5653, "text": "How to Use Bootstrap with React?" }, { "code": null, "e": 5731, "s": 5686, "text": "How to set vertical alignment in Bootstrap ?" }, { "code": null, "e": 5757, "s": 5731, "text": "Tailwind CSS vs Bootstrap" }, { "code": null, "e": 5824, "s": 5757, "text": "How to toggle password visibility in forms using Bootstrap-icons ?" }, { "code": null, "e": 5857, "s": 5824, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 5919, "s": 5857, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 5980, "s": 5919, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 6030, "s": 5980, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
Python | Pandas dataframe.std()
22 Oct, 2019 Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Pandas dataframe.std() function return sample standard deviation over requested axis. By default the standard deviations are normalized by N-1. It is a measure that is used to quantify the amount of variation or dispersion of a set of data values. For more information click here Syntax : DataFrame.std(axis=None, skipna=None, level=None, ddof=1, numeric_only=None, **kwargs) Parameters :axis : {index (0), columns (1)}skipna : Exclude NA/null values. If an entire row/column is NA, the result will be NAlevel : If the axis is a MultiIndex (hierarchical), count along a particular level, collapsing into a Seriesddof : Delta Degrees of Freedom. The divisor used in calculations is N – ddof, where N represents the number of elements.numeric_only : Include only float, int, boolean columns. If None, will attempt to use everything, then use only numeric data. Not implemented for Series. Return : std : Series or DataFrame (if level specified) For link to the CSV file used in the code, click here Example #1: Use std() function to find the standard deviation of data along the index axis. # importing pandas as pdimport pandas as pd # Creating the dataframe df = pd.read_csv("nba.csv") # Print the dataframedf Now find the standard deviation of all the numeric columns in the dataframe. We are going to skip the NaN values in the calculation of the standard deviation. # finding STDdf.std(axis = 0, skipna = True) Output : Example #2: Use std() function to find the standard deviation over the column axis. Find the standard deviation along the column axis. We are going to set skipna to be true. If we do not skip the NaN values then it will result in NaN values. # importing pandas as pdimport pandas as pd # Creating the dataframe df = pd.read_csv("nba.csv") # STD over the column axis.df.std(axis = 1, skipna = True) Output : Akanksha_Rai Python pandas-dataFrame Python pandas-dataFrame-methods Python-pandas Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Different ways to create Pandas Dataframe Enumerate() in Python How to Install PIP on Windows ? *args and **kwargs in Python Python Classes and Objects Python OOPs Concepts Convert integer to string in Python Introduction To PYTHON How to drop one or multiple columns in Pandas Dataframe
[ { "code": null, "e": 28, "s": 0, "text": "\n22 Oct, 2019" }, { "code": null, "e": 242, "s": 28, "text": "Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier." }, { "code": null, "e": 522, "s": 242, "text": "Pandas dataframe.std() function return sample standard deviation over requested axis. By default the standard deviations are normalized by N-1. It is a measure that is used to quantify the amount of variation or dispersion of a set of data values. For more information click here" }, { "code": null, "e": 618, "s": 522, "text": "Syntax : DataFrame.std(axis=None, skipna=None, level=None, ddof=1, numeric_only=None, **kwargs)" }, { "code": null, "e": 1129, "s": 618, "text": "Parameters :axis : {index (0), columns (1)}skipna : Exclude NA/null values. If an entire row/column is NA, the result will be NAlevel : If the axis is a MultiIndex (hierarchical), count along a particular level, collapsing into a Seriesddof : Delta Degrees of Freedom. The divisor used in calculations is N – ddof, where N represents the number of elements.numeric_only : Include only float, int, boolean columns. If None, will attempt to use everything, then use only numeric data. Not implemented for Series." }, { "code": null, "e": 1185, "s": 1129, "text": "Return : std : Series or DataFrame (if level specified)" }, { "code": null, "e": 1239, "s": 1185, "text": "For link to the CSV file used in the code, click here" }, { "code": null, "e": 1331, "s": 1239, "text": "Example #1: Use std() function to find the standard deviation of data along the index axis." }, { "code": "# importing pandas as pdimport pandas as pd # Creating the dataframe df = pd.read_csv(\"nba.csv\") # Print the dataframedf", "e": 1454, "s": 1331, "text": null }, { "code": null, "e": 1613, "s": 1454, "text": "Now find the standard deviation of all the numeric columns in the dataframe. We are going to skip the NaN values in the calculation of the standard deviation." }, { "code": "# finding STDdf.std(axis = 0, skipna = True)", "e": 1658, "s": 1613, "text": null }, { "code": null, "e": 1668, "s": 1658, "text": "Output : " }, { "code": null, "e": 1752, "s": 1668, "text": "Example #2: Use std() function to find the standard deviation over the column axis." }, { "code": null, "e": 1910, "s": 1752, "text": "Find the standard deviation along the column axis. We are going to set skipna to be true. If we do not skip the NaN values then it will result in NaN values." }, { "code": "# importing pandas as pdimport pandas as pd # Creating the dataframe df = pd.read_csv(\"nba.csv\") # STD over the column axis.df.std(axis = 1, skipna = True)", "e": 2068, "s": 1910, "text": null }, { "code": null, "e": 2077, "s": 2068, "text": "Output :" }, { "code": null, "e": 2090, "s": 2077, "text": "Akanksha_Rai" }, { "code": null, "e": 2114, "s": 2090, "text": "Python pandas-dataFrame" }, { "code": null, "e": 2146, "s": 2114, "text": "Python pandas-dataFrame-methods" }, { "code": null, "e": 2160, "s": 2146, "text": "Python-pandas" }, { "code": null, "e": 2167, "s": 2160, "text": "Python" }, { "code": null, "e": 2265, "s": 2167, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2283, "s": 2265, "text": "Python Dictionary" }, { "code": null, "e": 2325, "s": 2283, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 2347, "s": 2325, "text": "Enumerate() in Python" }, { "code": null, "e": 2379, "s": 2347, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2408, "s": 2379, "text": "*args and **kwargs in Python" }, { "code": null, "e": 2435, "s": 2408, "text": "Python Classes and Objects" }, { "code": null, "e": 2456, "s": 2435, "text": "Python OOPs Concepts" }, { "code": null, "e": 2492, "s": 2456, "text": "Convert integer to string in Python" }, { "code": null, "e": 2515, "s": 2492, "text": "Introduction To PYTHON" } ]
Java Program to List all Files in a Directory and Nested Sub-Directories
26 Jan, 2022 Prerequisites: File class Given a main directory/folder, list all the files from it, and if this directory has other nested sub-directories, list files from them. It is pretty easy to observe a simple recursion pattern in the above problem. Algorithm : Create a File object for the main directory.Get an array of files for the main directory.If array[i] is a file:Print out the file name.If array[i] is a directory :Print out directory name.Get array of files for current sub-directory.Repeat the step 3 and 4 with current sub-directory.Repeat the step 3 and 4 with next array[i]. Create a File object for the main directory. Get an array of files for the main directory. If array[i] is a file:Print out the file name. Print out the file name. If array[i] is a directory :Print out directory name.Get array of files for current sub-directory.Repeat the step 3 and 4 with current sub-directory. Print out directory name. Get array of files for current sub-directory. Repeat the step 3 and 4 with current sub-directory. Repeat the step 3 and 4 with next array[i]. Example 1: Java // Java program to print all files// in a folder(and sub-folders) import java.io.File; public class GFG { static void RecursivePrint(File[] arr, int index, int level) { // terminate condition if (index == arr.length) return; // tabs for internal levels for (int i = 0; i < level; i++) System.out.print("\t"); // for files if (arr[index].isFile()) System.out.println(arr[index].getName()); // for sub-directories else if (arr[index].isDirectory()) { System.out.println("[" + arr[index].getName() + "]"); // recursion for sub-directories RecursivePrint(arr[index].listFiles(), 0, level + 1); } // recursion for main directory RecursivePrint(arr, ++index, level); } // Driver Method public static void main(String[] args) { // Provide full path for directory(change // accordingly) String maindirpath = "C:\\Users\\Gaurav Miglani\\Desktop\\Test"; // File object File maindir = new File(maindirpath); if (maindir.exists() && maindir.isDirectory()) { // array for files and sub-directories // of directory pointed by maindir File arr[] = maindir.listFiles(); System.out.println( "**********************************************"); System.out.println( "Files from main directory : " + maindir); System.out.println( "**********************************************"); // Calling recursive method RecursivePrint(arr, 0, 0); } }} Output: ********************************************** Files from main directory : C:\Users\Gaurav Miglani\Desktop\Test ********************************************** Cormen.pdf Extra-Items.pdf XYZ.pdf [Docs] A.docx B.doc C.docx ABC.pdf JKL.pdf [sheets] XXX.csv YYY.csv results.pdf [Resumes] [Before2016] Resume2015.doc Resume2016.doc [Before2014] Resume2014.doc Resume2017.doc Resume2017.pdf QA.doc Testing.pdf Example 2: Below is another recursive program. Here we use recursion only for nested sub-directories. For main directory files, we use foreach loop. Java // Recursive Java program to print all files// in a folder(and sub-folders) import java.io.File; public class GFG { static void RecursivePrint(File[] arr, int level) { // for-each loop for main directory files for (File f : arr) { // tabs for internal levels for (int i = 0; i < level; i++) System.out.print("\t"); if (f.isFile()) System.out.println(f.getName()); else if (f.isDirectory()) { System.out.println("[" + f.getName() + "]"); // recursion for sub-directories RecursivePrint(f.listFiles(), level + 1); } } } // Driver Method public static void main(String[] args) { // Provide full path for directory(change // accordingly) String maindirpath = "C:\\Users\\Gaurav Miglani\\Desktop\\Test"; // File object File maindir = new File(maindirpath); if (maindir.exists() && maindir.isDirectory()) { // array for files and sub-directories // of directory pointed by maindir File arr[] = maindir.listFiles(); System.out.println( "**********************************************"); System.out.println( "Files from main directory : " + maindir); System.out.println( "**********************************************"); // Calling recursive method RecursivePrint(arr, 0); } }} Output: ********************************************** Files from main directory : C:\Users\Gaurav Miglani\Desktop\Test ********************************************** Cormen.pdf Extra-Items.pdf XYZ.pdf [Docs] A.docx B.doc C.docx ABC.pdf JKL.pdf [sheets] XXX.csv YYY.csv results.pdf [Resumes] [Before2016] Resume2015.doc Resume2016.doc [Before2014] Resume2014.doc Resume2017.doc Resume2017.pdf QA.doc Testing.pdf Example 3 – Below is another iterative program to get all file name using Stack DS Java // Iterative Program to get all file names in Directory and// SubDirectory import java.io.*; class GFG { public static void main(String[] args) { // provide complete path for directory(to be changed // accordingly) String mainDir = "c:\\GFG\\example"; // File object File file = new File(mainDir); Stack<File> s = new Stack<>(); s.push(file); // initially stack is not empty System.out.println("Content of Directory " + mainDir + " is"); while (!s.empty()) { File tmpF = s.pop(); // check if it is a file or not if (tmpF.isFile()) { // print file name can code here according // to our need System.out.println(tmpF.getName()); } else if (tmpF.isDirectory()) { // It's an directory hence list and push all // files in stack File[] f = tmpF.listFiles(); for (File fpp : f) { s.push(fpp); } } // else if ends here } // stack is not empty loop ends here } // main function ends here} Output: Content of Directory c:\GFG\example is example.txt testTwo.java testTwo.class test.java test.class test.java eg1.java eg1.class test.java test.class Students.java Students.class NOTE: The above code won’t compile on online IDE to compile and execute it download in your local system. This article is contributed by Gaurav Miglani. If you like GeeksforGeeks and would like to contribute, you can write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect or you want to share more information about the topic discussed above. nishkarshgandhi harshsethi2000 java-file-handling Java-I/O Java-List-Programs Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Interfaces in Java Queue Interface In Java Multidimensional Arrays in Java HashMap in Java with Examples Math pow() method in Java with Example PriorityQueue in Java Stack Class in Java List Interface in Java with Examples Initialize an ArrayList in Java ArrayList in Java
[ { "code": null, "e": 52, "s": 24, "text": "\n26 Jan, 2022" }, { "code": null, "e": 78, "s": 52, "text": "Prerequisites: File class" }, { "code": null, "e": 293, "s": 78, "text": "Given a main directory/folder, list all the files from it, and if this directory has other nested sub-directories, list files from them. It is pretty easy to observe a simple recursion pattern in the above problem." }, { "code": null, "e": 306, "s": 293, "text": "Algorithm : " }, { "code": null, "e": 634, "s": 306, "text": "Create a File object for the main directory.Get an array of files for the main directory.If array[i] is a file:Print out the file name.If array[i] is a directory :Print out directory name.Get array of files for current sub-directory.Repeat the step 3 and 4 with current sub-directory.Repeat the step 3 and 4 with next array[i]." }, { "code": null, "e": 679, "s": 634, "text": "Create a File object for the main directory." }, { "code": null, "e": 725, "s": 679, "text": "Get an array of files for the main directory." }, { "code": null, "e": 772, "s": 725, "text": "If array[i] is a file:Print out the file name." }, { "code": null, "e": 797, "s": 772, "text": "Print out the file name." }, { "code": null, "e": 947, "s": 797, "text": "If array[i] is a directory :Print out directory name.Get array of files for current sub-directory.Repeat the step 3 and 4 with current sub-directory." }, { "code": null, "e": 973, "s": 947, "text": "Print out directory name." }, { "code": null, "e": 1019, "s": 973, "text": "Get array of files for current sub-directory." }, { "code": null, "e": 1071, "s": 1019, "text": "Repeat the step 3 and 4 with current sub-directory." }, { "code": null, "e": 1115, "s": 1071, "text": "Repeat the step 3 and 4 with next array[i]." }, { "code": null, "e": 1126, "s": 1115, "text": "Example 1:" }, { "code": null, "e": 1131, "s": 1126, "text": "Java" }, { "code": "// Java program to print all files// in a folder(and sub-folders) import java.io.File; public class GFG { static void RecursivePrint(File[] arr, int index, int level) { // terminate condition if (index == arr.length) return; // tabs for internal levels for (int i = 0; i < level; i++) System.out.print(\"\\t\"); // for files if (arr[index].isFile()) System.out.println(arr[index].getName()); // for sub-directories else if (arr[index].isDirectory()) { System.out.println(\"[\" + arr[index].getName() + \"]\"); // recursion for sub-directories RecursivePrint(arr[index].listFiles(), 0, level + 1); } // recursion for main directory RecursivePrint(arr, ++index, level); } // Driver Method public static void main(String[] args) { // Provide full path for directory(change // accordingly) String maindirpath = \"C:\\\\Users\\\\Gaurav Miglani\\\\Desktop\\\\Test\"; // File object File maindir = new File(maindirpath); if (maindir.exists() && maindir.isDirectory()) { // array for files and sub-directories // of directory pointed by maindir File arr[] = maindir.listFiles(); System.out.println( \"**********************************************\"); System.out.println( \"Files from main directory : \" + maindir); System.out.println( \"**********************************************\"); // Calling recursive method RecursivePrint(arr, 0, 0); } }}", "e": 2888, "s": 1131, "text": null }, { "code": null, "e": 2900, "s": 2891, "text": "Output: " }, { "code": null, "e": 3382, "s": 2902, "text": "**********************************************\nFiles from main directory : C:\\Users\\Gaurav Miglani\\Desktop\\Test\n**********************************************\nCormen.pdf\nExtra-Items.pdf\nXYZ.pdf\n[Docs]\n A.docx\n B.doc\n C.docx\nABC.pdf\nJKL.pdf\n[sheets]\n XXX.csv\n YYY.csv\nresults.pdf\n[Resumes]\n [Before2016]\n Resume2015.doc\n Resume2016.doc\n [Before2014]\n Resume2014.doc\n Resume2017.doc\n Resume2017.pdf\n QA.doc\nTesting.pdf" }, { "code": null, "e": 3533, "s": 3384, "text": "Example 2: Below is another recursive program. Here we use recursion only for nested sub-directories. For main directory files, we use foreach loop." }, { "code": null, "e": 3540, "s": 3535, "text": "Java" }, { "code": "// Recursive Java program to print all files// in a folder(and sub-folders) import java.io.File; public class GFG { static void RecursivePrint(File[] arr, int level) { // for-each loop for main directory files for (File f : arr) { // tabs for internal levels for (int i = 0; i < level; i++) System.out.print(\"\\t\"); if (f.isFile()) System.out.println(f.getName()); else if (f.isDirectory()) { System.out.println(\"[\" + f.getName() + \"]\"); // recursion for sub-directories RecursivePrint(f.listFiles(), level + 1); } } } // Driver Method public static void main(String[] args) { // Provide full path for directory(change // accordingly) String maindirpath = \"C:\\\\Users\\\\Gaurav Miglani\\\\Desktop\\\\Test\"; // File object File maindir = new File(maindirpath); if (maindir.exists() && maindir.isDirectory()) { // array for files and sub-directories // of directory pointed by maindir File arr[] = maindir.listFiles(); System.out.println( \"**********************************************\"); System.out.println( \"Files from main directory : \" + maindir); System.out.println( \"**********************************************\"); // Calling recursive method RecursivePrint(arr, 0); } }}", "e": 5084, "s": 3540, "text": null }, { "code": null, "e": 5096, "s": 5087, "text": "Output: " }, { "code": null, "e": 5578, "s": 5098, "text": "**********************************************\nFiles from main directory : C:\\Users\\Gaurav Miglani\\Desktop\\Test\n**********************************************\nCormen.pdf\nExtra-Items.pdf\nXYZ.pdf\n[Docs]\n A.docx\n B.doc\n C.docx\nABC.pdf\nJKL.pdf\n[sheets]\n XXX.csv\n YYY.csv\nresults.pdf\n[Resumes]\n [Before2016]\n Resume2015.doc\n Resume2016.doc\n [Before2014]\n Resume2014.doc\n Resume2017.doc\n Resume2017.pdf\n QA.doc\nTesting.pdf" }, { "code": null, "e": 5590, "s": 5578, "text": "Example 3 –" }, { "code": null, "e": 5661, "s": 5590, "text": "Below is another iterative program to get all file name using Stack DS" }, { "code": null, "e": 5666, "s": 5661, "text": "Java" }, { "code": "// Iterative Program to get all file names in Directory and// SubDirectory import java.io.*; class GFG { public static void main(String[] args) { // provide complete path for directory(to be changed // accordingly) String mainDir = \"c:\\\\GFG\\\\example\"; // File object File file = new File(mainDir); Stack<File> s = new Stack<>(); s.push(file); // initially stack is not empty System.out.println(\"Content of Directory \" + mainDir + \" is\"); while (!s.empty()) { File tmpF = s.pop(); // check if it is a file or not if (tmpF.isFile()) { // print file name can code here according // to our need System.out.println(tmpF.getName()); } else if (tmpF.isDirectory()) { // It's an directory hence list and push all // files in stack File[] f = tmpF.listFiles(); for (File fpp : f) { s.push(fpp); } } // else if ends here } // stack is not empty loop ends here } // main function ends here}", "e": 6863, "s": 5666, "text": null }, { "code": null, "e": 6871, "s": 6863, "text": "Output:" }, { "code": null, "e": 7049, "s": 6871, "text": "Content of Directory c:\\GFG\\example is\nexample.txt\ntestTwo.java\ntestTwo.class\ntest.java\ntest.class\ntest.java\neg1.java\neg1.class\ntest.java\ntest.class\nStudents.java\nStudents.class" }, { "code": null, "e": 7155, "s": 7049, "text": "NOTE: The above code won’t compile on online IDE to compile and execute it download in your local system." }, { "code": null, "e": 7572, "s": 7155, "text": "This article is contributed by Gaurav Miglani. If you like GeeksforGeeks and would like to contribute, you can write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect or you want to share more information about the topic discussed above." }, { "code": null, "e": 7590, "s": 7574, "text": "nishkarshgandhi" }, { "code": null, "e": 7605, "s": 7590, "text": "harshsethi2000" }, { "code": null, "e": 7624, "s": 7605, "text": "java-file-handling" }, { "code": null, "e": 7633, "s": 7624, "text": "Java-I/O" }, { "code": null, "e": 7652, "s": 7633, "text": "Java-List-Programs" }, { "code": null, "e": 7657, "s": 7652, "text": "Java" }, { "code": null, "e": 7662, "s": 7657, "text": "Java" }, { "code": null, "e": 7760, "s": 7662, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 7779, "s": 7760, "text": "Interfaces in Java" }, { "code": null, "e": 7803, "s": 7779, "text": "Queue Interface In Java" }, { "code": null, "e": 7835, "s": 7803, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 7865, "s": 7835, "text": "HashMap in Java with Examples" }, { "code": null, "e": 7904, "s": 7865, "text": "Math pow() method in Java with Example" }, { "code": null, "e": 7926, "s": 7904, "text": "PriorityQueue in Java" }, { "code": null, "e": 7946, "s": 7926, "text": "Stack Class in Java" }, { "code": null, "e": 7983, "s": 7946, "text": "List Interface in Java with Examples" }, { "code": null, "e": 8015, "s": 7983, "text": "Initialize an ArrayList in Java" } ]
Matplotlib.figure.Figure.show() in Python
03 May, 2020 Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. The figure module provides the top-level Artist, the Figure, which contains all the plot elements. This module is used to control the default spacing of the subplots and top level container for all plot elements. The show() method figure module of matplotlib library is used to display the figure window. Syntax: show(self, warn=True) Parameters: This method accept the following parameters that are discussed below: warn : This parameter contains the boolean value. Returns: This method does not returns any value. Below examples illustrate the matplotlib.figure.Figure.show() function in matplotlib.figure: Example 1: # Implementation of matplotlib functionimport matplotlib.pyplot as pltimport numpy as np fig = plt.figure()x = np.arange(20) / 50y = (x + 0.1)*2 val1 = [True, False] * 10val2 = [False, True] * 10 plt.errorbar(x, y, xerr = 0.1, xlolims = True, label ='Line 1')y = (x + 0.3)*3 plt.errorbar(x + 0.6, y, xerr = 0.1, xuplims = val1, xlolims = val2, label ='Line 2') y = (x + 0.6)*4plt.errorbar(x + 1.2, y, xerr = 0.1, xuplims = True, label ='Line 3') plt.legend() fig.suptitle("""matplotlib.figure.Figure.show()function Example\n\n""", fontweight ="bold") fig.show() Output: Example 2: # Implementation of matplotlib functionimport numpy as npimport matplotlib.pyplot as plt x = np.linspace(0, 10, 500)y = np.sin(x**2)+np.cos(x) fig, ax = plt.subplots() ax.plot(x, y, label ='Line 1') ax.plot(x, y - 0.6, label ='Line 2') ax.legend() fig.suptitle("""matplotlib.figure.Figure.show()function Example\n\n""", fontweight ="bold") fig.show() Output: Matplotlib figure-class Python-matplotlib Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Python Classes and Objects Python OOPs Concepts Introduction To PYTHON How to drop one or multiple columns in Pandas Dataframe Python | os.path.join() method Check if element exists in list in Python How To Convert Python Dictionary To JSON? Python | Get unique values from a list Create a directory in Python
[ { "code": null, "e": 28, "s": 0, "text": "\n03 May, 2020" }, { "code": null, "e": 339, "s": 28, "text": "Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. The figure module provides the top-level Artist, the Figure, which contains all the plot elements. This module is used to control the default spacing of the subplots and top level container for all plot elements." }, { "code": null, "e": 431, "s": 339, "text": "The show() method figure module of matplotlib library is used to display the figure window." }, { "code": null, "e": 461, "s": 431, "text": "Syntax: show(self, warn=True)" }, { "code": null, "e": 543, "s": 461, "text": "Parameters: This method accept the following parameters that are discussed below:" }, { "code": null, "e": 593, "s": 543, "text": "warn : This parameter contains the boolean value." }, { "code": null, "e": 642, "s": 593, "text": "Returns: This method does not returns any value." }, { "code": null, "e": 735, "s": 642, "text": "Below examples illustrate the matplotlib.figure.Figure.show() function in matplotlib.figure:" }, { "code": null, "e": 746, "s": 735, "text": "Example 1:" }, { "code": "# Implementation of matplotlib functionimport matplotlib.pyplot as pltimport numpy as np fig = plt.figure()x = np.arange(20) / 50y = (x + 0.1)*2 val1 = [True, False] * 10val2 = [False, True] * 10 plt.errorbar(x, y, xerr = 0.1, xlolims = True, label ='Line 1')y = (x + 0.3)*3 plt.errorbar(x + 0.6, y, xerr = 0.1, xuplims = val1, xlolims = val2, label ='Line 2') y = (x + 0.6)*4plt.errorbar(x + 1.2, y, xerr = 0.1, xuplims = True, label ='Line 3') plt.legend() fig.suptitle(\"\"\"matplotlib.figure.Figure.show()function Example\\n\\n\"\"\", fontweight =\"bold\") fig.show() ", "e": 1447, "s": 746, "text": null }, { "code": null, "e": 1455, "s": 1447, "text": "Output:" }, { "code": null, "e": 1466, "s": 1455, "text": "Example 2:" }, { "code": "# Implementation of matplotlib functionimport numpy as npimport matplotlib.pyplot as plt x = np.linspace(0, 10, 500)y = np.sin(x**2)+np.cos(x) fig, ax = plt.subplots() ax.plot(x, y, label ='Line 1') ax.plot(x, y - 0.6, label ='Line 2') ax.legend() fig.suptitle(\"\"\"matplotlib.figure.Figure.show()function Example\\n\\n\"\"\", fontweight =\"bold\") fig.show() ", "e": 1833, "s": 1466, "text": null }, { "code": null, "e": 1841, "s": 1833, "text": "Output:" }, { "code": null, "e": 1865, "s": 1841, "text": "Matplotlib figure-class" }, { "code": null, "e": 1883, "s": 1865, "text": "Python-matplotlib" }, { "code": null, "e": 1890, "s": 1883, "text": "Python" }, { "code": null, "e": 1988, "s": 1890, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2020, "s": 1988, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2047, "s": 2020, "text": "Python Classes and Objects" }, { "code": null, "e": 2068, "s": 2047, "text": "Python OOPs Concepts" }, { "code": null, "e": 2091, "s": 2068, "text": "Introduction To PYTHON" }, { "code": null, "e": 2147, "s": 2091, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 2178, "s": 2147, "text": "Python | os.path.join() method" }, { "code": null, "e": 2220, "s": 2178, "text": "Check if element exists in list in Python" }, { "code": null, "e": 2262, "s": 2220, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 2301, "s": 2262, "text": "Python | Get unique values from a list" } ]
Convert values of an Object to Logical Vector in R Programming – as.logical() Function
08 Nov, 2021 as.logical() function in R Language is used to convert an object to a logical vector. Syntax: as.logical(x)Parameters: x: Numeric or character object R # R Program to convert# an object to logical vector # Creating a vectorx <- c(1, 2, 3, 0, 1.4, NA) # Calling as.logical() functionas.logical(T)as.logical("F")as.logical(2)as.logical(x) Output: [1] TRUE [1] FALSE [1] TRUE [1] TRUE TRUE TRUE FALSE TRUE NA R # R Program to convert# an object to logical vector # Creating matrixx1 <- matrix(c(1:4), 2, 2)x2 <- matrix(c(2, 0, 1, 1.3), 2, 2) # Calling as.logical() functionas.logical(x1)as.logical(x2) Output: [1] TRUE TRUE TRUE TRUE [1] TRUE FALSE TRUE TRUE kumar_satyam R Array-Functions R DataFrame-Function R List-Function R Matrix-Function R Object-Function R Vector-Function R Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Filter data by multiple conditions in R using Dplyr How to Replace specific values in column in R DataFrame ? Loops in R (for, while, repeat) How to Split Column Into Multiple Columns in R DataFrame? Change Color of Bars in Barchart using ggplot2 in R Group by function in R using Dplyr How to change Row Names of DataFrame in R ? Printing Output of an R Program How to Change Axis Scales in R Plots? How to filter R DataFrame by values in a column?
[ { "code": null, "e": 28, "s": 0, "text": "\n08 Nov, 2021" }, { "code": null, "e": 114, "s": 28, "text": "as.logical() function in R Language is used to convert an object to a logical vector." }, { "code": null, "e": 178, "s": 114, "text": "Syntax: as.logical(x)Parameters: x: Numeric or character object" }, { "code": null, "e": 180, "s": 178, "text": "R" }, { "code": "# R Program to convert# an object to logical vector # Creating a vectorx <- c(1, 2, 3, 0, 1.4, NA) # Calling as.logical() functionas.logical(T)as.logical(\"F\")as.logical(2)as.logical(x)", "e": 365, "s": 180, "text": null }, { "code": null, "e": 374, "s": 365, "text": "Output: " }, { "code": null, "e": 442, "s": 374, "text": "[1] TRUE\n[1] FALSE\n[1] TRUE\n[1] TRUE TRUE TRUE FALSE TRUE NA" }, { "code": null, "e": 444, "s": 442, "text": "R" }, { "code": "# R Program to convert# an object to logical vector # Creating matrixx1 <- matrix(c(1:4), 2, 2)x2 <- matrix(c(2, 0, 1, 1.3), 2, 2) # Calling as.logical() functionas.logical(x1)as.logical(x2)", "e": 635, "s": 444, "text": null }, { "code": null, "e": 644, "s": 635, "text": "Output: " }, { "code": null, "e": 696, "s": 644, "text": "[1] TRUE TRUE TRUE TRUE\n[1] TRUE FALSE TRUE TRUE" }, { "code": null, "e": 709, "s": 696, "text": "kumar_satyam" }, { "code": null, "e": 727, "s": 709, "text": "R Array-Functions" }, { "code": null, "e": 748, "s": 727, "text": "R DataFrame-Function" }, { "code": null, "e": 764, "s": 748, "text": "R List-Function" }, { "code": null, "e": 782, "s": 764, "text": "R Matrix-Function" }, { "code": null, "e": 800, "s": 782, "text": "R Object-Function" }, { "code": null, "e": 818, "s": 800, "text": "R Vector-Function" }, { "code": null, "e": 829, "s": 818, "text": "R Language" }, { "code": null, "e": 927, "s": 829, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 979, "s": 927, "text": "Filter data by multiple conditions in R using Dplyr" }, { "code": null, "e": 1037, "s": 979, "text": "How to Replace specific values in column in R DataFrame ?" }, { "code": null, "e": 1069, "s": 1037, "text": "Loops in R (for, while, repeat)" }, { "code": null, "e": 1127, "s": 1069, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 1179, "s": 1127, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 1214, "s": 1179, "text": "Group by function in R using Dplyr" }, { "code": null, "e": 1258, "s": 1214, "text": "How to change Row Names of DataFrame in R ?" }, { "code": null, "e": 1290, "s": 1258, "text": "Printing Output of an R Program" }, { "code": null, "e": 1328, "s": 1290, "text": "How to Change Axis Scales in R Plots?" } ]
Reverse a doubly circular linked list
05 Jul, 2022 The problem is to reverse the given doubly circular linked list. Examples: Input: Output: Algorithm: insertEnd(head, new_node) Declare last if head == NULL then new_node->next = new_node->prev = new_node head = new_node return last = head->prev new_node->next = head head->prev = new_node new_node->prev = last last->next = new_node reverse(head) Initialize new_head = NULL Declare last last = head->prev Initialize curr = last, prev while curr->prev != last prev = curr->prev insertEnd(&new_head, curr) curr = prev insertEnd(&new_head, curr) return new_head Explanation: The variable head in the parameter list of insertEnd() is a pointer to a pointer variable. reverse() traverses the doubly circular linked list starting with the head pointer in the backward direction and one by one gets the node in the traversal. It inserts those nodes at the end of the list that starts with the new_head pointer with the help of the function insertEnd() and finally returns the new_head. C++ Java Python3 C# Javascript // C++ implementation to reverse a// doubly circular linked list#include <bits/stdc++.h> using namespace std; // structure of a node of linked liststruct Node { int data; Node *next, *prev;}; // function to create and return a new nodeNode* getNode(int data){ Node* newNode = (Node*)malloc(sizeof(Node)); newNode->data = data; return newNode;} // Function to insert at the endvoid insertEnd(Node** head, Node* new_node){ // If the list is empty, create a single node // circular and doubly list if (*head == NULL) { new_node->next = new_node->prev = new_node; *head = new_node; return; } // If list is not empty /* Find last node */ Node* last = (*head)->prev; // Start is going to be next of new_node new_node->next = *head; // Make new node previous of start (*head)->prev = new_node; // Make last previous of new node new_node->prev = last; // Make new node next of old last last->next = new_node;} // Utility function to reverse a// doubly circular linked listNode* reverse(Node* head){ if (!head) return NULL; // Initialize a new head pointer Node* new_head = NULL; // get pointer to the last node Node* last = head->prev; // set 'curr' to last node Node *curr = last, *prev; // traverse list in backward direction while (curr->prev != last) { prev = curr->prev; // insert 'curr' at the end of the list // starting with the 'new_head' pointer insertEnd(&new_head, curr); curr = prev; } insertEnd(&new_head, curr); // head pointer of the reversed list return new_head;} // function to display a doubly circular list in// forward and backward directionvoid display(Node* head){ if (!head) return; Node* temp = head; cout << "Forward direction: "; while (temp->next != head) { cout << temp->data << " "; temp = temp->next; } cout << temp->data; Node* last = head->prev; temp = last; cout << "\nBackward direction: "; while (temp->prev != last) { cout << temp->data << " "; temp = temp->prev; } cout << temp->data;} // Driver program to test aboveint main(){ Node* head = NULL; insertEnd(&head, getNode(1)); insertEnd(&head, getNode(2)); insertEnd(&head, getNode(3)); insertEnd(&head, getNode(4)); insertEnd(&head, getNode(5)); cout << "Current list:\n"; display(head); head = reverse(head); cout << "\n\nReversed list:\n"; display(head); return 0;} // Java implementation to reverse a// doubly circular linked listclass GFG{ // structure of a node of linked liststatic class Node{ int data; Node next, prev;}; // function to create and return a new nodestatic Node getNode(int data){ Node newNode = new Node(); newNode.data = data; return newNode;} // Function to insert at the endstatic Node insertEnd(Node head, Node new_node){ // If the list is empty, create a single node // circular and doubly list if (head == null) { new_node.next = new_node.prev = new_node; head = new_node; return head; } // If list is not empty // Find last node / Node last = (head).prev; // Start is going to be next of new_node new_node.next = head; // Make new node previous of start (head).prev = new_node; // Make last previous of new node new_node.prev = last; // Make new node next of old last last.next = new_node; return head;} // Utility function to reverse a// doubly circular linked liststatic Node reverse(Node head){ if (head==null) return null; // Initialize a new head pointer Node new_head = null; // get pointer to the last node Node last = head.prev; // set 'curr' to last node Node curr = last, prev; // traverse list in backward direction while (curr.prev != last) { prev = curr.prev; // insert 'curr' at the end of the list // starting with the 'new_head' pointer new_head=insertEnd(new_head, curr); curr = prev; } new_head=insertEnd(new_head, curr); // head pointer of the reversed list return new_head;} // function to display a doubly circular list in// forward and backward directionstatic void display(Node head){ if (head==null) return; Node temp = head; System.out.print( "Forward direction: "); while (temp.next != head) { System.out.print( temp.data + " "); temp = temp.next; } System.out.print( temp.data + " "); Node last = head.prev; temp = last; System.out.print( "\nBackward direction: "); while (temp.prev != last) { System.out.print( temp.data + " "); temp = temp.prev; } System.out.print( temp.data + " ");} // Driver codepublic static void main(String args[]){ Node head = null; head =insertEnd(head, getNode(1)); head =insertEnd(head, getNode(2)); head =insertEnd(head, getNode(3)); head =insertEnd(head, getNode(4)); head =insertEnd(head, getNode(5)); System.out.print( "Current list:\n"); display(head); head = reverse(head); System.out.print( "\n\nReversed list:\n"); display(head);}} // This code is contributed by Arnab Kundu # Python3 implementation to reverse a# doubly circular linked listimport math # structure of a node of linked listclass Node: def __init__(self, data): self.data = data self.next = None # function to create and return a new nodedef getNode(data): newNode = Node(data) newNode.data = data return newNode # Function to insert at the enddef insertEnd(head, new_node): # If the list is empty, create a single node # circular and doubly list if (head == None) : new_node.next = new_node new_node.prev = new_node head = new_node return head # If list is not empty # Find last node last = head.prev # Start is going to be next of new_node new_node.next = head # Make new node previous of start head.prev = new_node # Make last previous of new node new_node.prev = last # Make new node next of old last last.next = new_node return head # Utility function to reverse a# doubly circular linked listdef reverse(head): if (head == None): return None # Initialize a new head pointer new_head = None # get pointer to the last node last = head.prev # set 'curr' to last node curr = last #*prev # traverse list in backward direction while (curr.prev != last): prev = curr.prev # insert 'curr' at the end of the list # starting with the 'new_head' pointer new_head = insertEnd(new_head, curr) curr = prev new_head = insertEnd(new_head, curr) # head pointer of the reversed list return new_head # function to display a doubly circular list in# forward and backward directiondef display(head): if (head == None): return temp = head print("Forward direction: ", end = "") while (temp.next != head): print(temp.data, end = " ") temp = temp.next print(temp.data) last = head.prev temp = last print("Backward direction: ", end = "") while (temp.prev != last): print(temp.data, end = " ") temp = temp.prev print(temp.data) # Driver Codeif __name__=='__main__': head = None head = insertEnd(head, getNode(1)) head = insertEnd(head, getNode(2)) head = insertEnd(head, getNode(3)) head = insertEnd(head, getNode(4)) head = insertEnd(head, getNode(5)) print("Current list:") display(head) head = reverse(head) print("\nReversed list:") display(head) # This code is contributed by Srathore // C# implementation to reverse a// doubly circular linked listusing System; class GFG{ // structure of a node of linked listpublic class Node{ public int data; public Node next, prev;}; // function to create and return a new nodestatic Node getNode(int data){ Node newNode = new Node(); newNode.data = data; return newNode;} // Function to insert at the endstatic Node insertEnd(Node head, Node new_node){ // If the list is empty, create a single node // circular and doubly list if (head == null) { new_node.next = new_node.prev = new_node; head = new_node; return head; } // If list is not empty // Find last node / Node last = (head).prev; // Start is going to be next of new_node new_node.next = head; // Make new node previous of start (head).prev = new_node; // Make last previous of new node new_node.prev = last; // Make new node next of old last last.next = new_node; return head;} // Utility function to reverse a// doubly circular linked liststatic Node reverse(Node head){ if (head == null) return null; // Initialize a new head pointer Node new_head = null; // get pointer to the last node Node last = head.prev; // set 'curr' to last node Node curr = last, prev; // traverse list in backward direction while (curr.prev != last) { prev = curr.prev; // insert 'curr' at the end of the list // starting with the 'new_head' pointer new_head=insertEnd(new_head, curr); curr = prev; } new_head=insertEnd(new_head, curr); // head pointer of the reversed list return new_head;} // function to display a doubly circular list in// forward and backward directionstatic void display(Node head){ if (head == null) return; Node temp = head; Console.Write( "Forward direction: "); while (temp.next != head) { Console.Write( temp.data + " "); temp = temp.next; } Console.Write( temp.data + " "); Node last = head.prev; temp = last; Console.Write( "\nBackward direction: "); while (temp.prev != last) { Console.Write( temp.data + " "); temp = temp.prev; } Console.Write( temp.data + " ");} // Driver codepublic static void Main(String []args){ Node head = null; head = insertEnd(head, getNode(1)); head = insertEnd(head, getNode(2)); head = insertEnd(head, getNode(3)); head = insertEnd(head, getNode(4)); head = insertEnd(head, getNode(5)); Console.Write( "Current list:\n"); display(head); head = reverse(head); Console.Write( "\n\nReversed list:\n"); display(head);}} // This code contributed by Rajput-Ji <script> // JavaScript implementation to reverse a // doubly circular linked list // structure of a node of linked list class Node { constructor() { this.data = 0; this.next = null; this.prev = null; } } // function to create and return a new node function getNode(data) { var newNode = new Node(); newNode.data = data; return newNode; } // Function to insert at the end function insertEnd(head, new_node) { // If the list is empty, create a single node // circular and doubly list if (head == null) { new_node.next = new_node.prev = new_node; head = new_node; return head; } // If list is not empty // Find last node / var last = head.prev; // Start is going to be next of new_node new_node.next = head; // Make new node previous of start head.prev = new_node; // Make last previous of new node new_node.prev = last; // Make new node next of old last last.next = new_node; return head; } // Utility function to reverse a // doubly circular linked list function reverse(head) { if (head == null) return null; // Initialize a new head pointer var new_head = null; // get pointer to the last node var last = head.prev; // set 'curr' to last node var curr = last, prev; // traverse list in backward direction while (curr.prev != last) { prev = curr.prev; // insert 'curr' at the end of the list // starting with the 'new_head' pointer new_head = insertEnd(new_head, curr); curr = prev; } new_head = insertEnd(new_head, curr); // head pointer of the reversed list return new_head; } // function to display a doubly circular list in // forward and backward direction function display(head) { if (head == null) return; var temp = head; document.write("Forward direction: "); while (temp.next != head) { document.write(temp.data + " "); temp = temp.next; } document.write(temp.data + " "); var last = head.prev; temp = last; document.write("<br>Backward direction: "); while (temp.prev != last) { document.write(temp.data + " "); temp = temp.prev; } document.write(temp.data + " "); } // Driver code var head = null; head = insertEnd(head, getNode(1)); head = insertEnd(head, getNode(2)); head = insertEnd(head, getNode(3)); head = insertEnd(head, getNode(4)); head = insertEnd(head, getNode(5)); document.write("Current list:<br>"); display(head); head = reverse(head); document.write("<br><br>Reversed list:<br>"); display(head); </script> Output: Current list: Forward direction: 1 2 3 4 5 Backward direction: 5 4 3 2 1 Reversed list: Forward direction: 5 4 3 2 1 Backward direction: 1 2 3 4 5 Time Complexity: O(n), as we are using a loop to traverse n times. Where n is the number of nodes in the linked list. Auxiliary Space: O(1), as we are not using any extra space. andrew1234 Rajput-Ji sapnasingh4991 rdtank simranarora5sos rohan07 simmytarika5 circular linked list doubly linked list Reverse Linked List Linked List Reverse circular linked list Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Introduction to Data Structures What is Data Structure: Types, Classifications and Applications Add two numbers represented by linked lists | Set 2 Types of Linked List Rearrange a given linked list in-place. Circular Singly Linked List | Insertion Find first node of loop in a linked list Flattening a Linked List Real-time application of Data Structures Clone a linked list with next and random pointer | Set 1
[ { "code": null, "e": 52, "s": 24, "text": "\n05 Jul, 2022" }, { "code": null, "e": 117, "s": 52, "text": "The problem is to reverse the given doubly circular linked list." }, { "code": null, "e": 135, "s": 117, "text": "Examples: Input: " }, { "code": null, "e": 145, "s": 135, "text": "Output: " }, { "code": null, "e": 158, "s": 145, "text": "Algorithm: " }, { "code": null, "e": 749, "s": 158, "text": "insertEnd(head, new_node) \n Declare last\n\n if head == NULL then\n new_node->next = new_node->prev = new_node\n head = new_node\n return \n \n last = head->prev\n new_node->next = head \n head->prev = new_node\n new_node->prev = last \n last->next = new_node\n\nreverse(head)\n Initialize new_head = NULL\n Declare last\n \n last = head->prev\n Initialize curr = last, prev\n \n while curr->prev != last\n prev = curr->prev\n insertEnd(&new_head, curr)\n curr = prev\n insertEnd(&new_head, curr)\n \n return new_head" }, { "code": null, "e": 1170, "s": 749, "text": "Explanation: The variable head in the parameter list of insertEnd() is a pointer to a pointer variable. reverse() traverses the doubly circular linked list starting with the head pointer in the backward direction and one by one gets the node in the traversal. It inserts those nodes at the end of the list that starts with the new_head pointer with the help of the function insertEnd() and finally returns the new_head. " }, { "code": null, "e": 1174, "s": 1170, "text": "C++" }, { "code": null, "e": 1179, "s": 1174, "text": "Java" }, { "code": null, "e": 1187, "s": 1179, "text": "Python3" }, { "code": null, "e": 1190, "s": 1187, "text": "C#" }, { "code": null, "e": 1201, "s": 1190, "text": "Javascript" }, { "code": "// C++ implementation to reverse a// doubly circular linked list#include <bits/stdc++.h> using namespace std; // structure of a node of linked liststruct Node { int data; Node *next, *prev;}; // function to create and return a new nodeNode* getNode(int data){ Node* newNode = (Node*)malloc(sizeof(Node)); newNode->data = data; return newNode;} // Function to insert at the endvoid insertEnd(Node** head, Node* new_node){ // If the list is empty, create a single node // circular and doubly list if (*head == NULL) { new_node->next = new_node->prev = new_node; *head = new_node; return; } // If list is not empty /* Find last node */ Node* last = (*head)->prev; // Start is going to be next of new_node new_node->next = *head; // Make new node previous of start (*head)->prev = new_node; // Make last previous of new node new_node->prev = last; // Make new node next of old last last->next = new_node;} // Utility function to reverse a// doubly circular linked listNode* reverse(Node* head){ if (!head) return NULL; // Initialize a new head pointer Node* new_head = NULL; // get pointer to the last node Node* last = head->prev; // set 'curr' to last node Node *curr = last, *prev; // traverse list in backward direction while (curr->prev != last) { prev = curr->prev; // insert 'curr' at the end of the list // starting with the 'new_head' pointer insertEnd(&new_head, curr); curr = prev; } insertEnd(&new_head, curr); // head pointer of the reversed list return new_head;} // function to display a doubly circular list in// forward and backward directionvoid display(Node* head){ if (!head) return; Node* temp = head; cout << \"Forward direction: \"; while (temp->next != head) { cout << temp->data << \" \"; temp = temp->next; } cout << temp->data; Node* last = head->prev; temp = last; cout << \"\\nBackward direction: \"; while (temp->prev != last) { cout << temp->data << \" \"; temp = temp->prev; } cout << temp->data;} // Driver program to test aboveint main(){ Node* head = NULL; insertEnd(&head, getNode(1)); insertEnd(&head, getNode(2)); insertEnd(&head, getNode(3)); insertEnd(&head, getNode(4)); insertEnd(&head, getNode(5)); cout << \"Current list:\\n\"; display(head); head = reverse(head); cout << \"\\n\\nReversed list:\\n\"; display(head); return 0;}", "e": 3742, "s": 1201, "text": null }, { "code": "// Java implementation to reverse a// doubly circular linked listclass GFG{ // structure of a node of linked liststatic class Node{ int data; Node next, prev;}; // function to create and return a new nodestatic Node getNode(int data){ Node newNode = new Node(); newNode.data = data; return newNode;} // Function to insert at the endstatic Node insertEnd(Node head, Node new_node){ // If the list is empty, create a single node // circular and doubly list if (head == null) { new_node.next = new_node.prev = new_node; head = new_node; return head; } // If list is not empty // Find last node / Node last = (head).prev; // Start is going to be next of new_node new_node.next = head; // Make new node previous of start (head).prev = new_node; // Make last previous of new node new_node.prev = last; // Make new node next of old last last.next = new_node; return head;} // Utility function to reverse a// doubly circular linked liststatic Node reverse(Node head){ if (head==null) return null; // Initialize a new head pointer Node new_head = null; // get pointer to the last node Node last = head.prev; // set 'curr' to last node Node curr = last, prev; // traverse list in backward direction while (curr.prev != last) { prev = curr.prev; // insert 'curr' at the end of the list // starting with the 'new_head' pointer new_head=insertEnd(new_head, curr); curr = prev; } new_head=insertEnd(new_head, curr); // head pointer of the reversed list return new_head;} // function to display a doubly circular list in// forward and backward directionstatic void display(Node head){ if (head==null) return; Node temp = head; System.out.print( \"Forward direction: \"); while (temp.next != head) { System.out.print( temp.data + \" \"); temp = temp.next; } System.out.print( temp.data + \" \"); Node last = head.prev; temp = last; System.out.print( \"\\nBackward direction: \"); while (temp.prev != last) { System.out.print( temp.data + \" \"); temp = temp.prev; } System.out.print( temp.data + \" \");} // Driver codepublic static void main(String args[]){ Node head = null; head =insertEnd(head, getNode(1)); head =insertEnd(head, getNode(2)); head =insertEnd(head, getNode(3)); head =insertEnd(head, getNode(4)); head =insertEnd(head, getNode(5)); System.out.print( \"Current list:\\n\"); display(head); head = reverse(head); System.out.print( \"\\n\\nReversed list:\\n\"); display(head);}} // This code is contributed by Arnab Kundu", "e": 6452, "s": 3742, "text": null }, { "code": "# Python3 implementation to reverse a# doubly circular linked listimport math # structure of a node of linked listclass Node: def __init__(self, data): self.data = data self.next = None # function to create and return a new nodedef getNode(data): newNode = Node(data) newNode.data = data return newNode # Function to insert at the enddef insertEnd(head, new_node): # If the list is empty, create a single node # circular and doubly list if (head == None) : new_node.next = new_node new_node.prev = new_node head = new_node return head # If list is not empty # Find last node last = head.prev # Start is going to be next of new_node new_node.next = head # Make new node previous of start head.prev = new_node # Make last previous of new node new_node.prev = last # Make new node next of old last last.next = new_node return head # Utility function to reverse a# doubly circular linked listdef reverse(head): if (head == None): return None # Initialize a new head pointer new_head = None # get pointer to the last node last = head.prev # set 'curr' to last node curr = last #*prev # traverse list in backward direction while (curr.prev != last): prev = curr.prev # insert 'curr' at the end of the list # starting with the 'new_head' pointer new_head = insertEnd(new_head, curr) curr = prev new_head = insertEnd(new_head, curr) # head pointer of the reversed list return new_head # function to display a doubly circular list in# forward and backward directiondef display(head): if (head == None): return temp = head print(\"Forward direction: \", end = \"\") while (temp.next != head): print(temp.data, end = \" \") temp = temp.next print(temp.data) last = head.prev temp = last print(\"Backward direction: \", end = \"\") while (temp.prev != last): print(temp.data, end = \" \") temp = temp.prev print(temp.data) # Driver Codeif __name__=='__main__': head = None head = insertEnd(head, getNode(1)) head = insertEnd(head, getNode(2)) head = insertEnd(head, getNode(3)) head = insertEnd(head, getNode(4)) head = insertEnd(head, getNode(5)) print(\"Current list:\") display(head) head = reverse(head) print(\"\\nReversed list:\") display(head) # This code is contributed by Srathore", "e": 8940, "s": 6452, "text": null }, { "code": "// C# implementation to reverse a// doubly circular linked listusing System; class GFG{ // structure of a node of linked listpublic class Node{ public int data; public Node next, prev;}; // function to create and return a new nodestatic Node getNode(int data){ Node newNode = new Node(); newNode.data = data; return newNode;} // Function to insert at the endstatic Node insertEnd(Node head, Node new_node){ // If the list is empty, create a single node // circular and doubly list if (head == null) { new_node.next = new_node.prev = new_node; head = new_node; return head; } // If list is not empty // Find last node / Node last = (head).prev; // Start is going to be next of new_node new_node.next = head; // Make new node previous of start (head).prev = new_node; // Make last previous of new node new_node.prev = last; // Make new node next of old last last.next = new_node; return head;} // Utility function to reverse a// doubly circular linked liststatic Node reverse(Node head){ if (head == null) return null; // Initialize a new head pointer Node new_head = null; // get pointer to the last node Node last = head.prev; // set 'curr' to last node Node curr = last, prev; // traverse list in backward direction while (curr.prev != last) { prev = curr.prev; // insert 'curr' at the end of the list // starting with the 'new_head' pointer new_head=insertEnd(new_head, curr); curr = prev; } new_head=insertEnd(new_head, curr); // head pointer of the reversed list return new_head;} // function to display a doubly circular list in// forward and backward directionstatic void display(Node head){ if (head == null) return; Node temp = head; Console.Write( \"Forward direction: \"); while (temp.next != head) { Console.Write( temp.data + \" \"); temp = temp.next; } Console.Write( temp.data + \" \"); Node last = head.prev; temp = last; Console.Write( \"\\nBackward direction: \"); while (temp.prev != last) { Console.Write( temp.data + \" \"); temp = temp.prev; } Console.Write( temp.data + \" \");} // Driver codepublic static void Main(String []args){ Node head = null; head = insertEnd(head, getNode(1)); head = insertEnd(head, getNode(2)); head = insertEnd(head, getNode(3)); head = insertEnd(head, getNode(4)); head = insertEnd(head, getNode(5)); Console.Write( \"Current list:\\n\"); display(head); head = reverse(head); Console.Write( \"\\n\\nReversed list:\\n\"); display(head);}} // This code contributed by Rajput-Ji", "e": 11656, "s": 8940, "text": null }, { "code": "<script> // JavaScript implementation to reverse a // doubly circular linked list // structure of a node of linked list class Node { constructor() { this.data = 0; this.next = null; this.prev = null; } } // function to create and return a new node function getNode(data) { var newNode = new Node(); newNode.data = data; return newNode; } // Function to insert at the end function insertEnd(head, new_node) { // If the list is empty, create a single node // circular and doubly list if (head == null) { new_node.next = new_node.prev = new_node; head = new_node; return head; } // If list is not empty // Find last node / var last = head.prev; // Start is going to be next of new_node new_node.next = head; // Make new node previous of start head.prev = new_node; // Make last previous of new node new_node.prev = last; // Make new node next of old last last.next = new_node; return head; } // Utility function to reverse a // doubly circular linked list function reverse(head) { if (head == null) return null; // Initialize a new head pointer var new_head = null; // get pointer to the last node var last = head.prev; // set 'curr' to last node var curr = last, prev; // traverse list in backward direction while (curr.prev != last) { prev = curr.prev; // insert 'curr' at the end of the list // starting with the 'new_head' pointer new_head = insertEnd(new_head, curr); curr = prev; } new_head = insertEnd(new_head, curr); // head pointer of the reversed list return new_head; } // function to display a doubly circular list in // forward and backward direction function display(head) { if (head == null) return; var temp = head; document.write(\"Forward direction: \"); while (temp.next != head) { document.write(temp.data + \" \"); temp = temp.next; } document.write(temp.data + \" \"); var last = head.prev; temp = last; document.write(\"<br>Backward direction: \"); while (temp.prev != last) { document.write(temp.data + \" \"); temp = temp.prev; } document.write(temp.data + \" \"); } // Driver code var head = null; head = insertEnd(head, getNode(1)); head = insertEnd(head, getNode(2)); head = insertEnd(head, getNode(3)); head = insertEnd(head, getNode(4)); head = insertEnd(head, getNode(5)); document.write(\"Current list:<br>\"); display(head); head = reverse(head); document.write(\"<br><br>Reversed list:<br>\"); display(head); </script>", "e": 14644, "s": 11656, "text": null }, { "code": null, "e": 14654, "s": 14644, "text": "Output: " }, { "code": null, "e": 14802, "s": 14654, "text": "Current list:\nForward direction: 1 2 3 4 5\nBackward direction: 5 4 3 2 1\n\nReversed list:\nForward direction: 5 4 3 2 1\nBackward direction: 1 2 3 4 5" }, { "code": null, "e": 14920, "s": 14802, "text": "Time Complexity: O(n), as we are using a loop to traverse n times. Where n is the number of nodes in the linked list." }, { "code": null, "e": 14980, "s": 14920, "text": "Auxiliary Space: O(1), as we are not using any extra space." }, { "code": null, "e": 14991, "s": 14980, "text": "andrew1234" }, { "code": null, "e": 15001, "s": 14991, "text": "Rajput-Ji" }, { "code": null, "e": 15016, "s": 15001, "text": "sapnasingh4991" }, { "code": null, "e": 15023, "s": 15016, "text": "rdtank" }, { "code": null, "e": 15039, "s": 15023, "text": "simranarora5sos" }, { "code": null, "e": 15047, "s": 15039, "text": "rohan07" }, { "code": null, "e": 15060, "s": 15047, "text": "simmytarika5" }, { "code": null, "e": 15081, "s": 15060, "text": "circular linked list" }, { "code": null, "e": 15100, "s": 15081, "text": "doubly linked list" }, { "code": null, "e": 15108, "s": 15100, "text": "Reverse" }, { "code": null, "e": 15120, "s": 15108, "text": "Linked List" }, { "code": null, "e": 15132, "s": 15120, "text": "Linked List" }, { "code": null, "e": 15140, "s": 15132, "text": "Reverse" }, { "code": null, "e": 15161, "s": 15140, "text": "circular linked list" }, { "code": null, "e": 15259, "s": 15161, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 15291, "s": 15259, "text": "Introduction to Data Structures" }, { "code": null, "e": 15355, "s": 15291, "text": "What is Data Structure: Types, Classifications and Applications" }, { "code": null, "e": 15407, "s": 15355, "text": "Add two numbers represented by linked lists | Set 2" }, { "code": null, "e": 15428, "s": 15407, "text": "Types of Linked List" }, { "code": null, "e": 15468, "s": 15428, "text": "Rearrange a given linked list in-place." }, { "code": null, "e": 15508, "s": 15468, "text": "Circular Singly Linked List | Insertion" }, { "code": null, "e": 15549, "s": 15508, "text": "Find first node of loop in a linked list" }, { "code": null, "e": 15574, "s": 15549, "text": "Flattening a Linked List" }, { "code": null, "e": 15615, "s": 15574, "text": "Real-time application of Data Structures" } ]
What are virtual functions in C#?
The virtual keyword is useful in modifying a method, property, indexer, or event. When you have a function defined in a class that you want to be implemented in an inherited class(es), you use virtual functions. The virtual functions could be implemented differently in different inherited class and the call to these functions will be decided at runtime. The following is a virtual function public virtual int area() { } Here is an example showing how to work with virtual functions − using System; namespace PolymorphismApplication { class Shape { protected int width, height; public Shape( int a = 0, int b = 0) { width = a; height = b; } public virtual int area() { Console.WriteLine("Parent class area :"); return 0; } } class Rectangle: Shape { public Rectangle( int a = 0, int b = 0): base(a, b) { } public override int area () { Console.WriteLine("Rectangle class area "); return (width * height); } } class Triangle: Shape { public Triangle(int a = 0, int b = 0): base(a, b) { } public override int area() { Console.WriteLine("Triangle class area:"); return (width * height / 2); } } class Caller { public void CallArea(Shape sh) { int a; a = sh.area(); Console.WriteLine("Area: {0}", a); } } class Tester { static void Main(string[] args) { Caller c = new Caller(); Rectangle r = new Rectangle(10, 7); Triangle t = new Triangle(10, 5); c.CallArea(r); c.CallArea(t); Console.ReadKey(); } } }
[ { "code": null, "e": 1543, "s": 1187, "text": "The virtual keyword is useful in modifying a method, property, indexer, or event. When you have a function defined in a class that you want to be implemented in an inherited class(es), you use virtual functions. The virtual functions could be implemented differently in different inherited class and the call to these functions will be decided at runtime." }, { "code": null, "e": 1579, "s": 1543, "text": "The following is a virtual function" }, { "code": null, "e": 1609, "s": 1579, "text": "public virtual int area() { }" }, { "code": null, "e": 1673, "s": 1609, "text": "Here is an example showing how to work with virtual functions −" }, { "code": null, "e": 2821, "s": 1673, "text": "using System;\n\nnamespace PolymorphismApplication {\n class Shape {\n protected int width, height;\n \n public Shape( int a = 0, int b = 0) {\n width = a;\n height = b;\n }\n\n public virtual int area() {\n Console.WriteLine(\"Parent class area :\");\n return 0;\n }\n }\n\n class Rectangle: Shape {\n public Rectangle( int a = 0, int b = 0): base(a, b) {\n\n }\n\n public override int area () {\n Console.WriteLine(\"Rectangle class area \");\n return (width * height);\n }\n }\n\n class Triangle: Shape {\n public Triangle(int a = 0, int b = 0): base(a, b) {\n }\n\n public override int area() {\n Console.WriteLine(\"Triangle class area:\");\n return (width * height / 2);\n }\n}\n\nclass Caller {\n public void CallArea(Shape sh) {\n int a;\n a = sh.area();\n Console.WriteLine(\"Area: {0}\", a);\n }\n}\n\nclass Tester {\n static void Main(string[] args) {\n Caller c = new Caller();\n Rectangle r = new Rectangle(10, 7);\n Triangle t = new Triangle(10, 5);\n\n c.CallArea(r);\n c.CallArea(t);\n Console.ReadKey();\n }\n }\n}" } ]
Search Bar using HTML, CSS and JavaScript
01 Jul, 2022 Every website needs a search bar through which a user can search the content of their concern on that page. A basic search bar can be made using HTML, CSS, and JavaScript only. Advance searching algorithms look for many things like related content and then shows the results. The one that we are going to make will look for substrings in a string. Using HTML In this section, we will write HTML part of the code. In HTML, we will just link our Stylesheets and our JavaScript file. Input tag is used for the creation of the search bar and it includes several attributes like type, placeholder, name. We also need a list of items which will hold different animal names that will allow us to search for animals through this. The classes and ID’s used in tags will be defined in stylesheet below. HTML <!DOCTYPE html><html> <head> <title> Creating Search Bar using HTML CSS and Javascript </title> <!-- linking the stylesheet(CSS) --> <link rel="stylesheet" type="text/css" href="./style.css"></head> <body> <!-- input tag --> <input id="searchbar" onkeyup="search_animal()" type="text" name="search" placeholder="Search animals.."> <!-- ordered list --> <ol id='list'> <li class="animals">Cat</li> <li class="animals">Dog</li> <li class="animals">Elephant</li> <li class="animals">Fish</li> <li class="animals">Gorilla</li> <li class="animals">Monkey</li> <li class="animals">Turtle</li> <li class="animals">Whale</li> <li class="animals">Aligator</li> <li class="animals">Donkey</li> <li class="animals">Horse</li> </ol> <!-- linking javascript --> <script src="./animals.js"></script></body> </html> Output: Using CSS Though the above input tag and the ordered list looks fine, it still needs some styling. For the search bar styling, some margin and padding are added to make it look clean. The measurements are in percentage so that it adjusts itself when used in any size of the screen (Mobile, Desktop etc). Webkit transition is used to change the width of the Search bar when clicked. The initial width of search bar is 30%, but when it is clicked, it will change to 70% with an ease-in ease-out transition of 0.15 seconds. CSS #searchbar{ margin-left: 15%; padding:15px; border-radius: 10px; } input[type=text] { width: 30%; -webkit-transition: width 0.15s ease-in-out; transition: width 0.15s ease-in-out; } /* When the input field gets focus, change its width to 100% */ input[type=text]:focus { width: 70%; } #list{ font-size: 1.5em; margin-left: 90px; } .animals{ display: list-item; } Output After adding Styling, our page should look like this. Note: If the styling of your page doesn’t change, make sure the style.css file is in the same folder as index.html. It is still incomplete, as we still need the JavaScript to complete the functionality of this search bar. Using JavaScript In the HTML code of search bar, we gave the input an id=”searchbar” and onkeyup we called, the function “search_animal”. onkeyup calls the function every time a key is released on the keyboard. We first get our input using getElementById. Make sure to convert it to lower case to avoid case sensitivity while searching. An array of documents is stored in x. This contains every list that has id=”animals”. After that a loop is run to check if innerHTML of every document includes the input substring if it doesn’t, the display property is set to ‘None’ so that it is invisible on the front end. Javascript // JavaScript codefunction search_animal() { let input = document.getElementById('searchbar').value input=input.toLowerCase(); let x = document.getElementsByClassName('animals'); for (i = 0; i < x.length; i++) { if (!x[i].innerHTML.toLowerCase().includes(input)) { x[i].style.display="none"; } else { x[i].style.display="list-item"; } }} Output: JavaScript is best known for web page development but it is also used in a variety of non-browser environments. You can learn JavaScript from the ground up by following this JavaScript Tutorial and JavaScript Examples. HTML is the foundation of webpages, is used for webpage development by structuring websites and web apps.You can learn HTML from the ground up by following this HTML Tutorial and HTML Examples. CSS is the foundation of webpages, is used for webpage development by styling websites and web apps.You can learn CSS from the ground up by following this CSS Tutorial and CSS Examples. varshagumber28 CSS HTML JavaScript Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Design a Tribute Page using HTML & CSS How to set space between the flexbox ? How to Upload Image into Database and Display it using PHP ? Build a Survey Form using HTML and CSS CSS | :not(:last-child):after Selector REST API (Introduction) Hide or show elements in HTML using display property How to set the default value for an HTML <select> element ? How to set input type date in dd-mm-yyyy format using HTML ? Design a Tribute Page using HTML & CSS
[ { "code": null, "e": 54, "s": 26, "text": "\n01 Jul, 2022" }, { "code": null, "e": 403, "s": 54, "text": "Every website needs a search bar through which a user can search the content of their concern on that page. A basic search bar can be made using HTML, CSS, and JavaScript only. Advance searching algorithms look for many things like related content and then shows the results. The one that we are going to make will look for substrings in a string. " }, { "code": null, "e": 414, "s": 403, "text": "Using HTML" }, { "code": null, "e": 849, "s": 414, "text": "In this section, we will write HTML part of the code. In HTML, we will just link our Stylesheets and our JavaScript file. Input tag is used for the creation of the search bar and it includes several attributes like type, placeholder, name. We also need a list of items which will hold different animal names that will allow us to search for animals through this. The classes and ID’s used in tags will be defined in stylesheet below. " }, { "code": null, "e": 854, "s": 849, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <title> Creating Search Bar using HTML CSS and Javascript </title> <!-- linking the stylesheet(CSS) --> <link rel=\"stylesheet\" type=\"text/css\" href=\"./style.css\"></head> <body> <!-- input tag --> <input id=\"searchbar\" onkeyup=\"search_animal()\" type=\"text\" name=\"search\" placeholder=\"Search animals..\"> <!-- ordered list --> <ol id='list'> <li class=\"animals\">Cat</li> <li class=\"animals\">Dog</li> <li class=\"animals\">Elephant</li> <li class=\"animals\">Fish</li> <li class=\"animals\">Gorilla</li> <li class=\"animals\">Monkey</li> <li class=\"animals\">Turtle</li> <li class=\"animals\">Whale</li> <li class=\"animals\">Aligator</li> <li class=\"animals\">Donkey</li> <li class=\"animals\">Horse</li> </ol> <!-- linking javascript --> <script src=\"./animals.js\"></script></body> </html>", "e": 1817, "s": 854, "text": null }, { "code": null, "e": 1825, "s": 1817, "text": "Output:" }, { "code": null, "e": 1837, "s": 1827, "text": "Using CSS" }, { "code": null, "e": 2348, "s": 1837, "text": "Though the above input tag and the ordered list looks fine, it still needs some styling. For the search bar styling, some margin and padding are added to make it look clean. The measurements are in percentage so that it adjusts itself when used in any size of the screen (Mobile, Desktop etc). Webkit transition is used to change the width of the Search bar when clicked. The initial width of search bar is 30%, but when it is clicked, it will change to 70% with an ease-in ease-out transition of 0.15 seconds." }, { "code": null, "e": 2352, "s": 2348, "text": "CSS" }, { "code": " #searchbar{ margin-left: 15%; padding:15px; border-radius: 10px; } input[type=text] { width: 30%; -webkit-transition: width 0.15s ease-in-out; transition: width 0.15s ease-in-out; } /* When the input field gets focus, change its width to 100% */ input[type=text]:focus { width: 70%; } #list{ font-size: 1.5em; margin-left: 90px; } .animals{ display: list-item; } ", "e": 2788, "s": 2352, "text": null }, { "code": null, "e": 2851, "s": 2788, "text": "Output After adding Styling, our page should look like this. " }, { "code": null, "e": 3074, "s": 2851, "text": "Note: If the styling of your page doesn’t change, make sure the style.css file is in the same folder as index.html. It is still incomplete, as we still need the JavaScript to complete the functionality of this search bar. " }, { "code": null, "e": 3091, "s": 3074, "text": "Using JavaScript" }, { "code": null, "e": 3286, "s": 3091, "text": "In the HTML code of search bar, we gave the input an id=”searchbar” and onkeyup we called, the function “search_animal”. onkeyup calls the function every time a key is released on the keyboard. " }, { "code": null, "e": 3688, "s": 3286, "text": "We first get our input using getElementById. Make sure to convert it to lower case to avoid case sensitivity while searching. An array of documents is stored in x. This contains every list that has id=”animals”. After that a loop is run to check if innerHTML of every document includes the input substring if it doesn’t, the display property is set to ‘None’ so that it is invisible on the front end. " }, { "code": null, "e": 3699, "s": 3688, "text": "Javascript" }, { "code": "// JavaScript codefunction search_animal() { let input = document.getElementById('searchbar').value input=input.toLowerCase(); let x = document.getElementsByClassName('animals'); for (i = 0; i < x.length; i++) { if (!x[i].innerHTML.toLowerCase().includes(input)) { x[i].style.display=\"none\"; } else { x[i].style.display=\"list-item\"; } }}", "e": 4126, "s": 3699, "text": null }, { "code": null, "e": 4135, "s": 4126, "text": "Output: " }, { "code": null, "e": 4356, "s": 4137, "text": "JavaScript is best known for web page development but it is also used in a variety of non-browser environments. You can learn JavaScript from the ground up by following this JavaScript Tutorial and JavaScript Examples." }, { "code": null, "e": 4550, "s": 4356, "text": "HTML is the foundation of webpages, is used for webpage development by structuring websites and web apps.You can learn HTML from the ground up by following this HTML Tutorial and HTML Examples." }, { "code": null, "e": 4736, "s": 4550, "text": "CSS is the foundation of webpages, is used for webpage development by styling websites and web apps.You can learn CSS from the ground up by following this CSS Tutorial and CSS Examples." }, { "code": null, "e": 4751, "s": 4736, "text": "varshagumber28" }, { "code": null, "e": 4755, "s": 4751, "text": "CSS" }, { "code": null, "e": 4760, "s": 4755, "text": "HTML" }, { "code": null, "e": 4771, "s": 4760, "text": "JavaScript" }, { "code": null, "e": 4788, "s": 4771, "text": "Web Technologies" }, { "code": null, "e": 4793, "s": 4788, "text": "HTML" }, { "code": null, "e": 4891, "s": 4793, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4930, "s": 4891, "text": "Design a Tribute Page using HTML & CSS" }, { "code": null, "e": 4969, "s": 4930, "text": "How to set space between the flexbox ?" }, { "code": null, "e": 5030, "s": 4969, "text": "How to Upload Image into Database and Display it using PHP ?" }, { "code": null, "e": 5069, "s": 5030, "text": "Build a Survey Form using HTML and CSS" }, { "code": null, "e": 5108, "s": 5069, "text": "CSS | :not(:last-child):after Selector" }, { "code": null, "e": 5132, "s": 5108, "text": "REST API (Introduction)" }, { "code": null, "e": 5185, "s": 5132, "text": "Hide or show elements in HTML using display property" }, { "code": null, "e": 5245, "s": 5185, "text": "How to set the default value for an HTML <select> element ?" }, { "code": null, "e": 5306, "s": 5245, "text": "How to set input type date in dd-mm-yyyy format using HTML ?" } ]
Python VLC MediaListPlayer – Getting Current State
29 Aug, 2020 In this article we will see how we can current state of the MediaListPlayer object in the python vlc module. VLC media player is a free and open-source portable cross-platform media player software and streaming media server developed by the VideoLAN project. Media list player is used to play multiple media in a row for example playing a series, instead of taking single media it accepts media list. Its working is almost similar like the MediaPlayer object but it is capable of playing list of media. State can be playing paused or closed, we can pause and resume the media list player any time with the help of set_pause method, and it can be start playing with the help of play method. In order to do this we will use get_state method with the MediaListPlayer object Syntax : media_list_player.get_state() Argument : It takes no argument Return : It returns State object Below is the implementation # importing vlc moduleimport vlc # importing time moduleimport time # creating a media player objectmedia_player = vlc.MediaListPlayer() # creating Instance class objectplayer = vlc.Instance() # creating a new media list objectmedia_list = player.media_list_new() # creating a new mediamedia = player.media_new("death_note.mkv") # adding media to media listmedia_list.add_media(media) # setting media list to the media playermedia_player.set_media_list(media_list) # start playing videomedia_player.play() # wait so the video can be played for 5 seconds# irrespective for length of videotime.sleep(5) # getting media player current statevalue = media_player.get_state() # printing valueprint(value) Output : State.Playing Another exampleBelow is the implementation # importing vlc moduleimport vlc # importing time moduleimport time # creating a media player objectmedia_player = vlc.MediaListPlayer() # creating Instance class objectplayer = vlc.Instance() # creating a new media listmedia_list = player.media_list_new() # creating a new mediamedia = player.media_new("1.mp4") # adding media to media listmedia_list.add_media(media) # setting media list to the media playermedia_player.set_media_list(media_list) # start playing videomedia_player.play() # wait so the video can be played for 5 seconds# irrespective for length of videotime.sleep(5) # getting media player current statevalue = media_player.get_state() # printing valueprint(value) Output : State.Playing Python vlc-mediaPlayer Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Different ways to create Pandas Dataframe Enumerate() in Python Read a file line by line in Python How to Install PIP on Windows ? *args and **kwargs in Python Python Classes and Objects Iterate over a list in Python Convert integer to string in Python Python OOPs Concepts
[ { "code": null, "e": 28, "s": 0, "text": "\n29 Aug, 2020" }, { "code": null, "e": 719, "s": 28, "text": "In this article we will see how we can current state of the MediaListPlayer object in the python vlc module. VLC media player is a free and open-source portable cross-platform media player software and streaming media server developed by the VideoLAN project. Media list player is used to play multiple media in a row for example playing a series, instead of taking single media it accepts media list. Its working is almost similar like the MediaPlayer object but it is capable of playing list of media. State can be playing paused or closed, we can pause and resume the media list player any time with the help of set_pause method, and it can be start playing with the help of play method." }, { "code": null, "e": 800, "s": 719, "text": "In order to do this we will use get_state method with the MediaListPlayer object" }, { "code": null, "e": 839, "s": 800, "text": "Syntax : media_list_player.get_state()" }, { "code": null, "e": 871, "s": 839, "text": "Argument : It takes no argument" }, { "code": null, "e": 904, "s": 871, "text": "Return : It returns State object" }, { "code": null, "e": 932, "s": 904, "text": "Below is the implementation" }, { "code": "# importing vlc moduleimport vlc # importing time moduleimport time # creating a media player objectmedia_player = vlc.MediaListPlayer() # creating Instance class objectplayer = vlc.Instance() # creating a new media list objectmedia_list = player.media_list_new() # creating a new mediamedia = player.media_new(\"death_note.mkv\") # adding media to media listmedia_list.add_media(media) # setting media list to the media playermedia_player.set_media_list(media_list) # start playing videomedia_player.play() # wait so the video can be played for 5 seconds# irrespective for length of videotime.sleep(5) # getting media player current statevalue = media_player.get_state() # printing valueprint(value)", "e": 1646, "s": 932, "text": null }, { "code": null, "e": 1655, "s": 1646, "text": "Output :" }, { "code": null, "e": 1670, "s": 1655, "text": "State.Playing\n" }, { "code": null, "e": 1713, "s": 1670, "text": "Another exampleBelow is the implementation" }, { "code": "# importing vlc moduleimport vlc # importing time moduleimport time # creating a media player objectmedia_player = vlc.MediaListPlayer() # creating Instance class objectplayer = vlc.Instance() # creating a new media listmedia_list = player.media_list_new() # creating a new mediamedia = player.media_new(\"1.mp4\") # adding media to media listmedia_list.add_media(media) # setting media list to the media playermedia_player.set_media_list(media_list) # start playing videomedia_player.play() # wait so the video can be played for 5 seconds# irrespective for length of videotime.sleep(5) # getting media player current statevalue = media_player.get_state() # printing valueprint(value)", "e": 2409, "s": 1713, "text": null }, { "code": null, "e": 2418, "s": 2409, "text": "Output :" }, { "code": null, "e": 2433, "s": 2418, "text": "State.Playing\n" }, { "code": null, "e": 2456, "s": 2433, "text": "Python vlc-mediaPlayer" }, { "code": null, "e": 2463, "s": 2456, "text": "Python" }, { "code": null, "e": 2561, "s": 2463, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2579, "s": 2561, "text": "Python Dictionary" }, { "code": null, "e": 2621, "s": 2579, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 2643, "s": 2621, "text": "Enumerate() in Python" }, { "code": null, "e": 2678, "s": 2643, "text": "Read a file line by line in Python" }, { "code": null, "e": 2710, "s": 2678, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2739, "s": 2710, "text": "*args and **kwargs in Python" }, { "code": null, "e": 2766, "s": 2739, "text": "Python Classes and Objects" }, { "code": null, "e": 2796, "s": 2766, "text": "Iterate over a list in Python" }, { "code": null, "e": 2832, "s": 2796, "text": "Convert integer to string in Python" } ]
HTML5 - MathML
The HTML syntax of HTML5 allows for MathML elements to be used inside a document using <math>...</math> tags. Most of the web browsers can display MathML tags. If your browser does not support MathML, then I would suggest you to use latest version of Firefox. Following is a valid HTML5 document with MathML − <!doctype html> <html> <head> <meta charset = "UTF-8"> <title>Pythagorean theorem</title> </head> <body> <math xmlns = "http://www.w3.org/1998/Math/MathML"> <mrow> <msup><mi>a</mi><mn>2</mn></msup> <mo>+</mo> <msup><mi>b</mi><mn>2</mn></msup> <mo> = </mo> <msup><mi>c</mi><mn>2</mn></msup> </mrow> </math> </body> </html> This will produce the following result − Consider, following is the markup which makes use of the characters &InvisibleTimes; − <!doctype html> <html> <head> <meta charset = "UTF-8"> <title>MathML Examples</title> </head> <body> <math xmlns = "http://www.w3.org/1998/Math/MathML"> <mrow> <mrow> <msup> <mi>x</mi> <mn>2</mn> </msup> <mo>+</mo> <mrow> <mn>4</mn> <mo>⁢</mo> <mi>x</mi> </mrow> <mo>+</mo> <mn>4</mn> </mrow> <mo>=</mo> <mn>0</mn> </mrow> </math> </body> </html> This would produce the following result. If you are not able to see proper result like x2 + 4x + 4 = 0, then use Firefox 3.5 or higher version. This will produce the following result − Consider the following example which would be used to represent a simple 2x2 matrix − <!doctype html> <html> <head> <meta charset = "UTF-8"> <title>MathML Examples</title> </head> <body> <math xmlns = "http://www.w3.org/1998/Math/MathML"> <mrow> <mi>A</mi> <mo>=</mo> <mfenced open = "[" close="]"> <mtable> <mtr> <mtd><mi>x</mi></mtd> <mtd><mi>y</mi></mtd> </mtr> <mtr> <mtd><mi>z</mi></mtd> <mtd><mi>w</mi></mtd> </mtr> </mtable> </mfenced> </mrow> </math> </body> </html> This will produce the following result − This would produce the following result. If you are not able to see proper result, then use Firefox 3.5 or higher version. 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": 2718, "s": 2608, "text": "The HTML syntax of HTML5 allows for MathML elements to be used inside a document using <math>...</math> tags." }, { "code": null, "e": 2868, "s": 2718, "text": "Most of the web browsers can display MathML tags. If your browser does not support MathML, then I would suggest you to use latest version of Firefox." }, { "code": null, "e": 2918, "s": 2868, "text": "Following is a valid HTML5 document with MathML −" }, { "code": null, "e": 3375, "s": 2918, "text": "<!doctype html>\n\n<html>\n <head>\n <meta charset = \"UTF-8\">\n <title>Pythagorean theorem</title>\n </head>\n\t\n <body>\n <math xmlns = \"http://www.w3.org/1998/Math/MathML\">\n\t\t\n <mrow>\n <msup><mi>a</mi><mn>2</mn></msup>\n <mo>+</mo>\n\t\t\t\t\n <msup><mi>b</mi><mn>2</mn></msup>\n <mo> = </mo>\n\t\t\t\t\n <msup><mi>c</mi><mn>2</mn></msup>\n </mrow>\n\t\t\t\n </math>\n </body>\n</html> " }, { "code": null, "e": 3416, "s": 3375, "text": "This will produce the following result −" }, { "code": null, "e": 3503, "s": 3416, "text": "Consider, following is the markup which makes use of the characters &InvisibleTimes; −" }, { "code": null, "e": 4197, "s": 3503, "text": "<!doctype html>\n\n<html>\n <head>\n <meta charset = \"UTF-8\">\n <title>MathML Examples</title>\n </head>\n\t\n <body>\n <math xmlns = \"http://www.w3.org/1998/Math/MathML\">\n\t\t\n <mrow>\t\t\t\n <mrow>\n\t\t\t\t\n <msup>\n <mi>x</mi>\n <mn>2</mn>\n </msup>\n\t\t\t\t\t\n <mo>+</mo>\n\t\t\t\t\t\n <mrow>\n <mn>4</mn>\n <mo>⁢</mo>\n <mi>x</mi>\n </mrow>\n\t\t\t\t\t\n <mo>+</mo>\n <mn>4</mn>\n\t\t\t\t\t\n </mrow>\n\t\t\t\t\n <mo>=</mo>\n <mn>0</mn>\n\t\t\t\t \n </mrow>\n </math>\n </body>\n</html> " }, { "code": null, "e": 4341, "s": 4197, "text": "This would produce the following result. If you are not able to see proper result like x2 + 4x + 4 = 0, then use Firefox 3.5 or higher version." }, { "code": null, "e": 4382, "s": 4341, "text": "This will produce the following result −" }, { "code": null, "e": 4468, "s": 4382, "text": "Consider the following example which would be used to represent a simple 2x2 matrix −" }, { "code": null, "e": 5183, "s": 4468, "text": "<!doctype html>\n\n<html>\n <head>\n <meta charset = \"UTF-8\">\n <title>MathML Examples</title>\n </head>\n\t\n <body>\n <math xmlns = \"http://www.w3.org/1998/Math/MathML\">\n\t\t\n <mrow>\n <mi>A</mi>\n <mo>=</mo>\n\t\t\t\n <mfenced open = \"[\" close=\"]\">\n\t\t\t\n <mtable>\n <mtr>\n <mtd><mi>x</mi></mtd>\n <mtd><mi>y</mi></mtd>\n </mtr>\n\t\t\t\t\t\n <mtr>\n <mtd><mi>z</mi></mtd>\n <mtd><mi>w</mi></mtd>\n </mtr>\n </mtable>\n \n </mfenced>\n </mrow>\n </math>\n\n </body>\n</html> " }, { "code": null, "e": 5224, "s": 5183, "text": "This will produce the following result −" }, { "code": null, "e": 5347, "s": 5224, "text": "This would produce the following result. If you are not able to see proper result, then use Firefox 3.5 or higher version." }, { "code": null, "e": 5380, "s": 5347, "text": "\n 19 Lectures \n 2 hours \n" }, { "code": null, "e": 5394, "s": 5380, "text": " Anadi Sharma" }, { "code": null, "e": 5429, "s": 5394, "text": "\n 16 Lectures \n 1.5 hours \n" }, { "code": null, "e": 5443, "s": 5429, "text": " Anadi Sharma" }, { "code": null, "e": 5478, "s": 5443, "text": "\n 18 Lectures \n 1.5 hours \n" }, { "code": null, "e": 5495, "s": 5478, "text": " Frahaan Hussain" }, { "code": null, "e": 5530, "s": 5495, "text": "\n 57 Lectures \n 5.5 hours \n" }, { "code": null, "e": 5561, "s": 5530, "text": " DigiFisk (Programming Is Fun)" }, { "code": null, "e": 5594, "s": 5561, "text": "\n 54 Lectures \n 6 hours \n" }, { "code": null, "e": 5625, "s": 5594, "text": " DigiFisk (Programming Is Fun)" }, { "code": null, "e": 5660, "s": 5625, "text": "\n 45 Lectures \n 5.5 hours \n" }, { "code": null, "e": 5691, "s": 5660, "text": " DigiFisk (Programming Is Fun)" }, { "code": null, "e": 5698, "s": 5691, "text": " Print" }, { "code": null, "e": 5709, "s": 5698, "text": " Add Notes" } ]
Python program to list Sort by Number value in String - GeeksforGeeks
18 Jul, 2021 Given a List of strings, the task is to write a Python program to sort list by the number present in the Strings. If no number is present, they will be taken to the front of the list. Input : test_list = [“gfg is 4”, “all no 1”, “geeks over 7 seas”, “and 100 planets”] Output : [‘all no 1’, ‘gfg is 4’, ‘geeks over 7 seas’, ‘and 100 planets’] Explanation : 1 < 4 < 7 < 100, numbers in strings deciding order. Input : test_list = [“gfg is 4”, “geeks over 7 seas”, “and 100 planets”] Output : [‘gfg is 4’, ‘geeks over 7 seas’, ‘and 100 planets’] Explanation : 4 < 7 < 100, numbers in strings deciding order. Method 1 : Using sort(), split() and isdigit() In this, we perform the task of in-place sorting using sort(), and perform task of getting number from string using split() and final detection is done using isdigit(). Example: Python3 import sys def num_sort(strn): # getting number using isdigit() and split() computed_num = [ele for ele in strn.split() if ele.isdigit()] # assigning lowest weightage to strings # with no numbers if len(computed_num) > 0: return int(computed_num[0]) return -1 # initializing Matrixtest_list = ["gfg is", "all no 7", "geeks over seas", "and planets 5"] # printing original listprint("The original list is : " + str(test_list)) # performing sorttest_list.sort(key=num_sort) # printing resultprint("Sorted Strings : " + str(test_list)) Output: The original list is : [‘gfg is’, ‘all no 7’, ‘geeks over seas’, ‘and planets 5’] Sorted Strings : [‘gfg is’, ‘geeks over seas’, ‘and planets 5’, ‘all no 7’] Method 2 : Using sorted(), lambda, split() and isdigit() In this, lambda function is used to inject sort functionality performed using sorted(). Rest each process is similar to above explained method. Example: Python3 # initializing Matrixtest_list = ["all no 100", "gfg is", "geeks over seas 62", "and planets 3"] # printing original listprint("The original list is : " + str(test_list)) # performing sorting# lambda function injecting functionalityres = sorted(test_list, key=lambda strn: -1 if len([ele for ele in strn.split() if ele.isdigit()]) == 0 else int([ele for ele in strn.split() if ele.isdigit()][0])) # printing resultprint("Sorted Strings : " + str(res)) Output: The original list is : [‘all no 100’, ‘gfg is’, ‘geeks over seas 62’, ‘and planets 3’] Sorted Strings : [‘gfg is’, ‘and planets 3’, ‘geeks over seas 62’, ‘all no 100’] Python list-programs Python string-programs Python Python Programs 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 Python | os.path.join() method Defaultdict in Python Python | Split string into list of characters Python | Get dictionary keys as a list Python | Convert a list to dictionary Python program to check whether a number is Prime or not
[ { "code": null, "e": 24292, "s": 24264, "text": "\n18 Jul, 2021" }, { "code": null, "e": 24476, "s": 24292, "text": "Given a List of strings, the task is to write a Python program to sort list by the number present in the Strings. If no number is present, they will be taken to the front of the list." }, { "code": null, "e": 24701, "s": 24476, "text": "Input : test_list = [“gfg is 4”, “all no 1”, “geeks over 7 seas”, “and 100 planets”] Output : [‘all no 1’, ‘gfg is 4’, ‘geeks over 7 seas’, ‘and 100 planets’] Explanation : 1 < 4 < 7 < 100, numbers in strings deciding order." }, { "code": null, "e": 24899, "s": 24701, "text": "Input : test_list = [“gfg is 4”, “geeks over 7 seas”, “and 100 planets”] Output : [‘gfg is 4’, ‘geeks over 7 seas’, ‘and 100 planets’] Explanation : 4 < 7 < 100, numbers in strings deciding order. " }, { "code": null, "e": 24946, "s": 24899, "text": "Method 1 : Using sort(), split() and isdigit()" }, { "code": null, "e": 25116, "s": 24946, "text": "In this, we perform the task of in-place sorting using sort(), and perform task of getting number from string using split() and final detection is done using isdigit(). " }, { "code": null, "e": 25126, "s": 25116, "text": "Example: " }, { "code": null, "e": 25134, "s": 25126, "text": "Python3" }, { "code": "import sys def num_sort(strn): # getting number using isdigit() and split() computed_num = [ele for ele in strn.split() if ele.isdigit()] # assigning lowest weightage to strings # with no numbers if len(computed_num) > 0: return int(computed_num[0]) return -1 # initializing Matrixtest_list = [\"gfg is\", \"all no 7\", \"geeks over seas\", \"and planets 5\"] # printing original listprint(\"The original list is : \" + str(test_list)) # performing sorttest_list.sort(key=num_sort) # printing resultprint(\"Sorted Strings : \" + str(test_list))", "e": 25704, "s": 25134, "text": null }, { "code": null, "e": 25712, "s": 25704, "text": "Output:" }, { "code": null, "e": 25794, "s": 25712, "text": "The original list is : [‘gfg is’, ‘all no 7’, ‘geeks over seas’, ‘and planets 5’]" }, { "code": null, "e": 25870, "s": 25794, "text": "Sorted Strings : [‘gfg is’, ‘geeks over seas’, ‘and planets 5’, ‘all no 7’]" }, { "code": null, "e": 25928, "s": 25870, "text": "Method 2 : Using sorted(), lambda, split() and isdigit()" }, { "code": null, "e": 26072, "s": 25928, "text": "In this, lambda function is used to inject sort functionality performed using sorted(). Rest each process is similar to above explained method." }, { "code": null, "e": 26081, "s": 26072, "text": "Example:" }, { "code": null, "e": 26089, "s": 26081, "text": "Python3" }, { "code": "# initializing Matrixtest_list = [\"all no 100\", \"gfg is\", \"geeks over seas 62\", \"and planets 3\"] # printing original listprint(\"The original list is : \" + str(test_list)) # performing sorting# lambda function injecting functionalityres = sorted(test_list, key=lambda strn: -1 if len([ele for ele in strn.split() if ele.isdigit()]) == 0 else int([ele for ele in strn.split() if ele.isdigit()][0])) # printing resultprint(\"Sorted Strings : \" + str(res))", "e": 26614, "s": 26089, "text": null }, { "code": null, "e": 26622, "s": 26614, "text": "Output:" }, { "code": null, "e": 26709, "s": 26622, "text": "The original list is : [‘all no 100’, ‘gfg is’, ‘geeks over seas 62’, ‘and planets 3’]" }, { "code": null, "e": 26790, "s": 26709, "text": "Sorted Strings : [‘gfg is’, ‘and planets 3’, ‘geeks over seas 62’, ‘all no 100’]" }, { "code": null, "e": 26811, "s": 26790, "text": "Python list-programs" }, { "code": null, "e": 26834, "s": 26811, "text": "Python string-programs" }, { "code": null, "e": 26841, "s": 26834, "text": "Python" }, { "code": null, "e": 26857, "s": 26841, "text": "Python Programs" }, { "code": null, "e": 26955, "s": 26857, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26987, "s": 26955, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27029, "s": 26987, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 27085, "s": 27029, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 27127, "s": 27085, "text": "Check if element exists in list in Python" }, { "code": null, "e": 27158, "s": 27127, "text": "Python | os.path.join() method" }, { "code": null, "e": 27180, "s": 27158, "text": "Defaultdict in Python" }, { "code": null, "e": 27226, "s": 27180, "text": "Python | Split string into list of characters" }, { "code": null, "e": 27265, "s": 27226, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 27303, "s": 27265, "text": "Python | Convert a list to dictionary" } ]
Bootstrap Alerts , Wells, Pagination and Pager - GeeksforGeeks
12 Jan, 2022 Introduction and InstallationGrid SystemButtons, Glyphicons, TablesVertical Forms, Horizontal Forms, Inline FormsDropDowns and Responsive TabsProgress Bar and Jumbotron Introduction and Installation Grid System Buttons, Glyphicons, Tables Vertical Forms, Horizontal Forms, Inline Forms DropDowns and Responsive Tabs Progress Bar and Jumbotron Alerts We often see certain alerts on some websites before or after completing an action. These alert messages are highlighted texts that are important to take in consideration while performing a process. Bootstrap allows us to show these alert messages on our website using predefined classes.How to add alert messages using bootstrap classes- Inside a div element,add an alert class.Use the following classes to style the colour of the message boxGreen – alert-successBlue – alert-infoYellow –alert-warningRed – alert-dangerWrite the text you want to write for the alert message and close the div element. Inside a div element,add an alert class. Use the following classes to style the colour of the message boxGreen – alert-successBlue – alert-infoYellow –alert-warningRed – alert-danger Write the text you want to write for the alert message and close the div element. HTML <div class="alert alert-success"> <strong>Success!</strong></div> <div class="alert alert-info"> <strong>Info!</strong></div> <div class="alert alert-warning"> <strong>Warning!</strong></div> <div class="alert alert-danger"> <strong>Danger!</strong></div> Output: Dismissable Alerts : To close an alert message, you need to add a x icon in your alert. To add the icon include a class alert-dismissable to your div element. Then add a class close and data-dismiss=”alert” to a link or a button like this : HTML <div class="alert alert-success alert-dismissable"><a href="#" class="close" c aria-label="close">×</a> <strong>Success!</strong></div> <div class="alert alert-info alert-dismissable"><a href="#" class="close" data-dismiss="alert" aria-label="close">×</a> <strong>Info!</strong></div> <div class="alert alert-warning alert-dismissable"><a href="#" class="close" data-dismiss="alert" aria-label="close">×</a> <strong>Warning!</strong></div> <div class="alert alert-danger alert-dismissable"><a href="#" class="close" data-dismiss="alert" aria-label="close">×</a> <strong>Danger!</strong></div> Output: Alert links : To add a link to your alert message , just add a alert-link class inside the ‘a’ element. This will create a link in the same font colour as that of the alert message box. Then use the ‘a’ tag to add a link to the text like this: HTML <div class="alert alert-success"> <strong>Success!</strong><a href="#" class="alert-link">read this message</a></div> <div class="alert alert-info alert-dismissable"> <strong>Info!</strong><a href="#" class="alert-link">read this message</a></div> <div class="alert alert-warning alert-dismissable"> <strong>Warning!</strong><a href="#" class="alert-link">read this message</a></div> <div class="alert alert-danger alert-dismissable"> <strong>Danger!</strong><a href="#" class="alert-link">read this message</a></div> Output: Wells A well class is simply used to add a grey box around some text with rounded corners and some padding.To add a well in your webpage just include the well class in a div element, then write the text you want to keep in the well and close the div tag. HTML <div class="well">This is a Well</div> Output Well Size : The default size of the well is medium but we can increase or decrease the size of the well using class well-lg and well-sm respectively. HTML <div class="well well-lg">This is a large Well</div><div class="well well-sm">This is a small Well</div> Output Pagination We all have seen a website which has lots of webpages or when we search on google there are a lot of search results in different webpages which are numbered for 1. This feature can be easily added in a website using bootstrap.The predefined class used for pagination is .paginationTo add pagination to your website, include pagination class inside a ul tag like this- HTML <ul class="pagination"> <li><a href="#">1</a></li> <li><a href="#">2</a></li> <li><a href="#">3</a></li> <li><a href="#">4</a></li> <li><a href="#">5</a></li></ul> Output Active Page : To display the active page , use class active like this- HTML <ul class="pagination"> <li><a href="#">1</a></li> <li class="active"><a href="#">2</a></li> <li><a href="#">3</a></li> <li><a href="#">4</a></li> <li><a href="#">5</a></li></ul> Output Disabled Page : To disable a page to go to a certain link , use class disabled like this- HTML <ul class="pagination"> <li><a href="#">1</a></li> <li class="disabled"><a href="#">2</a></li> <li><a href="#">3</a></li> <li><a href="#">4</a></li> <li><a href="#">5</a></li></ul> Output Pager We all have seen ‘previous’ and ‘next’ buttons on a webpage to navigate to other pages. Bootstrap provides a predefined class to implement this pager efficiently. A pager provides links to move to the next or previous page.To add a pager to your webpage, add a class ‘pager’ to a div element and provide the links for previous and next page like this- HTML <ul class = "pager"> <li><a href = "#">Previous</a></li> <li><a href = "#">Next</a></li></ul> Output To align these navigation buttons to the side of the webpage , use class ‘previous’ and ‘next’ with the links like this- HTML <ul class="pager"> <li class="previous"><a href="#">Previous</a></li> <li class="next"><a href="#">Next</a></li></ul> Output This article is contributed by Ayush Saxena. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. ysachin2314 Web technologies Bootstrap Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to change navigation bar color in Bootstrap ? Form validation using jQuery How to pass data into a bootstrap modal? How to align navbar items to the right in Bootstrap 4 ? How to Show Images on Click using HTML ? Roadmap to Become a Web Developer in 2022 Installation of Node.js on Linux How to insert spaces/tabs in text using HTML/CSS? How to fetch data from an API in ReactJS ? Top 10 Projects For Beginners To Practice HTML and CSS Skills
[ { "code": null, "e": 28466, "s": 28438, "text": "\n12 Jan, 2022" }, { "code": null, "e": 28635, "s": 28466, "text": "Introduction and InstallationGrid SystemButtons, Glyphicons, TablesVertical Forms, Horizontal Forms, Inline FormsDropDowns and Responsive TabsProgress Bar and Jumbotron" }, { "code": null, "e": 28665, "s": 28635, "text": "Introduction and Installation" }, { "code": null, "e": 28677, "s": 28665, "text": "Grid System" }, { "code": null, "e": 28705, "s": 28677, "text": "Buttons, Glyphicons, Tables" }, { "code": null, "e": 28752, "s": 28705, "text": "Vertical Forms, Horizontal Forms, Inline Forms" }, { "code": null, "e": 28782, "s": 28752, "text": "DropDowns and Responsive Tabs" }, { "code": null, "e": 28809, "s": 28782, "text": "Progress Bar and Jumbotron" }, { "code": null, "e": 28816, "s": 28809, "text": "Alerts" }, { "code": null, "e": 29154, "s": 28816, "text": "We often see certain alerts on some websites before or after completing an action. These alert messages are highlighted texts that are important to take in consideration while performing a process. Bootstrap allows us to show these alert messages on our website using predefined classes.How to add alert messages using bootstrap classes-" }, { "code": null, "e": 29417, "s": 29154, "text": "Inside a div element,add an alert class.Use the following classes to style the colour of the message boxGreen – alert-successBlue – alert-infoYellow –alert-warningRed – alert-dangerWrite the text you want to write for the alert message and close the div element." }, { "code": null, "e": 29458, "s": 29417, "text": "Inside a div element,add an alert class." }, { "code": null, "e": 29600, "s": 29458, "text": "Use the following classes to style the colour of the message boxGreen – alert-successBlue – alert-infoYellow –alert-warningRed – alert-danger" }, { "code": null, "e": 29682, "s": 29600, "text": "Write the text you want to write for the alert message and close the div element." }, { "code": null, "e": 29687, "s": 29682, "text": "HTML" }, { "code": "<div class=\"alert alert-success\"> <strong>Success!</strong></div> <div class=\"alert alert-info\"> <strong>Info!</strong></div> <div class=\"alert alert-warning\"> <strong>Warning!</strong></div> <div class=\"alert alert-danger\"> <strong>Danger!</strong></div>", "e": 29950, "s": 29687, "text": null }, { "code": null, "e": 29958, "s": 29950, "text": "Output:" }, { "code": null, "e": 30199, "s": 29958, "text": "Dismissable Alerts : To close an alert message, you need to add a x icon in your alert. To add the icon include a class alert-dismissable to your div element. Then add a class close and data-dismiss=”alert” to a link or a button like this :" }, { "code": null, "e": 30204, "s": 30199, "text": "HTML" }, { "code": "<div class=\"alert alert-success alert-dismissable\"><a href=\"#\" class=\"close\" c aria-label=\"close\">×</a> <strong>Success!</strong></div> <div class=\"alert alert-info alert-dismissable\"><a href=\"#\" class=\"close\" data-dismiss=\"alert\" aria-label=\"close\">×</a> <strong>Info!</strong></div> <div class=\"alert alert-warning alert-dismissable\"><a href=\"#\" class=\"close\" data-dismiss=\"alert\" aria-label=\"close\">×</a> <strong>Warning!</strong></div> <div class=\"alert alert-danger alert-dismissable\"><a href=\"#\" class=\"close\" data-dismiss=\"alert\" aria-label=\"close\">×</a> <strong>Danger!</strong></div>", "e": 30804, "s": 30204, "text": null }, { "code": null, "e": 30812, "s": 30804, "text": "Output:" }, { "code": null, "e": 31056, "s": 30812, "text": "Alert links : To add a link to your alert message , just add a alert-link class inside the ‘a’ element. This will create a link in the same font colour as that of the alert message box. Then use the ‘a’ tag to add a link to the text like this:" }, { "code": null, "e": 31061, "s": 31056, "text": "HTML" }, { "code": "<div class=\"alert alert-success\"> <strong>Success!</strong><a href=\"#\" class=\"alert-link\">read this message</a></div> <div class=\"alert alert-info alert-dismissable\"> <strong>Info!</strong><a href=\"#\" class=\"alert-link\">read this message</a></div> <div class=\"alert alert-warning alert-dismissable\"> <strong>Warning!</strong><a href=\"#\" class=\"alert-link\">read this message</a></div> <div class=\"alert alert-danger alert-dismissable\"> <strong>Danger!</strong><a href=\"#\" class=\"alert-link\">read this message</a></div>", "e": 31586, "s": 31061, "text": null }, { "code": null, "e": 31594, "s": 31586, "text": "Output:" }, { "code": null, "e": 31600, "s": 31594, "text": "Wells" }, { "code": null, "e": 31849, "s": 31600, "text": "A well class is simply used to add a grey box around some text with rounded corners and some padding.To add a well in your webpage just include the well class in a div element, then write the text you want to keep in the well and close the div tag." }, { "code": null, "e": 31854, "s": 31849, "text": "HTML" }, { "code": "<div class=\"well\">This is a Well</div>", "e": 31893, "s": 31854, "text": null }, { "code": null, "e": 31900, "s": 31893, "text": "Output" }, { "code": null, "e": 32050, "s": 31900, "text": "Well Size : The default size of the well is medium but we can increase or decrease the size of the well using class well-lg and well-sm respectively." }, { "code": null, "e": 32055, "s": 32050, "text": "HTML" }, { "code": "<div class=\"well well-lg\">This is a large Well</div><div class=\"well well-sm\">This is a small Well</div>", "e": 32160, "s": 32055, "text": null }, { "code": null, "e": 32167, "s": 32160, "text": "Output" }, { "code": null, "e": 32178, "s": 32167, "text": "Pagination" }, { "code": null, "e": 32546, "s": 32178, "text": "We all have seen a website which has lots of webpages or when we search on google there are a lot of search results in different webpages which are numbered for 1. This feature can be easily added in a website using bootstrap.The predefined class used for pagination is .paginationTo add pagination to your website, include pagination class inside a ul tag like this-" }, { "code": null, "e": 32551, "s": 32546, "text": "HTML" }, { "code": "<ul class=\"pagination\"> <li><a href=\"#\">1</a></li> <li><a href=\"#\">2</a></li> <li><a href=\"#\">3</a></li> <li><a href=\"#\">4</a></li> <li><a href=\"#\">5</a></li></ul> ", "e": 32721, "s": 32551, "text": null }, { "code": null, "e": 32728, "s": 32721, "text": "Output" }, { "code": null, "e": 32799, "s": 32728, "text": "Active Page : To display the active page , use class active like this-" }, { "code": null, "e": 32804, "s": 32799, "text": "HTML" }, { "code": "<ul class=\"pagination\"> <li><a href=\"#\">1</a></li> <li class=\"active\"><a href=\"#\">2</a></li> <li><a href=\"#\">3</a></li> <li><a href=\"#\">4</a></li> <li><a href=\"#\">5</a></li></ul> ", "e": 32989, "s": 32804, "text": null }, { "code": null, "e": 32996, "s": 32989, "text": "Output" }, { "code": null, "e": 33086, "s": 32996, "text": "Disabled Page : To disable a page to go to a certain link , use class disabled like this-" }, { "code": null, "e": 33091, "s": 33086, "text": "HTML" }, { "code": "<ul class=\"pagination\"> <li><a href=\"#\">1</a></li> <li class=\"disabled\"><a href=\"#\">2</a></li> <li><a href=\"#\">3</a></li> <li><a href=\"#\">4</a></li> <li><a href=\"#\">5</a></li></ul> ", "e": 33278, "s": 33091, "text": null }, { "code": null, "e": 33285, "s": 33278, "text": "Output" }, { "code": null, "e": 33291, "s": 33285, "text": "Pager" }, { "code": null, "e": 33643, "s": 33291, "text": "We all have seen ‘previous’ and ‘next’ buttons on a webpage to navigate to other pages. Bootstrap provides a predefined class to implement this pager efficiently. A pager provides links to move to the next or previous page.To add a pager to your webpage, add a class ‘pager’ to a div element and provide the links for previous and next page like this-" }, { "code": null, "e": 33648, "s": 33643, "text": "HTML" }, { "code": "<ul class = \"pager\"> <li><a href = \"#\">Previous</a></li> <li><a href = \"#\">Next</a></li></ul>", "e": 33746, "s": 33648, "text": null }, { "code": null, "e": 33753, "s": 33746, "text": "Output" }, { "code": null, "e": 33874, "s": 33753, "text": "To align these navigation buttons to the side of the webpage , use class ‘previous’ and ‘next’ with the links like this-" }, { "code": null, "e": 33879, "s": 33874, "text": "HTML" }, { "code": "<ul class=\"pager\"> <li class=\"previous\"><a href=\"#\">Previous</a></li> <li class=\"next\"><a href=\"#\">Next</a></li></ul> ", "e": 34000, "s": 33879, "text": null }, { "code": null, "e": 34007, "s": 34000, "text": "Output" }, { "code": null, "e": 34298, "s": 34007, "text": "This article is contributed by Ayush Saxena. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks." }, { "code": null, "e": 34423, "s": 34298, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 34435, "s": 34423, "text": "ysachin2314" }, { "code": null, "e": 34452, "s": 34435, "text": "Web technologies" }, { "code": null, "e": 34462, "s": 34452, "text": "Bootstrap" }, { "code": null, "e": 34479, "s": 34462, "text": "Web Technologies" }, { "code": null, "e": 34577, "s": 34479, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 34586, "s": 34577, "text": "Comments" }, { "code": null, "e": 34599, "s": 34586, "text": "Old Comments" }, { "code": null, "e": 34649, "s": 34599, "text": "How to change navigation bar color in Bootstrap ?" }, { "code": null, "e": 34678, "s": 34649, "text": "Form validation using jQuery" }, { "code": null, "e": 34719, "s": 34678, "text": "How to pass data into a bootstrap modal?" }, { "code": null, "e": 34775, "s": 34719, "text": "How to align navbar items to the right in Bootstrap 4 ?" }, { "code": null, "e": 34816, "s": 34775, "text": "How to Show Images on Click using HTML ?" }, { "code": null, "e": 34858, "s": 34816, "text": "Roadmap to Become a Web Developer in 2022" }, { "code": null, "e": 34891, "s": 34858, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 34941, "s": 34891, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 34984, "s": 34941, "text": "How to fetch data from an API in ReactJS ?" } ]
Errors in C/C++
In C or C++, we face different kinds of errors. These errors can be categorized into five different types. These are like below − Syntax Error Run-Time Error Linker Error Logical Error Semantic Error Let us see these errors one by one − This kind of errors are occurred, when it violates the rule of C++ writing techniques or syntaxes. This kind of errors are generally indicated by the compiler before compilation. Sometimes these are known as compile time error. In this example, we will see how to get syntax error if we do not put semicolon after one line. #include<stdio.h> main() { printf("Hello World") } Error] expected ';' before '}' token This kind of errors are occurred, when the program is executing. As this is not compilation error, so the compilation will be successfully done. We can check this error if we try to divide a number with 0. #include<stdio.h> main() { int x = 52; int y = 0; printf("Div : %f", x/y); } Program crashes during runtime. This kind of errors are occurred, when the program is compiled successfully, and trying to link the different object file with the main object file. When this error is occurred, the executable is not generated, For example some wrong function prototyping, incorrect header file etc. If the main() is written as Main(), this will generate linked error. #include<stdio.h> main() { int x = 52; int y = 0; printf("Div : %f", x/y); } C:\crossdev\src\mingw-w64-v3-git\mingw-w64-crt\crt\crt0_c.cundefined reference to `WinMain' Sometimes, we may not get the desired output. If the syntax and other things are correct, then also, we may not get correct output due to some logical issues. These are called the logical error. Sometimes, we put a semicolon after a loop, that is syntactically correct, but will create one blank loop. In that case, it will show desired output. #include<stdio.h> main() { int i; for(i = 0; i<5; i++); { printf("Hello World"); } } Here we want the line will be printed five times. But only one time it will be printed for the block of code. This kind of error occurs when it is syntactically correct but has no meaning. This is like grammatical mistakes. If some expression is given at the left side of assignment operator, this may generate semantic error. #include<stdio.h> main() { int x, y, z; x = 10; y = 20; x + y = z; } [Error] lvalue required as left operand of assignment
[ { "code": null, "e": 1192, "s": 1062, "text": "In C or C++, we face different kinds of errors. These errors can be categorized into five different types. These are like below −" }, { "code": null, "e": 1205, "s": 1192, "text": "Syntax Error" }, { "code": null, "e": 1220, "s": 1205, "text": "Run-Time Error" }, { "code": null, "e": 1233, "s": 1220, "text": "Linker Error" }, { "code": null, "e": 1247, "s": 1233, "text": "Logical Error" }, { "code": null, "e": 1262, "s": 1247, "text": "Semantic Error" }, { "code": null, "e": 1299, "s": 1262, "text": "Let us see these errors one by one −" }, { "code": null, "e": 1527, "s": 1299, "text": "This kind of errors are occurred, when it violates the rule of C++ writing techniques or syntaxes. This kind of errors are generally indicated by the compiler before compilation. Sometimes these are known as compile time error." }, { "code": null, "e": 1623, "s": 1527, "text": "In this example, we will see how to get syntax error if we do not put semicolon after one line." }, { "code": null, "e": 1677, "s": 1623, "text": "#include<stdio.h>\nmain() {\n printf(\"Hello World\")\n}" }, { "code": null, "e": 1714, "s": 1677, "text": "Error] expected ';' before '}' token" }, { "code": null, "e": 1920, "s": 1714, "text": "This kind of errors are occurred, when the program is executing. As this is not compilation error, so the compilation will be successfully done. We can check this error if we try to divide a number with 0." }, { "code": null, "e": 2006, "s": 1920, "text": "#include<stdio.h>\nmain() {\n int x = 52;\n int y = 0;\n printf(\"Div : %f\", x/y);\n}" }, { "code": null, "e": 2038, "s": 2006, "text": "Program crashes during runtime." }, { "code": null, "e": 2390, "s": 2038, "text": "This kind of errors are occurred, when the program is compiled successfully, and trying to link the different object file with the main object file. When this error is occurred, the executable is not generated, For example some wrong function prototyping, incorrect header file etc. If the main() is written as Main(), this will generate linked error." }, { "code": null, "e": 2476, "s": 2390, "text": "#include<stdio.h>\nmain() {\n int x = 52;\n int y = 0;\n printf(\"Div : %f\", x/y);\n}" }, { "code": null, "e": 2568, "s": 2476, "text": "C:\\crossdev\\src\\mingw-w64-v3-git\\mingw-w64-crt\\crt\\crt0_c.cundefined reference to `WinMain'" }, { "code": null, "e": 2913, "s": 2568, "text": "Sometimes, we may not get the desired output. If the syntax and other things are correct, then also, we may not get correct output due to some logical issues. These are called the logical error. Sometimes, we put a semicolon after a loop, that is syntactically correct, but will create one blank loop. In that case, it will show desired output." }, { "code": null, "e": 3013, "s": 2913, "text": "#include<stdio.h>\nmain() {\n int i;\n for(i = 0; i<5; i++); {\n printf(\"Hello World\");\n }\n}" }, { "code": null, "e": 3123, "s": 3013, "text": "Here we want the line will be printed five times. But only one time it will be printed for the block of code." }, { "code": null, "e": 3340, "s": 3123, "text": "This kind of error occurs when it is syntactically correct but has no meaning. This is like grammatical mistakes. If some expression is given at the left side of assignment operator, this may generate semantic error." }, { "code": null, "e": 3422, "s": 3340, "text": "#include<stdio.h>\n\nmain() {\n int x, y, z;\n x = 10;\n y = 20;\n x + y = z;\n}" }, { "code": null, "e": 3476, "s": 3422, "text": "[Error] lvalue required as left operand of assignment" } ]
Django - Sessions
As discussed earlier, we can use client side cookies to store a lot of useful data for the web app. We have seen before that we can use client side cookies to store various data useful for our web app. This leads to lot of security holes depending on the importance of the data you want to save. For security reasons, Django has a session framework for cookies handling. Sessions are used to abstract the receiving and sending of cookies, data is saved on server side (like in database), and the client side cookie just has a session ID for identification. Sessions are also useful to avoid cases where the user browser is set to ‘not accept’ cookies. In Django, enabling session is done in your project settings.py, by adding some lines to the MIDDLEWARE_CLASSES and the INSTALLED_APPS options. This should be done while creating the project, but it's always good to know, so MIDDLEWARE_CLASSES should have − 'django.contrib.sessions.middleware.SessionMiddleware' And INSTALLED_APPS should have − 'django.contrib.sessions' By default, Django saves session information in database (django_session table or collection), but you can configure the engine to store information using other ways like: in file or in cache. When session is enabled, every request (first argument of any view in Django) has a session (dict) attribute. Let's create a simple sample to see how to create and save sessions. We have built a simple login system before (see Django form processing chapter and Django Cookies Handling chapter). Let us save the username in a cookie so, if not signed out, when accessing our login page you won’t see the login form. Basically, let's make our login system we used in Django Cookies handling more secure, by saving cookies server side. For this, first lets change our login view to save our username cookie server side − def login(request): username = 'not logged in' if request.method == 'POST': MyLoginForm = LoginForm(request.POST) if MyLoginForm.is_valid(): username = MyLoginForm.cleaned_data['username'] request.session['username'] = username else: MyLoginForm = LoginForm() return render(request, 'loggedin.html', {"username" : username} Then let us create formView view for the login form, where we won’t display the form if cookie is set − def formView(request): if request.session.has_key('username'): username = request.session['username'] return render(request, 'loggedin.html', {"username" : username}) else: return render(request, 'login.html', {}) Now let us change the url.py file to change the url so it pairs with our new view − from django.conf.urls import patterns, url from django.views.generic import TemplateView urlpatterns = patterns('myapp.views', url(r'^connection/','formView', name = 'loginform'), url(r'^login/', 'login', name = 'login')) When accessing /myapp/connection, you will get to see the following page − And you will get redirected to the following page − Now if you try to access /myapp/connection again, you will get redirected to the second screen directly. Let's create a simple logout view that erases our cookie. def logout(request): try: del request.session['username'] except: pass return HttpResponse("<strong>You are logged out.</strong>") And pair it with a logout URL in myapp/url.py url(r'^logout/', 'logout', name = 'logout'), Now, if you access /myapp/logout, you will get the following page − If you access /myapp/connection again, you will get the login form (screen 1). We have seen how to store and access a session, but it's good to know that the session attribute of the request have some other useful actions like − set_expiry (value) − Sets the expiration time for the session. set_expiry (value) − Sets the expiration time for the session. get_expiry_age() − Returns the number of seconds until this session expires. get_expiry_age() − Returns the number of seconds until this session expires. get_expiry_date() − Returns the date this session will expire. get_expiry_date() − Returns the date this session will expire. clear_expired() − Removes expired sessions from the session store. clear_expired() − Removes expired sessions from the session store. get_expire_at_browser_close() − Returns either True or False, depending on whether the user’s session cookies have expired when the user’s web browser is closed. get_expire_at_browser_close() − Returns either True or False, depending on whether the user’s session cookies have expired when the user’s web browser is closed. 39 Lectures 3.5 hours John Elder 36 Lectures 2.5 hours John Elder 28 Lectures 2 hours John Elder 20 Lectures 1 hours John Elder 35 Lectures 3 hours John Elder 79 Lectures 10 hours Rathan Kumar Print Add Notes Bookmark this page
[ { "code": null, "e": 2341, "s": 2045, "text": "As discussed earlier, we can use client side cookies to store a lot of useful data for the web app. We have seen before that we can use client side cookies to store various data useful for our web app. This leads to lot of security holes depending on the importance of the data you want to save." }, { "code": null, "e": 2697, "s": 2341, "text": "For security reasons, Django has a session framework for cookies handling. Sessions are used to abstract the receiving and sending of cookies, data is saved on server side (like in database), and the client side cookie just has a session ID for identification. Sessions are also useful to avoid cases where the user browser is set to ‘not accept’ cookies." }, { "code": null, "e": 2955, "s": 2697, "text": "In Django, enabling session is done in your project settings.py, by adding some lines to the MIDDLEWARE_CLASSES and the INSTALLED_APPS options. This should be done while creating the project, but it's always good to know, so MIDDLEWARE_CLASSES should have −" }, { "code": null, "e": 3011, "s": 2955, "text": "'django.contrib.sessions.middleware.SessionMiddleware'\n" }, { "code": null, "e": 3044, "s": 3011, "text": "And INSTALLED_APPS should have −" }, { "code": null, "e": 3071, "s": 3044, "text": "'django.contrib.sessions'\n" }, { "code": null, "e": 3264, "s": 3071, "text": "By default, Django saves session information in database (django_session table or collection), but you can configure the engine to store information using other ways like: in file or in cache." }, { "code": null, "e": 3374, "s": 3264, "text": "When session is enabled, every request (first argument of any view in Django) has a session (dict) attribute." }, { "code": null, "e": 3798, "s": 3374, "text": "Let's create a simple sample to see how to create and save sessions. We have built a simple login system before (see Django form processing chapter and Django Cookies Handling chapter). Let us save the username in a cookie so, if not signed out, when accessing our login page you won’t see the login form. Basically, let's make our login system we used in Django Cookies handling more secure, by saving cookies server side." }, { "code": null, "e": 3883, "s": 3798, "text": "For this, first lets change our login view to save our username cookie server side −" }, { "code": null, "e": 4276, "s": 3883, "text": "def login(request):\n username = 'not logged in'\n \n if request.method == 'POST':\n MyLoginForm = LoginForm(request.POST)\n \n if MyLoginForm.is_valid():\n username = MyLoginForm.cleaned_data['username']\n request.session['username'] = username\n else:\n MyLoginForm = LoginForm()\n\t\t\t\n return render(request, 'loggedin.html', {\"username\" : username}" }, { "code": null, "e": 4380, "s": 4276, "text": "Then let us create formView view for the login form, where we won’t display the form if cookie is set −" }, { "code": null, "e": 4618, "s": 4380, "text": "def formView(request):\n if request.session.has_key('username'):\n username = request.session['username']\n return render(request, 'loggedin.html', {\"username\" : username})\n else:\n return render(request, 'login.html', {})" }, { "code": null, "e": 4702, "s": 4618, "text": "Now let us change the url.py file to change the url so it pairs with our new view −" }, { "code": null, "e": 4931, "s": 4702, "text": "from django.conf.urls import patterns, url\nfrom django.views.generic import TemplateView\n\nurlpatterns = patterns('myapp.views',\n url(r'^connection/','formView', name = 'loginform'),\n url(r'^login/', 'login', name = 'login'))" }, { "code": null, "e": 5006, "s": 4931, "text": "When accessing /myapp/connection, you will get to see the following page −" }, { "code": null, "e": 5058, "s": 5006, "text": "And you will get redirected to the following page −" }, { "code": null, "e": 5163, "s": 5058, "text": "Now if you try to access /myapp/connection again, you will get redirected to the second screen directly." }, { "code": null, "e": 5221, "s": 5163, "text": "Let's create a simple logout view that erases our cookie." }, { "code": null, "e": 5373, "s": 5221, "text": "def logout(request):\n try:\n del request.session['username']\n except:\n pass\n return HttpResponse(\"<strong>You are logged out.</strong>\")" }, { "code": null, "e": 5419, "s": 5373, "text": "And pair it with a logout URL in myapp/url.py" }, { "code": null, "e": 5465, "s": 5419, "text": "url(r'^logout/', 'logout', name = 'logout'),\n" }, { "code": null, "e": 5533, "s": 5465, "text": "Now, if you access /myapp/logout, you will get the following page −" }, { "code": null, "e": 5612, "s": 5533, "text": "If you access /myapp/connection again, you will get the login form (screen 1)." }, { "code": null, "e": 5762, "s": 5612, "text": "We have seen how to store and access a session, but it's good to know that the session attribute of the request have some other useful actions like −" }, { "code": null, "e": 5825, "s": 5762, "text": "set_expiry (value) − Sets the expiration time for the session." }, { "code": null, "e": 5888, "s": 5825, "text": "set_expiry (value) − Sets the expiration time for the session." }, { "code": null, "e": 5965, "s": 5888, "text": "get_expiry_age() − Returns the number of seconds until this session expires." }, { "code": null, "e": 6042, "s": 5965, "text": "get_expiry_age() − Returns the number of seconds until this session expires." }, { "code": null, "e": 6105, "s": 6042, "text": "get_expiry_date() − Returns the date this session will expire." }, { "code": null, "e": 6168, "s": 6105, "text": "get_expiry_date() − Returns the date this session will expire." }, { "code": null, "e": 6235, "s": 6168, "text": "clear_expired() − Removes expired sessions from the session store." }, { "code": null, "e": 6302, "s": 6235, "text": "clear_expired() − Removes expired sessions from the session store." }, { "code": null, "e": 6464, "s": 6302, "text": "get_expire_at_browser_close() − Returns either True or False, depending on whether the user’s session cookies have expired when the user’s web browser is closed." }, { "code": null, "e": 6626, "s": 6464, "text": "get_expire_at_browser_close() − Returns either True or False, depending on whether the user’s session cookies have expired when the user’s web browser is closed." }, { "code": null, "e": 6661, "s": 6626, "text": "\n 39 Lectures \n 3.5 hours \n" }, { "code": null, "e": 6673, "s": 6661, "text": " John Elder" }, { "code": null, "e": 6708, "s": 6673, "text": "\n 36 Lectures \n 2.5 hours \n" }, { "code": null, "e": 6720, "s": 6708, "text": " John Elder" }, { "code": null, "e": 6753, "s": 6720, "text": "\n 28 Lectures \n 2 hours \n" }, { "code": null, "e": 6765, "s": 6753, "text": " John Elder" }, { "code": null, "e": 6798, "s": 6765, "text": "\n 20 Lectures \n 1 hours \n" }, { "code": null, "e": 6810, "s": 6798, "text": " John Elder" }, { "code": null, "e": 6843, "s": 6810, "text": "\n 35 Lectures \n 3 hours \n" }, { "code": null, "e": 6855, "s": 6843, "text": " John Elder" }, { "code": null, "e": 6889, "s": 6855, "text": "\n 79 Lectures \n 10 hours \n" }, { "code": null, "e": 6903, "s": 6889, "text": " Rathan Kumar" }, { "code": null, "e": 6910, "s": 6903, "text": " Print" }, { "code": null, "e": 6921, "s": 6910, "text": " Add Notes" } ]
Check if an Object is of Type Numeric in R Programming - is.numeric() Function - GeeksforGeeks
16 Jun, 2020 is.numeric() function in R Language is used to check if the object passed to it as argument is of numeric type. Syntax: is.numeric(x) Parameters:x: Object to be checked Example 1: # R program to check if # object is of numeric type # Calling is.numeric() functionis.numeric(1)is.numeric(1.5)is.numeric(-1.5) Output: [1] TRUE [1] TRUE [1] TRUE Example 2: # R program to check if # object is of numeric type # Creating a matrixx1 <- matrix(c(1:9), 3, 3) # Calling is.numeric() functionis.numeric(x1) Output: [1] TRUE R List-Function R Math-Function R Matrix-Function R Object-Function R Vector-Function R Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Filter data by multiple conditions in R using Dplyr Loops in R (for, while, repeat) Change Color of Bars in Barchart using ggplot2 in R How to change Row Names of DataFrame in R ? How to Change Axis Scales in R Plots? Group by function in R using Dplyr K-Means Clustering in R Programming Remove rows with NA in one column of R DataFrame How to Split Column Into Multiple Columns in R DataFrame? R Programming Language - Introduction
[ { "code": null, "e": 24918, "s": 24890, "text": "\n16 Jun, 2020" }, { "code": null, "e": 25030, "s": 24918, "text": "is.numeric() function in R Language is used to check if the object passed to it as argument is of numeric type." }, { "code": null, "e": 25052, "s": 25030, "text": "Syntax: is.numeric(x)" }, { "code": null, "e": 25087, "s": 25052, "text": "Parameters:x: Object to be checked" }, { "code": null, "e": 25098, "s": 25087, "text": "Example 1:" }, { "code": "# R program to check if # object is of numeric type # Calling is.numeric() functionis.numeric(1)is.numeric(1.5)is.numeric(-1.5)", "e": 25227, "s": 25098, "text": null }, { "code": null, "e": 25235, "s": 25227, "text": "Output:" }, { "code": null, "e": 25263, "s": 25235, "text": "[1] TRUE\n[1] TRUE\n[1] TRUE\n" }, { "code": null, "e": 25274, "s": 25263, "text": "Example 2:" }, { "code": "# R program to check if # object is of numeric type # Creating a matrixx1 <- matrix(c(1:9), 3, 3) # Calling is.numeric() functionis.numeric(x1)", "e": 25420, "s": 25274, "text": null }, { "code": null, "e": 25428, "s": 25420, "text": "Output:" }, { "code": null, "e": 25438, "s": 25428, "text": "[1] TRUE\n" }, { "code": null, "e": 25454, "s": 25438, "text": "R List-Function" }, { "code": null, "e": 25470, "s": 25454, "text": "R Math-Function" }, { "code": null, "e": 25488, "s": 25470, "text": "R Matrix-Function" }, { "code": null, "e": 25506, "s": 25488, "text": "R Object-Function" }, { "code": null, "e": 25524, "s": 25506, "text": "R Vector-Function" }, { "code": null, "e": 25535, "s": 25524, "text": "R Language" }, { "code": null, "e": 25633, "s": 25535, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25685, "s": 25633, "text": "Filter data by multiple conditions in R using Dplyr" }, { "code": null, "e": 25717, "s": 25685, "text": "Loops in R (for, while, repeat)" }, { "code": null, "e": 25769, "s": 25717, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 25813, "s": 25769, "text": "How to change Row Names of DataFrame in R ?" }, { "code": null, "e": 25851, "s": 25813, "text": "How to Change Axis Scales in R Plots?" }, { "code": null, "e": 25886, "s": 25851, "text": "Group by function in R using Dplyr" }, { "code": null, "e": 25922, "s": 25886, "text": "K-Means Clustering in R Programming" }, { "code": null, "e": 25971, "s": 25922, "text": "Remove rows with NA in one column of R DataFrame" }, { "code": null, "e": 26029, "s": 25971, "text": "How to Split Column Into Multiple Columns in R DataFrame?" } ]
Java RMI Application
To write an RMI Java application, you would have to follow the steps given below − Define the remote interface Develop the implementation class (remote object) Develop the server program Develop the client program Compile the application Execute the application A remote interface provides the description of all the methods of a particular remote object. The client communicates with this remote interface. To create a remote interface − Create an interface that extends the predefined interface Remote which belongs to the package. Create an interface that extends the predefined interface Remote which belongs to the package. Declare all the business methods that can be invoked by the client in this interface. Declare all the business methods that can be invoked by the client in this interface. Since there is a chance of network issues during remote calls, an exception named RemoteException may occur; throw it. Since there is a chance of network issues during remote calls, an exception named RemoteException may occur; throw it. Following is an example of a remote interface. Here we have defined an interface with the name Hello and it has a method called printMsg(). import java.rmi.Remote; import java.rmi.RemoteException; // Creating Remote interface for our application public interface Hello extends Remote { void printMsg() throws RemoteException; } We need to implement the remote interface created in the earlier step. (We can write an implementation class separately or we can directly make the server program implement this interface.) To develop an implementation class − Implement the interface created in the previous step. Provide implementation to all the abstract methods of the remote interface. Following is an implementation class. Here, we have created a class named ImplExample and implemented the interface Hello created in the previous step and provided body for this method which prints a message. // Implementing the remote interface public class ImplExample implements Hello { // Implementing the interface method public void printMsg() { System.out.println("This is an example RMI program"); } } An RMI server program should implement the remote interface or extend the implementation class. Here, we should create a remote object and bind it to the RMIregistry. To develop a server program − Create a client class from where you want invoke the remote object. Create a client class from where you want invoke the remote object. Create a remote object by instantiating the implementation class as shown below. Create a remote object by instantiating the implementation class as shown below. Export the remote object using the method exportObject() of the class named UnicastRemoteObject which belongs to the package java.rmi.server. Export the remote object using the method exportObject() of the class named UnicastRemoteObject which belongs to the package java.rmi.server. Get the RMI registry using the getRegistry() method of the LocateRegistry class which belongs to the package java.rmi.registry. Get the RMI registry using the getRegistry() method of the LocateRegistry class which belongs to the package java.rmi.registry. Bind the remote object created to the registry using the bind() method of the class named Registry. To this method, pass a string representing the bind name and the object exported, as parameters. Bind the remote object created to the registry using the bind() method of the class named Registry. To this method, pass a string representing the bind name and the object exported, as parameters. Following is an example of an RMI server program. import java.rmi.registry.Registry; import java.rmi.registry.LocateRegistry; import java.rmi.RemoteException; import java.rmi.server.UnicastRemoteObject; public class Server extends ImplExample { public Server() {} public static void main(String args[]) { try { // Instantiating the implementation class ImplExample obj = new ImplExample(); // Exporting the object of implementation class // (here we are exporting the remote object to the stub) Hello stub = (Hello) UnicastRemoteObject.exportObject(obj, 0); // Binding the remote object (stub) in the registry Registry registry = LocateRegistry.getRegistry(); registry.bind("Hello", stub); System.err.println("Server ready"); } catch (Exception e) { System.err.println("Server exception: " + e.toString()); e.printStackTrace(); } } } Write a client program in it, fetch the remote object and invoke the required method using this object. To develop a client program − Create a client class from where your intended to invoke the remote object. Create a client class from where your intended to invoke the remote object. Get the RMI registry using the getRegistry() method of the LocateRegistry class which belongs to the package java.rmi.registry. Get the RMI registry using the getRegistry() method of the LocateRegistry class which belongs to the package java.rmi.registry. Fetch the object from the registry using the method lookup() of the class Registry which belongs to the package java.rmi.registry. To this method, you need to pass a string value representing the bind name as a parameter. This will return you the remote object. Fetch the object from the registry using the method lookup() of the class Registry which belongs to the package java.rmi.registry. To this method, you need to pass a string value representing the bind name as a parameter. This will return you the remote object. The lookup() returns an object of type remote, down cast it to the type Hello. The lookup() returns an object of type remote, down cast it to the type Hello. Finally invoke the required method using the obtained remote object. Finally invoke the required method using the obtained remote object. Following is an example of an RMI client program. import java.rmi.registry.LocateRegistry; import java.rmi.registry.Registry; public class Client { private Client() {} public static void main(String[] args) { try { // Getting the registry Registry registry = LocateRegistry.getRegistry(null); // Looking up the registry for the remote object Hello stub = (Hello) registry.lookup("Hello"); // Calling the remote method using the obtained object stub.printMsg(); // System.out.println("Remote method invoked"); } catch (Exception e) { System.err.println("Client exception: " + e.toString()); e.printStackTrace(); } } } To compile the application − Compile the Remote interface. Compile the implementation class. Compile the server program. Compile the client program. Or, Open the folder where you have stored all the programs and compile all the Java files as shown below. Javac *.java Step 1 − Start the rmi registry using the following command. start rmiregistry This will start an rmi registry on a separate window as shown below. Step 2 − Run the server class file as shown below. Java Server Step 3 − Run the client class file as shown below. java Client Verification − As soon you start the client, you would see the following output in the server. 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": 1780, "s": 1697, "text": "To write an RMI Java application, you would have to follow the steps given below −" }, { "code": null, "e": 1808, "s": 1780, "text": "Define the remote interface" }, { "code": null, "e": 1857, "s": 1808, "text": "Develop the implementation class (remote object)" }, { "code": null, "e": 1884, "s": 1857, "text": "Develop the server program" }, { "code": null, "e": 1911, "s": 1884, "text": "Develop the client program" }, { "code": null, "e": 1935, "s": 1911, "text": "Compile the application" }, { "code": null, "e": 1959, "s": 1935, "text": "Execute the application" }, { "code": null, "e": 2105, "s": 1959, "text": "A remote interface provides the description of all the methods of a particular remote object. The client communicates with this remote interface." }, { "code": null, "e": 2136, "s": 2105, "text": "To create a remote interface −" }, { "code": null, "e": 2231, "s": 2136, "text": "Create an interface that extends the predefined interface Remote which belongs to the package." }, { "code": null, "e": 2326, "s": 2231, "text": "Create an interface that extends the predefined interface Remote which belongs to the package." }, { "code": null, "e": 2412, "s": 2326, "text": "Declare all the business methods that can be invoked by the client in this interface." }, { "code": null, "e": 2498, "s": 2412, "text": "Declare all the business methods that can be invoked by the client in this interface." }, { "code": null, "e": 2617, "s": 2498, "text": "Since there is a chance of network issues during remote calls, an exception named RemoteException may occur; throw it." }, { "code": null, "e": 2736, "s": 2617, "text": "Since there is a chance of network issues during remote calls, an exception named RemoteException may occur; throw it." }, { "code": null, "e": 2876, "s": 2736, "text": "Following is an example of a remote interface. Here we have defined an interface with the name Hello and it has a method called printMsg()." }, { "code": null, "e": 3077, "s": 2876, "text": "import java.rmi.Remote; \nimport java.rmi.RemoteException; \n\n// Creating Remote interface for our application \npublic interface Hello extends Remote { \n void printMsg() throws RemoteException; \n} " }, { "code": null, "e": 3267, "s": 3077, "text": "We need to implement the remote interface created in the earlier step. (We can write an implementation class separately or we can directly make the server program implement this interface.)" }, { "code": null, "e": 3304, "s": 3267, "text": "To develop an implementation class −" }, { "code": null, "e": 3358, "s": 3304, "text": "Implement the interface created in the previous step." }, { "code": null, "e": 3434, "s": 3358, "text": "Provide implementation to all the abstract methods of the remote interface." }, { "code": null, "e": 3643, "s": 3434, "text": "Following is an implementation class. Here, we have created a class named ImplExample and implemented the interface Hello created in the previous step and provided body for this method which prints a message." }, { "code": null, "e": 3874, "s": 3643, "text": "// Implementing the remote interface \npublic class ImplExample implements Hello { \n \n // Implementing the interface method \n public void printMsg() { \n System.out.println(\"This is an example RMI program\"); \n } \n} " }, { "code": null, "e": 4041, "s": 3874, "text": "An RMI server program should implement the remote interface or extend the implementation class. Here, we should create a remote object and bind it to the RMIregistry." }, { "code": null, "e": 4071, "s": 4041, "text": "To develop a server program −" }, { "code": null, "e": 4139, "s": 4071, "text": "Create a client class from where you want invoke the remote object." }, { "code": null, "e": 4207, "s": 4139, "text": "Create a client class from where you want invoke the remote object." }, { "code": null, "e": 4288, "s": 4207, "text": "Create a remote object by instantiating the implementation class as shown below." }, { "code": null, "e": 4369, "s": 4288, "text": "Create a remote object by instantiating the implementation class as shown below." }, { "code": null, "e": 4511, "s": 4369, "text": "Export the remote object using the method exportObject() of the class named UnicastRemoteObject which belongs to the package java.rmi.server." }, { "code": null, "e": 4653, "s": 4511, "text": "Export the remote object using the method exportObject() of the class named UnicastRemoteObject which belongs to the package java.rmi.server." }, { "code": null, "e": 4781, "s": 4653, "text": "Get the RMI registry using the getRegistry() method of the LocateRegistry class which belongs to the package java.rmi.registry." }, { "code": null, "e": 4909, "s": 4781, "text": "Get the RMI registry using the getRegistry() method of the LocateRegistry class which belongs to the package java.rmi.registry." }, { "code": null, "e": 5106, "s": 4909, "text": "Bind the remote object created to the registry using the bind() method of the class named Registry. To this method, pass a string representing the bind name and the object exported, as parameters." }, { "code": null, "e": 5303, "s": 5106, "text": "Bind the remote object created to the registry using the bind() method of the class named Registry. To this method, pass a string representing the bind name and the object exported, as parameters." }, { "code": null, "e": 5353, "s": 5303, "text": "Following is an example of an RMI server program." }, { "code": null, "e": 6315, "s": 5353, "text": "import java.rmi.registry.Registry; \nimport java.rmi.registry.LocateRegistry; \nimport java.rmi.RemoteException; \nimport java.rmi.server.UnicastRemoteObject; \n\npublic class Server extends ImplExample { \n public Server() {} \n public static void main(String args[]) { \n try { \n // Instantiating the implementation class \n ImplExample obj = new ImplExample(); \n \n // Exporting the object of implementation class \n // (here we are exporting the remote object to the stub) \n Hello stub = (Hello) UnicastRemoteObject.exportObject(obj, 0); \n \n // Binding the remote object (stub) in the registry \n Registry registry = LocateRegistry.getRegistry(); \n \n registry.bind(\"Hello\", stub); \n System.err.println(\"Server ready\"); \n } catch (Exception e) { \n System.err.println(\"Server exception: \" + e.toString()); \n e.printStackTrace(); \n } \n } \n} " }, { "code": null, "e": 6419, "s": 6315, "text": "Write a client program in it, fetch the remote object and invoke the required method using this object." }, { "code": null, "e": 6449, "s": 6419, "text": "To develop a client program −" }, { "code": null, "e": 6525, "s": 6449, "text": "Create a client class from where your intended to invoke the remote object." }, { "code": null, "e": 6601, "s": 6525, "text": "Create a client class from where your intended to invoke the remote object." }, { "code": null, "e": 6729, "s": 6601, "text": "Get the RMI registry using the getRegistry() method of the LocateRegistry class which belongs to the package java.rmi.registry." }, { "code": null, "e": 6857, "s": 6729, "text": "Get the RMI registry using the getRegistry() method of the LocateRegistry class which belongs to the package java.rmi.registry." }, { "code": null, "e": 7119, "s": 6857, "text": "Fetch the object from the registry using the method lookup() of the class Registry which belongs to the package java.rmi.registry.\nTo this method, you need to pass a string value representing the bind name as a parameter. This will return you the remote object." }, { "code": null, "e": 7250, "s": 7119, "text": "Fetch the object from the registry using the method lookup() of the class Registry which belongs to the package java.rmi.registry." }, { "code": null, "e": 7381, "s": 7250, "text": "To this method, you need to pass a string value representing the bind name as a parameter. This will return you the remote object." }, { "code": null, "e": 7460, "s": 7381, "text": "The lookup() returns an object of type remote, down cast it to the type Hello." }, { "code": null, "e": 7539, "s": 7460, "text": "The lookup() returns an object of type remote, down cast it to the type Hello." }, { "code": null, "e": 7608, "s": 7539, "text": "Finally invoke the required method using the obtained remote object." }, { "code": null, "e": 7677, "s": 7608, "text": "Finally invoke the required method using the obtained remote object." }, { "code": null, "e": 7727, "s": 7677, "text": "Following is an example of an RMI client program." }, { "code": null, "e": 8445, "s": 7727, "text": "import java.rmi.registry.LocateRegistry; \nimport java.rmi.registry.Registry; \n\npublic class Client { \n private Client() {} \n public static void main(String[] args) { \n try { \n // Getting the registry \n Registry registry = LocateRegistry.getRegistry(null); \n \n // Looking up the registry for the remote object \n Hello stub = (Hello) registry.lookup(\"Hello\"); \n \n // Calling the remote method using the obtained object \n stub.printMsg(); \n \n // System.out.println(\"Remote method invoked\"); \n } catch (Exception e) {\n System.err.println(\"Client exception: \" + e.toString()); \n e.printStackTrace(); \n } \n } \n}" }, { "code": null, "e": 8474, "s": 8445, "text": "To compile the application −" }, { "code": null, "e": 8504, "s": 8474, "text": "Compile the Remote interface." }, { "code": null, "e": 8538, "s": 8504, "text": "Compile the implementation class." }, { "code": null, "e": 8566, "s": 8538, "text": "Compile the server program." }, { "code": null, "e": 8594, "s": 8566, "text": "Compile the client program." }, { "code": null, "e": 8598, "s": 8594, "text": "Or," }, { "code": null, "e": 8700, "s": 8598, "text": "Open the folder where you have stored all the programs and compile all the Java files as shown below." }, { "code": null, "e": 8714, "s": 8700, "text": "Javac *.java\n" }, { "code": null, "e": 8775, "s": 8714, "text": "Step 1 − Start the rmi registry using the following command." }, { "code": null, "e": 8794, "s": 8775, "text": "start rmiregistry\n" }, { "code": null, "e": 8863, "s": 8794, "text": "This will start an rmi registry on a separate window as shown below." }, { "code": null, "e": 8914, "s": 8863, "text": "Step 2 − Run the server class file as shown below." }, { "code": null, "e": 8927, "s": 8914, "text": "Java Server\n" }, { "code": null, "e": 8978, "s": 8927, "text": "Step 3 − Run the client class file as shown below." }, { "code": null, "e": 8992, "s": 8978, "text": "java Client \n" }, { "code": null, "e": 9087, "s": 8992, "text": "Verification − As soon you start the client, you would see the following output in the server." }, { "code": null, "e": 9120, "s": 9087, "text": "\n 16 Lectures \n 2 hours \n" }, { "code": null, "e": 9136, "s": 9120, "text": " Malhar Lathkar" }, { "code": null, "e": 9169, "s": 9136, "text": "\n 19 Lectures \n 5 hours \n" }, { "code": null, "e": 9185, "s": 9169, "text": " Malhar Lathkar" }, { "code": null, "e": 9220, "s": 9185, "text": "\n 25 Lectures \n 2.5 hours \n" }, { "code": null, "e": 9234, "s": 9220, "text": " Anadi Sharma" }, { "code": null, "e": 9268, "s": 9234, "text": "\n 126 Lectures \n 7 hours \n" }, { "code": null, "e": 9282, "s": 9268, "text": " Tushar Kale" }, { "code": null, "e": 9319, "s": 9282, "text": "\n 119 Lectures \n 17.5 hours \n" }, { "code": null, "e": 9334, "s": 9319, "text": " Monica Mittal" }, { "code": null, "e": 9367, "s": 9334, "text": "\n 76 Lectures \n 7 hours \n" }, { "code": null, "e": 9386, "s": 9367, "text": " Arnab Chakraborty" }, { "code": null, "e": 9393, "s": 9386, "text": " Print" }, { "code": null, "e": 9404, "s": 9393, "text": " Add Notes" } ]
How to perform Increment in MySQL Update?
To update values incrementally in MySQL, you need to create a variable with the help of SET command. The syntax to create a variable is as follows − set @anyVariableName := 0; To update value, you need to use UPDATE command. Let us begin with creating a table. The query to create a table − mysql> create table UpdateValueIncrementally −> ( −> ProductId int −> ); Query OK, 0 rows affected (0.90 sec) Insert records in the table with the help of select statement. The query is as follows − mysql> insert into UpdateValueIncrementally values(10); Query OK, 1 row affected (0.15 sec) mysql> insert into UpdateValueIncrementally values(100); Query OK, 1 row affected (0.16 sec) mysql> insert into UpdateValueIncrementally values(1000); Query OK, 1 row affected (0.09 sec) mysql> insert into UpdateValueIncrementally values(110); Query OK, 1 row affected (0.17 sec) mysql> insert into UpdateValueIncrementally values(102); Query OK, 1 row affected (0.11 sec) Display all records from the table with the help of select statement. The query is as follows − mysql> select *from UpdateValueIncrementally; The following is the output − +-----------+ | ProductId | +-----------+ | 10 | | 100 | | 1000 | | 110 | | 102 | +-----------+ 5 rows in set (0.00 sec) The following is the query to update values incrementally − mysql> set @incrementValue := 33333; Query OK, 0 rows affected (0.00 sec) A variable is created above and the value is initialized to 33333. The following is the query to update the values and incrementing − mysql> update UpdateValueIncrementally set ProductId = (select @incrementValue := @incrementValue + @incrementValue); Query OK, 5 rows affected (0.21 sec) Rows matched: 5 Changed: 5 Warnings: 0 In the above query, I have incremented the value with the current value of @incrementValue. Now you can check whether the value is updated or not − mysql> select *from UpdateValueIncrementally ; The following is the output − +-----------+ | ProductId | +-----------+ | 66666 | | 133332 | | 266664 | | 533328 | | 1066656 | +-----------+ 5 rows in set (0.00 sec)
[ { "code": null, "e": 1211, "s": 1062, "text": "To update values incrementally in MySQL, you need to create a variable with the help of SET command. The syntax to create a variable is as follows −" }, { "code": null, "e": 1238, "s": 1211, "text": "set @anyVariableName := 0;" }, { "code": null, "e": 1353, "s": 1238, "text": "To update value, you need to use UPDATE command. Let us begin with creating a table. The query to create a table −" }, { "code": null, "e": 1472, "s": 1353, "text": "mysql> create table UpdateValueIncrementally\n −> (\n −> ProductId int\n −> );\nQuery OK, 0 rows affected (0.90 sec)" }, { "code": null, "e": 1561, "s": 1472, "text": "Insert records in the table with the help of select statement. The query is as follows −" }, { "code": null, "e": 2030, "s": 1561, "text": "mysql> insert into UpdateValueIncrementally values(10);\nQuery OK, 1 row affected (0.15 sec)\n\nmysql> insert into UpdateValueIncrementally values(100);\nQuery OK, 1 row affected (0.16 sec)\n\nmysql> insert into UpdateValueIncrementally values(1000);\nQuery OK, 1 row affected (0.09 sec)\n\nmysql> insert into UpdateValueIncrementally values(110);\nQuery OK, 1 row affected (0.17 sec)\n\nmysql> insert into UpdateValueIncrementally values(102);\nQuery OK, 1 row affected (0.11 sec)" }, { "code": null, "e": 2126, "s": 2030, "text": "Display all records from the table with the help of select statement. The query is as follows −" }, { "code": null, "e": 2172, "s": 2126, "text": "mysql> select *from UpdateValueIncrementally;" }, { "code": null, "e": 2202, "s": 2172, "text": "The following is the output −" }, { "code": null, "e": 2353, "s": 2202, "text": "+-----------+\n| ProductId |\n+-----------+\n| 10 |\n| 100 |\n| 1000 |\n| 110 |\n| 102 |\n+-----------+\n5 rows in set (0.00 sec)" }, { "code": null, "e": 2413, "s": 2353, "text": "The following is the query to update values incrementally −" }, { "code": null, "e": 2487, "s": 2413, "text": "mysql> set @incrementValue := 33333;\nQuery OK, 0 rows affected (0.00 sec)" }, { "code": null, "e": 2621, "s": 2487, "text": "A variable is created above and the value is initialized to 33333. The following is the query to update the values and incrementing −" }, { "code": null, "e": 2815, "s": 2621, "text": "mysql> update UpdateValueIncrementally set ProductId = (select @incrementValue := @incrementValue + @incrementValue);\nQuery OK, 5 rows affected (0.21 sec)\nRows matched: 5 Changed: 5 Warnings: 0" }, { "code": null, "e": 2963, "s": 2815, "text": "In the above query, I have incremented the value with the current value of @incrementValue. Now you can check whether the value is updated or not −" }, { "code": null, "e": 3010, "s": 2963, "text": "mysql> select *from UpdateValueIncrementally ;" }, { "code": null, "e": 3040, "s": 3010, "text": "The following is the output −" }, { "code": null, "e": 3191, "s": 3040, "text": "+-----------+\n| ProductId |\n+-----------+\n| 66666 |\n| 133332 |\n| 266664 |\n| 533328 |\n| 1066656 |\n+-----------+\n5 rows in set (0.00 sec)" } ]
Set Flex Items into equal width columns with Bootstrap
To set flex items to be of equal width column, use the flex-fill class. The class displays the items as equal width. In the below example screenshot, you can see that we have four flex items with equal width columns − The flex-fill class is used for every flex items and in this way, we can set equal width. Below, we have two flex items − <div class="p-2 flex-fill"> Example 1 </div> <div class="p-2 flex-fill"> Example 2 </div> Live Demo The following is an example showing how to set flex items into equal width columns using the flex-fill class − <!DOCTYPE html> <html lang="en"> <head> <title>Bootstrap Example</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/js/bootstrap.min.js"></script> </head> <body> <div class="container mt-3"> <p>With flex-fill</p> <div class="d-flex mb-3 bg-primary"> <div class="p-2 flex-fill bg-danger">Example 1</div> <div class="p-2 flex-fill bg-warning">Example 2</div> <div class="p-2 flex-fill bg-info">Example 3</div> <div class="p-2 flex-fill bg-danger">Example 4</div> </div> <p>Without .flex-fill:</p> <div class="d-flex mb-3 bg-secondary"> <div class="p-2 bg-danger">Example 1</div> <div class="p-2 bg-warning">Example 2</div> <div class="p-2 bg-info">Example 3</div> <div class="p-2 bg-warning">Example 4</div> </div> </div> </body> </html>
[ { "code": null, "e": 1280, "s": 1062, "text": "To set flex items to be of equal width column, use the flex-fill class. The class displays the items as equal width. In the below example screenshot, you can see that we have four flex items with equal width columns −" }, { "code": null, "e": 1402, "s": 1280, "text": "The flex-fill class is used for every flex items and in this way, we can set equal width. Below, we have two flex items −" }, { "code": null, "e": 1492, "s": 1402, "text": "<div class=\"p-2 flex-fill\">\nExample 1\n</div>\n<div class=\"p-2 flex-fill\">\nExample 2\n</div>" }, { "code": null, "e": 1502, "s": 1492, "text": "Live Demo" }, { "code": null, "e": 1613, "s": 1502, "text": "The following is an example showing how to set flex items into equal width columns using the flex-fill class −" }, { "code": null, "e": 2790, "s": 1613, "text": "<!DOCTYPE html>\n<html lang=\"en\">\n <head>\n <title>Bootstrap Example</title>\n <meta charset=\"utf-8\">\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css\">\n <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"></script>\n <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/js/bootstrap.min.js\"></script>\n </head>\n <body>\n <div class=\"container mt-3\">\n <p>With flex-fill</p>\n <div class=\"d-flex mb-3 bg-primary\">\n <div class=\"p-2 flex-fill bg-danger\">Example 1</div>\n <div class=\"p-2 flex-fill bg-warning\">Example 2</div>\n <div class=\"p-2 flex-fill bg-info\">Example 3</div>\n <div class=\"p-2 flex-fill bg-danger\">Example 4</div>\n </div>\n <p>Without .flex-fill:</p>\n <div class=\"d-flex mb-3 bg-secondary\">\n <div class=\"p-2 bg-danger\">Example 1</div>\n <div class=\"p-2 bg-warning\">Example 2</div>\n <div class=\"p-2 bg-info\">Example 3</div>\n <div class=\"p-2 bg-warning\">Example 4</div>\n </div>\n </div>\n </body>\n</html>" } ]
Top 3 Alternative Python Packages for Pandas | by Cornellius Yudha Wijaya | Towards Data Science
If you enjoy my content and want to get more in-depth knowledge regarding data or just daily life as a Data Scientist, please consider subscribing to my newsletter here. For many modern data scientists, Python is the programming language that was used for their everyday work — as a consequence, the data analysis would be done using one of the most data packages, which are Pandas. Many online courses and lectures would introduce Pandas as the basis for every data analysis with Python. In my opinion, Pandas is still the most useful and viable package to do your data analysis in Python. However, for comparison purposes, I want to introduce you to several Pandas package alternatives. I don’t intend to convince people to switch from Pandas to another package, but I only want people to know that there are alternatives for Pandas package. So, what are these Pandas alternative packages? Let’s get into it! Polars is a DataFrame library designed to processing data with a fast lighting time by implementing Rust Programming language and using Arrow as the foundation. Polars premise is to give the users a swifter experience in comparison to Pandas package. The ideal situation to use the Polars package is when you have data that were too big for Pandas but too small for using Spark. For you who familiar with the Pandas workflow, Polars would not be that different — there is some extra functionality, but overall they are pretty similar. Let’s try to experiment with the Polars package. First, we need to install Polars in your Python environment. pip install polars After that, I would create a DataFrame sample using the Polars package. import polars as pldf= pl.DataFrame({'Patient':['Anna','Be','Charlie','Duke','Earth','Faux','Goal','Him'], 'Weight':[41,56,78,55,80,84,36,91], 'Segment':[1,2,1,1,3,2,1,1] })df Similar to Pandas DataFrame, the interface and the data analysis workflow is feels familiar. A little bit different is how the data type is on the top of the data, and no index was showing. Let’s try using some of the functions that available in Polars. #Print DataFrame datatypeprint(df.dtypes)#Print DataFrame columnsprint(df.columns)#Print DataFrame top 5print(df.head())#Conditional Selectionprint(df[df['Weight'] < 70]) There are many available functions in Polars that have the same function as Pandas functions, and there is a possibility of conditional selection. I didn’t say that all the function that available in Pandas is available on Polars. For example, when I want to do index selection using iloc. df.iloc[1] The error is raised when I want to make index selection. This is because the Pandas Index concept did not apply in Polars. One special concept that applicable in Polars is Expression. In Polars, you could produce a consecutively executed function (which is called Expression) and piped together. Let’s use an example to understand the concept. #Parallel Expression df[[ #Expression for executing the stats (sum) and create the column names "sum" pl.sum("Weight").alias("sum"), pl.min("Weight").alias("min"), pl.max("Weight").alias("max"), pl.std("Weight").alias("std dev"), pl.var("Weight").alias("variance"),]] If we borrow the Pandas concept, often what we did above is something similar to the Pandas conditional selection. However, in our case with Polars, an expression execution resulted in another dataset when we were passing the expression. The main selling point for using Polars is still their faster execution time. So, how fast the Polars execution time compared to Pandas? In this case, let me borrow the image example from the Polars documentation to give you the comparison. The image above was the time comparison when Inner joined using three different methods: Polars Inner Join, Pandas Inner Join, and Polars Inner Join Parallel. As you can see, Pandas execution time is slower when the data size becomes bigger when you compared it to Polars. It might not have that much difference in execution time in a smaller data size, but it becomes clearer when the data size is bigger. Dask is a Python package for parallel computing in Python. There are two main parts in Dask, there are: Task Scheduling. Similar to Airflow, it is used to optimized the computation process by automatically executing tasks.Big Data Collection. Parallel data frame like Numpy arrays or Pandas data frame object — specific for parallel processing. Task Scheduling. Similar to Airflow, it is used to optimized the computation process by automatically executing tasks. Big Data Collection. Parallel data frame like Numpy arrays or Pandas data frame object — specific for parallel processing. In simpler terms, Dask offers a data frame or array object like you could find in Pandas, but it is processed in parallel for faster execution time, and it offers a task scheduler. As this article only cover the alternative for Pandas, we would not test the Task Scheduling functionality. Instead, we would focus on the Dask data frame object. Let’s try a few simple Dask functions example — but first, we need to install the Dask package (Anaconda has it by default). #If you want to install dask completelypython -m pip install "dask[complete]"#If you want to install dask core onlypython -m pip install dask After you have the dask installed, let’s try Dask functions. Initially, we could initiate a dashboard to monitor the data processing. import daskfrom dask.distributed import Client, progressclient = Client(processes=False, threads_per_worker=4, n_workers=1, memory_limit='2GB')client Dask provides you a client dashboard in a different port that you could access after you initiate it. When you click on the Dashboard link, it will look like the following image. I would say that this dashboard is easy to understand, and it includes all your current activities with dask. You could try to check out all the nice tabs that the dask dashboard has, but let’s continue for now. Let’s try to create a dask array for now. (something like what Numpy have) import dask.array as dax = da.random.random((10000, 10000), chunks=(1000, 1000))x When the dask array was created, you would receive the matrix information just like above. This array would become your base for the dask data frame. Let’s try to create a dataset from dask to have a more detailed example. df = dask.datasets.timeseries()df Dask data frame has a similar structure with Pandas data frame object, but because the Dask data frame is lazy, it would not print the data on your Jupyter Notebook. However, you could execute many functions that existed in Pandas on Dask. Let’s take a few examples for that. df.head() If you are using the .head function, you could print the top five data. If you want to make the conditional selection, it is still similar to Pandas. Although, it needs a special function to execute it. Let me show you an example code. df[df['x'] >0.9] If you do it normally, you will acquire the dask data frame structure. In case you want to obtain the Pandas data frame, you need to use the .compute function. df[df['x'] >0.9].compute() This is the actual data you get when you compute the dask data frame conditional selection. Everything on dask is about parallel and fast computation, so if you decide to use dask, it is better to have familiarity with Pandas. The ideal situation for dask is when you have a high computational dataset, but if your data is comfortably processed with your computer RAM, then stick with Pandas. There are still so many things you could do with dask; I suggest you visit their website to explore more. Vaex is a Python package used for processing and exploring big tabular datasets with interfaces similar to Pandas. Vaex documentation shows that it can calculate statistics such as mean, sum, count, standard deviation, etc., on an N-dimensional grid up to a billion (109) objects/rows per second. It means Vaex is Pandas alternative that is also used to improve the execution time. The Vaex workflow is similar to Pandas API, which means if you already familiar with Pandas, then it would not be hard for you to using Vaex. Let’s start the example by installing Vaex. pip install vaex When you have finished installing the Vaex package, we could try to use the dataset example to looks at the Vaex data frame. import vaexdf = vaex.example()df Similar to Pandas application, you could do the conditional selection. df[df['x'] > 88] However, just the Vaex documentation stated, “A core feature of Vaex is the extremely efficient calculation of statistics on N-dimensional grids. This rather useful for making visualisations of large datasets.” Let’s try to use simple statistical methods. df.count(), df.max('x'), df.mean('L') The result is presented as an array object with the detail of the value data type. Another function that Vaex selling is the plotting function, where you could apply a statistical function to the plot function. For example, instead of using the usual count statistic, I use the mean of the ‘E’ column with a limit of 99.7% data only that was shown. df.plot1d(df['x'], what='mean(E)', limits='99.7%') For more advanced plotting functions, you could visit the Vaex documentation. What is important to know is that Vaex selling point is their fast statistical computational and big data visualization exploration functionality. However, if you have a smaller dataset — you could stick with Pandas. As a Data Scientist who uses Python as their analysis tool, you would certainly use the Pandas package to help your data exploration. However, there are a few Pandas alternative you could use — especially when you are dealing with big data, they are: PolarsDaskVeux Polars Dask Veux I hope it helps! Visit me on my LinkedIn or Twitter If you are not subscribed as a Medium Member, please consider subscribing through my referral.
[ { "code": null, "e": 342, "s": 172, "text": "If you enjoy my content and want to get more in-depth knowledge regarding data or just daily life as a Data Scientist, please consider subscribing to my newsletter here." }, { "code": null, "e": 661, "s": 342, "text": "For many modern data scientists, Python is the programming language that was used for their everyday work — as a consequence, the data analysis would be done using one of the most data packages, which are Pandas. Many online courses and lectures would introduce Pandas as the basis for every data analysis with Python." }, { "code": null, "e": 1016, "s": 661, "text": "In my opinion, Pandas is still the most useful and viable package to do your data analysis in Python. However, for comparison purposes, I want to introduce you to several Pandas package alternatives. I don’t intend to convince people to switch from Pandas to another package, but I only want people to know that there are alternatives for Pandas package." }, { "code": null, "e": 1083, "s": 1016, "text": "So, what are these Pandas alternative packages? Let’s get into it!" }, { "code": null, "e": 1462, "s": 1083, "text": "Polars is a DataFrame library designed to processing data with a fast lighting time by implementing Rust Programming language and using Arrow as the foundation. Polars premise is to give the users a swifter experience in comparison to Pandas package. The ideal situation to use the Polars package is when you have data that were too big for Pandas but too small for using Spark." }, { "code": null, "e": 1728, "s": 1462, "text": "For you who familiar with the Pandas workflow, Polars would not be that different — there is some extra functionality, but overall they are pretty similar. Let’s try to experiment with the Polars package. First, we need to install Polars in your Python environment." }, { "code": null, "e": 1747, "s": 1728, "text": "pip install polars" }, { "code": null, "e": 1819, "s": 1747, "text": "After that, I would create a DataFrame sample using the Polars package." }, { "code": null, "e": 2029, "s": 1819, "text": "import polars as pldf= pl.DataFrame({'Patient':['Anna','Be','Charlie','Duke','Earth','Faux','Goal','Him'], 'Weight':[41,56,78,55,80,84,36,91], 'Segment':[1,2,1,1,3,2,1,1] })df" }, { "code": null, "e": 2283, "s": 2029, "text": "Similar to Pandas DataFrame, the interface and the data analysis workflow is feels familiar. A little bit different is how the data type is on the top of the data, and no index was showing. Let’s try using some of the functions that available in Polars." }, { "code": null, "e": 2454, "s": 2283, "text": "#Print DataFrame datatypeprint(df.dtypes)#Print DataFrame columnsprint(df.columns)#Print DataFrame top 5print(df.head())#Conditional Selectionprint(df[df['Weight'] < 70])" }, { "code": null, "e": 2744, "s": 2454, "text": "There are many available functions in Polars that have the same function as Pandas functions, and there is a possibility of conditional selection. I didn’t say that all the function that available in Pandas is available on Polars. For example, when I want to do index selection using iloc." }, { "code": null, "e": 2755, "s": 2744, "text": "df.iloc[1]" }, { "code": null, "e": 2878, "s": 2755, "text": "The error is raised when I want to make index selection. This is because the Pandas Index concept did not apply in Polars." }, { "code": null, "e": 3099, "s": 2878, "text": "One special concept that applicable in Polars is Expression. In Polars, you could produce a consecutively executed function (which is called Expression) and piped together. Let’s use an example to understand the concept." }, { "code": null, "e": 3410, "s": 3099, "text": "#Parallel Expression df[[ #Expression for executing the stats (sum) and create the column names \"sum\" pl.sum(\"Weight\").alias(\"sum\"), pl.min(\"Weight\").alias(\"min\"), pl.max(\"Weight\").alias(\"max\"), pl.std(\"Weight\").alias(\"std dev\"), pl.var(\"Weight\").alias(\"variance\"),]]" }, { "code": null, "e": 3648, "s": 3410, "text": "If we borrow the Pandas concept, often what we did above is something similar to the Pandas conditional selection. However, in our case with Polars, an expression execution resulted in another dataset when we were passing the expression." }, { "code": null, "e": 3889, "s": 3648, "text": "The main selling point for using Polars is still their faster execution time. So, how fast the Polars execution time compared to Pandas? In this case, let me borrow the image example from the Polars documentation to give you the comparison." }, { "code": null, "e": 4296, "s": 3889, "text": "The image above was the time comparison when Inner joined using three different methods: Polars Inner Join, Pandas Inner Join, and Polars Inner Join Parallel. As you can see, Pandas execution time is slower when the data size becomes bigger when you compared it to Polars. It might not have that much difference in execution time in a smaller data size, but it becomes clearer when the data size is bigger." }, { "code": null, "e": 4400, "s": 4296, "text": "Dask is a Python package for parallel computing in Python. There are two main parts in Dask, there are:" }, { "code": null, "e": 4641, "s": 4400, "text": "Task Scheduling. Similar to Airflow, it is used to optimized the computation process by automatically executing tasks.Big Data Collection. Parallel data frame like Numpy arrays or Pandas data frame object — specific for parallel processing." }, { "code": null, "e": 4760, "s": 4641, "text": "Task Scheduling. Similar to Airflow, it is used to optimized the computation process by automatically executing tasks." }, { "code": null, "e": 4883, "s": 4760, "text": "Big Data Collection. Parallel data frame like Numpy arrays or Pandas data frame object — specific for parallel processing." }, { "code": null, "e": 5064, "s": 4883, "text": "In simpler terms, Dask offers a data frame or array object like you could find in Pandas, but it is processed in parallel for faster execution time, and it offers a task scheduler." }, { "code": null, "e": 5352, "s": 5064, "text": "As this article only cover the alternative for Pandas, we would not test the Task Scheduling functionality. Instead, we would focus on the Dask data frame object. Let’s try a few simple Dask functions example — but first, we need to install the Dask package (Anaconda has it by default)." }, { "code": null, "e": 5494, "s": 5352, "text": "#If you want to install dask completelypython -m pip install \"dask[complete]\"#If you want to install dask core onlypython -m pip install dask" }, { "code": null, "e": 5628, "s": 5494, "text": "After you have the dask installed, let’s try Dask functions. Initially, we could initiate a dashboard to monitor the data processing." }, { "code": null, "e": 5793, "s": 5628, "text": "import daskfrom dask.distributed import Client, progressclient = Client(processes=False, threads_per_worker=4, n_workers=1, memory_limit='2GB')client" }, { "code": null, "e": 5972, "s": 5793, "text": "Dask provides you a client dashboard in a different port that you could access after you initiate it. When you click on the Dashboard link, it will look like the following image." }, { "code": null, "e": 6259, "s": 5972, "text": "I would say that this dashboard is easy to understand, and it includes all your current activities with dask. You could try to check out all the nice tabs that the dask dashboard has, but let’s continue for now. Let’s try to create a dask array for now. (something like what Numpy have)" }, { "code": null, "e": 6341, "s": 6259, "text": "import dask.array as dax = da.random.random((10000, 10000), chunks=(1000, 1000))x" }, { "code": null, "e": 6564, "s": 6341, "text": "When the dask array was created, you would receive the matrix information just like above. This array would become your base for the dask data frame. Let’s try to create a dataset from dask to have a more detailed example." }, { "code": null, "e": 6598, "s": 6564, "text": "df = dask.datasets.timeseries()df" }, { "code": null, "e": 6874, "s": 6598, "text": "Dask data frame has a similar structure with Pandas data frame object, but because the Dask data frame is lazy, it would not print the data on your Jupyter Notebook. However, you could execute many functions that existed in Pandas on Dask. Let’s take a few examples for that." }, { "code": null, "e": 6884, "s": 6874, "text": "df.head()" }, { "code": null, "e": 7120, "s": 6884, "text": "If you are using the .head function, you could print the top five data. If you want to make the conditional selection, it is still similar to Pandas. Although, it needs a special function to execute it. Let me show you an example code." }, { "code": null, "e": 7137, "s": 7120, "text": "df[df['x'] >0.9]" }, { "code": null, "e": 7297, "s": 7137, "text": "If you do it normally, you will acquire the dask data frame structure. In case you want to obtain the Pandas data frame, you need to use the .compute function." }, { "code": null, "e": 7324, "s": 7297, "text": "df[df['x'] >0.9].compute()" }, { "code": null, "e": 7823, "s": 7324, "text": "This is the actual data you get when you compute the dask data frame conditional selection. Everything on dask is about parallel and fast computation, so if you decide to use dask, it is better to have familiarity with Pandas. The ideal situation for dask is when you have a high computational dataset, but if your data is comfortably processed with your computer RAM, then stick with Pandas. There are still so many things you could do with dask; I suggest you visit their website to explore more." }, { "code": null, "e": 8205, "s": 7823, "text": "Vaex is a Python package used for processing and exploring big tabular datasets with interfaces similar to Pandas. Vaex documentation shows that it can calculate statistics such as mean, sum, count, standard deviation, etc., on an N-dimensional grid up to a billion (109) objects/rows per second. It means Vaex is Pandas alternative that is also used to improve the execution time." }, { "code": null, "e": 8391, "s": 8205, "text": "The Vaex workflow is similar to Pandas API, which means if you already familiar with Pandas, then it would not be hard for you to using Vaex. Let’s start the example by installing Vaex." }, { "code": null, "e": 8408, "s": 8391, "text": "pip install vaex" }, { "code": null, "e": 8533, "s": 8408, "text": "When you have finished installing the Vaex package, we could try to use the dataset example to looks at the Vaex data frame." }, { "code": null, "e": 8566, "s": 8533, "text": "import vaexdf = vaex.example()df" }, { "code": null, "e": 8637, "s": 8566, "text": "Similar to Pandas application, you could do the conditional selection." }, { "code": null, "e": 8654, "s": 8637, "text": "df[df['x'] > 88]" }, { "code": null, "e": 8910, "s": 8654, "text": "However, just the Vaex documentation stated, “A core feature of Vaex is the extremely efficient calculation of statistics on N-dimensional grids. This rather useful for making visualisations of large datasets.” Let’s try to use simple statistical methods." }, { "code": null, "e": 8948, "s": 8910, "text": "df.count(), df.max('x'), df.mean('L')" }, { "code": null, "e": 9297, "s": 8948, "text": "The result is presented as an array object with the detail of the value data type. Another function that Vaex selling is the plotting function, where you could apply a statistical function to the plot function. For example, instead of using the usual count statistic, I use the mean of the ‘E’ column with a limit of 99.7% data only that was shown." }, { "code": null, "e": 9348, "s": 9297, "text": "df.plot1d(df['x'], what='mean(E)', limits='99.7%')" }, { "code": null, "e": 9643, "s": 9348, "text": "For more advanced plotting functions, you could visit the Vaex documentation. What is important to know is that Vaex selling point is their fast statistical computational and big data visualization exploration functionality. However, if you have a smaller dataset — you could stick with Pandas." }, { "code": null, "e": 9894, "s": 9643, "text": "As a Data Scientist who uses Python as their analysis tool, you would certainly use the Pandas package to help your data exploration. However, there are a few Pandas alternative you could use — especially when you are dealing with big data, they are:" }, { "code": null, "e": 9909, "s": 9894, "text": "PolarsDaskVeux" }, { "code": null, "e": 9916, "s": 9909, "text": "Polars" }, { "code": null, "e": 9921, "s": 9916, "text": "Dask" }, { "code": null, "e": 9926, "s": 9921, "text": "Veux" }, { "code": null, "e": 9943, "s": 9926, "text": "I hope it helps!" }, { "code": null, "e": 9978, "s": 9943, "text": "Visit me on my LinkedIn or Twitter" } ]
Reverse a string using Stack | Practice | GeeksforGeeks
You are given a string S, the task is to reverse the string using stack. Example 1: Input: S="GeeksforGeeks" Output: skeeGrofskeeG Your Task: You don't need to read input or print anything. Your task is to complete the function reverse() which takes the string S as an input parameter and returns the reversed string. Expected Time Complexity: O(N) Expected Auxiliary Space: O(N) Constraints: 1 ≤ length of the string ≤ 100 0 itmithu14318 hours ago C++ Solution //0.01 second //return the address of the stringchar* reverse(char *S, int len){ //code here stack<char> st; for(int i=0; i<len; i++){ st.push(S[i]); } int i=0; while (!st.empty()) { S[i++] =st.top(); st.pop(); } return S;} 0 dsssoni6 days ago JAVA Solution : public String reverse(String S){ Stack<Character> st = new Stack<Character>(); StringBuilder reversed = new StringBuilder(); for(int i=0; i<S.length(); i++){ st.push(S.charAt(i)); } int i = 0; while(i<st.size()){ reversed.append(st.pop()); } return reversed.toString(); } +1 hrithikjain98891 week ago //return the address of the stringchar* reverse(char *s, int len){ //code here stack<char> ss; for(int i=0;i<len;i++) ss.push(s[i]); int i=0; while(ss.size()!=0) { s[i++]=ss.top(); ss.pop(); } return s;} 0 paritoshpranjal32 weeks ago class Solution { public String reverse(String S){ Stack<Character> st=new Stack<>(); char arr[]=new char[100]; for(int i=0;i<S.length();i++) { st.push(S.charAt(i)); } for(int i=0;i<S.length();i++) { arr[i]= st.pop(); } String string = String.valueOf(arr); return string; } } 0 mayank180919992 weeks ago char* reverse(char *S, int len) { //code here stack<int>st; for(int i=0;i<len;i++){ st.push(S[i]); } int i=0; while(!st.empty()){ S[i++]=st.top(); st.pop(); } return S; } 0 hharshit81182 weeks ago char* reverse(char *S, int len){ stack<char> s; for(int i = 0; i< len; i++){ s.push(S[i]); } int index = 0; while(!s.empty()){ S[index++] = s.top(); s.pop(); } return S;} 0 ashishpatel39462 weeks ago simple java solution class Solution { public String reverse(String S){ Stack <Character> s = new Stack<>(); for(int i = 0; i<S.length(); i++){ s.push(S.charAt(i)); }String str = ""; while(s.isEmpty()==false){ str = str+s.pop(); } return str; } } 0 harshscode2 weeks ago stack<int> st; for(int i=0;i<len;i++) st.push(s[i]); for(int i=0;i<len;i++) { s[i]=st.top(); st.pop(); } return s; 0 himanshu0719cse193 weeks ago Using Recursion Stack public String reverse(String s){ if(s.length()==0) { return ""; } char c=s.charAt(0); String ans=reverse(s.substring(1)); ans=ans+c; return ans; } 0 amarrajsmart1971 month ago C++ Easy Code .Time Taken =0.0/1.7 Sec. stack<char> st; for(int i=0;i<len;i++) { st.push(S[i]); } for(int i=0;i<len;i++) { S[i]=st.top(); st.pop(); } return S; 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": 311, "s": 238, "text": "You are given a string S, the task is to reverse the string using stack." }, { "code": null, "e": 324, "s": 313, "text": "Example 1:" }, { "code": null, "e": 372, "s": 324, "text": "\nInput: S=\"GeeksforGeeks\"\nOutput: skeeGrofskeeG" }, { "code": null, "e": 561, "s": 374, "text": "Your Task:\nYou don't need to read input or print anything. Your task is to complete the function reverse() which takes the string S as an input parameter and returns the reversed string." }, { "code": null, "e": 625, "s": 563, "text": "Expected Time Complexity: O(N)\nExpected Auxiliary Space: O(N)" }, { "code": null, "e": 671, "s": 627, "text": "Constraints:\n1 ≤ length of the string ≤ 100" }, { "code": null, "e": 675, "s": 673, "text": "0" }, { "code": null, "e": 698, "s": 675, "text": "itmithu14318 hours ago" }, { "code": null, "e": 711, "s": 698, "text": "C++ Solution" }, { "code": null, "e": 726, "s": 711, "text": "//0.01 second " }, { "code": null, "e": 970, "s": 726, "text": "//return the address of the stringchar* reverse(char *S, int len){ //code here stack<char> st; for(int i=0; i<len; i++){ st.push(S[i]); } int i=0; while (!st.empty()) { S[i++] =st.top(); st.pop(); } return S;}" }, { "code": null, "e": 972, "s": 970, "text": "0" }, { "code": null, "e": 990, "s": 972, "text": "dsssoni6 days ago" }, { "code": null, "e": 1007, "s": 990, "text": "JAVA Solution : " }, { "code": null, "e": 1379, "s": 1009, "text": "public String reverse(String S){ Stack<Character> st = new Stack<Character>(); StringBuilder reversed = new StringBuilder(); for(int i=0; i<S.length(); i++){ st.push(S.charAt(i)); } int i = 0; while(i<st.size()){ reversed.append(st.pop()); } return reversed.toString(); }" }, { "code": null, "e": 1382, "s": 1379, "text": "+1" }, { "code": null, "e": 1408, "s": 1382, "text": "hrithikjain98891 week ago" }, { "code": null, "e": 1649, "s": 1408, "text": "//return the address of the stringchar* reverse(char *s, int len){ //code here stack<char> ss; for(int i=0;i<len;i++) ss.push(s[i]); int i=0; while(ss.size()!=0) { s[i++]=ss.top(); ss.pop(); } return s;}" }, { "code": null, "e": 1651, "s": 1649, "text": "0" }, { "code": null, "e": 1679, "s": 1651, "text": "paritoshpranjal32 weeks ago" }, { "code": null, "e": 2070, "s": 1679, "text": "class Solution { public String reverse(String S){ Stack<Character> st=new Stack<>(); char arr[]=new char[100]; for(int i=0;i<S.length();i++) { st.push(S.charAt(i)); } for(int i=0;i<S.length();i++) { arr[i]= st.pop(); } String string = String.valueOf(arr); return string; }" }, { "code": null, "e": 2072, "s": 2070, "text": "}" }, { "code": null, "e": 2074, "s": 2072, "text": "0" }, { "code": null, "e": 2100, "s": 2074, "text": "mayank180919992 weeks ago" }, { "code": null, "e": 2327, "s": 2100, "text": "char* reverse(char *S, int len)\n{\n //code here\n stack<int>st;\n for(int i=0;i<len;i++){\n st.push(S[i]);\n }\n int i=0;\n while(!st.empty()){\n S[i++]=st.top();\n st.pop();\n }\n return S;\n}" }, { "code": null, "e": 2329, "s": 2327, "text": "0" }, { "code": null, "e": 2353, "s": 2329, "text": "hharshit81182 weeks ago" }, { "code": null, "e": 2550, "s": 2353, "text": "char* reverse(char *S, int len){ stack<char> s; for(int i = 0; i< len; i++){ s.push(S[i]); } int index = 0; while(!s.empty()){ S[index++] = s.top(); s.pop(); } return S;}" }, { "code": null, "e": 2552, "s": 2550, "text": "0" }, { "code": null, "e": 2579, "s": 2552, "text": "ashishpatel39462 weeks ago" }, { "code": null, "e": 2600, "s": 2579, "text": "simple java solution" }, { "code": null, "e": 2859, "s": 2600, "text": "class Solution { public String reverse(String S){ Stack <Character> s = new Stack<>(); for(int i = 0; i<S.length(); i++){ s.push(S.charAt(i)); }String str = \"\"; while(s.isEmpty()==false){ str = str+s.pop(); } return str; }" }, { "code": null, "e": 2861, "s": 2859, "text": "}" }, { "code": null, "e": 2863, "s": 2861, "text": "0" }, { "code": null, "e": 2885, "s": 2863, "text": "harshscode2 weeks ago" }, { "code": null, "e": 3033, "s": 2888, "text": "stack<int> st; for(int i=0;i<len;i++) st.push(s[i]); for(int i=0;i<len;i++) { s[i]=st.top(); st.pop(); } return s;" }, { "code": null, "e": 3035, "s": 3033, "text": "0" }, { "code": null, "e": 3064, "s": 3035, "text": "himanshu0719cse193 weeks ago" }, { "code": null, "e": 3086, "s": 3064, "text": "Using Recursion Stack" }, { "code": null, "e": 3287, "s": 3086, "text": "public String reverse(String s){ if(s.length()==0) { return \"\"; } char c=s.charAt(0); String ans=reverse(s.substring(1)); ans=ans+c; return ans; }" }, { "code": null, "e": 3289, "s": 3287, "text": "0" }, { "code": null, "e": 3316, "s": 3289, "text": "amarrajsmart1971 month ago" }, { "code": null, "e": 3359, "s": 3318, "text": "C++ Easy Code .Time Taken =0.0/1.7 Sec." }, { "code": null, "e": 3518, "s": 3359, "text": "stack<char> st; for(int i=0;i<len;i++) { st.push(S[i]); } for(int i=0;i<len;i++) { S[i]=st.top(); st.pop(); } return S;" }, { "code": null, "e": 3664, "s": 3518, "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": 3700, "s": 3664, "text": " Login to access your submissions. " }, { "code": null, "e": 3710, "s": 3700, "text": "\nProblem\n" }, { "code": null, "e": 3720, "s": 3710, "text": "\nContest\n" }, { "code": null, "e": 3783, "s": 3720, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 3931, "s": 3783, "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": 4139, "s": 3931, "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": 4245, "s": 4139, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
Class getDeclaredConstructor() method in Java with Examples - GeeksforGeeks
16 Dec, 2019 The getDeclaredConstructor() method of java.lang.Class class is used to get the specified constructor of this class with the specified parameter type. The method returns the specified constructor of this class in the form of Constructor object. Syntax: public Constructor<T> getDeclaredConstructor(Class[] parameterType) throws NoSuchMethodException, SecurityException Parameter: This constructor accepts a parameters parameterType which is the array of parameter type for the specified constructor. Return Value: This method returns the specified constructor of this class in the form of Constructor objects. Exception This method throws: NoSuchMethodException if a constructor with the specified name is not found. SecurityException if a security manager is present and the security conditions are not met.Below programs demonstrate the getDeclaredConstructor() method.Example 1:// Java program to demonstrate// getDeclaredConstructor() method import java.util.*; public class Test { public Test() {} public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException { // returns the Class object for this class Class myClass = Class.forName("Test"); System.out.println("Class represented by myClass: " + myClass.toString()); Class[] parameterType = null; // Get the constructor of myClass // using getDeclaredConstructor() method System.out.println( "Constructor of myClass: " + myClass.getDeclaredConstructor(parameterType)); }}Output:Class represented by myClass: class Test Constructor of myClass: public Test() Example 2:// Java program to demonstrate// getDeclaredConstructor() constructor import java.util.*; class Main { private Main() {} public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException { // returns the Class object for this class Class myClass = Class.forName("Main"); System.out.println("Class represented by myClass: " + myClass.toString()); Class[] parameterType = new Class[1]; parameterType[0] = Long.class; try { // Get the constructor of myClass // using getDeclaredConstructor() method System.out.println( "Constructor of myClass: " + myClass.getDeclaredConstructor(parameterType)); } catch (Exception e) { System.out.println(e); } }}Output:Class represented by myClass: class Main java.lang.NoSuchMethodException: Main.(java.lang.Long) Reference: https://docs.oracle.com/javase/9/docs/api/java/lang/Class.html#getDeclaredConstructor-java.lang.Class...-My Personal Notes arrow_drop_upSave Below programs demonstrate the getDeclaredConstructor() method. Example 1: // Java program to demonstrate// getDeclaredConstructor() method import java.util.*; public class Test { public Test() {} public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException { // returns the Class object for this class Class myClass = Class.forName("Test"); System.out.println("Class represented by myClass: " + myClass.toString()); Class[] parameterType = null; // Get the constructor of myClass // using getDeclaredConstructor() method System.out.println( "Constructor of myClass: " + myClass.getDeclaredConstructor(parameterType)); }} Class represented by myClass: class Test Constructor of myClass: public Test() Example 2: // Java program to demonstrate// getDeclaredConstructor() constructor import java.util.*; class Main { private Main() {} public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException { // returns the Class object for this class Class myClass = Class.forName("Main"); System.out.println("Class represented by myClass: " + myClass.toString()); Class[] parameterType = new Class[1]; parameterType[0] = Long.class; try { // Get the constructor of myClass // using getDeclaredConstructor() method System.out.println( "Constructor of myClass: " + myClass.getDeclaredConstructor(parameterType)); } catch (Exception e) { System.out.println(e); } }} Class represented by myClass: class Main java.lang.NoSuchMethodException: Main.(java.lang.Long) Reference: https://docs.oracle.com/javase/9/docs/api/java/lang/Class.html#getDeclaredConstructor-java.lang.Class...- 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. Stream In Java Different ways of Reading a text file in Java Constructors in Java Exceptions in Java Functional Interfaces in Java Generics in Java Comparator Interface in Java with Examples HashMap get() Method in Java Introduction to Java Difference between Abstract Class and Interface in Java
[ { "code": null, "e": 23948, "s": 23920, "text": "\n16 Dec, 2019" }, { "code": null, "e": 24193, "s": 23948, "text": "The getDeclaredConstructor() method of java.lang.Class class is used to get the specified constructor of this class with the specified parameter type. The method returns the specified constructor of this class in the form of Constructor object." }, { "code": null, "e": 24201, "s": 24193, "text": "Syntax:" }, { "code": null, "e": 24332, "s": 24201, "text": "public Constructor<T>\n getDeclaredConstructor(Class[] parameterType)\n throws NoSuchMethodException, SecurityException\n" }, { "code": null, "e": 24463, "s": 24332, "text": "Parameter: This constructor accepts a parameters parameterType which is the array of parameter type for the specified constructor." }, { "code": null, "e": 24573, "s": 24463, "text": "Return Value: This method returns the specified constructor of this class in the form of Constructor objects." }, { "code": null, "e": 24603, "s": 24573, "text": "Exception This method throws:" }, { "code": null, "e": 24680, "s": 24603, "text": "NoSuchMethodException if a constructor with the specified name is not found." }, { "code": null, "e": 26768, "s": 24680, "text": "SecurityException if a security manager is present and the security conditions are not met.Below programs demonstrate the getDeclaredConstructor() method.Example 1:// Java program to demonstrate// getDeclaredConstructor() method import java.util.*; public class Test { public Test() {} public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException { // returns the Class object for this class Class myClass = Class.forName(\"Test\"); System.out.println(\"Class represented by myClass: \" + myClass.toString()); Class[] parameterType = null; // Get the constructor of myClass // using getDeclaredConstructor() method System.out.println( \"Constructor of myClass: \" + myClass.getDeclaredConstructor(parameterType)); }}Output:Class represented by myClass: class Test\nConstructor of myClass: public Test()\nExample 2:// Java program to demonstrate// getDeclaredConstructor() constructor import java.util.*; class Main { private Main() {} public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException { // returns the Class object for this class Class myClass = Class.forName(\"Main\"); System.out.println(\"Class represented by myClass: \" + myClass.toString()); Class[] parameterType = new Class[1]; parameterType[0] = Long.class; try { // Get the constructor of myClass // using getDeclaredConstructor() method System.out.println( \"Constructor of myClass: \" + myClass.getDeclaredConstructor(parameterType)); } catch (Exception e) { System.out.println(e); } }}Output:Class represented by myClass: class Main\njava.lang.NoSuchMethodException: Main.(java.lang.Long)\nReference: https://docs.oracle.com/javase/9/docs/api/java/lang/Class.html#getDeclaredConstructor-java.lang.Class...-My Personal Notes\narrow_drop_upSave" }, { "code": null, "e": 26832, "s": 26768, "text": "Below programs demonstrate the getDeclaredConstructor() method." }, { "code": null, "e": 26843, "s": 26832, "text": "Example 1:" }, { "code": "// Java program to demonstrate// getDeclaredConstructor() method import java.util.*; public class Test { public Test() {} public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException { // returns the Class object for this class Class myClass = Class.forName(\"Test\"); System.out.println(\"Class represented by myClass: \" + myClass.toString()); Class[] parameterType = null; // Get the constructor of myClass // using getDeclaredConstructor() method System.out.println( \"Constructor of myClass: \" + myClass.getDeclaredConstructor(parameterType)); }}", "e": 27551, "s": 26843, "text": null }, { "code": null, "e": 27631, "s": 27551, "text": "Class represented by myClass: class Test\nConstructor of myClass: public Test()\n" }, { "code": null, "e": 27642, "s": 27631, "text": "Example 2:" }, { "code": "// Java program to demonstrate// getDeclaredConstructor() constructor import java.util.*; class Main { private Main() {} public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException { // returns the Class object for this class Class myClass = Class.forName(\"Main\"); System.out.println(\"Class represented by myClass: \" + myClass.toString()); Class[] parameterType = new Class[1]; parameterType[0] = Long.class; try { // Get the constructor of myClass // using getDeclaredConstructor() method System.out.println( \"Constructor of myClass: \" + myClass.getDeclaredConstructor(parameterType)); } catch (Exception e) { System.out.println(e); } }}", "e": 28509, "s": 27642, "text": null }, { "code": null, "e": 28606, "s": 28509, "text": "Class represented by myClass: class Main\njava.lang.NoSuchMethodException: Main.(java.lang.Long)\n" }, { "code": null, "e": 28723, "s": 28606, "text": "Reference: https://docs.oracle.com/javase/9/docs/api/java/lang/Class.html#getDeclaredConstructor-java.lang.Class...-" }, { "code": null, "e": 28738, "s": 28723, "text": "Java-Functions" }, { "code": null, "e": 28756, "s": 28738, "text": "Java-lang package" }, { "code": null, "e": 28772, "s": 28756, "text": "Java.lang.Class" }, { "code": null, "e": 28777, "s": 28772, "text": "Java" }, { "code": null, "e": 28782, "s": 28777, "text": "Java" }, { "code": null, "e": 28880, "s": 28782, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28895, "s": 28880, "text": "Stream In Java" }, { "code": null, "e": 28941, "s": 28895, "text": "Different ways of Reading a text file in Java" }, { "code": null, "e": 28962, "s": 28941, "text": "Constructors in Java" }, { "code": null, "e": 28981, "s": 28962, "text": "Exceptions in Java" }, { "code": null, "e": 29011, "s": 28981, "text": "Functional Interfaces in Java" }, { "code": null, "e": 29028, "s": 29011, "text": "Generics in Java" }, { "code": null, "e": 29071, "s": 29028, "text": "Comparator Interface in Java with Examples" }, { "code": null, "e": 29100, "s": 29071, "text": "HashMap get() Method in Java" }, { "code": null, "e": 29121, "s": 29100, "text": "Introduction to Java" } ]
100% Stacked Column Chart
Following is an example of a 100% stacked bar chart. We've already seen the configuration used to draw this chart in Google Charts Configuration Syntax chapter. So, let's see the complete example. We've used isStacked configuration to show stacked chart. // Set chart options var options = { isStacked: 'percent' }; googlecharts_column_percentage.htm <html> <head> <title>Google Charts Tutorial</title> <script type = "text/javascript" src = "https://www.gstatic.com/charts/loader.js"> </script> <script type = "text/javascript"> google.charts.load('current', {packages: ['corechart']}); </script> </head> <body> <div id = "container" style = "width: 550px; height: 400px; margin: 0 auto"> </div> <script language = "JavaScript"> function drawChart() { // Define the chart to be drawn. var data = google.visualization.arrayToDataTable([ ['Year', 'Asia', 'Europe'], ['2012', 900, 390], ['2013', 1000, 400], ['2014', 1170, 440], ['2015', 1250, 480], ['2016', 1530, 540] ]); var options = { title: 'Population (in millions)', isStacked:'percent' }; // Instantiate and draw the chart. var chart = new google.visualization.ColumnChart(document.getElementById('container')); chart.draw(data, options); } google.charts.setOnLoadCallback(drawChart); </script> </body> </html> Verify the result. Print Add Notes Bookmark this page
[ { "code": null, "e": 2458, "s": 2261, "text": "Following is an example of a 100% stacked bar chart. We've already seen the configuration used to draw this chart in Google Charts Configuration Syntax chapter. So, let's see the complete example." }, { "code": null, "e": 2516, "s": 2458, "text": "We've used isStacked configuration to show stacked chart." }, { "code": null, "e": 2580, "s": 2516, "text": "// Set chart options\nvar options = {\n isStacked: 'percent'\n};" }, { "code": null, "e": 2615, "s": 2580, "text": "googlecharts_column_percentage.htm" }, { "code": null, "e": 3897, "s": 2615, "text": "<html>\n <head>\n <title>Google Charts Tutorial</title>\n <script type = \"text/javascript\" src = \"https://www.gstatic.com/charts/loader.js\">\n </script>\n <script type = \"text/javascript\">\n google.charts.load('current', {packages: ['corechart']}); \n </script>\n </head>\n \n <body>\n <div id = \"container\" style = \"width: 550px; height: 400px; margin: 0 auto\">\n </div>\n <script language = \"JavaScript\">\n function drawChart() {\n // Define the chart to be drawn.\n var data = google.visualization.arrayToDataTable([\n ['Year', 'Asia', 'Europe'],\n ['2012', 900, 390],\n ['2013', 1000, 400],\n ['2014', 1170, 440],\n ['2015', 1250, 480],\n ['2016', 1530, 540]\n ]);\n\n var options = {\n title: 'Population (in millions)',\n isStacked:'percent'\t \n }; \n\n // Instantiate and draw the chart.\n var chart = new google.visualization.ColumnChart(document.getElementById('container'));\n chart.draw(data, options);\n }\n google.charts.setOnLoadCallback(drawChart);\n </script>\n </body>\n</html>" }, { "code": null, "e": 3916, "s": 3897, "text": "Verify the result." }, { "code": null, "e": 3923, "s": 3916, "text": " Print" }, { "code": null, "e": 3934, "s": 3923, "text": " Add Notes" } ]
DAX Date & Time - EDATE function
Returns the date that is the indicated number of months before or after the start date. EDATE (<start_date>, <month>) start_date A date that represents the start date. It can be in datetime or text format. months An integer that represents the number of months before or after start_date. If months is not an integer, it is truncated. A date in datetime format. You can use EDATE to calculate maturity dates or due dates that fall on the same day of the month as the date of issue. DAX works with dates in datetime format. Dates stored in other formats are converted implicitly. If start_date is not a valid date, EDATE returns an error value. Make sure that the column reference or date that you supply as the first parameter is a date. If start_date is not a valid date, EDATE returns an error value. Make sure that the column reference or date that you supply as the first parameter is a date. DAX EDATE function uses the locale and date/time settings of the client computer to understand the text value in order to perform the conversion. For example, If the current date/time settings represent dates in the format of Month/Day/Year, then the string, "1/8/2016" is understood as a datetime value equivalent to 8th January, 2016. If the current date/time settings represent dates in the format of Day/Month/Year, the same string would be understood as a datetime value equivalent to 1st August, 2016. DAX EDATE function uses the locale and date/time settings of the client computer to understand the text value in order to perform the conversion. For example, If the current date/time settings represent dates in the format of Month/Day/Year, then the string, "1/8/2016" is understood as a datetime value equivalent to 8th January, 2016. If the current date/time settings represent dates in the format of Month/Day/Year, then the string, "1/8/2016" is understood as a datetime value equivalent to 8th January, 2016. If the current date/time settings represent dates in the format of Day/Month/Year, the same string would be understood as a datetime value equivalent to 1st August, 2016. If the current date/time settings represent dates in the format of Day/Month/Year, the same string would be understood as a datetime value equivalent to 1st August, 2016. = EDATE (DATE (2015,1,1),9) returns 10/1/2015 12:00:00 AM = EDATE (DATE (2015,1,30),1) returns 2/28/2015 12:00:00 AM = EDATE (DATE (2015,1,29),1) returns 2/28/2015 12:00:00 AM 53 Lectures 5.5 hours Abhay Gadiya 24 Lectures 2 hours Randy Minder 26 Lectures 4.5 hours Randy Minder Print Add Notes Bookmark this page
[ { "code": null, "e": 2089, "s": 2001, "text": "Returns the date that is the indicated number of months before or after the start date." }, { "code": null, "e": 2121, "s": 2089, "text": "EDATE (<start_date>, <month>) \n" }, { "code": null, "e": 2132, "s": 2121, "text": "start_date" }, { "code": null, "e": 2171, "s": 2132, "text": "A date that represents the start date." }, { "code": null, "e": 2209, "s": 2171, "text": "It can be in datetime or text format." }, { "code": null, "e": 2216, "s": 2209, "text": "months" }, { "code": null, "e": 2292, "s": 2216, "text": "An integer that represents the number of months before or after start_date." }, { "code": null, "e": 2338, "s": 2292, "text": "If months is not an integer, it is truncated." }, { "code": null, "e": 2365, "s": 2338, "text": "A date in datetime format." }, { "code": null, "e": 2485, "s": 2365, "text": "You can use EDATE to calculate maturity dates or due dates that fall on the same day of the month as the date of issue." }, { "code": null, "e": 2582, "s": 2485, "text": "DAX works with dates in datetime format. Dates stored in other formats are converted implicitly." }, { "code": null, "e": 2741, "s": 2582, "text": "If start_date is not a valid date, EDATE returns an error value.\nMake sure that the column reference or date that you supply as the first parameter is a date." }, { "code": null, "e": 2806, "s": 2741, "text": "If start_date is not a valid date, EDATE returns an error value." }, { "code": null, "e": 2900, "s": 2806, "text": "Make sure that the column reference or date that you supply as the first parameter is a date." }, { "code": null, "e": 3411, "s": 2900, "text": "DAX EDATE function uses the locale and date/time settings of the client computer to understand the text value in order to perform the conversion. For example,\n\nIf the current date/time settings represent dates in the format of Month/Day/Year, then the string, \"1/8/2016\" is understood as a datetime value equivalent to 8th January, 2016.\nIf the current date/time settings represent dates in the format of Day/Month/Year, the same string would be understood as a datetime value equivalent to 1st August, 2016.\n\n" }, { "code": null, "e": 3570, "s": 3411, "text": "DAX EDATE function uses the locale and date/time settings of the client computer to understand the text value in order to perform the conversion. For example," }, { "code": null, "e": 3748, "s": 3570, "text": "If the current date/time settings represent dates in the format of Month/Day/Year, then the string, \"1/8/2016\" is understood as a datetime value equivalent to 8th January, 2016." }, { "code": null, "e": 3926, "s": 3748, "text": "If the current date/time settings represent dates in the format of Month/Day/Year, then the string, \"1/8/2016\" is understood as a datetime value equivalent to 8th January, 2016." }, { "code": null, "e": 4097, "s": 3926, "text": "If the current date/time settings represent dates in the format of Day/Month/Year, the same string would be understood as a datetime value equivalent to 1st August, 2016." }, { "code": null, "e": 4268, "s": 4097, "text": "If the current date/time settings represent dates in the format of Day/Month/Year, the same string would be understood as a datetime value equivalent to 1st August, 2016." }, { "code": null, "e": 4447, "s": 4268, "text": "= EDATE (DATE (2015,1,1),9) returns 10/1/2015 12:00:00 AM \n= EDATE (DATE (2015,1,30),1) returns 2/28/2015 12:00:00 AM \n= EDATE (DATE (2015,1,29),1) returns 2/28/2015 12:00:00 AM " }, { "code": null, "e": 4482, "s": 4447, "text": "\n 53 Lectures \n 5.5 hours \n" }, { "code": null, "e": 4496, "s": 4482, "text": " Abhay Gadiya" }, { "code": null, "e": 4529, "s": 4496, "text": "\n 24 Lectures \n 2 hours \n" }, { "code": null, "e": 4543, "s": 4529, "text": " Randy Minder" }, { "code": null, "e": 4578, "s": 4543, "text": "\n 26 Lectures \n 4.5 hours \n" }, { "code": null, "e": 4592, "s": 4578, "text": " Randy Minder" }, { "code": null, "e": 4599, "s": 4592, "text": " Print" }, { "code": null, "e": 4610, "s": 4599, "text": " Add Notes" } ]
Create a paragraph element with some text and append it to end of document body using jQuery - GeeksforGeeks
31 Dec, 2020 In this article, we will create a paragraph element with some text and append it to the end of the document body using jQuery. To append some text at the end of the document body, we use add() and appendTo() methods. The jQuery add() method is used to add elements to the existing group of elements. This method can add elements to the whole document, or just inside the context element if the context parameter is defined. Syntax: $(selector).add(element, context_parameter) The jQuery appendTo() is an inbuilt method that is used to insert an HTML element at the end of the selected element. Syntax: $(content).appendTo(selector) Example: HTML <!DOCTYPE html><html lang="en"> <head> <!-- Import jQuery cdn library --> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"> </script> <script> $(document).ready(function () { $("button").click(function () { $("button").add(" <p>Hello World!</p>") .appendTo(document.body); }); }); </script></head> <body style="text-align: center;"> <h1 style="color: green;"> GeeksforGeeks </h1> <h3> How to create a paragraph element with some text and append it <br>to the end of the document body using jQuery? </h3> <p>GeeksforGeeks computer science portal</p> <span>GeeksforGeeks</span> <br><br> <button>Click Here!</button></body> </html> Output: Before Click Button: After Click Button: Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course. CSS-Misc HTML-Misc jQuery-Misc CSS HTML JQuery Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Design a web page using HTML and CSS Form validation using jQuery How to set space between the flexbox ? Search Bar using HTML, CSS and JavaScript How to Create Time-Table schedule using HTML ? How to set the default value for an HTML <select> element ? How to set input type date in dd-mm-yyyy format using HTML ? Hide or show elements in HTML using display property How to Insert Form Data into Database using PHP ? REST API (Introduction)
[ { "code": null, "e": 25461, "s": 25433, "text": "\n31 Dec, 2020" }, { "code": null, "e": 25885, "s": 25461, "text": "In this article, we will create a paragraph element with some text and append it to the end of the document body using jQuery. To append some text at the end of the document body, we use add() and appendTo() methods. The jQuery add() method is used to add elements to the existing group of elements. This method can add elements to the whole document, or just inside the context element if the context parameter is defined." }, { "code": null, "e": 25893, "s": 25885, "text": "Syntax:" }, { "code": null, "e": 25937, "s": 25893, "text": "$(selector).add(element, context_parameter)" }, { "code": null, "e": 26055, "s": 25937, "text": "The jQuery appendTo() is an inbuilt method that is used to insert an HTML element at the end of the selected element." }, { "code": null, "e": 26063, "s": 26055, "text": "Syntax:" }, { "code": null, "e": 26093, "s": 26063, "text": "$(content).appendTo(selector)" }, { "code": null, "e": 26102, "s": 26093, "text": "Example:" }, { "code": null, "e": 26107, "s": 26102, "text": "HTML" }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <!-- Import jQuery cdn library --> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"> </script> <script> $(document).ready(function () { $(\"button\").click(function () { $(\"button\").add(\" <p>Hello World!</p>\") .appendTo(document.body); }); }); </script></head> <body style=\"text-align: center;\"> <h1 style=\"color: green;\"> GeeksforGeeks </h1> <h3> How to create a paragraph element with some text and append it <br>to the end of the document body using jQuery? </h3> <p>GeeksforGeeks computer science portal</p> <span>GeeksforGeeks</span> <br><br> <button>Click Here!</button></body> </html>", "e": 26944, "s": 26107, "text": null }, { "code": null, "e": 26952, "s": 26944, "text": "Output:" }, { "code": null, "e": 26973, "s": 26952, "text": "Before Click Button:" }, { "code": null, "e": 26993, "s": 26973, "text": "After Click Button:" }, { "code": null, "e": 27130, "s": 26993, "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": 27139, "s": 27130, "text": "CSS-Misc" }, { "code": null, "e": 27149, "s": 27139, "text": "HTML-Misc" }, { "code": null, "e": 27161, "s": 27149, "text": "jQuery-Misc" }, { "code": null, "e": 27165, "s": 27161, "text": "CSS" }, { "code": null, "e": 27170, "s": 27165, "text": "HTML" }, { "code": null, "e": 27177, "s": 27170, "text": "JQuery" }, { "code": null, "e": 27194, "s": 27177, "text": "Web Technologies" }, { "code": null, "e": 27199, "s": 27194, "text": "HTML" }, { "code": null, "e": 27297, "s": 27199, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27334, "s": 27297, "text": "Design a web page using HTML and CSS" }, { "code": null, "e": 27363, "s": 27334, "text": "Form validation using jQuery" }, { "code": null, "e": 27402, "s": 27363, "text": "How to set space between the flexbox ?" }, { "code": null, "e": 27444, "s": 27402, "text": "Search Bar using HTML, CSS and JavaScript" }, { "code": null, "e": 27491, "s": 27444, "text": "How to Create Time-Table schedule using HTML ?" }, { "code": null, "e": 27551, "s": 27491, "text": "How to set the default value for an HTML <select> element ?" }, { "code": null, "e": 27612, "s": 27551, "text": "How to set input type date in dd-mm-yyyy format using HTML ?" }, { "code": null, "e": 27665, "s": 27612, "text": "Hide or show elements in HTML using display property" }, { "code": null, "e": 27715, "s": 27665, "text": "How to Insert Form Data into Database using PHP ?" } ]
Python | Pandas Timestamp.weekday - GeeksforGeeks
21 Jan, 2019 Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Pandas Timestamp.weekday() function return the day of the week represented by the date in the given Timestamp object. Monday == 0 ... Sunday == 6. Syntax :Timestamp.weekday() Parameters : None Return : day of the week Example #1: Use Timestamp.weekday() function to return the day of the week for the date in the given Timestamp object. # importing pandas as pdimport pandas as pd # Create the Timestamp objectts = pd.Timestamp(year = 2011, month = 11, day = 21, hour = 10, second = 49, tz = 'US/Central') # Print the Timestamp objectprint(ts) Output : Now we will use the Timestamp.weekday() function to return the day of the week. # return the day of the weekts.weekday() Output : As we can see in the output, the Timestamp.weekday() function has returned 0 indicating that the day is Monday. Example #2: Use Timestamp.weekday() function to return the day of the week for the date in the given Timestamp object. # importing pandas as pdimport pandas as pd # Create the Timestamp objectts = pd.Timestamp(year = 2009, month = 5, day = 31, hour = 4, second = 49, tz = 'Europe/Berlin') # Print the Timestamp objectprint(ts) Output : Now we will use the Timestamp.weekday() function to return the day of the week. # return the day of the weekts.weekday() Output : As we can see in the output, the Timestamp.weekday() function has returned 6 indicating that the day is Sunday. Python Pandas-Timestamp Python-pandas Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Enumerate() in Python How to Install PIP on Windows ? Different ways to create Pandas Dataframe Create a Pandas DataFrame from Lists *args and **kwargs in Python How To Convert Python Dictionary To JSON? sum() function in Python How to drop one or multiple columns in Pandas Dataframe Print lists in Python (4 Different Ways)
[ { "code": null, "e": 24864, "s": 24836, "text": "\n21 Jan, 2019" }, { "code": null, "e": 25078, "s": 24864, "text": "Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier." }, { "code": null, "e": 25225, "s": 25078, "text": "Pandas Timestamp.weekday() function return the day of the week represented by the date in the given Timestamp object. Monday == 0 ... Sunday == 6." }, { "code": null, "e": 25253, "s": 25225, "text": "Syntax :Timestamp.weekday()" }, { "code": null, "e": 25271, "s": 25253, "text": "Parameters : None" }, { "code": null, "e": 25296, "s": 25271, "text": "Return : day of the week" }, { "code": null, "e": 25415, "s": 25296, "text": "Example #1: Use Timestamp.weekday() function to return the day of the week for the date in the given Timestamp object." }, { "code": "# importing pandas as pdimport pandas as pd # Create the Timestamp objectts = pd.Timestamp(year = 2011, month = 11, day = 21, hour = 10, second = 49, tz = 'US/Central') # Print the Timestamp objectprint(ts)", "e": 25644, "s": 25415, "text": null }, { "code": null, "e": 25653, "s": 25644, "text": "Output :" }, { "code": null, "e": 25733, "s": 25653, "text": "Now we will use the Timestamp.weekday() function to return the day of the week." }, { "code": "# return the day of the weekts.weekday()", "e": 25774, "s": 25733, "text": null }, { "code": null, "e": 25783, "s": 25774, "text": "Output :" }, { "code": null, "e": 26014, "s": 25783, "text": "As we can see in the output, the Timestamp.weekday() function has returned 0 indicating that the day is Monday. Example #2: Use Timestamp.weekday() function to return the day of the week for the date in the given Timestamp object." }, { "code": "# importing pandas as pdimport pandas as pd # Create the Timestamp objectts = pd.Timestamp(year = 2009, month = 5, day = 31, hour = 4, second = 49, tz = 'Europe/Berlin') # Print the Timestamp objectprint(ts)", "e": 26242, "s": 26014, "text": null }, { "code": null, "e": 26251, "s": 26242, "text": "Output :" }, { "code": null, "e": 26331, "s": 26251, "text": "Now we will use the Timestamp.weekday() function to return the day of the week." }, { "code": "# return the day of the weekts.weekday()", "e": 26372, "s": 26331, "text": null }, { "code": null, "e": 26381, "s": 26372, "text": "Output :" }, { "code": null, "e": 26493, "s": 26381, "text": "As we can see in the output, the Timestamp.weekday() function has returned 6 indicating that the day is Sunday." }, { "code": null, "e": 26517, "s": 26493, "text": "Python Pandas-Timestamp" }, { "code": null, "e": 26531, "s": 26517, "text": "Python-pandas" }, { "code": null, "e": 26538, "s": 26531, "text": "Python" }, { "code": null, "e": 26636, "s": 26538, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26654, "s": 26636, "text": "Python Dictionary" }, { "code": null, "e": 26676, "s": 26654, "text": "Enumerate() in Python" }, { "code": null, "e": 26708, "s": 26676, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 26750, "s": 26708, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 26787, "s": 26750, "text": "Create a Pandas DataFrame from Lists" }, { "code": null, "e": 26816, "s": 26787, "text": "*args and **kwargs in Python" }, { "code": null, "e": 26858, "s": 26816, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 26883, "s": 26858, "text": "sum() function in Python" }, { "code": null, "e": 26939, "s": 26883, "text": "How to drop one or multiple columns in Pandas Dataframe" } ]
How to identify Japanese candlesticks patterns in Python | by Gianluca Malato | Towards Data Science
Japanese candlesticks are one of the most important tools for a discretionary or quantitative trader. They are the first example of a particular trading style called price action. Let’s see what they are and how they can be used in Python. Note from Towards Data Science’s editors: While we allow independent authors to publish articles in accordance with our rules and guidelines, we do not endorse each author’s contribution. You should not rely on an author’s works without seeking professional advice. See our Reader Terms for details. Japanese candlesticks are a particular chart type. For each time period, they show the maximum, the minimum, the opening and the closing price. Let’s see an example chart: Each day is represented by a symbol called candle. Each candle is made by a real body, an upper shadow and a lower shadow. Candles have a color. They are usually white, green or blue if the close price is greater than the open price (bullish candle). They are black or red if the close price is lower than the open price (bearish candle). This kind of chart is very useful because it gives us a lot of information in a simple symbol, but the most important use is related to patterns. Patterns are a combination of candles that show a particular graphical shape and they are useful to spot price reversals. Let’s see some of them. Here follows a list of the most common patterns with the Python code that lets us identify them. You can find the whole code in my GitHub repository here: https://github.com/gianlucamalato/machinelearning/blob/master/Candlesticks.ipynb First, we must install yfinance library to download market data. !pip install yfinance Then we can import pandas and finance. import pandas as pdimport yfinance For this example, we’re going to use S&P 500 daily data of the last 5 months. ticker = yfinance.Ticker("SPY")df = ticker.history(period = '5mo') Now we are going to create as many columns as the patterns, each with a boolean value that is True if the pattern occurs and false if it doesn’t. So, we have to scan among the historical data. We’re going to use a for loop. We calculate the real body width and the candle range. for i in range(2,df.shape[0]): current = df.iloc[i,:] prev = df.iloc[i-1,:] prev_2 = df.iloc[i-2,:] realbody = abs(current['Open'] - current['Close']) candle_range = current['High'] - current['Low'] idx = df.index[i] Let’s now see some patterns and their code, that must be included inside the for loop. Bullish swing is a simple 3-candle pattern. The second candle has the lowest low among the three. The color of the candles is irrelevant. It’s a signal that spots a possible bullish rally of the price. So, the code is, simply: df.loc[idx,'Bullish swing'] = current['Low'] > prev['Low'] and prev['Low'] < prev_2['Low'] A bearish swing is the opposite of a bullish swing. It’s made of 3 candles and the second candle has the highest high. The color of the candles is irrelevant. And here’s the code: df.loc[idx,'Bearish swing'] = current['High'] < prev['High'] and prev['High'] > prev_2['High'] Pin bars are very frequent and powerful patterns. It’s commonly known that a pin bar has a very long shadow and a small real body. It’s very important to point that a pin bar is not only such a candle, but it must protrude from the surrounding price action. So, a bullish pin bar must have a lower low with respect to the previous candle. We can define a “small” real body as a real body whose width is less than the candle range divided by 3. A bullish pin bar will then have the real body located in the upper half of the candle. The color of the candle is irrelevant. Here’s the code of the bullish pin bar: df.loc[idx,'Bullish pinbar'] = realbody <= candle_range/3 and min(current['Open'], current['Close']) > (current['High'] + current['Low'])/2 and current['Low'] < prev['Low'] The bearish pin bar is just like the bullish pin bar, but the real body is now located in the lower half of the candle and it has a higher high than the previous candle. Here’s the code: df.loc[idx,'Bearish pinbar'] = realbody <= candle_range/3 and max(current['Open'] , current['Close']) < (current['High'] + current['Low'])/2 and current['High'] > prev['High'] Inside bar is a pattern made by two candles. The second candle is entirely included in the range of the first candle. The color is irrelevant. This pattern shows a contraction in volatility that may be a prelude to a strong directional explosion. Here’s the code: df.loc[idx,'Inside bar'] = current['High'] < prev['High'] and current['Low'] > prev['Low'] The outside bar is the opposite of the inside bar. The candle range includes the previous candle entirely. Here’s the code: df.loc[idx,'Outside bar'] = current['High'] > prev['High'] and current['Low'] < prev['Low'] Bullish engulfing is a strong bullish pattern. It’s an outside bar with a huge, bullish real body. We can define a “huge” as a real body whose width takes more than 80% of the candle range. Here’s the code: df.loc[idx,'Bullish engulfing'] = current['High'] > prev['High'] and current['Low'] < prev['Low'] and realbody >= 0.8 * candle_range and current['Close'] > current['Open'] Bearish engulfing is the opposite of bullish engulfing. A huge, bearish candle engulfs the previous candle completely. Here’s the code: df.loc[idx,'Bearish engulfing'] = current['High'] > prev['High'] and current['Low'] < prev['Low'] and realbody >= 0.8 * candle_range and current['Close'] < current['Open'] Here follows the complete code. Remember that we have to fill blanks with False. for i in range(2,df.shape[0]): current = df.iloc[i,:] prev = df.iloc[i-1,:] prev_2 = df.iloc[i-2,:]realbody = abs(current['Open'] - current['Close']) candle_range = current['High'] - current['Low']idx = df.index[i] # Bullish swing df.loc[idx,'Bullish swing'] = current['Low'] > prev['Low'] and prev['Low'] < prev_2['Low']# Bearish swing df.loc[idx,'Bearish swing'] = current['High'] < prev['High'] and prev['High'] > prev_2['High']# Bullish pinbar df.loc[idx,'Bullish pinbar'] = realbody <= candle_range/3 and min(current['Open'], current['Close']) > (current['High'] + current['Low'])/2 and current['Low'] < prev['Low']# Bearish pinbar df.loc[idx,'Bearish pinbar'] = realbody <= candle_range/3 and max(current['Open'] , current['Close']) < (current['High'] + current['Low'])/2 and current['High'] > prev['High'] # Inside bar df.loc[idx,'Inside bar'] = current['High'] < prev['High'] and current['Low'] > prev['Low'] # Outside bar df.loc[idx,'Outside bar'] = current['High'] > prev['High'] and current['Low'] < prev['Low'] # Bullish engulfing df.loc[idx,'Bullish engulfing'] = current['High'] > prev['High'] and current['Low'] < prev['Low'] and realbody >= 0.8 * candle_range and current['Close'] > current['Open']# Bearish engulfing df.loc[idx,'Bearish engulfing'] = current['High'] > prev['High'] and current['Low'] < prev['Low'] and realbody >= 0.8 * candle_range and current['Close'] < current['Open']df.fillna(False, inplace=True) Our data frame will finally look like this: Filtering the rows according to the value of the columns will make us backtest any trading strategy that uses such patterns. Japanese candlesticks patterns are very useful for spotting trend reversals. There are many different patterns that have not been described in this article, but here you can find the most important patterns. A Python implementation of such patterns can be very useful to anybody who wants to start the adventure of algorithmic trading.
[ { "code": null, "e": 351, "s": 171, "text": "Japanese candlesticks are one of the most important tools for a discretionary or quantitative trader. They are the first example of a particular trading style called price action." }, { "code": null, "e": 411, "s": 351, "text": "Let’s see what they are and how they can be used in Python." }, { "code": null, "e": 711, "s": 411, "text": "Note from Towards Data Science’s editors: While we allow independent authors to publish articles in accordance with our rules and guidelines, we do not endorse each author’s contribution. You should not rely on an author’s works without seeking professional advice. See our Reader Terms for details." }, { "code": null, "e": 855, "s": 711, "text": "Japanese candlesticks are a particular chart type. For each time period, they show the maximum, the minimum, the opening and the closing price." }, { "code": null, "e": 883, "s": 855, "text": "Let’s see an example chart:" }, { "code": null, "e": 1006, "s": 883, "text": "Each day is represented by a symbol called candle. Each candle is made by a real body, an upper shadow and a lower shadow." }, { "code": null, "e": 1222, "s": 1006, "text": "Candles have a color. They are usually white, green or blue if the close price is greater than the open price (bullish candle). They are black or red if the close price is lower than the open price (bearish candle)." }, { "code": null, "e": 1514, "s": 1222, "text": "This kind of chart is very useful because it gives us a lot of information in a simple symbol, but the most important use is related to patterns. Patterns are a combination of candles that show a particular graphical shape and they are useful to spot price reversals. Let’s see some of them." }, { "code": null, "e": 1611, "s": 1514, "text": "Here follows a list of the most common patterns with the Python code that lets us identify them." }, { "code": null, "e": 1750, "s": 1611, "text": "You can find the whole code in my GitHub repository here: https://github.com/gianlucamalato/machinelearning/blob/master/Candlesticks.ipynb" }, { "code": null, "e": 1815, "s": 1750, "text": "First, we must install yfinance library to download market data." }, { "code": null, "e": 1837, "s": 1815, "text": "!pip install yfinance" }, { "code": null, "e": 1876, "s": 1837, "text": "Then we can import pandas and finance." }, { "code": null, "e": 1911, "s": 1876, "text": "import pandas as pdimport yfinance" }, { "code": null, "e": 1989, "s": 1911, "text": "For this example, we’re going to use S&P 500 daily data of the last 5 months." }, { "code": null, "e": 2056, "s": 1989, "text": "ticker = yfinance.Ticker(\"SPY\")df = ticker.history(period = '5mo')" }, { "code": null, "e": 2202, "s": 2056, "text": "Now we are going to create as many columns as the patterns, each with a boolean value that is True if the pattern occurs and false if it doesn’t." }, { "code": null, "e": 2335, "s": 2202, "text": "So, we have to scan among the historical data. We’re going to use a for loop. We calculate the real body width and the candle range." }, { "code": null, "e": 2558, "s": 2335, "text": "for i in range(2,df.shape[0]): current = df.iloc[i,:] prev = df.iloc[i-1,:] prev_2 = df.iloc[i-2,:] realbody = abs(current['Open'] - current['Close']) candle_range = current['High'] - current['Low'] idx = df.index[i]" }, { "code": null, "e": 2645, "s": 2558, "text": "Let’s now see some patterns and their code, that must be included inside the for loop." }, { "code": null, "e": 2847, "s": 2645, "text": "Bullish swing is a simple 3-candle pattern. The second candle has the lowest low among the three. The color of the candles is irrelevant. It’s a signal that spots a possible bullish rally of the price." }, { "code": null, "e": 2872, "s": 2847, "text": "So, the code is, simply:" }, { "code": null, "e": 2963, "s": 2872, "text": "df.loc[idx,'Bullish swing'] = current['Low'] > prev['Low'] and prev['Low'] < prev_2['Low']" }, { "code": null, "e": 3122, "s": 2963, "text": "A bearish swing is the opposite of a bullish swing. It’s made of 3 candles and the second candle has the highest high. The color of the candles is irrelevant." }, { "code": null, "e": 3143, "s": 3122, "text": "And here’s the code:" }, { "code": null, "e": 3238, "s": 3143, "text": "df.loc[idx,'Bearish swing'] = current['High'] < prev['High'] and prev['High'] > prev_2['High']" }, { "code": null, "e": 3577, "s": 3238, "text": "Pin bars are very frequent and powerful patterns. It’s commonly known that a pin bar has a very long shadow and a small real body. It’s very important to point that a pin bar is not only such a candle, but it must protrude from the surrounding price action. So, a bullish pin bar must have a lower low with respect to the previous candle." }, { "code": null, "e": 3809, "s": 3577, "text": "We can define a “small” real body as a real body whose width is less than the candle range divided by 3. A bullish pin bar will then have the real body located in the upper half of the candle. The color of the candle is irrelevant." }, { "code": null, "e": 3849, "s": 3809, "text": "Here’s the code of the bullish pin bar:" }, { "code": null, "e": 4023, "s": 3849, "text": "df.loc[idx,'Bullish pinbar'] = realbody <= candle_range/3 and min(current['Open'], current['Close']) > (current['High'] + current['Low'])/2 and current['Low'] < prev['Low']" }, { "code": null, "e": 4193, "s": 4023, "text": "The bearish pin bar is just like the bullish pin bar, but the real body is now located in the lower half of the candle and it has a higher high than the previous candle." }, { "code": null, "e": 4210, "s": 4193, "text": "Here’s the code:" }, { "code": null, "e": 4386, "s": 4210, "text": "df.loc[idx,'Bearish pinbar'] = realbody <= candle_range/3 and max(current['Open'] , current['Close']) < (current['High'] + current['Low'])/2 and current['High'] > prev['High']" }, { "code": null, "e": 4529, "s": 4386, "text": "Inside bar is a pattern made by two candles. The second candle is entirely included in the range of the first candle. The color is irrelevant." }, { "code": null, "e": 4633, "s": 4529, "text": "This pattern shows a contraction in volatility that may be a prelude to a strong directional explosion." }, { "code": null, "e": 4650, "s": 4633, "text": "Here’s the code:" }, { "code": null, "e": 4741, "s": 4650, "text": "df.loc[idx,'Inside bar'] = current['High'] < prev['High'] and current['Low'] > prev['Low']" }, { "code": null, "e": 4848, "s": 4741, "text": "The outside bar is the opposite of the inside bar. The candle range includes the previous candle entirely." }, { "code": null, "e": 4865, "s": 4848, "text": "Here’s the code:" }, { "code": null, "e": 4957, "s": 4865, "text": "df.loc[idx,'Outside bar'] = current['High'] > prev['High'] and current['Low'] < prev['Low']" }, { "code": null, "e": 5147, "s": 4957, "text": "Bullish engulfing is a strong bullish pattern. It’s an outside bar with a huge, bullish real body. We can define a “huge” as a real body whose width takes more than 80% of the candle range." }, { "code": null, "e": 5164, "s": 5147, "text": "Here’s the code:" }, { "code": null, "e": 5336, "s": 5164, "text": "df.loc[idx,'Bullish engulfing'] = current['High'] > prev['High'] and current['Low'] < prev['Low'] and realbody >= 0.8 * candle_range and current['Close'] > current['Open']" }, { "code": null, "e": 5455, "s": 5336, "text": "Bearish engulfing is the opposite of bullish engulfing. A huge, bearish candle engulfs the previous candle completely." }, { "code": null, "e": 5472, "s": 5455, "text": "Here’s the code:" }, { "code": null, "e": 5644, "s": 5472, "text": "df.loc[idx,'Bearish engulfing'] = current['High'] > prev['High'] and current['Low'] < prev['Low'] and realbody >= 0.8 * candle_range and current['Close'] < current['Open']" }, { "code": null, "e": 5725, "s": 5644, "text": "Here follows the complete code. Remember that we have to fill blanks with False." }, { "code": null, "e": 7190, "s": 5725, "text": "for i in range(2,df.shape[0]): current = df.iloc[i,:] prev = df.iloc[i-1,:] prev_2 = df.iloc[i-2,:]realbody = abs(current['Open'] - current['Close']) candle_range = current['High'] - current['Low']idx = df.index[i] # Bullish swing df.loc[idx,'Bullish swing'] = current['Low'] > prev['Low'] and prev['Low'] < prev_2['Low']# Bearish swing df.loc[idx,'Bearish swing'] = current['High'] < prev['High'] and prev['High'] > prev_2['High']# Bullish pinbar df.loc[idx,'Bullish pinbar'] = realbody <= candle_range/3 and min(current['Open'], current['Close']) > (current['High'] + current['Low'])/2 and current['Low'] < prev['Low']# Bearish pinbar df.loc[idx,'Bearish pinbar'] = realbody <= candle_range/3 and max(current['Open'] , current['Close']) < (current['High'] + current['Low'])/2 and current['High'] > prev['High'] # Inside bar df.loc[idx,'Inside bar'] = current['High'] < prev['High'] and current['Low'] > prev['Low'] # Outside bar df.loc[idx,'Outside bar'] = current['High'] > prev['High'] and current['Low'] < prev['Low'] # Bullish engulfing df.loc[idx,'Bullish engulfing'] = current['High'] > prev['High'] and current['Low'] < prev['Low'] and realbody >= 0.8 * candle_range and current['Close'] > current['Open']# Bearish engulfing df.loc[idx,'Bearish engulfing'] = current['High'] > prev['High'] and current['Low'] < prev['Low'] and realbody >= 0.8 * candle_range and current['Close'] < current['Open']df.fillna(False, inplace=True)" }, { "code": null, "e": 7234, "s": 7190, "text": "Our data frame will finally look like this:" }, { "code": null, "e": 7359, "s": 7234, "text": "Filtering the rows according to the value of the columns will make us backtest any trading strategy that uses such patterns." } ]
SQL - UNIQUE Constraint
The UNIQUE Constraint prevents two records from having identical values in a column. In the CUSTOMERS table, for example, you might want to prevent two or more people from having an identical age. For example, the following SQL query creates a new table called CUSTOMERS and adds five columns. Here, the AGE column is set to UNIQUE, so that you cannot have two records with the same age. CREATE TABLE CUSTOMERS( ID INT NOT NULL, NAME VARCHAR (20) NOT NULL, AGE INT NOT NULL UNIQUE, ADDRESS CHAR (25) , SALARY DECIMAL (18, 2), PRIMARY KEY (ID) ); If the CUSTOMERS table has already been created, then to add a UNIQUE constraint to the AGE column. You would write a statement like the query that is given in the code block below. ALTER TABLE CUSTOMERS MODIFY AGE INT NOT NULL UNIQUE; You can also use the following syntax, which supports naming the constraint in multiple columns as well. ALTER TABLE CUSTOMERS ADD CONSTRAINT myUniqueConstraint UNIQUE(AGE, SALARY); To drop a UNIQUE constraint, use the following SQL query. ALTER TABLE CUSTOMERS DROP CONSTRAINT myUniqueConstraint; If you are using MySQL, then you can use the following syntax − ALTER TABLE CUSTOMERS DROP INDEX myUniqueConstraint; 42 Lectures 5 hours Anadi Sharma 14 Lectures 2 hours Anadi Sharma 44 Lectures 4.5 hours Anadi Sharma 94 Lectures 7 hours Abhishek And Pukhraj 80 Lectures 6.5 hours Oracle Master Training | 150,000+ Students Worldwide 31 Lectures 6 hours Eduonix Learning Solutions Print Add Notes Bookmark this page
[ { "code": null, "e": 2650, "s": 2453, "text": "The UNIQUE Constraint prevents two records from having identical values in a column. In the CUSTOMERS table, for example, you might want to prevent two or more people from having an identical age." }, { "code": null, "e": 2841, "s": 2650, "text": "For example, the following SQL query creates a new table called CUSTOMERS and adds five columns. Here, the AGE column is set to UNIQUE, so that you cannot have two records with the same age." }, { "code": null, "e": 3060, "s": 2841, "text": "CREATE TABLE CUSTOMERS(\n ID INT NOT NULL,\n NAME VARCHAR (20) NOT NULL,\n AGE INT NOT NULL UNIQUE,\n ADDRESS CHAR (25) ,\n SALARY DECIMAL (18, 2), \n PRIMARY KEY (ID)\n);" }, { "code": null, "e": 3242, "s": 3060, "text": "If the CUSTOMERS table has already been created, then to add a UNIQUE constraint to the AGE column. You would write a statement like the query that is given in the code block below." }, { "code": null, "e": 3299, "s": 3242, "text": "ALTER TABLE CUSTOMERS\n MODIFY AGE INT NOT NULL UNIQUE;" }, { "code": null, "e": 3404, "s": 3299, "text": "You can also use the following syntax, which supports naming the constraint in multiple columns as well." }, { "code": null, "e": 3484, "s": 3404, "text": "ALTER TABLE CUSTOMERS\n ADD CONSTRAINT myUniqueConstraint UNIQUE(AGE, SALARY);" }, { "code": null, "e": 3542, "s": 3484, "text": "To drop a UNIQUE constraint, use the following SQL query." }, { "code": null, "e": 3603, "s": 3542, "text": "ALTER TABLE CUSTOMERS\n DROP CONSTRAINT myUniqueConstraint;" }, { "code": null, "e": 3667, "s": 3603, "text": "If you are using MySQL, then you can use the following syntax −" }, { "code": null, "e": 3724, "s": 3667, "text": "ALTER TABLE CUSTOMERS\n DROP INDEX myUniqueConstraint;\n" }, { "code": null, "e": 3757, "s": 3724, "text": "\n 42 Lectures \n 5 hours \n" }, { "code": null, "e": 3771, "s": 3757, "text": " Anadi Sharma" }, { "code": null, "e": 3804, "s": 3771, "text": "\n 14 Lectures \n 2 hours \n" }, { "code": null, "e": 3818, "s": 3804, "text": " Anadi Sharma" }, { "code": null, "e": 3853, "s": 3818, "text": "\n 44 Lectures \n 4.5 hours \n" }, { "code": null, "e": 3867, "s": 3853, "text": " Anadi Sharma" }, { "code": null, "e": 3900, "s": 3867, "text": "\n 94 Lectures \n 7 hours \n" }, { "code": null, "e": 3922, "s": 3900, "text": " Abhishek And Pukhraj" }, { "code": null, "e": 3957, "s": 3922, "text": "\n 80 Lectures \n 6.5 hours \n" }, { "code": null, "e": 4011, "s": 3957, "text": " Oracle Master Training | 150,000+ Students Worldwide" }, { "code": null, "e": 4044, "s": 4011, "text": "\n 31 Lectures \n 6 hours \n" }, { "code": null, "e": 4072, "s": 4044, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 4079, "s": 4072, "text": " Print" }, { "code": null, "e": 4090, "s": 4079, "text": " Add Notes" } ]
Master data visualization with ggplot2: theme() customization | by Abhinav Malasi | Towards Data Science
This is the last article from the series master the data visualization using the ggplot2 package. The complete list of tutorials are as follows: Scatter and box plots (link)Histograms, Bar, and Density plots (link)Circular plots (pie charts, spider plots, and bar plots) (link)Theme(): customize to increase workflow Scatter and box plots (link) Histograms, Bar, and Density plots (link) Circular plots (pie charts, spider plots, and bar plots) (link) Theme(): customize to increase workflow Theme customization is key to increasing work efficiency for those who are regularly changing the default theme settings to make their visualizations more attractive. The default theme used by ggplot2 package is theme_gray(). So, for this tutorial, we will use the theme_gray() function to create our own customized function, theme_customized(). We will divide this tutorial into the following sections: Dataset & packagesExtracting the theme functionCustomizing the theme functionOverriding certain parameters Dataset & packages Extracting the theme function Customizing the theme function Overriding certain parameters For this tutorial, we will be using the earth surface temperature dataset focusing on the global temperature changes between 1750–2015. The link for the dataset is here. We will use the lubridate package to create new variables with information on Year and Month. Apart from the ggplot2, tidyverse, and lubridate packages, we will be using the extrafont package to import more fonts into R from our OS. As I am a Windows user, the arguments will be related to Windows OS. Check the reference for installing using Apple or Linux systems. So, let us now start to customize the theme which will be done by extracting the source code of the default theme function. To get the source code of a function in R, just type in the function name in the R console and press enter. This way it will provide you the entire code. In our case, we will be using theme_gray(), so we can just run theme_grayon the console and we will get complete source code as shown below. We will be using the above code to create our customized function. Before going any further into customization, we will get rid of the last command ggplot_global$theme... . A lot can be customized in the default theme but for the time being, we will focus on few key things. Feel free to explore the other possibilities. The default font families available in R are sans, serif, mono, and symbol. If you are looking to add more font families to your existing fonts in R, then that can be achieved by extrafont package. Use the following code snippet to add fonts to R for customization in Windows OS. To assign the font of your choice just state it in the function argument when calling the function. For demonstration purposes, I have assigned base_family=“Algerian” . theme_customized <- function(base_size=11, base_family = "Agerian", base_line_size = base_size/22, base_rect_size = base_size/22) The default colors can also be overridden by assigning new colors. For example, the background color of the plot panel can be changed from white to a different color by providing a different fill value as highlighted below: rect = element_rect(fill = "white", colour = "black", size = 0.5, linetype = 1)# replace plot panel background color to redrect = element_rect(fill = "red", colour = "black", size = 0.5, linetype = 1) The font color for the axis titles can be changed using the color argument in the element_text() function. text = element_text(family = base_family, face = "plain", colour = "black", size = base_size, lineheight = 0.9, hjust = 0.5, vjust = 0.5, angle = 0, margin = margin(), debug = FALSE) The color for the axis texts and ticks can be altered using these functions: # axis textaxis.text = element_text(size = rel(0.8), colour = "grey30")# axis ticksaxis.ticks = element_line(colour = "grey20") The default font size for theme_gray() is 11, which might not be the of the proper size for some display mediums. So, the default value can be changed to a more desired value by assigning it to the base_size argument of the theme function. theme_customized <- function(base_size=11, base_family = "Agerian", base_line_size = base_size/22, base_rect_size = base_size/22) Another important feature to notice is the rel() function, which defines the relative size with respect to the base_size value. So, let us customize the theme. Now, we know how to customize the theme in R. Let us now put it into practice by visualizing the monthly average temperature variation over the period from 1750–2015. So for the current customized theme, let us set base_size value to 15, base_family to Algerian, and change the color scheme and use the color scheme of Canva. To override the default theme of ggplot2, we will use theme_set() function and this way we can implement the theme_customized(). # overriding teh default themetheme_set(theme_customized()) Now we can replot the average temperature variation with our new customized theme. To make quick changes in the theme, we will be using theme_update() function. Let's say we want to use black color for the panel grid instead of gray in the custom theme, then we just need to override the value for element_line() function. theme_customized = theme_update(panel.grid = element_line(colour = "black")) In the final tutorial on mastering data visualizations with ggplot2 package, we learned to customize our own themes that certainly can boost the workflow especially if your work deals with creating visuals for different sectors requiring different color themes, font types, and sizes. Apart from customizing your theme, we further learned to override the default theme by using set_theme() function. Later we saw to make minor changes in the customized theme we can directly use the theme_update() function to change values of ceratin function arguments without revisiting the entire function. I hope you all enjoyed the series dedicated to plotting with ggplot2 package. In case you missed any tutorial of the series, the links are posted below. Feel free to comment and share your opinions and views. Further readings from this series or on visualizations using ggplot2 package. towardsdatascience.com towardsdatascience.com towardsdatascience.com towardsdatascience.com towardsdatascience.com towardsdatascience.com https://cran.r-project.org/web/packages/svglite/vignettes/fonts.htmlhttps://r-coder.com/custom-fonts-r/https://ggplot2.tidyverse.org/reference/theme_get.html https://cran.r-project.org/web/packages/svglite/vignettes/fonts.html https://r-coder.com/custom-fonts-r/ https://ggplot2.tidyverse.org/reference/theme_get.html The link to the complete code is here. You can connect with me on LinkedIn and Twitter to follow my data science and data visualization journey.
[ { "code": null, "e": 317, "s": 172, "text": "This is the last article from the series master the data visualization using the ggplot2 package. The complete list of tutorials are as follows:" }, { "code": null, "e": 489, "s": 317, "text": "Scatter and box plots (link)Histograms, Bar, and Density plots (link)Circular plots (pie charts, spider plots, and bar plots) (link)Theme(): customize to increase workflow" }, { "code": null, "e": 518, "s": 489, "text": "Scatter and box plots (link)" }, { "code": null, "e": 560, "s": 518, "text": "Histograms, Bar, and Density plots (link)" }, { "code": null, "e": 624, "s": 560, "text": "Circular plots (pie charts, spider plots, and bar plots) (link)" }, { "code": null, "e": 664, "s": 624, "text": "Theme(): customize to increase workflow" }, { "code": null, "e": 1068, "s": 664, "text": "Theme customization is key to increasing work efficiency for those who are regularly changing the default theme settings to make their visualizations more attractive. The default theme used by ggplot2 package is theme_gray(). So, for this tutorial, we will use the theme_gray() function to create our own customized function, theme_customized(). We will divide this tutorial into the following sections:" }, { "code": null, "e": 1175, "s": 1068, "text": "Dataset & packagesExtracting the theme functionCustomizing the theme functionOverriding certain parameters" }, { "code": null, "e": 1194, "s": 1175, "text": "Dataset & packages" }, { "code": null, "e": 1224, "s": 1194, "text": "Extracting the theme function" }, { "code": null, "e": 1255, "s": 1224, "text": "Customizing the theme function" }, { "code": null, "e": 1285, "s": 1255, "text": "Overriding certain parameters" }, { "code": null, "e": 1455, "s": 1285, "text": "For this tutorial, we will be using the earth surface temperature dataset focusing on the global temperature changes between 1750–2015. The link for the dataset is here." }, { "code": null, "e": 1549, "s": 1455, "text": "We will use the lubridate package to create new variables with information on Year and Month." }, { "code": null, "e": 1822, "s": 1549, "text": "Apart from the ggplot2, tidyverse, and lubridate packages, we will be using the extrafont package to import more fonts into R from our OS. As I am a Windows user, the arguments will be related to Windows OS. Check the reference for installing using Apple or Linux systems." }, { "code": null, "e": 1946, "s": 1822, "text": "So, let us now start to customize the theme which will be done by extracting the source code of the default theme function." }, { "code": null, "e": 2241, "s": 1946, "text": "To get the source code of a function in R, just type in the function name in the R console and press enter. This way it will provide you the entire code. In our case, we will be using theme_gray(), so we can just run theme_grayon the console and we will get complete source code as shown below." }, { "code": null, "e": 2414, "s": 2241, "text": "We will be using the above code to create our customized function. Before going any further into customization, we will get rid of the last command ggplot_global$theme... ." }, { "code": null, "e": 2562, "s": 2414, "text": "A lot can be customized in the default theme but for the time being, we will focus on few key things. Feel free to explore the other possibilities." }, { "code": null, "e": 2842, "s": 2562, "text": "The default font families available in R are sans, serif, mono, and symbol. If you are looking to add more font families to your existing fonts in R, then that can be achieved by extrafont package. Use the following code snippet to add fonts to R for customization in Windows OS." }, { "code": null, "e": 3011, "s": 2842, "text": "To assign the font of your choice just state it in the function argument when calling the function. For demonstration purposes, I have assigned base_family=“Algerian” ." }, { "code": null, "e": 3199, "s": 3011, "text": "theme_customized <- function(base_size=11, base_family = \"Agerian\", base_line_size = base_size/22, base_rect_size = base_size/22)" }, { "code": null, "e": 3423, "s": 3199, "text": "The default colors can also be overridden by assigning new colors. For example, the background color of the plot panel can be changed from white to a different color by providing a different fill value as highlighted below:" }, { "code": null, "e": 3624, "s": 3423, "text": "rect = element_rect(fill = \"white\", colour = \"black\", size = 0.5, linetype = 1)# replace plot panel background color to redrect = element_rect(fill = \"red\", colour = \"black\", size = 0.5, linetype = 1)" }, { "code": null, "e": 3731, "s": 3624, "text": "The font color for the axis titles can be changed using the color argument in the element_text() function." }, { "code": null, "e": 3972, "s": 3731, "text": "text = element_text(family = base_family, face = \"plain\", colour = \"black\", size = base_size, lineheight = 0.9, hjust = 0.5, vjust = 0.5, angle = 0, margin = margin(), debug = FALSE)" }, { "code": null, "e": 4049, "s": 3972, "text": "The color for the axis texts and ticks can be altered using these functions:" }, { "code": null, "e": 4177, "s": 4049, "text": "# axis textaxis.text = element_text(size = rel(0.8), colour = \"grey30\")# axis ticksaxis.ticks = element_line(colour = \"grey20\")" }, { "code": null, "e": 4417, "s": 4177, "text": "The default font size for theme_gray() is 11, which might not be the of the proper size for some display mediums. So, the default value can be changed to a more desired value by assigning it to the base_size argument of the theme function." }, { "code": null, "e": 4605, "s": 4417, "text": "theme_customized <- function(base_size=11, base_family = \"Agerian\", base_line_size = base_size/22, base_rect_size = base_size/22)" }, { "code": null, "e": 4733, "s": 4605, "text": "Another important feature to notice is the rel() function, which defines the relative size with respect to the base_size value." }, { "code": null, "e": 4765, "s": 4733, "text": "So, let us customize the theme." }, { "code": null, "e": 4932, "s": 4765, "text": "Now, we know how to customize the theme in R. Let us now put it into practice by visualizing the monthly average temperature variation over the period from 1750–2015." }, { "code": null, "e": 5091, "s": 4932, "text": "So for the current customized theme, let us set base_size value to 15, base_family to Algerian, and change the color scheme and use the color scheme of Canva." }, { "code": null, "e": 5220, "s": 5091, "text": "To override the default theme of ggplot2, we will use theme_set() function and this way we can implement the theme_customized()." }, { "code": null, "e": 5282, "s": 5220, "text": "# overriding teh default themetheme_set(theme_customized()) " }, { "code": null, "e": 5365, "s": 5282, "text": "Now we can replot the average temperature variation with our new customized theme." }, { "code": null, "e": 5605, "s": 5365, "text": "To make quick changes in the theme, we will be using theme_update() function. Let's say we want to use black color for the panel grid instead of gray in the custom theme, then we just need to override the value for element_line() function." }, { "code": null, "e": 5682, "s": 5605, "text": "theme_customized = theme_update(panel.grid = element_line(colour = \"black\"))" }, { "code": null, "e": 6276, "s": 5682, "text": "In the final tutorial on mastering data visualizations with ggplot2 package, we learned to customize our own themes that certainly can boost the workflow especially if your work deals with creating visuals for different sectors requiring different color themes, font types, and sizes. Apart from customizing your theme, we further learned to override the default theme by using set_theme() function. Later we saw to make minor changes in the customized theme we can directly use the theme_update() function to change values of ceratin function arguments without revisiting the entire function." }, { "code": null, "e": 6485, "s": 6276, "text": "I hope you all enjoyed the series dedicated to plotting with ggplot2 package. In case you missed any tutorial of the series, the links are posted below. Feel free to comment and share your opinions and views." }, { "code": null, "e": 6563, "s": 6485, "text": "Further readings from this series or on visualizations using ggplot2 package." }, { "code": null, "e": 6586, "s": 6563, "text": "towardsdatascience.com" }, { "code": null, "e": 6609, "s": 6586, "text": "towardsdatascience.com" }, { "code": null, "e": 6632, "s": 6609, "text": "towardsdatascience.com" }, { "code": null, "e": 6655, "s": 6632, "text": "towardsdatascience.com" }, { "code": null, "e": 6678, "s": 6655, "text": "towardsdatascience.com" }, { "code": null, "e": 6701, "s": 6678, "text": "towardsdatascience.com" }, { "code": null, "e": 6859, "s": 6701, "text": "https://cran.r-project.org/web/packages/svglite/vignettes/fonts.htmlhttps://r-coder.com/custom-fonts-r/https://ggplot2.tidyverse.org/reference/theme_get.html" }, { "code": null, "e": 6928, "s": 6859, "text": "https://cran.r-project.org/web/packages/svglite/vignettes/fonts.html" }, { "code": null, "e": 6964, "s": 6928, "text": "https://r-coder.com/custom-fonts-r/" }, { "code": null, "e": 7019, "s": 6964, "text": "https://ggplot2.tidyverse.org/reference/theme_get.html" }, { "code": null, "e": 7058, "s": 7019, "text": "The link to the complete code is here." } ]
Introducing Mito — How To Generate Pandas Code While Editing a Spreadsheet | by Dario Radečić | Towards Data Science
Disclaimer: This is not a sponsored article. I don’t have any affiliation with Mito or the creators of the library. The article shows an unbiased overview of the library, intending to make data science tools accessible to the broader masses. The world of data science tools and libraries is becoming (or already is) saturated. It’s difficult for anything new to gain traction without a massive wow-factor. That’s where Mito caught my attention. The idea behind the library is simple — you edit the dataset as a spreadsheet, and Mito automatically generates Python Pandas code. Is it any good? Well, yeah, but continue reading for a more profound overview. This article is structured as follows: Installing Mito Dataset Loading Adding and Removing Columns Filtering and Sorting Data Summary Statistics Saving and Loading Analyses The Verdict The Mito package has two prerequisites: Python 3.6 or newer Node.js I’m assuming you have Python installed, but Node might be the issue. Please take a minute to install it, and you’re ready to proceed. From here, let’s create a virtual environment for Mito: python3 -m venv mitoenv And now let’s activate it: source mitoenv/bin/activate Great! We can install the package next with the following command: pip install mitosheet Almost there — we’ll also need Jupyter Lab extension manager: jupyter labextension install @jupyter-widgets/jupyterlab-manager@2 And that’s it! You can launch Jupyter lab with the following command: jupyter lab Let’s proceed with dataset loading in the next section. Once Jupyter is loaded, you can execute the following code to open a new Mito sheet: import mitosheetmitosheet.sheet() Here’s the resulting output: You’ll have to enter your email to continue. Once done, you’ll see a blank sheet: You can click on the Import button to load in a dataset. We’ll use the well-known Titanic dataset for this article. Here’s how it should look like after the initial loading: And that’s how easy it is to load a CSV file! Mito automatically writes Pandas code in the cell below. The following image shows how it should look like by now: Let’s see how to add and remove columns next. One of the most fundamental operations in data preprocessing is adding and removing attributes. Mito does this through Add Col and Del Col buttons in the top menu. Let’s start by adding columns. Click on the Add Col button — this will add a column with an arbitrary name to the table below (M in my case). To add data, you can click on the first row and enter the formula the same as with Excel! Here’s an example — the following formula will return 1 if the value of the Sex attribute is male, and 0 otherwise: You can click on the column name to change it to something more appropriate — like IsMale. Mito generates the following Pandas code behind the surface: titanic_csv.insert(2, ‘M’, 0)titanic_csv[‘M’] = IF(titanic_csv[‘Sex’] == “male”, 1, 0)titanic_csv.rename(columns={“M”: “IsMale”}, inplace=True) Let’s see how to delete a column next. Simply select the column you want to remove and click on the Del Col button. A popup window like this one will appear: From there, simply confirm that you want to remove the column. Mito will generate the following code for you: titanic_csv.drop(‘PassengerId’, axis=1, inplace=True) And that’s how easy it is to add and remove columns. Let’s see how to filter and sort the data next. It isn’t easy to imagine any data analysis workflow without some sort of filtering and sorting operations. The good news is — these are easy to do with Mito. Let’s start with filtering. A side menu will pop up when you select a column: Under Filter, select the appropriate option. Let’s include only these records where the Age column is not missing, and the values are between 40 and 42. You’ll have to add an entire group to have multiple filtering conditions, as shown below: Here’s the code that Mito writes behind the scenes: titanic_csv = titanic_csv[((titanic_csv.Age.notnull()) & (titanic_csv[‘Age’] > 40) & (titanic_csv[‘Age’] <= 42))]titanic_csv = titanic_csv.reset_index(drop=True) It’s a bit messy, but it gets the job done. Onto the sorting next. It’s a much easier operation to implement. You need to select the column and select the ascending or descending option. Here’s how you can sort the filtered dataset descendingly by the Fare column: Here’s the generated code for sorting: titanic_csv = titanic_csv.sort_values(by=’Fare’, ascending=False, na_position=’first’)titanic_csv = titanic_csv.reset_index(drop=True) And that’s it for basic sorting and filtering. Let’s look at another interesting feature next — summary statistics. If there’s one thing you’ll do a lot in any data analysis workload, that’s summary statistics. The basic idea is to print the most interesting statistical values for a column and maybe show some data visualizations. As it turns out, Mito does that automatically. All you need to do is to select an attribute and click on Summary Stats in the right menu. Let’s do just that for the Age column: As you can see, the distribution of the variable is shown first, followed by the summary statistics: Let’s take a look at one more feature of Mito before calling it a day. In Excel terms, saving an analysis with Mito is like recording a macro, but with Python. You can save any analysis by clicking on the Save button in the top menu. It will bring up a modal window asking you to name the analysis and to confirm the saving: To repeat an analysis, click on the Replay button. It will ask you to select one of the saved ones — as shown below: The replaying feature may come in handy for some repetitive operations from separate notebooks, provided that you don’t want to copy-paste the code. And that’s just enough for today. We’ve gone over the most common features and tried them out on a small dataset. The question remains — should you use Mito? As a data scientist, I don’t see why you shouldn’t, especially if you’re skilled in Excel and want to get started with Python and Pandas. Mito can make the transition process that much easier. The automated code generation function can also be beneficial to beginner and intermediate Pandas users, as it lets you know if there’s an alternative or easier way to do something with the library. To conclude — give Mito a try. It’s free, and you have nothing to lose. I’d love to hear your opinion on the library in the comment section below. Loved the article? Become a Medium member to continue learning without limits. I’ll receive a portion of your membership fee if you use the following link, with no extra cost to you. medium.com Mito Website — https://trymito.ioMito Documentation — https://docs.trymito.io Mito Website — https://trymito.io Mito Documentation — https://docs.trymito.io 3 Programming Books Every Data Scientist Must Read How to Make Python Statically Typed — The Essential Guide Object Orientated Programming with Python — Everything You Need to Know Python Dictionaries: Everything You Need to Know Introducing f-Strings — The Best Options for String Formatting in Python Follow me on Medium for more stories like this Sign up for my newsletter Connect on LinkedIn Check out my website
[ { "code": null, "e": 414, "s": 172, "text": "Disclaimer: This is not a sponsored article. I don’t have any affiliation with Mito or the creators of the library. The article shows an unbiased overview of the library, intending to make data science tools accessible to the broader masses." }, { "code": null, "e": 617, "s": 414, "text": "The world of data science tools and libraries is becoming (or already is) saturated. It’s difficult for anything new to gain traction without a massive wow-factor. That’s where Mito caught my attention." }, { "code": null, "e": 828, "s": 617, "text": "The idea behind the library is simple — you edit the dataset as a spreadsheet, and Mito automatically generates Python Pandas code. Is it any good? Well, yeah, but continue reading for a more profound overview." }, { "code": null, "e": 867, "s": 828, "text": "This article is structured as follows:" }, { "code": null, "e": 883, "s": 867, "text": "Installing Mito" }, { "code": null, "e": 899, "s": 883, "text": "Dataset Loading" }, { "code": null, "e": 927, "s": 899, "text": "Adding and Removing Columns" }, { "code": null, "e": 954, "s": 927, "text": "Filtering and Sorting Data" }, { "code": null, "e": 973, "s": 954, "text": "Summary Statistics" }, { "code": null, "e": 1001, "s": 973, "text": "Saving and Loading Analyses" }, { "code": null, "e": 1013, "s": 1001, "text": "The Verdict" }, { "code": null, "e": 1053, "s": 1013, "text": "The Mito package has two prerequisites:" }, { "code": null, "e": 1073, "s": 1053, "text": "Python 3.6 or newer" }, { "code": null, "e": 1081, "s": 1073, "text": "Node.js" }, { "code": null, "e": 1215, "s": 1081, "text": "I’m assuming you have Python installed, but Node might be the issue. Please take a minute to install it, and you’re ready to proceed." }, { "code": null, "e": 1271, "s": 1215, "text": "From here, let’s create a virtual environment for Mito:" }, { "code": null, "e": 1295, "s": 1271, "text": "python3 -m venv mitoenv" }, { "code": null, "e": 1322, "s": 1295, "text": "And now let’s activate it:" }, { "code": null, "e": 1350, "s": 1322, "text": "source mitoenv/bin/activate" }, { "code": null, "e": 1417, "s": 1350, "text": "Great! We can install the package next with the following command:" }, { "code": null, "e": 1439, "s": 1417, "text": "pip install mitosheet" }, { "code": null, "e": 1501, "s": 1439, "text": "Almost there — we’ll also need Jupyter Lab extension manager:" }, { "code": null, "e": 1568, "s": 1501, "text": "jupyter labextension install @jupyter-widgets/jupyterlab-manager@2" }, { "code": null, "e": 1638, "s": 1568, "text": "And that’s it! You can launch Jupyter lab with the following command:" }, { "code": null, "e": 1650, "s": 1638, "text": "jupyter lab" }, { "code": null, "e": 1706, "s": 1650, "text": "Let’s proceed with dataset loading in the next section." }, { "code": null, "e": 1791, "s": 1706, "text": "Once Jupyter is loaded, you can execute the following code to open a new Mito sheet:" }, { "code": null, "e": 1825, "s": 1791, "text": "import mitosheetmitosheet.sheet()" }, { "code": null, "e": 1854, "s": 1825, "text": "Here’s the resulting output:" }, { "code": null, "e": 1936, "s": 1854, "text": "You’ll have to enter your email to continue. Once done, you’ll see a blank sheet:" }, { "code": null, "e": 2110, "s": 1936, "text": "You can click on the Import button to load in a dataset. We’ll use the well-known Titanic dataset for this article. Here’s how it should look like after the initial loading:" }, { "code": null, "e": 2271, "s": 2110, "text": "And that’s how easy it is to load a CSV file! Mito automatically writes Pandas code in the cell below. The following image shows how it should look like by now:" }, { "code": null, "e": 2317, "s": 2271, "text": "Let’s see how to add and remove columns next." }, { "code": null, "e": 2481, "s": 2317, "text": "One of the most fundamental operations in data preprocessing is adding and removing attributes. Mito does this through Add Col and Del Col buttons in the top menu." }, { "code": null, "e": 2713, "s": 2481, "text": "Let’s start by adding columns. Click on the Add Col button — this will add a column with an arbitrary name to the table below (M in my case). To add data, you can click on the first row and enter the formula the same as with Excel!" }, { "code": null, "e": 2829, "s": 2713, "text": "Here’s an example — the following formula will return 1 if the value of the Sex attribute is male, and 0 otherwise:" }, { "code": null, "e": 2981, "s": 2829, "text": "You can click on the column name to change it to something more appropriate — like IsMale. Mito generates the following Pandas code behind the surface:" }, { "code": null, "e": 3125, "s": 2981, "text": "titanic_csv.insert(2, ‘M’, 0)titanic_csv[‘M’] = IF(titanic_csv[‘Sex’] == “male”, 1, 0)titanic_csv.rename(columns={“M”: “IsMale”}, inplace=True)" }, { "code": null, "e": 3283, "s": 3125, "text": "Let’s see how to delete a column next. Simply select the column you want to remove and click on the Del Col button. A popup window like this one will appear:" }, { "code": null, "e": 3393, "s": 3283, "text": "From there, simply confirm that you want to remove the column. Mito will generate the following code for you:" }, { "code": null, "e": 3447, "s": 3393, "text": "titanic_csv.drop(‘PassengerId’, axis=1, inplace=True)" }, { "code": null, "e": 3548, "s": 3447, "text": "And that’s how easy it is to add and remove columns. Let’s see how to filter and sort the data next." }, { "code": null, "e": 3706, "s": 3548, "text": "It isn’t easy to imagine any data analysis workflow without some sort of filtering and sorting operations. The good news is — these are easy to do with Mito." }, { "code": null, "e": 3784, "s": 3706, "text": "Let’s start with filtering. A side menu will pop up when you select a column:" }, { "code": null, "e": 4027, "s": 3784, "text": "Under Filter, select the appropriate option. Let’s include only these records where the Age column is not missing, and the values are between 40 and 42. You’ll have to add an entire group to have multiple filtering conditions, as shown below:" }, { "code": null, "e": 4079, "s": 4027, "text": "Here’s the code that Mito writes behind the scenes:" }, { "code": null, "e": 4241, "s": 4079, "text": "titanic_csv = titanic_csv[((titanic_csv.Age.notnull()) & (titanic_csv[‘Age’] > 40) & (titanic_csv[‘Age’] <= 42))]titanic_csv = titanic_csv.reset_index(drop=True)" }, { "code": null, "e": 4285, "s": 4241, "text": "It’s a bit messy, but it gets the job done." }, { "code": null, "e": 4506, "s": 4285, "text": "Onto the sorting next. It’s a much easier operation to implement. You need to select the column and select the ascending or descending option. Here’s how you can sort the filtered dataset descendingly by the Fare column:" }, { "code": null, "e": 4545, "s": 4506, "text": "Here’s the generated code for sorting:" }, { "code": null, "e": 4680, "s": 4545, "text": "titanic_csv = titanic_csv.sort_values(by=’Fare’, ascending=False, na_position=’first’)titanic_csv = titanic_csv.reset_index(drop=True)" }, { "code": null, "e": 4796, "s": 4680, "text": "And that’s it for basic sorting and filtering. Let’s look at another interesting feature next — summary statistics." }, { "code": null, "e": 5012, "s": 4796, "text": "If there’s one thing you’ll do a lot in any data analysis workload, that’s summary statistics. The basic idea is to print the most interesting statistical values for a column and maybe show some data visualizations." }, { "code": null, "e": 5189, "s": 5012, "text": "As it turns out, Mito does that automatically. All you need to do is to select an attribute and click on Summary Stats in the right menu. Let’s do just that for the Age column:" }, { "code": null, "e": 5290, "s": 5189, "text": "As you can see, the distribution of the variable is shown first, followed by the summary statistics:" }, { "code": null, "e": 5361, "s": 5290, "text": "Let’s take a look at one more feature of Mito before calling it a day." }, { "code": null, "e": 5524, "s": 5361, "text": "In Excel terms, saving an analysis with Mito is like recording a macro, but with Python. You can save any analysis by clicking on the Save button in the top menu." }, { "code": null, "e": 5615, "s": 5524, "text": "It will bring up a modal window asking you to name the analysis and to confirm the saving:" }, { "code": null, "e": 5732, "s": 5615, "text": "To repeat an analysis, click on the Replay button. It will ask you to select one of the saved ones — as shown below:" }, { "code": null, "e": 5881, "s": 5732, "text": "The replaying feature may come in handy for some repetitive operations from separate notebooks, provided that you don’t want to copy-paste the code." }, { "code": null, "e": 6039, "s": 5881, "text": "And that’s just enough for today. We’ve gone over the most common features and tried them out on a small dataset. The question remains — should you use Mito?" }, { "code": null, "e": 6232, "s": 6039, "text": "As a data scientist, I don’t see why you shouldn’t, especially if you’re skilled in Excel and want to get started with Python and Pandas. Mito can make the transition process that much easier." }, { "code": null, "e": 6431, "s": 6232, "text": "The automated code generation function can also be beneficial to beginner and intermediate Pandas users, as it lets you know if there’s an alternative or easier way to do something with the library." }, { "code": null, "e": 6578, "s": 6431, "text": "To conclude — give Mito a try. It’s free, and you have nothing to lose. I’d love to hear your opinion on the library in the comment section below." }, { "code": null, "e": 6761, "s": 6578, "text": "Loved the article? Become a Medium member to continue learning without limits. I’ll receive a portion of your membership fee if you use the following link, with no extra cost to you." }, { "code": null, "e": 6772, "s": 6761, "text": "medium.com" }, { "code": null, "e": 6850, "s": 6772, "text": "Mito Website — https://trymito.ioMito Documentation — https://docs.trymito.io" }, { "code": null, "e": 6884, "s": 6850, "text": "Mito Website — https://trymito.io" }, { "code": null, "e": 6929, "s": 6884, "text": "Mito Documentation — https://docs.trymito.io" }, { "code": null, "e": 6980, "s": 6929, "text": "3 Programming Books Every Data Scientist Must Read" }, { "code": null, "e": 7038, "s": 6980, "text": "How to Make Python Statically Typed — The Essential Guide" }, { "code": null, "e": 7110, "s": 7038, "text": "Object Orientated Programming with Python — Everything You Need to Know" }, { "code": null, "e": 7159, "s": 7110, "text": "Python Dictionaries: Everything You Need to Know" }, { "code": null, "e": 7232, "s": 7159, "text": "Introducing f-Strings — The Best Options for String Formatting in Python" }, { "code": null, "e": 7279, "s": 7232, "text": "Follow me on Medium for more stories like this" }, { "code": null, "e": 7305, "s": 7279, "text": "Sign up for my newsletter" }, { "code": null, "e": 7325, "s": 7305, "text": "Connect on LinkedIn" } ]
You Want to Learn Rust but You Don’t Know Where to Start | by Shinichi Okada | Towards Data Science
Table of ContentsIntroduction🦀 Rust Toolchains🦀 Rust Free Online Books and Resources🦀 Rust Official Links🦀 Video Tutorials🦀 Podcast🦀 Interactive Learning🦀 Online Books & Tutorials🦀 Cheat Sheets🦀 Rust Community 🦀 Coding Challenge🦀 Rust IDE Extensions🦀 Rust Ecosystem🦀 Resource for Intermediate UsersConclusion [Latest updates: 2020–09–02] Rust is a modern systems programming language focusing on safety, speed, and concurrency. The following graph from The Benchmarks Game shows how Rust is fast comparing other programming languages. You can find a comparison against the Go language here. In this article, you will find the basic Rust tools, latest documents, tutorials, videos, and online resources. After reading this you can navigate yourself and start learning Rust programming language efficiently in a way that suits your learning style. When you install Rust, you are installing rustc, cargo, rustup and other standard tools. So let’s find out what Rust toolchains do first before finding all resources. Toolchains are a set of tools that help the language produce a functional code. They can provide extended functionality from either a simple compiler and linker program, or additional libraries, an IDE, or a debugger. rustup installs the Rust programming language, enabling you to easily switch between stable, beta, and nightly compilers and keep them updated. You can update Rust: $ rustup update rustc is the compiler for the Rust programming language. Compilers take your source code and produce binary code, either as a library or executable. You will use Cargo to run a Rust program instead of rustc. You can find more details in the reference aboutrustc. Cargo is the Rust package manager. Cargo downloads your Rust package’s dependencies, compiles your packages, makes distributable packages, and uploads them to crates.io, the Rust community’s package registry. Clippy is a Rust linter. rustfmt formats Rust code according to style guidelines. You can find the official tool states in this link. You can’t avoid The Rust Programming Language before you try other resources. This is the first and complete book you need to read about Rust. This book covers topics for beginners to advanced users. It explains all the details with a lot of examples and diagrams. If you learn more from examples Rust by Example is for you. It is a collection of runnable examples that illustrate various Rust concepts and standard libraries. You can find more than 20 examples. You can edit and run Rust codes from your browser. You will find intermediate and advanced online resources at the end. The Rust Cookbook is a collection of simple examples that demonstrate good practices to accomplish common programming tasks, using the crates of the Rust ecosystem. You can find a lot of information on the Rust official website. A crate is a Rust binary or library and you can find the Rust community’s crate registry at https://crates.io/. A package is one or more crates that provide a set of functionality. A package contains a Cargo.toml file that describes how to build those crates. The Rust Standard Library provides the Rust standard library documentation. The Rust Playground provides the top 100 most downloaded crates from craits.io and the crates from the Rust Cookbook. Learn Rust provides guides and documentation you need. You can find project tool libraries by categories at Awesome Rust. Ferrous Teaching Material covers basics to advanced topics with slideshows. It provides sample codes and explanations are concise. If you want to know about the Rust errors in detail, Rust Compiler Error Index list all Rust errors with examples. Error in your terminal: Error details in Rust Compiler Error Index: If you like learning from videos, then the following videos will help you. Rust: What is Ownership and Borrowing? by Gary Explains. Ryan Levick created a series of Rust tutorials. Genus-v Programming has Actix related video tutorials including authentication service, web development, and GraphQL with Actix. Rust Web development | Boilerplate free with Rocket, June 2020, 22 min. Rust Programming: Browser computation with WebAssembly, June 2020, 1 hr 55 min. Video material curated by the Rust team. Intro to Rust | COM209 teaches some of the basics of Rust, and then build and run a simple app. The video was taken in May 2020. David Pedersen posted his live coding on Youtube and Twich.tv. They are from June 2020. In Jonathan Teaches Jason Rust!, Jonathan attempts to teach Jason Turner Rust fundamentals in a couple of hours. This video was taken in May 2020, 3 hrs 36 min. In 12 Things to Help You Learn Rust Gary explains loops, variables, functions, tuples, strings, and more. The video was taken in April 2020. Learning Rust: Rustlings shows pair programming on some Rustlings exercises. The video was taken in August 2019. Streaming Rust with Ryan Levick Crust of Rust: Iterators from May 2020. Build a Bitcoin-like Blockchain in Rust and Substrate from May 2020. into_rust() is from 2016, but it explains the basic concepts such as ownership, shared borrows, and mutable borrows. Baseline.Rust by zaitt.works. Hello Rust! Choosing Rust — Clint Frederickson Clint shares Iron his experience with choosing Rust and why it might be the right choice for your next project. The Rustacean Station Podcast is a community project for creating podcast content for the Rust programming language. If you like learning by doing, then these are for you. Tour of Rust is a step by step guide through the features of the Rust programming language. It covers basics, basic control flow, basic data structure types, and Generic types. rustlings has small exercises to get you used to reading and writing Rust code. You can use this along with The Rust Programming Language. You can start the exercises: rultlings watch When you save the file, it will automatically check the answer and gives you feedback. Once you completed an exercise, you need to remove the line: // I AM NOT DONE When you save the file, it will move on to the next exercise. rustlings provides helpful hints giving the document link. Exercism is 100% free code practice and mentorship. It is entirely open source and relies on the contributions of thousands of volunteers. It will guide you on how to install it on your computer. You can learn not only Rust but also 50 other programming languages. When you complete a coding challenge on your computer, you upload your solution and review it with a mentor. towardsdatascience.com towardsdatascience.com towardsdatascience.com Nelson Elhage is creating the Ultimate Tic Tac Toe with Rust. Clear explanation of Rust’s module system by Sheshbabu Chinnakonda DEV has more than 70 Rust related articles in June 2020. If you are a JavaScript developer, Shesh has posts for you. e.g. Rust for JavaScript Developers — Functions and Control Flow. A Gentle Introduction to Rust by Steve J Donovan Build a Smart Bookmarking Tool with Rust and Rocket by Joe Previte Extremely Simple Rust Rocket Framework Tutorial Learning Rust You can find about Rust libraries/crates in 24daysofrust. Rust + Actix + CosmosDB (MongoDB) tutorial api Extremely Simple Rust Rocket Framework Tutorial Build a Smart Bookmarking Tool with Rust and Rocket Rust Sokoban is an extended tutorial on making a Sokoban copy in Rust. It uses an existing 2D game engine, pre-made assets and by the end, it’ll have a fully working game. You can find examples of how to use it. Learn Rust With Entirely Too Many Linked Lists. The online book teaches basic and advanced Rust programming by implement 6 linked lists. A half-hour to learn Rust explains Rust keywords and symbols. The Periodic Table of Rust Types: This table organizes Rust types into an orthogonal tabular form, making them easier to understand and reason. Rust String Conversions Rust Iterator Cheat Sheet Rust Container Cheet Sheet Rust Community page. I highly recommend “This week in Rust”. It delivers weekly most up-to-date information about Rust. “Rust Blog” is the main Rust blog. The core team uses this blog to announce big developments in the world of Rust. “Inside Rust blog” is aimed a those who wish to follow along with Rust development. Brian’s “Rust blog articles” page is organized by categories and has many blog articles. If you are a C programmer, Cliff L. Biffle’s “Learn Rust the Dangerous Way” is for you. Llogiq on stuff Niko Matsakis Rust Discord has many active members and one of the sections is for beginners. Rust Users Forum is for help, discussion, and announcements related to the Rust programming language. Stackoverflow has more than 16000 questions. Shepmaster who is the co-founder of the world’s first Rust consultancy answered many Rust questions. Reddit’s “The Rust Programming Language” has 105K members. · #rustlang, #learnrust, and #learningrust· Rust Language· Steve Klabnik· Aidan Hobson Sayers· Ashley Williams· Carol Nichols· Niko Matsakis· Nick Cameron· Pietro Albini· Lin Clark· Florian Gilcher· Kyle J Strand· This Week in Rust· Jonathan Turner There are many Rust Meetup groups running online meetings. You can find meetings in Rust Community Calendar as well. LeetCode has many problems you can solve online with Rust. exercism.io has 92 exercises on the Rust track. Sphere online judge has many problems you can challenge. You take part in writing the code for games that you play directly online at CodinGame. You can write your code in Rust. You can find Rust integration for your editor here. If you are a VS Code user, you can install rls-vscode extension. Rust Language Server, the RLS provides a server that runs in the background, providing IDEs, editors, and other tools with information about Rust programs. It supports code completion, jumps to the definition, code formatting, and many more. Rust Lang Compiler Team create the rls-2.0 working group. The goal is to make better user RLS experience. You can find their implementation in the rust-analyzer and the rust-analyzer supports different IDEs. You can find how much your editor supports Rust at Are we (I)DE yet? You can find many libraries at crates.io. Here are some of the categories you might be interested in. Actix is the fastest framework according to Web Framework Benchmarks. There are ten active Rust web frameworks. Actix, Rocket, Gotham, Seed, etc. You can find more information from the web framework comparison. Simple Rocket Web Framework Tutorial | POST Request The fastest Rust template engine, sailfish. It claims 200x faster than handlebars. If you are interested in WebAssembly, then the following links will help you. Rust official page on WebAssembly WASM working group and Rust and WebAssembly book by the group. Rust and WebAssembly from Scratch: Hello World with Strings Getting started with WebAssembly and Rust WebAssembly with Rust and React (Using create-react-app) Using Rust and WebAssembly to Process Pixels from a Video Feed Understanding WebAssembly text format Compiling from Rust to WebAssembly Bringing WebAssembly outside the web with WASI by Lin Clark explains how WASI works and explore how different use cases can benefit from it. Yew is a Rust/Wasm framework for building client web apps. Rust + WebAssembly — EdgeXR @ Netlight by Aleksander Heintz Rust official page on Networking. Rust official page on Embedded devices. The Embedded Rust Book. Rust bindings for the FLTK Graphical User Interface library, fltk-rs. The video tutorial is here. Data Science at Home has a series of podcasts on Rust and machine learning. Amadeus provides a harmonious distributed data analysis in Rust. ndarray is equivalent to Python’s numpy. Porting Godot Games To Rust (Part 1) Rust Game Development Working Group has monthly newsletters. The ggez is a lightweight game framework for making 2D games with minimum friction. It aims to implement an API based on (a Rustified version of) the LÖVE game framework. It contains portable 2D drawing, sound, resource loading, and event handling. Specs is an Entity-Component System(ESC) written in Rust. It is the most popular ESC library. godot-rust is Rust bindings to the Godot game engine. Gorgeous Godot games in Rust. Legion ECS with Godot and Rust. Rust official page on Command-line apps. Rustbox is a library that provides API which allows the programmer to write text-based user interfaces. Tui-rs is a Rust library to build rich terminal user interfaces and dashboards. Termion is a pure Rust, bindless library for low-level handling, manipulating, and reading information about terminals. Crossterm is a pure-rust, terminal manipulation library that makes it possible to write cross-platform text-based interfaces. Pancurses is a curses library for Rust to provide a more Rustic interface over the usual curses functions for ease of use while remaining close enough to curses to make porting easy. StructOpt parses command line arguments by defining a struct. It combines clap with custom derive. clap or Command Line Argument Parser is a simple-to-use, efficient, and fully-configurable library for parsing command line arguments. Gtk-rs is Rust bindings for GTK+ 3, Cairo, GtkSourceView and other GLib-compatible libraries. It provides many UI widgets out-of-the-box. OSDev, Operating System Development in Rust posts give a regular overview of the most important changes to the RustOSDev tools and libraries. bindgen automatically generates Rust FFI bindings to C (and some C++) libraries. PyO3 includes running and interacting with Python code from a Rust binary.Mara’s Blog goes through the process of creating inline-python. You can find more bindings at carates.io. Serde is a framework for serializing and deserializing Rust data structures. Serialization takes an in-memory data structure and converts it into a series of bytes that can be stored and transferred. Deserialization takes a series of bytes and converts it to an in-memory data structure that can be consumed programmatically. Diesel is a Safe, Extensible ORM and Query Builder for Rust. If you feel adventurous, you can check one of the following. Command Line Applications in Rust has great exercises for a beginner who is new to the language and writing a program with a simple command-line interface (CLI). You’ll be exposed to a few of the core concepts of Rust as well as the main aspects of CLI applications. Rust API Guidelines is a set of recommendations on how to design and present APIs for the Rust programming language. The rustc book rustc is the compiler for the Rust programming language. Compilers take your source code and produce binary code, either as a library or executable. The Cargo book tells you all about Cargo. You can read about Rust’s new large changes in The Edition Guide. Rust Language Cheat Sheet is for experienced programmers and intermediate Rust users. If you prefer visual example-driven content, this is for you. You can download a PDF from it’s Github repo. Rust Forge serves as a repository of supplementary documentation useful for members of The Rust Programming Language. The Rust Reference is the primary reference for the Rust programming language. It provides language construct and use, the memory model, concurrency model, runtime services, and more. Philipp Oppermann wrote Writing an OS in Rust. Michael F Bryan wrote about ArrayVec in Implementing ArrayVec Using Const Generics. Diving into Rust with a CLI shows how to create a CLI application. dtolnay wrote about Rust macro development case studies. A practical guide to async in Rust by Carl Fredrik Samson Secure Rust Guidelines — ANSSI (National Cybersecurity Agency of France) Rust OpenCV bindings Embedded development Rust Design Patterns Tips for Faster Rust Compile Times Rust verification tools Learning Rust: Let’s Build a Parser Small strings in Rust Servo is a modern, high-performance browser engine designed for both application and embedded use. MICHAEL-F-BRYAN is writing Rust articles. Barely Functional is writing Rust articles. Niko Matsakis writes his ideas on Rust. learn-opengl-rs vulkann-tutorial-rs Ferrous Teaching Material embedded-trainings-2020 There is a milliard of online resources. I hope you found the most suitable learning resource and start learning Rust Programming Language. Please let me know if I missed anything. Get full access to every story on Medium by becoming a member.
[ { "code": null, "e": 481, "s": 172, "text": "Table of ContentsIntroduction🦀 Rust Toolchains🦀 Rust Free Online Books and Resources🦀 Rust Official Links🦀 Video Tutorials🦀 Podcast🦀 Interactive Learning🦀 Online Books & Tutorials🦀 Cheat Sheets🦀 Rust Community 🦀 Coding Challenge🦀 Rust IDE Extensions🦀 Rust Ecosystem🦀 Resource for Intermediate UsersConclusion" }, { "code": null, "e": 510, "s": 481, "text": "[Latest updates: 2020–09–02]" }, { "code": null, "e": 600, "s": 510, "text": "Rust is a modern systems programming language focusing on safety, speed, and concurrency." }, { "code": null, "e": 763, "s": 600, "text": "The following graph from The Benchmarks Game shows how Rust is fast comparing other programming languages. You can find a comparison against the Go language here." }, { "code": null, "e": 875, "s": 763, "text": "In this article, you will find the basic Rust tools, latest documents, tutorials, videos, and online resources." }, { "code": null, "e": 1018, "s": 875, "text": "After reading this you can navigate yourself and start learning Rust programming language efficiently in a way that suits your learning style." }, { "code": null, "e": 1185, "s": 1018, "text": "When you install Rust, you are installing rustc, cargo, rustup and other standard tools. So let’s find out what Rust toolchains do first before finding all resources." }, { "code": null, "e": 1403, "s": 1185, "text": "Toolchains are a set of tools that help the language produce a functional code. They can provide extended functionality from either a simple compiler and linker program, or additional libraries, an IDE, or a debugger." }, { "code": null, "e": 1547, "s": 1403, "text": "rustup installs the Rust programming language, enabling you to easily switch between stable, beta, and nightly compilers and keep them updated." }, { "code": null, "e": 1568, "s": 1547, "text": "You can update Rust:" }, { "code": null, "e": 1584, "s": 1568, "text": "$ rustup update" }, { "code": null, "e": 1792, "s": 1584, "text": "rustc is the compiler for the Rust programming language. Compilers take your source code and produce binary code, either as a library or executable. You will use Cargo to run a Rust program instead of rustc." }, { "code": null, "e": 1847, "s": 1792, "text": "You can find more details in the reference aboutrustc." }, { "code": null, "e": 2056, "s": 1847, "text": "Cargo is the Rust package manager. Cargo downloads your Rust package’s dependencies, compiles your packages, makes distributable packages, and uploads them to crates.io, the Rust community’s package registry." }, { "code": null, "e": 2081, "s": 2056, "text": "Clippy is a Rust linter." }, { "code": null, "e": 2138, "s": 2081, "text": "rustfmt formats Rust code according to style guidelines." }, { "code": null, "e": 2190, "s": 2138, "text": "You can find the official tool states in this link." }, { "code": null, "e": 2455, "s": 2190, "text": "You can’t avoid The Rust Programming Language before you try other resources. This is the first and complete book you need to read about Rust. This book covers topics for beginners to advanced users. It explains all the details with a lot of examples and diagrams." }, { "code": null, "e": 2653, "s": 2455, "text": "If you learn more from examples Rust by Example is for you. It is a collection of runnable examples that illustrate various Rust concepts and standard libraries. You can find more than 20 examples." }, { "code": null, "e": 2704, "s": 2653, "text": "You can edit and run Rust codes from your browser." }, { "code": null, "e": 2773, "s": 2704, "text": "You will find intermediate and advanced online resources at the end." }, { "code": null, "e": 2938, "s": 2773, "text": "The Rust Cookbook is a collection of simple examples that demonstrate good practices to accomplish common programming tasks, using the crates of the Rust ecosystem." }, { "code": null, "e": 3002, "s": 2938, "text": "You can find a lot of information on the Rust official website." }, { "code": null, "e": 3114, "s": 3002, "text": "A crate is a Rust binary or library and you can find the Rust community’s crate registry at https://crates.io/." }, { "code": null, "e": 3262, "s": 3114, "text": "A package is one or more crates that provide a set of functionality. A package contains a Cargo.toml file that describes how to build those crates." }, { "code": null, "e": 3338, "s": 3262, "text": "The Rust Standard Library provides the Rust standard library documentation." }, { "code": null, "e": 3456, "s": 3338, "text": "The Rust Playground provides the top 100 most downloaded crates from craits.io and the crates from the Rust Cookbook." }, { "code": null, "e": 3511, "s": 3456, "text": "Learn Rust provides guides and documentation you need." }, { "code": null, "e": 3578, "s": 3511, "text": "You can find project tool libraries by categories at Awesome Rust." }, { "code": null, "e": 3709, "s": 3578, "text": "Ferrous Teaching Material covers basics to advanced topics with slideshows. It provides sample codes and explanations are concise." }, { "code": null, "e": 3824, "s": 3709, "text": "If you want to know about the Rust errors in detail, Rust Compiler Error Index list all Rust errors with examples." }, { "code": null, "e": 3848, "s": 3824, "text": "Error in your terminal:" }, { "code": null, "e": 3892, "s": 3848, "text": "Error details in Rust Compiler Error Index:" }, { "code": null, "e": 3967, "s": 3892, "text": "If you like learning from videos, then the following videos will help you." }, { "code": null, "e": 4024, "s": 3967, "text": "Rust: What is Ownership and Borrowing? by Gary Explains." }, { "code": null, "e": 4072, "s": 4024, "text": "Ryan Levick created a series of Rust tutorials." }, { "code": null, "e": 4201, "s": 4072, "text": "Genus-v Programming has Actix related video tutorials including authentication service, web development, and GraphQL with Actix." }, { "code": null, "e": 4273, "s": 4201, "text": "Rust Web development | Boilerplate free with Rocket, June 2020, 22 min." }, { "code": null, "e": 4353, "s": 4273, "text": "Rust Programming: Browser computation with WebAssembly, June 2020, 1 hr 55 min." }, { "code": null, "e": 4394, "s": 4353, "text": "Video material curated by the Rust team." }, { "code": null, "e": 4523, "s": 4394, "text": "Intro to Rust | COM209 teaches some of the basics of Rust, and then build and run a simple app. The video was taken in May 2020." }, { "code": null, "e": 4611, "s": 4523, "text": "David Pedersen posted his live coding on Youtube and Twich.tv. They are from June 2020." }, { "code": null, "e": 4772, "s": 4611, "text": "In Jonathan Teaches Jason Rust!, Jonathan attempts to teach Jason Turner Rust fundamentals in a couple of hours. This video was taken in May 2020, 3 hrs 36 min." }, { "code": null, "e": 4913, "s": 4772, "text": "In 12 Things to Help You Learn Rust Gary explains loops, variables, functions, tuples, strings, and more. The video was taken in April 2020." }, { "code": null, "e": 5026, "s": 4913, "text": "Learning Rust: Rustlings shows pair programming on some Rustlings exercises. The video was taken in August 2019." }, { "code": null, "e": 5058, "s": 5026, "text": "Streaming Rust with Ryan Levick" }, { "code": null, "e": 5098, "s": 5058, "text": "Crust of Rust: Iterators from May 2020." }, { "code": null, "e": 5167, "s": 5098, "text": "Build a Bitcoin-like Blockchain in Rust and Substrate from May 2020." }, { "code": null, "e": 5284, "s": 5167, "text": "into_rust() is from 2016, but it explains the basic concepts such as ownership, shared borrows, and mutable borrows." }, { "code": null, "e": 5314, "s": 5284, "text": "Baseline.Rust by zaitt.works." }, { "code": null, "e": 5326, "s": 5314, "text": "Hello Rust!" }, { "code": null, "e": 5473, "s": 5326, "text": "Choosing Rust — Clint Frederickson Clint shares Iron his experience with choosing Rust and why it might be the right choice for your next project." }, { "code": null, "e": 5590, "s": 5473, "text": "The Rustacean Station Podcast is a community project for creating podcast content for the Rust programming language." }, { "code": null, "e": 5645, "s": 5590, "text": "If you like learning by doing, then these are for you." }, { "code": null, "e": 5822, "s": 5645, "text": "Tour of Rust is a step by step guide through the features of the Rust programming language. It covers basics, basic control flow, basic data structure types, and Generic types." }, { "code": null, "e": 5961, "s": 5822, "text": "rustlings has small exercises to get you used to reading and writing Rust code. You can use this along with The Rust Programming Language." }, { "code": null, "e": 5990, "s": 5961, "text": "You can start the exercises:" }, { "code": null, "e": 6006, "s": 5990, "text": "rultlings watch" }, { "code": null, "e": 6093, "s": 6006, "text": "When you save the file, it will automatically check the answer and gives you feedback." }, { "code": null, "e": 6154, "s": 6093, "text": "Once you completed an exercise, you need to remove the line:" }, { "code": null, "e": 6171, "s": 6154, "text": "// I AM NOT DONE" }, { "code": null, "e": 6233, "s": 6171, "text": "When you save the file, it will move on to the next exercise." }, { "code": null, "e": 6292, "s": 6233, "text": "rustlings provides helpful hints giving the document link." }, { "code": null, "e": 6431, "s": 6292, "text": "Exercism is 100% free code practice and mentorship. It is entirely open source and relies on the contributions of thousands of volunteers." }, { "code": null, "e": 6557, "s": 6431, "text": "It will guide you on how to install it on your computer. You can learn not only Rust but also 50 other programming languages." }, { "code": null, "e": 6666, "s": 6557, "text": "When you complete a coding challenge on your computer, you upload your solution and review it with a mentor." }, { "code": null, "e": 6689, "s": 6666, "text": "towardsdatascience.com" }, { "code": null, "e": 6712, "s": 6689, "text": "towardsdatascience.com" }, { "code": null, "e": 6735, "s": 6712, "text": "towardsdatascience.com" }, { "code": null, "e": 6797, "s": 6735, "text": "Nelson Elhage is creating the Ultimate Tic Tac Toe with Rust." }, { "code": null, "e": 6864, "s": 6797, "text": "Clear explanation of Rust’s module system by Sheshbabu Chinnakonda" }, { "code": null, "e": 6921, "s": 6864, "text": "DEV has more than 70 Rust related articles in June 2020." }, { "code": null, "e": 7047, "s": 6921, "text": "If you are a JavaScript developer, Shesh has posts for you. e.g. Rust for JavaScript Developers — Functions and Control Flow." }, { "code": null, "e": 7096, "s": 7047, "text": "A Gentle Introduction to Rust by Steve J Donovan" }, { "code": null, "e": 7163, "s": 7096, "text": "Build a Smart Bookmarking Tool with Rust and Rocket by Joe Previte" }, { "code": null, "e": 7211, "s": 7163, "text": "Extremely Simple Rust Rocket Framework Tutorial" }, { "code": null, "e": 7225, "s": 7211, "text": "Learning Rust" }, { "code": null, "e": 7283, "s": 7225, "text": "You can find about Rust libraries/crates in 24daysofrust." }, { "code": null, "e": 7330, "s": 7283, "text": "Rust + Actix + CosmosDB (MongoDB) tutorial api" }, { "code": null, "e": 7378, "s": 7330, "text": "Extremely Simple Rust Rocket Framework Tutorial" }, { "code": null, "e": 7430, "s": 7378, "text": "Build a Smart Bookmarking Tool with Rust and Rocket" }, { "code": null, "e": 7642, "s": 7430, "text": "Rust Sokoban is an extended tutorial on making a Sokoban copy in Rust. It uses an existing 2D game engine, pre-made assets and by the end, it’ll have a fully working game. You can find examples of how to use it." }, { "code": null, "e": 7779, "s": 7642, "text": "Learn Rust With Entirely Too Many Linked Lists. The online book teaches basic and advanced Rust programming by implement 6 linked lists." }, { "code": null, "e": 7841, "s": 7779, "text": "A half-hour to learn Rust explains Rust keywords and symbols." }, { "code": null, "e": 7985, "s": 7841, "text": "The Periodic Table of Rust Types: This table organizes Rust types into an orthogonal tabular form, making them easier to understand and reason." }, { "code": null, "e": 8009, "s": 7985, "text": "Rust String Conversions" }, { "code": null, "e": 8035, "s": 8009, "text": "Rust Iterator Cheat Sheet" }, { "code": null, "e": 8062, "s": 8035, "text": "Rust Container Cheet Sheet" }, { "code": null, "e": 8083, "s": 8062, "text": "Rust Community page." }, { "code": null, "e": 8182, "s": 8083, "text": "I highly recommend “This week in Rust”. It delivers weekly most up-to-date information about Rust." }, { "code": null, "e": 8297, "s": 8182, "text": "“Rust Blog” is the main Rust blog. The core team uses this blog to announce big developments in the world of Rust." }, { "code": null, "e": 8381, "s": 8297, "text": "“Inside Rust blog” is aimed a those who wish to follow along with Rust development." }, { "code": null, "e": 8470, "s": 8381, "text": "Brian’s “Rust blog articles” page is organized by categories and has many blog articles." }, { "code": null, "e": 8558, "s": 8470, "text": "If you are a C programmer, Cliff L. Biffle’s “Learn Rust the Dangerous Way” is for you." }, { "code": null, "e": 8574, "s": 8558, "text": "Llogiq on stuff" }, { "code": null, "e": 8588, "s": 8574, "text": "Niko Matsakis" }, { "code": null, "e": 8667, "s": 8588, "text": "Rust Discord has many active members and one of the sections is for beginners." }, { "code": null, "e": 8769, "s": 8667, "text": "Rust Users Forum is for help, discussion, and announcements related to the Rust programming language." }, { "code": null, "e": 8915, "s": 8769, "text": "Stackoverflow has more than 16000 questions. Shepmaster who is the co-founder of the world’s first Rust consultancy answered many Rust questions." }, { "code": null, "e": 8974, "s": 8915, "text": "Reddit’s “The Rust Programming Language” has 105K members." }, { "code": null, "e": 9223, "s": 8974, "text": "· #rustlang, #learnrust, and #learningrust· Rust Language· Steve Klabnik· Aidan Hobson Sayers· Ashley Williams· Carol Nichols· Niko Matsakis· Nick Cameron· Pietro Albini· Lin Clark· Florian Gilcher· Kyle J Strand· This Week in Rust· Jonathan Turner" }, { "code": null, "e": 9340, "s": 9223, "text": "There are many Rust Meetup groups running online meetings. You can find meetings in Rust Community Calendar as well." }, { "code": null, "e": 9399, "s": 9340, "text": "LeetCode has many problems you can solve online with Rust." }, { "code": null, "e": 9447, "s": 9399, "text": "exercism.io has 92 exercises on the Rust track." }, { "code": null, "e": 9504, "s": 9447, "text": "Sphere online judge has many problems you can challenge." }, { "code": null, "e": 9625, "s": 9504, "text": "You take part in writing the code for games that you play directly online at CodinGame. You can write your code in Rust." }, { "code": null, "e": 9742, "s": 9625, "text": "You can find Rust integration for your editor here. If you are a VS Code user, you can install rls-vscode extension." }, { "code": null, "e": 9984, "s": 9742, "text": "Rust Language Server, the RLS provides a server that runs in the background, providing IDEs, editors, and other tools with information about Rust programs. It supports code completion, jumps to the definition, code formatting, and many more." }, { "code": null, "e": 10090, "s": 9984, "text": "Rust Lang Compiler Team create the rls-2.0 working group. The goal is to make better user RLS experience." }, { "code": null, "e": 10192, "s": 10090, "text": "You can find their implementation in the rust-analyzer and the rust-analyzer supports different IDEs." }, { "code": null, "e": 10261, "s": 10192, "text": "You can find how much your editor supports Rust at Are we (I)DE yet?" }, { "code": null, "e": 10363, "s": 10261, "text": "You can find many libraries at crates.io. Here are some of the categories you might be interested in." }, { "code": null, "e": 10574, "s": 10363, "text": "Actix is the fastest framework according to Web Framework Benchmarks. There are ten active Rust web frameworks. Actix, Rocket, Gotham, Seed, etc. You can find more information from the web framework comparison." }, { "code": null, "e": 10626, "s": 10574, "text": "Simple Rocket Web Framework Tutorial | POST Request" }, { "code": null, "e": 10709, "s": 10626, "text": "The fastest Rust template engine, sailfish. It claims 200x faster than handlebars." }, { "code": null, "e": 10787, "s": 10709, "text": "If you are interested in WebAssembly, then the following links will help you." }, { "code": null, "e": 10821, "s": 10787, "text": "Rust official page on WebAssembly" }, { "code": null, "e": 10884, "s": 10821, "text": "WASM working group and Rust and WebAssembly book by the group." }, { "code": null, "e": 10944, "s": 10884, "text": "Rust and WebAssembly from Scratch: Hello World with Strings" }, { "code": null, "e": 10986, "s": 10944, "text": "Getting started with WebAssembly and Rust" }, { "code": null, "e": 11043, "s": 10986, "text": "WebAssembly with Rust and React (Using create-react-app)" }, { "code": null, "e": 11106, "s": 11043, "text": "Using Rust and WebAssembly to Process Pixels from a Video Feed" }, { "code": null, "e": 11144, "s": 11106, "text": "Understanding WebAssembly text format" }, { "code": null, "e": 11179, "s": 11144, "text": "Compiling from Rust to WebAssembly" }, { "code": null, "e": 11320, "s": 11179, "text": "Bringing WebAssembly outside the web with WASI by Lin Clark explains how WASI works and explore how different use cases can benefit from it." }, { "code": null, "e": 11379, "s": 11320, "text": "Yew is a Rust/Wasm framework for building client web apps." }, { "code": null, "e": 11439, "s": 11379, "text": "Rust + WebAssembly — EdgeXR @ Netlight by Aleksander Heintz" }, { "code": null, "e": 11473, "s": 11439, "text": "Rust official page on Networking." }, { "code": null, "e": 11513, "s": 11473, "text": "Rust official page on Embedded devices." }, { "code": null, "e": 11537, "s": 11513, "text": "The Embedded Rust Book." }, { "code": null, "e": 11635, "s": 11537, "text": "Rust bindings for the FLTK Graphical User Interface library, fltk-rs. The video tutorial is here." }, { "code": null, "e": 11711, "s": 11635, "text": "Data Science at Home has a series of podcasts on Rust and machine learning." }, { "code": null, "e": 11776, "s": 11711, "text": "Amadeus provides a harmonious distributed data analysis in Rust." }, { "code": null, "e": 11817, "s": 11776, "text": "ndarray is equivalent to Python’s numpy." }, { "code": null, "e": 11854, "s": 11817, "text": "Porting Godot Games To Rust (Part 1)" }, { "code": null, "e": 11915, "s": 11854, "text": "Rust Game Development Working Group has monthly newsletters." }, { "code": null, "e": 12165, "s": 11915, "text": "The ggez is a lightweight game framework for making 2D games with minimum friction. It aims to implement an API based on (a Rustified version of) the LÖVE game framework. It contains portable 2D drawing, sound, resource loading, and event handling." }, { "code": null, "e": 12259, "s": 12165, "text": "Specs is an Entity-Component System(ESC) written in Rust. It is the most popular ESC library." }, { "code": null, "e": 12313, "s": 12259, "text": "godot-rust is Rust bindings to the Godot game engine." }, { "code": null, "e": 12343, "s": 12313, "text": "Gorgeous Godot games in Rust." }, { "code": null, "e": 12375, "s": 12343, "text": "Legion ECS with Godot and Rust." }, { "code": null, "e": 12416, "s": 12375, "text": "Rust official page on Command-line apps." }, { "code": null, "e": 12520, "s": 12416, "text": "Rustbox is a library that provides API which allows the programmer to write text-based user interfaces." }, { "code": null, "e": 12600, "s": 12520, "text": "Tui-rs is a Rust library to build rich terminal user interfaces and dashboards." }, { "code": null, "e": 12720, "s": 12600, "text": "Termion is a pure Rust, bindless library for low-level handling, manipulating, and reading information about terminals." }, { "code": null, "e": 12846, "s": 12720, "text": "Crossterm is a pure-rust, terminal manipulation library that makes it possible to write cross-platform text-based interfaces." }, { "code": null, "e": 13029, "s": 12846, "text": "Pancurses is a curses library for Rust to provide a more Rustic interface over the usual curses functions for ease of use while remaining close enough to curses to make porting easy." }, { "code": null, "e": 13128, "s": 13029, "text": "StructOpt parses command line arguments by defining a struct. It combines clap with custom derive." }, { "code": null, "e": 13263, "s": 13128, "text": "clap or Command Line Argument Parser is a simple-to-use, efficient, and fully-configurable library for parsing command line arguments." }, { "code": null, "e": 13401, "s": 13263, "text": "Gtk-rs is Rust bindings for GTK+ 3, Cairo, GtkSourceView and other GLib-compatible libraries. It provides many UI widgets out-of-the-box." }, { "code": null, "e": 13543, "s": 13401, "text": "OSDev, Operating System Development in Rust posts give a regular overview of the most important changes to the RustOSDev tools and libraries." }, { "code": null, "e": 13624, "s": 13543, "text": "bindgen automatically generates Rust FFI bindings to C (and some C++) libraries." }, { "code": null, "e": 13762, "s": 13624, "text": "PyO3 includes running and interacting with Python code from a Rust binary.Mara’s Blog goes through the process of creating inline-python." }, { "code": null, "e": 13804, "s": 13762, "text": "You can find more bindings at carates.io." }, { "code": null, "e": 13881, "s": 13804, "text": "Serde is a framework for serializing and deserializing Rust data structures." }, { "code": null, "e": 14130, "s": 13881, "text": "Serialization takes an in-memory data structure and converts it into a series of bytes that can be stored and transferred. Deserialization takes a series of bytes and converts it to an in-memory data structure that can be consumed programmatically." }, { "code": null, "e": 14191, "s": 14130, "text": "Diesel is a Safe, Extensible ORM and Query Builder for Rust." }, { "code": null, "e": 14252, "s": 14191, "text": "If you feel adventurous, you can check one of the following." }, { "code": null, "e": 14519, "s": 14252, "text": "Command Line Applications in Rust has great exercises for a beginner who is new to the language and writing a program with a simple command-line interface (CLI). You’ll be exposed to a few of the core concepts of Rust as well as the main aspects of CLI applications." }, { "code": null, "e": 14636, "s": 14519, "text": "Rust API Guidelines is a set of recommendations on how to design and present APIs for the Rust programming language." }, { "code": null, "e": 14800, "s": 14636, "text": "The rustc book rustc is the compiler for the Rust programming language. Compilers take your source code and produce binary code, either as a library or executable." }, { "code": null, "e": 14842, "s": 14800, "text": "The Cargo book tells you all about Cargo." }, { "code": null, "e": 14908, "s": 14842, "text": "You can read about Rust’s new large changes in The Edition Guide." }, { "code": null, "e": 15102, "s": 14908, "text": "Rust Language Cheat Sheet is for experienced programmers and intermediate Rust users. If you prefer visual example-driven content, this is for you. You can download a PDF from it’s Github repo." }, { "code": null, "e": 15220, "s": 15102, "text": "Rust Forge serves as a repository of supplementary documentation useful for members of The Rust Programming Language." }, { "code": null, "e": 15404, "s": 15220, "text": "The Rust Reference is the primary reference for the Rust programming language. It provides language construct and use, the memory model, concurrency model, runtime services, and more." }, { "code": null, "e": 15451, "s": 15404, "text": "Philipp Oppermann wrote Writing an OS in Rust." }, { "code": null, "e": 15535, "s": 15451, "text": "Michael F Bryan wrote about ArrayVec in Implementing ArrayVec Using Const Generics." }, { "code": null, "e": 15602, "s": 15535, "text": "Diving into Rust with a CLI shows how to create a CLI application." }, { "code": null, "e": 15659, "s": 15602, "text": "dtolnay wrote about Rust macro development case studies." }, { "code": null, "e": 15717, "s": 15659, "text": "A practical guide to async in Rust by Carl Fredrik Samson" }, { "code": null, "e": 15790, "s": 15717, "text": "Secure Rust Guidelines — ANSSI (National Cybersecurity Agency of France)" }, { "code": null, "e": 15811, "s": 15790, "text": "Rust OpenCV bindings" }, { "code": null, "e": 15832, "s": 15811, "text": "Embedded development" }, { "code": null, "e": 15853, "s": 15832, "text": "Rust Design Patterns" }, { "code": null, "e": 15888, "s": 15853, "text": "Tips for Faster Rust Compile Times" }, { "code": null, "e": 15912, "s": 15888, "text": "Rust verification tools" }, { "code": null, "e": 15948, "s": 15912, "text": "Learning Rust: Let’s Build a Parser" }, { "code": null, "e": 15970, "s": 15948, "text": "Small strings in Rust" }, { "code": null, "e": 16069, "s": 15970, "text": "Servo is a modern, high-performance browser engine designed for both application and embedded use." }, { "code": null, "e": 16111, "s": 16069, "text": "MICHAEL-F-BRYAN is writing Rust articles." }, { "code": null, "e": 16155, "s": 16111, "text": "Barely Functional is writing Rust articles." }, { "code": null, "e": 16195, "s": 16155, "text": "Niko Matsakis writes his ideas on Rust." }, { "code": null, "e": 16211, "s": 16195, "text": "learn-opengl-rs" }, { "code": null, "e": 16231, "s": 16211, "text": "vulkann-tutorial-rs" }, { "code": null, "e": 16257, "s": 16231, "text": "Ferrous Teaching Material" }, { "code": null, "e": 16281, "s": 16257, "text": "embedded-trainings-2020" }, { "code": null, "e": 16421, "s": 16281, "text": "There is a milliard of online resources. I hope you found the most suitable learning resource and start learning Rust Programming Language." }, { "code": null, "e": 16462, "s": 16421, "text": "Please let me know if I missed anything." } ]
How to make Rounded buttons in Tkinter - GeeksforGeeks
17 Dec, 2020 Tkinter is a Python module that is used to create GUI (Graphical User Interface) applications with the help of a variety of widgets and functions. Like any other GUI module, it also supports images i.e you can use images in the application to make it more attractive. In this article, we will discuss How to make a Rounded Button in Tkinter, There is no in-built method to make rounded buttons in Tkinter. For making the button rounded we will define borderwidth value to zero borderwidth: It will represent the size of the border around the label. By default, borderwidth is 2 pixels. “bd” can also be used as a shorthand for borderwidth. Step-by-step implementation: Step 1: Create a Normal Tkinter Window. Python3 # Import modulefrom tkinter import * # Create objectroot = Tk() # Adjust sizeroot.geometry("400x400") # Execute tkinterroot.mainloop() Output: Step 2: Add button and image. Python3 # Add Imagelogin_btn = PhotoImage(file = "Image Path") # Create button and imageimg = Button(root, image = login_btn, borderwidth = 0) img.pack() Output: Below is the full implementation: Python3 # Import Modulefrom tkinter import * # Create Objectroot = Tk() # Set geometryroot.geometry("400x400") # Add Imagelogin_btn = PhotoImage(file = "Image Path") # Create button and imageimg = Button(root, image = login_btn, borderwidth = 0) img.pack() # Execute Tkinterroot.mainloop() Output: Python-tkinter Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments 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 Python | Pandas dataframe.groupby() Python | Get unique values from a list Defaultdict in Python Python | os.path.join() method Python Classes and Objects Create a directory in Python
[ { "code": null, "e": 23901, "s": 23873, "text": "\n17 Dec, 2020" }, { "code": null, "e": 24169, "s": 23901, "text": "Tkinter is a Python module that is used to create GUI (Graphical User Interface) applications with the help of a variety of widgets and functions. Like any other GUI module, it also supports images i.e you can use images in the application to make it more attractive." }, { "code": null, "e": 24378, "s": 24169, "text": "In this article, we will discuss How to make a Rounded Button in Tkinter, There is no in-built method to make rounded buttons in Tkinter. For making the button rounded we will define borderwidth value to zero" }, { "code": null, "e": 24541, "s": 24378, "text": "borderwidth: It will represent the size of the border around the label. By default, borderwidth is 2 pixels. “bd” can also be used as a shorthand for borderwidth." }, { "code": null, "e": 24570, "s": 24541, "text": "Step-by-step implementation:" }, { "code": null, "e": 24610, "s": 24570, "text": "Step 1: Create a Normal Tkinter Window." }, { "code": null, "e": 24618, "s": 24610, "text": "Python3" }, { "code": "# Import modulefrom tkinter import * # Create objectroot = Tk() # Adjust sizeroot.geometry(\"400x400\") # Execute tkinterroot.mainloop()", "e": 24756, "s": 24618, "text": null }, { "code": null, "e": 24764, "s": 24756, "text": "Output:" }, { "code": null, "e": 24794, "s": 24764, "text": "Step 2: Add button and image." }, { "code": null, "e": 24802, "s": 24794, "text": "Python3" }, { "code": "# Add Imagelogin_btn = PhotoImage(file = \"Image Path\") # Create button and imageimg = Button(root, image = login_btn, borderwidth = 0) img.pack()", "e": 24962, "s": 24802, "text": null }, { "code": null, "e": 24970, "s": 24962, "text": "Output:" }, { "code": null, "e": 25004, "s": 24970, "text": "Below is the full implementation:" }, { "code": null, "e": 25012, "s": 25004, "text": "Python3" }, { "code": "# Import Modulefrom tkinter import * # Create Objectroot = Tk() # Set geometryroot.geometry(\"400x400\") # Add Imagelogin_btn = PhotoImage(file = \"Image Path\") # Create button and imageimg = Button(root, image = login_btn, borderwidth = 0) img.pack() # Execute Tkinterroot.mainloop()", "e": 25312, "s": 25012, "text": null }, { "code": null, "e": 25320, "s": 25312, "text": "Output:" }, { "code": null, "e": 25335, "s": 25320, "text": "Python-tkinter" }, { "code": null, "e": 25342, "s": 25335, "text": "Python" }, { "code": null, "e": 25440, "s": 25342, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25449, "s": 25440, "text": "Comments" }, { "code": null, "e": 25462, "s": 25449, "text": "Old Comments" }, { "code": null, "e": 25494, "s": 25462, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 25550, "s": 25494, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 25592, "s": 25550, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 25634, "s": 25592, "text": "Check if element exists in list in Python" }, { "code": null, "e": 25670, "s": 25634, "text": "Python | Pandas dataframe.groupby()" }, { "code": null, "e": 25709, "s": 25670, "text": "Python | Get unique values from a list" }, { "code": null, "e": 25731, "s": 25709, "text": "Defaultdict in Python" }, { "code": null, "e": 25762, "s": 25731, "text": "Python | os.path.join() method" }, { "code": null, "e": 25789, "s": 25762, "text": "Python Classes and Objects" } ]