title
stringlengths
3
221
text
stringlengths
17
477k
parsed
listlengths
0
3.17k
How to open a port in the Windows Operating System using PowerShell?
To open a port in the Windows Operating system, we need to know a few things. Like For which Profile we need to open port (Public, private, or Domain)? - Optional For which Profile we need to open port (Public, private, or Domain)? - Optional Which port do we need to open (port Number)? Which port do we need to open (port Number)? The direction of the port – Inbound (i.e Incoming requests) or Outbound (i.e. Outgoing requests). The direction of the port – Inbound (i.e Incoming requests) or Outbound (i.e. Outgoing requests). Protocol by name (TCP, UDP, ICMPv4, or ICMPv6) or Number (0-255). Protocol by name (TCP, UDP, ICMPv4, or ICMPv6) or Number (0-255). Once we have all the details we can open the port. In the below example, we need to open a port 5985 (WINRM HTTP) port on the computer which is currently blocked. So we will use the below command. New-NetFirewallRule -DisplayName "Allow WINRM HTTP Port" ` -Direction Outbound ` -LocalPort 5985 ` -Protocol TCP ` -Action Allow To open multiple ports, New-NetFirewallRule -DisplayName "Allow web ports" ` -Direction Outbound ` -LocalPort 80,8080 ` -Protocol TCP ` -Action All Once you open the Firewall settings, you can check the ports are listed in the allowed list. To perform the same settings on the remote computer, you need to use the Invoke-Command cmdlet. Make sure that the remote computer is accessible and has the WINRM connectivity before opening the port on the remote computer. Invoke-Command -ComputerName Test1-Win2k12 -ScriptBlock{ New-NetFirewallRule -DisplayName "Allow web ports" ` -Direction Outbound ` -LocalPort 80,8080 ` -Protocol TCP ` -Action All } If we don’t specify Direction (Inbound or Outbound), both directions ports will be opened by default.
[ { "code": null, "e": 1145, "s": 1062, "text": "To open a port in the Windows Operating system, we need to know a few things. Like" }, { "code": null, "e": 1225, "s": 1145, "text": "For which Profile we need to open port (Public, private, or Domain)? - Optional" }, { "code": null, "e": 1305, "s": 1225, "text": "For which Profile we need to open port (Public, private, or Domain)? - Optional" }, { "code": null, "e": 1350, "s": 1305, "text": "Which port do we need to open (port Number)?" }, { "code": null, "e": 1395, "s": 1350, "text": "Which port do we need to open (port Number)?" }, { "code": null, "e": 1493, "s": 1395, "text": "The direction of the port – Inbound (i.e Incoming requests) or Outbound (i.e. Outgoing requests)." }, { "code": null, "e": 1591, "s": 1493, "text": "The direction of the port – Inbound (i.e Incoming requests) or Outbound (i.e. Outgoing requests)." }, { "code": null, "e": 1657, "s": 1591, "text": "Protocol by name (TCP, UDP, ICMPv4, or ICMPv6) or Number (0-255)." }, { "code": null, "e": 1723, "s": 1657, "text": "Protocol by name (TCP, UDP, ICMPv4, or ICMPv6) or Number (0-255)." }, { "code": null, "e": 1920, "s": 1723, "text": "Once we have all the details we can open the port. In the below example, we need to open a port 5985 (WINRM HTTP) port on the computer which is currently blocked. So we will use the below command." }, { "code": null, "e": 2129, "s": 1920, "text": "New-NetFirewallRule -DisplayName \"Allow WINRM HTTP Port\" `\n -Direction Outbound `\n -LocalPort 5985 `\n -Protocol TCP `\n -Action Allow" }, { "code": null, "e": 2153, "s": 2129, "text": "To open multiple ports," }, { "code": null, "e": 2359, "s": 2153, "text": "New-NetFirewallRule -DisplayName \"Allow web ports\" `\n -Direction Outbound `\n -LocalPort 80,8080 `\n -Protocol TCP `\n -Action All\n\n" }, { "code": null, "e": 2452, "s": 2359, "text": "Once you open the Firewall settings, you can check the ports are listed in the allowed list." }, { "code": null, "e": 2676, "s": 2452, "text": "To perform the same settings on the remote computer, you need to use the Invoke-Command cmdlet. Make sure that the remote computer is accessible and has the WINRM connectivity before opening the port on the remote computer." }, { "code": null, "e": 2879, "s": 2676, "text": "Invoke-Command -ComputerName Test1-Win2k12 -ScriptBlock{\n New-NetFirewallRule -DisplayName \"Allow web ports\" `\n -Direction Outbound `\n -LocalPort 80,8080 `\n -Protocol TCP `\n -Action All\n}" }, { "code": null, "e": 2981, "s": 2879, "text": "If we don’t specify Direction (Inbound or Outbound), both directions ports will be opened by default." } ]
Rotate a Linked List | Practice | GeeksforGeeks
Given a singly linked list of size N. The task is to left-shift the linked list by k nodes, where k is a given positive integer smaller than or equal to length of the linked list. Example 1: Input: N = 5 value[] = {2, 4, 7, 8, 9} k = 3 Output: 8 9 2 4 7 Explanation: Rotate 1: 4 -> 7 -> 8 -> 9 -> 2 Rotate 2: 7 -> 8 -> 9 -> 2 -> 4 Rotate 3: 8 -> 9 -> 2 -> 4 -> 7 Example 2: Input: N = 8 value[] = {1, 2, 3, 4, 5, 6, 7, 8} k = 4 Output: 5 6 7 8 1 2 3 4 Your Task: You don't need to read input or print anything. Your task is to complete the function rotate() which takes a head reference as the first argument and k as the second argument, and returns the head of the rotated linked list. Expected Time Complexity: O(N). Expected Auxiliary Space: O(1). Constraints: 1 <= N <= 103 1 <= k <= N 0 sarshdeep054in 12 hours public Node rotate(Node head, int k) { int n=0; ArrayList<Node> al=new ArrayList<Node>(); Node ex=head; while(head!=null){ al.add(head); head=head.next; n++; } if(n==k) return ex; int temp=k; Node ret=al.get(k); k=k%n; Node[] arr=new Node[n]; for(int i=0;i<n;i++){ arr[(n-k+i)%n]=al.get(i); } for(int j=1;j<n;j++){ ret.next=arr[j]; ret=arr[j]; } ret.next=null; return al.get(temp); } 0 taiphanvan2403in 4 hours Node* rotate(Node* head, int k) { Node*tail=head; int cnt=0; Node* pivot=NULL; while(tail->next!=NULL){ cnt++; if(cnt==k) pivot=tail; tail=tail->next; } if (pivot == NULL) return head; Node* tam=head; head=pivot->next; pivot->next=NULL; tail->next=tam; return head; } 0 vats7aryan012 days ago Node* rotate(Node* head, int k) { Node* temp=head,*start=head,*end=head; while(end->next!=NULL) end=end->next; while(k--) { end->next=start; head=start->next; start->next=NULL; end=end->next; start=head; } return head; } 0 anushkakaushik2002192 days ago *EASY CPP SOLUTION* Node* rotate(Node* head, int k) { Node* temp=head; Node* start=head; Node* end=head; while(end->next!=NULL) { end=end->next; } while(k>0) { end->next=start; head=start->next; start->next=NULL; end=end->next; start=head; k--; } return head; } 0 darkseid72 days ago ONE PASS || C++ || O(N) || O(1) Node* rotate(Node* head, int k){ Node* i = head; Node* j = head; for(int y=1;y<k;y++)j=j->next; if(j->next==NULL){ return head; } Node* l = j; while(l->next!=NULL)l=l->next; l->next=i; Node* Head = j->next; j->next=NULL; return Head; } 0 indusridharavath1232 days ago Node* rotate(Node* head, int k) { // Your code here if(k==0) { return head; } Node* temp=head; while(temp->next!=NULL) { temp=temp->next; } while(k>0) { Node* temp2=new Node(head->data); temp->next=temp2; temp=temp2; head=head->next; k--; } return head; } +1 mdzama4 days ago C++ || Simple & Clean || 1 Pass Solution Node* rotate(Node* head, int k) { if (!k || !head || !head->next) return head; int position = 1; Node *save, *tail; save = tail = nullptr; Node* temp = head; while (temp) { // In onepass solution. if (position == k) save = temp; if (!temp->next) tail = temp; temp = temp->next; position++; } if (save != tail) { tail->next = head; head = save->next; save->next = nullptr; } return head; } 0 pimplevaibhav016 days ago // java Solutionclass Solution{ //Function to rotate a linked list. public Node rotate(Node head, int k) { // add code here Node tail=head; while(tail.next!=null){ tail=tail.next; } for(int i=0;i<k;i++){ tail.next =head; Node fistNode=head.next; head.next=null; tail=head; head=fistNode; } //System.out.println(tail.data); return head; }} 0 shemanthkgp6 days ago // C++ solution class Solution{ public: //Function to rotate a linked list. Node* rotate(Node* head, int k) { if(k==0){ exit(0); } Node* temp= head; while(temp->next!=NULL){ temp = temp->next; } temp->next = head; temp=head; for(int i=0;i<k-1;i++){ temp=temp->next; } head = temp->next; temp->next=NULL; return head; } }; 0 rajkumarraj1 week ago class Solution { public: //Function to rotate a linked list. Node* rotate(Node* head, int k) { // Your code here Node *temp; int c=1; temp=head; if(head==NULL||head->next==NULL) return head; else { while(temp->next!=NULL) {temp=temp->next; c++; } temp->next=head; temp=head; for(int i=1;i<c-k;i++) { temp=temp->next; } head=temp->next; temp->next=NULL; return head; } } }; 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": 419, "s": 238, "text": "Given a singly linked list of size N. The task is to left-shift the linked list by k nodes, where k is a given positive integer smaller than or equal to length of the linked list. " }, { "code": null, "e": 430, "s": 419, "text": "Example 1:" }, { "code": null, "e": 603, "s": 430, "text": "Input:\nN = 5\nvalue[] = {2, 4, 7, 8, 9}\nk = 3\nOutput: 8 9 2 4 7\nExplanation:\nRotate 1: 4 -> 7 -> 8 -> 9 -> 2\nRotate 2: 7 -> 8 -> 9 -> 2 -> 4\nRotate 3: 8 -> 9 -> 2 -> 4 -> 7\n" }, { "code": null, "e": 614, "s": 603, "text": "Example 2:" }, { "code": null, "e": 693, "s": 614, "text": "Input:\nN = 8\nvalue[] = {1, 2, 3, 4, 5, 6, 7, 8}\nk = 4\nOutput: 5 6 7 8 1 2 3 4\n" }, { "code": null, "e": 930, "s": 693, "text": "\nYour Task:\nYou don't need to read input or print anything. Your task is to complete the function rotate() which takes a head reference as the first argument and k as the second argument, and returns the head of the rotated linked list." }, { "code": null, "e": 994, "s": 930, "text": "Expected Time Complexity: O(N).\nExpected Auxiliary Space: O(1)." }, { "code": null, "e": 1033, "s": 994, "text": "Constraints:\n1 <= N <= 103\n1 <= k <= N" }, { "code": null, "e": 1035, "s": 1033, "text": "0" }, { "code": null, "e": 1059, "s": 1035, "text": "sarshdeep054in 12 hours" }, { "code": null, "e": 1579, "s": 1059, "text": "public Node rotate(Node head, int k) { int n=0; ArrayList<Node> al=new ArrayList<Node>(); Node ex=head; while(head!=null){ al.add(head); head=head.next; n++; } if(n==k) return ex; int temp=k; Node ret=al.get(k); k=k%n; Node[] arr=new Node[n]; for(int i=0;i<n;i++){ arr[(n-k+i)%n]=al.get(i); } for(int j=1;j<n;j++){ ret.next=arr[j]; ret=arr[j]; } ret.next=null; return al.get(temp); }" }, { "code": null, "e": 1581, "s": 1579, "text": "0" }, { "code": null, "e": 1606, "s": 1581, "text": "taiphanvan2403in 4 hours" }, { "code": null, "e": 2018, "s": 1606, "text": "Node* rotate(Node* head, int k)\n {\n Node*tail=head;\n int cnt=0;\n Node* pivot=NULL;\n while(tail->next!=NULL){\n cnt++;\n if(cnt==k) pivot=tail;\n tail=tail->next;\n }\n if (pivot == NULL)\n return head;\n Node* tam=head;\n head=pivot->next;\n pivot->next=NULL;\n tail->next=tam;\n return head;\n }" }, { "code": null, "e": 2020, "s": 2018, "text": "0" }, { "code": null, "e": 2043, "s": 2020, "text": "vats7aryan012 days ago" }, { "code": null, "e": 2364, "s": 2043, "text": "Node* rotate(Node* head, int k) { Node* temp=head,*start=head,*end=head; while(end->next!=NULL) end=end->next; while(k--) { end->next=start; head=start->next; start->next=NULL; end=end->next; start=head; } return head; }" }, { "code": null, "e": 2366, "s": 2364, "text": "0" }, { "code": null, "e": 2397, "s": 2366, "text": "anushkakaushik2002192 days ago" }, { "code": null, "e": 2417, "s": 2397, "text": "*EASY CPP SOLUTION*" }, { "code": null, "e": 2795, "s": 2419, "text": "Node* rotate(Node* head, int k) { Node* temp=head; Node* start=head; Node* end=head; while(end->next!=NULL) { end=end->next; } while(k>0) { end->next=start; head=start->next; start->next=NULL; end=end->next; start=head; k--; } return head; }" }, { "code": null, "e": 2797, "s": 2795, "text": "0" }, { "code": null, "e": 2817, "s": 2797, "text": "darkseid72 days ago" }, { "code": null, "e": 2849, "s": 2817, "text": "ONE PASS || C++ || O(N) || O(1)" }, { "code": null, "e": 3189, "s": 2849, "text": "Node* rotate(Node* head, int k){\n Node* i = head;\n Node* j = head;\n for(int y=1;y<k;y++)j=j->next;\n if(j->next==NULL){\n return head;\n }\n Node* l = j;\n while(l->next!=NULL)l=l->next;\n l->next=i;\n Node* Head = j->next;\n j->next=NULL;\n return Head;\n }" }, { "code": null, "e": 3191, "s": 3189, "text": "0" }, { "code": null, "e": 3221, "s": 3191, "text": "indusridharavath1232 days ago" }, { "code": null, "e": 3643, "s": 3221, "text": " Node* rotate(Node* head, int k) { // Your code here if(k==0) { return head; } Node* temp=head; while(temp->next!=NULL) { temp=temp->next; } while(k>0) { Node* temp2=new Node(head->data); temp->next=temp2; temp=temp2; head=head->next; k--; } return head; }" }, { "code": null, "e": 3646, "s": 3643, "text": "+1" }, { "code": null, "e": 3663, "s": 3646, "text": "mdzama4 days ago" }, { "code": null, "e": 3704, "s": 3663, "text": "C++ || Simple & Clean || 1 Pass Solution" }, { "code": null, "e": 4280, "s": 3704, "text": "Node* rotate(Node* head, int k) {\n if (!k || !head || !head->next) return head;\n \n int position = 1;\n Node *save, *tail;\n save = tail = nullptr;\n \n Node* temp = head;\n while (temp) { // In onepass solution.\n if (position == k) save = temp;\n if (!temp->next) tail = temp;\n temp = temp->next;\n position++;\n }\n if (save != tail) {\n tail->next = head;\n head = save->next;\n save->next = nullptr;\n }\n return head;\n }" }, { "code": null, "e": 4282, "s": 4280, "text": "0" }, { "code": null, "e": 4308, "s": 4282, "text": "pimplevaibhav016 days ago" }, { "code": null, "e": 4779, "s": 4308, "text": "// java Solutionclass Solution{ //Function to rotate a linked list. public Node rotate(Node head, int k) { // add code here Node tail=head; while(tail.next!=null){ tail=tail.next; } for(int i=0;i<k;i++){ tail.next =head; Node fistNode=head.next; head.next=null; tail=head; head=fistNode; } //System.out.println(tail.data); return head; }}" }, { "code": null, "e": 4781, "s": 4779, "text": "0" }, { "code": null, "e": 4803, "s": 4781, "text": "shemanthkgp6 days ago" }, { "code": null, "e": 4820, "s": 4803, "text": "// C++ solution " }, { "code": null, "e": 5249, "s": 4822, "text": "class Solution{ public: //Function to rotate a linked list. Node* rotate(Node* head, int k) { if(k==0){ exit(0); } Node* temp= head; while(temp->next!=NULL){ temp = temp->next; } temp->next = head; temp=head; for(int i=0;i<k-1;i++){ temp=temp->next; } head = temp->next; temp->next=NULL; return head; } };" }, { "code": null, "e": 5251, "s": 5249, "text": "0" }, { "code": null, "e": 5273, "s": 5251, "text": "rajkumarraj1 week ago" }, { "code": null, "e": 5864, "s": 5273, "text": "class Solution\n{\n public:\n //Function to rotate a linked list.\n Node* rotate(Node* head, int k)\n {\n // Your code here\n Node *temp;\n int c=1;\n temp=head;\n if(head==NULL||head->next==NULL)\n return head;\n else\n {\n while(temp->next!=NULL)\n {temp=temp->next;\n c++;\n }\n \n temp->next=head;\n temp=head;\n for(int i=1;i<c-k;i++)\n {\n temp=temp->next;\n }\n head=temp->next;\n temp->next=NULL;\n return head;\n }\n \n }\n};" }, { "code": null, "e": 6010, "s": 5864, "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": 6046, "s": 6010, "text": " Login to access your submissions. " }, { "code": null, "e": 6056, "s": 6046, "text": "\nProblem\n" }, { "code": null, "e": 6066, "s": 6056, "text": "\nContest\n" }, { "code": null, "e": 6129, "s": 6066, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 6277, "s": 6129, "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": 6485, "s": 6277, "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": 6591, "s": 6485, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
Flutter - Provider Package - GeeksforGeeks
01 Feb, 2021 The provider package is an easy to use package which is basically a wrapper around the InheritedWidgets that makes it easier to use and manage. It provides a state management technique that is used for managing a piece of data around the app. The basic classes available in the provider package are – ChangeNotifierProvider<T extends ChangeNotifier> It listens to a ChangeNotifier extended by the model class, exposes it to its children and descendants, and rebuilds depends whenever notifyListeners is called. ChangeNotifierProvider( create: (context) => DataModel(), child: ... ) Consumer<T> It obtains the provider from its ancestors and passes the value obtained to the builder. @override Widget build(BuildContext context) { return Consumer<DataModel>( builder: (context, data, child) => DataWidget(par1: par1, par2: par2), child: Text(data.first), ); } FutureProvider<T> This class listens for a Future and then passes its values to its children and descendants. Constructors FutureProvider<T>( {Key key, @required Create<Future<T>> create, T initialData, ErrorBuilder<T> catchError, UpdateShouldNotify<T> updateShouldNotify, bool lazy, TransitionBuilder builder, Widget child} ) This creates a Future from create and subscribes to it. FutureProvider.value( {Key key, @required Future<T> value, T initialData, ErrorBuilder<T> catchError, UpdateShouldNotify<T> updateShouldNotify, TransitionBuilder builder, Widget child} ) This constructor notifies the changed values to the FutureProvider children. Ex: FutureProvider<Model>(create: (context) => Model(),) InheritedProvider<T> The InheritedProvider provides a general implementation of the InheritedWidget. MultiProvider A provider that is used to provide more than one class at the same time. MultiProvider( providers: [ Provider<Model1>(create: (context) => Model1()), StreamProvider<Model2>(create: (context) => Model2()), FutureProvider<Model3>(create: (context) => Model3()), ], child: someWidget, ) Provider<T> It is the basic provider. ProxyProvider<T, R> This provider depends on other providers for value. The value can be used by create or update. Constructor ProxyProvider( {Key key, Create<R> create, @required ProxyProviderBuilder<T, R> update, UpdateShouldNotify<R> updateShouldNotify, Dispose<R> dispose, bool lazy, TransitionBuilder builder, Widget child} ) This initializes key for subclasses. StreamProvider<T> This class listens for a Stream and then passes its values to its children and descendants. This can be used as Constructors StreamProvider<T>( {Key key, @required Create<Stream<T>> create, T initialData, ErrorBuilder<T> catchError, UpdateShouldNotify<T> updateShouldNotify, bool lazy, TransitionBuilder builder, Widget child} ) This creates a stream using create and subscribes to it. StreamProvider.value( {Key key, @required Stream<T> value, T initialData, ErrorBuilder<T> catchError, UpdateShouldNotify<T> updateShouldNotify, bool lazy, TransitionBuilder builder, Widget child} ) This constructor notifies the changed values to the StreamProvider children. Ex: StreamProvider<Model>(create: (context) => Model(),) ValueListenableProvider<T> This class receives changes in value by subscribing to a ValueListenable. ValueListenableProvider<T>.value( {Key key, @required ValueListenable<T> value, UpdateShouldNotify<T> updateShouldNotify, TransitionBuilder builder, Widget child} ) This constructor shows the changed values to its children. Apart from these, there are a number of other classes that are available depending upon the need but these are the most used classes. For using the provider package we need to add the provider package to the dependencies section of pubspec.yaml and click on the get button to get the dependencies. dependencies: flutter: sdk: flutter provider: ^4.3.2+4 #ADD We will be looking at a simple example app First of all, we will be defining a model library inside of the lib folder which consists of item.dart and item_data.dart. Apart from these, the lib will have 3 more dart files namely the main.dart, home.dart, and item_list.dart. The item.dart is a simple class that defines what are the attributes that the item class will hold and a toggle method. Dart import 'package:flutter/foundation.dart'; class Item { String item; bool completed; Item({@required this.item, this.completed = false}); void toggle() { completed = !completed; }} The item_data.dart contains a list that will hold the data of the Item class defined above. There are methods to perform tasks such as add, toggle, and remove an item from the list. Dart import 'dart:collection';import 'package:flutter/foundation.dart';import '../model/item.dart'; class ItemData with ChangeNotifier { List<Item> _items = []; UnmodifiableListView<Item> get items => UnmodifiableListView(_items); get size => _items.length; void addItem(Item item) { _items.add(item); notifyListeners(); } void toggleItem(Item item) { item.toggle(); notifyListeners(); } void removeItem(Item item) { _items.remove(item); notifyListeners(); }} Now that the model is defined we will clean up the main.dart as Dart import 'package:flutter/material.dart';import 'package:provider/provider.dart';import 'model/item_data.dart';import 'home.dart'; void main() { runApp(MyApp());} class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return ChangeNotifierProvider( create: (context) => ItemData(), child: MaterialApp( debugShowCheckedModeBanner: false, title: 'Provider Demo', theme: ThemeData( primarySwatch: Colors.green, ), home: Home(), ), ); }} The main.dart has a ChangeNotifierProvider which acts as a parent to the material app. As our app is quite small we have defined the provider at the top only. In case your app is quite large you can place the provider at the top of the widget that needs the data and not on the top. The item_list.dart creates a ListView builder of the data coming from the list. It uses the Consumer to get the data. Dart import 'package:flutter/material.dart';import 'package:provider/provider.dart';import 'model/item_data.dart'; class ItemList extends StatelessWidget { @override Widget build(BuildContext context) { return Consumer<ItemData>(builder: (context, data, child) { return ListView.builder( scrollDirection: Axis.vertical, shrinkWrap: true, itemCount: data.size, itemBuilder: (context, index) { final item = data.items[index]; return GestureDetector( onLongPress: () => data.removeItem(item), child: Container( padding: EdgeInsets.symmetric(vertical: 5), child: ListTile( leading: CircleAvatar( backgroundColor: Colors.blueGrey, child: Text(item.item[0]), ), title: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Text( item.item, style: TextStyle( decoration: item.completed ? TextDecoration.lineThrough : null, fontSize: 16, fontWeight: FontWeight.bold), ), Checkbox( value: item.completed, onChanged: (c) => data.toggleItem(item), ), ], ), ), ), ); }, ); }); }} At last, we will be writing the code for the home.dart file which contains the data that is to be displayed on the screen. It also contains a TextField and a button to add the data to the list. Output: Apart from Provider, there are other State Management also available such as – StatefulWidget: These are the widgets provided in the material package. These widgets have an internal state which can be re-built if the input changes or if the widget’s state changes. InheritedWidget: These are simple widgets that hold the data that are to be used by its children or descendants. These provide a simple mechanism to move data to a child much below in the widget tree. There is an element associated with it that changes the data when the element updates. The provider package is basically a wrapper around the InheritedWidgets. ScopedModel: This library is taken from the Fuchsia codebase which provides a method to pass the data from Parents to their children. When the model changes the children are rebuilt. Our class can extend the Model class to create our own Models. ScopedModel Widget is wrapped around the widget whose data needs to be sent down the widget tree. ScopedModelDescendant Widget is used to listen to changes that happen to the Model and rebuild the child. BLoC: Business Logic Component. This technique allows us to handle data as a Stream of events. It comes in between the UI and the data that handles the logic for the application. The main components of BLoC are Sink and Stream. The StreamController handles these components. The sink is used to add data/events and the Stream is used to listen to them. android Flutter Picked Dart Flutter Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Flutter - Custom Bottom Navigation Bar ListView Class in Flutter Flutter - Flexible Widget What is widgets in Flutter? Flutter - Stack Widget Flutter - Custom Bottom Navigation Bar Flutter Tutorial Flutter - Flexible Widget Flutter - Stack Widget Flutter - BorderRadius Widget
[ { "code": null, "e": 24010, "s": 23982, "text": "\n01 Feb, 2021" }, { "code": null, "e": 24253, "s": 24010, "text": "The provider package is an easy to use package which is basically a wrapper around the InheritedWidgets that makes it easier to use and manage. It provides a state management technique that is used for managing a piece of data around the app." }, { "code": null, "e": 24311, "s": 24253, "text": "The basic classes available in the provider package are –" }, { "code": null, "e": 24521, "s": 24311, "text": "ChangeNotifierProvider<T extends ChangeNotifier> It listens to a ChangeNotifier extended by the model class, exposes it to its children and descendants, and rebuilds depends whenever notifyListeners is called." }, { "code": null, "e": 24596, "s": 24521, "text": "ChangeNotifierProvider(\n create: (context) => DataModel(),\n child: ...\n)" }, { "code": null, "e": 24697, "s": 24596, "text": "Consumer<T> It obtains the provider from its ancestors and passes the value obtained to the builder." }, { "code": null, "e": 24891, "s": 24697, "text": "@override\n Widget build(BuildContext context) {\n return Consumer<DataModel>(\n builder: (context, data, child) => DataWidget(par1: par1, par2: par2),\n child: Text(data.first),\n );\n }" }, { "code": null, "e": 25001, "s": 24891, "text": "FutureProvider<T> This class listens for a Future and then passes its values to its children and descendants." }, { "code": null, "e": 25668, "s": 25001, "text": "Constructors\nFutureProvider<T>(\n {Key key,\n @required Create<Future<T>> create,\n T initialData,\n ErrorBuilder<T> catchError,\n UpdateShouldNotify<T> updateShouldNotify,\n bool lazy,\n TransitionBuilder builder,\n Widget child}\n)\nThis creates a Future from create and subscribes to it.\n\nFutureProvider.value(\n {Key key, \n @required Future<T> value, \n T initialData, \n ErrorBuilder<T> catchError, \n UpdateShouldNotify<T> updateShouldNotify, \n TransitionBuilder builder, \n Widget child}\n )\nThis constructor notifies the changed values to the FutureProvider children.\n\nEx: FutureProvider<Model>(create: (context) =>\n Model(),)" }, { "code": null, "e": 25769, "s": 25668, "text": "InheritedProvider<T> The InheritedProvider provides a general implementation of the InheritedWidget." }, { "code": null, "e": 25856, "s": 25769, "text": "MultiProvider A provider that is used to provide more than one class at the same time." }, { "code": null, "e": 26085, "s": 25856, "text": "MultiProvider(\n providers: [\n Provider<Model1>(create: (context) => Model1()),\n StreamProvider<Model2>(create: (context) => Model2()),\n FutureProvider<Model3>(create: (context) => Model3()),\n ],\n child: someWidget,\n)" }, { "code": null, "e": 26123, "s": 26085, "text": "Provider<T> It is the basic provider." }, { "code": null, "e": 26238, "s": 26123, "text": "ProxyProvider<T, R> This provider depends on other providers for value. The value can be used by create or update." }, { "code": null, "e": 26525, "s": 26238, "text": "Constructor\nProxyProvider(\n {Key key, \n Create<R> create, \n @required ProxyProviderBuilder<T, R> update, \n UpdateShouldNotify<R> updateShouldNotify, \n Dispose<R> dispose, bool lazy, \n TransitionBuilder builder, \n Widget child}\n)\nThis initializes key for subclasses." }, { "code": null, "e": 26655, "s": 26525, "text": "StreamProvider<T> This class listens for a Stream and then passes its values to its children and descendants. This can be used as" }, { "code": null, "e": 27335, "s": 26655, "text": "Constructors\nStreamProvider<T>(\n {Key key,\n @required Create<Stream<T>> create,\n T initialData,\n ErrorBuilder<T> catchError,\n UpdateShouldNotify<T> updateShouldNotify,\n bool lazy,\n TransitionBuilder builder,\n Widget child}\n)\nThis creates a stream using create and subscribes to it.\n\nStreamProvider.value(\n {Key key, \n @required Stream<T> value, \n T initialData, \n ErrorBuilder<T> catchError, \n UpdateShouldNotify<T> updateShouldNotify, \n bool lazy, \n TransitionBuilder builder, \n Widget child}\n)\nThis constructor notifies the changed values to the StreamProvider children.\n\nEx: StreamProvider<Model>(create: (context) =>\n Model(),)" }, { "code": null, "e": 27436, "s": 27335, "text": "ValueListenableProvider<T> This class receives changes in value by subscribing to a ValueListenable." }, { "code": null, "e": 27680, "s": 27436, "text": "ValueListenableProvider<T>.value(\n {Key key,\n @required ValueListenable<T> value,\n UpdateShouldNotify<T> updateShouldNotify,\n TransitionBuilder builder,\n Widget child}\n)\nThis constructor shows the changed values to its children." }, { "code": null, "e": 27814, "s": 27680, "text": "Apart from these, there are a number of other classes that are available depending upon the need but these are the most used classes." }, { "code": null, "e": 27978, "s": 27814, "text": "For using the provider package we need to add the provider package to the dependencies section of pubspec.yaml and click on the get button to get the dependencies." }, { "code": null, "e": 28046, "s": 27978, "text": "dependencies:\n flutter:\n sdk: flutter\n provider: ^4.3.2+4 #ADD" }, { "code": null, "e": 28089, "s": 28046, "text": "We will be looking at a simple example app" }, { "code": null, "e": 28320, "s": 28089, "text": "First of all, we will be defining a model library inside of the lib folder which consists of item.dart and item_data.dart. Apart from these, the lib will have 3 more dart files namely the main.dart, home.dart, and item_list.dart. " }, { "code": null, "e": 28440, "s": 28320, "text": "The item.dart is a simple class that defines what are the attributes that the item class will hold and a toggle method." }, { "code": null, "e": 28445, "s": 28440, "text": "Dart" }, { "code": "import 'package:flutter/foundation.dart'; class Item { String item; bool completed; Item({@required this.item, this.completed = false}); void toggle() { completed = !completed; }}", "e": 28634, "s": 28445, "text": null }, { "code": null, "e": 28816, "s": 28634, "text": "The item_data.dart contains a list that will hold the data of the Item class defined above. There are methods to perform tasks such as add, toggle, and remove an item from the list." }, { "code": null, "e": 28821, "s": 28816, "text": "Dart" }, { "code": "import 'dart:collection';import 'package:flutter/foundation.dart';import '../model/item.dart'; class ItemData with ChangeNotifier { List<Item> _items = []; UnmodifiableListView<Item> get items => UnmodifiableListView(_items); get size => _items.length; void addItem(Item item) { _items.add(item); notifyListeners(); } void toggleItem(Item item) { item.toggle(); notifyListeners(); } void removeItem(Item item) { _items.remove(item); notifyListeners(); }}", "e": 29312, "s": 28821, "text": null }, { "code": null, "e": 29376, "s": 29312, "text": "Now that the model is defined we will clean up the main.dart as" }, { "code": null, "e": 29381, "s": 29376, "text": "Dart" }, { "code": "import 'package:flutter/material.dart';import 'package:provider/provider.dart';import 'model/item_data.dart';import 'home.dart'; void main() { runApp(MyApp());} class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return ChangeNotifierProvider( create: (context) => ItemData(), child: MaterialApp( debugShowCheckedModeBanner: false, title: 'Provider Demo', theme: ThemeData( primarySwatch: Colors.green, ), home: Home(), ), ); }}", "e": 29914, "s": 29381, "text": null }, { "code": null, "e": 30197, "s": 29914, "text": "The main.dart has a ChangeNotifierProvider which acts as a parent to the material app. As our app is quite small we have defined the provider at the top only. In case your app is quite large you can place the provider at the top of the widget that needs the data and not on the top." }, { "code": null, "e": 30315, "s": 30197, "text": "The item_list.dart creates a ListView builder of the data coming from the list. It uses the Consumer to get the data." }, { "code": null, "e": 30320, "s": 30315, "text": "Dart" }, { "code": "import 'package:flutter/material.dart';import 'package:provider/provider.dart';import 'model/item_data.dart'; class ItemList extends StatelessWidget { @override Widget build(BuildContext context) { return Consumer<ItemData>(builder: (context, data, child) { return ListView.builder( scrollDirection: Axis.vertical, shrinkWrap: true, itemCount: data.size, itemBuilder: (context, index) { final item = data.items[index]; return GestureDetector( onLongPress: () => data.removeItem(item), child: Container( padding: EdgeInsets.symmetric(vertical: 5), child: ListTile( leading: CircleAvatar( backgroundColor: Colors.blueGrey, child: Text(item.item[0]), ), title: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Text( item.item, style: TextStyle( decoration: item.completed ? TextDecoration.lineThrough : null, fontSize: 16, fontWeight: FontWeight.bold), ), Checkbox( value: item.completed, onChanged: (c) => data.toggleItem(item), ), ], ), ), ), ); }, ); }); }}", "e": 31889, "s": 30320, "text": null }, { "code": null, "e": 32083, "s": 31889, "text": "At last, we will be writing the code for the home.dart file which contains the data that is to be displayed on the screen. It also contains a TextField and a button to add the data to the list." }, { "code": null, "e": 32091, "s": 32083, "text": "Output:" }, { "code": null, "e": 32170, "s": 32091, "text": "Apart from Provider, there are other State Management also available such as –" }, { "code": null, "e": 32356, "s": 32170, "text": "StatefulWidget: These are the widgets provided in the material package. These widgets have an internal state which can be re-built if the input changes or if the widget’s state changes." }, { "code": null, "e": 32717, "s": 32356, "text": "InheritedWidget: These are simple widgets that hold the data that are to be used by its children or descendants. These provide a simple mechanism to move data to a child much below in the widget tree. There is an element associated with it that changes the data when the element updates. The provider package is basically a wrapper around the InheritedWidgets." }, { "code": null, "e": 33167, "s": 32717, "text": "ScopedModel: This library is taken from the Fuchsia codebase which provides a method to pass the data from Parents to their children. When the model changes the children are rebuilt. Our class can extend the Model class to create our own Models. ScopedModel Widget is wrapped around the widget whose data needs to be sent down the widget tree. ScopedModelDescendant Widget is used to listen to changes that happen to the Model and rebuild the child." }, { "code": null, "e": 33520, "s": 33167, "text": "BLoC: Business Logic Component. This technique allows us to handle data as a Stream of events. It comes in between the UI and the data that handles the logic for the application. The main components of BLoC are Sink and Stream. The StreamController handles these components. The sink is used to add data/events and the Stream is used to listen to them." }, { "code": null, "e": 33528, "s": 33520, "text": "android" }, { "code": null, "e": 33536, "s": 33528, "text": "Flutter" }, { "code": null, "e": 33543, "s": 33536, "text": "Picked" }, { "code": null, "e": 33548, "s": 33543, "text": "Dart" }, { "code": null, "e": 33556, "s": 33548, "text": "Flutter" }, { "code": null, "e": 33654, "s": 33556, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 33693, "s": 33654, "text": "Flutter - Custom Bottom Navigation Bar" }, { "code": null, "e": 33719, "s": 33693, "text": "ListView Class in Flutter" }, { "code": null, "e": 33745, "s": 33719, "text": "Flutter - Flexible Widget" }, { "code": null, "e": 33773, "s": 33745, "text": "What is widgets in Flutter?" }, { "code": null, "e": 33796, "s": 33773, "text": "Flutter - Stack Widget" }, { "code": null, "e": 33835, "s": 33796, "text": "Flutter - Custom Bottom Navigation Bar" }, { "code": null, "e": 33852, "s": 33835, "text": "Flutter Tutorial" }, { "code": null, "e": 33878, "s": 33852, "text": "Flutter - Flexible Widget" }, { "code": null, "e": 33901, "s": 33878, "text": "Flutter - Stack Widget" } ]
What is Shallow Copy and how it is different from Deep Copy in C#?
Shallow Copy − A shallow copy of an object copies the "main" object, but doesn’t copy the inner objects. The "inner objects" are shared between the original object and its copy. The problem with the shallow copy is that the two objects are not independent. If you modify the one object, the change will be reflected in the other object. Deep Copy − A deep copy is a fully independent copy of an object. If we copied our object, we would copy the entire object structure. If you modify the one object, the change will not be reflected in the other object. class Program{ static void Main(string[] args){ //Shallow Copy ShallowCopy obj = new ShallowCopy(); obj.a = 10; ShallowCopy obj1 = new ShallowCopy(); obj1 = obj; Console.WriteLine("{0} {1}", obj1.a, obj.a); // 10,10 obj1.a = 5; Console.WriteLine("{0} {1}", obj1.a, obj.a); //5,5 //Deep Copy DeepCopy d = new DeepCopy(); d.a = 10; DeepCopy d1 = new DeepCopy(); d1.a = d.a; Console.WriteLine("{0} {1}", d1.a, d.a); // 10,10 d1.a = 5; Console.WriteLine("{0} {1}", d1.a, d.a); //5,10 Console.ReadLine(); } } class ShallowCopy{ public int a = 10; } class DeepCopy{ public int a = 10; } 10 10 5 5 10 10 5 10
[ { "code": null, "e": 1077, "s": 1062, "text": "Shallow Copy −" }, { "code": null, "e": 1167, "s": 1077, "text": "A shallow copy of an object copies the \"main\" object, but doesn’t copy the inner\nobjects." }, { "code": null, "e": 1240, "s": 1167, "text": "The \"inner objects\" are shared between the original object and its copy." }, { "code": null, "e": 1399, "s": 1240, "text": "The problem with the shallow copy is that the two objects are not independent. If you\nmodify the one object, the change will be reflected in the other object." }, { "code": null, "e": 1411, "s": 1399, "text": "Deep Copy −" }, { "code": null, "e": 1533, "s": 1411, "text": "A deep copy is a fully independent copy of an object. If we copied our object, we\nwould copy the entire object structure." }, { "code": null, "e": 1617, "s": 1533, "text": "If you modify the one object, the change will not be reflected in the other object." }, { "code": null, "e": 2312, "s": 1617, "text": "class Program{\n static void Main(string[] args){\n //Shallow Copy\n ShallowCopy obj = new ShallowCopy();\n obj.a = 10;\n ShallowCopy obj1 = new ShallowCopy();\n obj1 = obj;\n Console.WriteLine(\"{0} {1}\", obj1.a, obj.a); // 10,10\n obj1.a = 5;\n Console.WriteLine(\"{0} {1}\", obj1.a, obj.a); //5,5\n //Deep Copy\n DeepCopy d = new DeepCopy();\n d.a = 10;\n DeepCopy d1 = new DeepCopy();\n d1.a = d.a;\n Console.WriteLine(\"{0} {1}\", d1.a, d.a); // 10,10\n d1.a = 5;\n Console.WriteLine(\"{0} {1}\", d1.a, d.a); //5,10\n Console.ReadLine();\n }\n}\nclass ShallowCopy{\n public int a = 10;\n}\nclass DeepCopy{\n public int a = 10;\n}" }, { "code": null, "e": 2333, "s": 2312, "text": "10 10\n5 5\n10 10\n5 10" } ]
Tryit Editor v3.7
Tryit basic HTML paragraphs
[]
jQuery - preventDefault() Method
The preventDefault() method prevents the browser from executing the default action. You can use the method isDefaultPrevented to know whether this method was ever called (on that event object). Here is the simple syntax to use this method − event.preventDefault() Here is the description of all the parameters used by this method − NA NA Following is a simple example a simple showing the usage of this method. This example demonstrate how you can stop the browser from changing the page to the href of any anchors. <html> <head> <title>The jQuery Example</title> <script type = "text/javascript" src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"> </script> <script type = "text/javascript" language = "javascript"> $(document).ready(function() { $("a").click(function(event){ event.preventDefault(); alert( "Default behavior is disabled!" ); }); }); </script> </head> <body> <span>Click the following link and it won't work:</span> <a href = "https://www.google.com">GOOGLE Inc.</a> </body> </html> This will produce following result − 27 Lectures 1 hours Mahesh Kumar 27 Lectures 1.5 hours Pratik Singh 72 Lectures 4.5 hours Frahaan Hussain 60 Lectures 9 hours Eduonix Learning Solutions 17 Lectures 2 hours Sandip Bhattacharya 12 Lectures 53 mins Laurence Svekis Print Add Notes Bookmark this page
[ { "code": null, "e": 2406, "s": 2322, "text": "The preventDefault() method prevents the browser from executing the default action." }, { "code": null, "e": 2516, "s": 2406, "text": "You can use the method isDefaultPrevented to know whether this method was ever called (on that event object)." }, { "code": null, "e": 2563, "s": 2516, "text": "Here is the simple syntax to use this method −" }, { "code": null, "e": 2588, "s": 2563, "text": "event.preventDefault() \n" }, { "code": null, "e": 2656, "s": 2588, "text": "Here is the description of all the parameters used by this method −" }, { "code": null, "e": 2659, "s": 2656, "text": "NA" }, { "code": null, "e": 2662, "s": 2659, "text": "NA" }, { "code": null, "e": 2840, "s": 2662, "text": "Following is a simple example a simple showing the usage of this method. This example demonstrate how you can stop the browser from changing the page to the href of any anchors." }, { "code": null, "e": 3488, "s": 2840, "text": "<html>\n <head>\n <title>The jQuery Example</title>\n <script type = \"text/javascript\" \n src = \"https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js\">\n </script>\n\t\t\n <script type = \"text/javascript\" language = \"javascript\">\n $(document).ready(function() {\n $(\"a\").click(function(event){\n event.preventDefault();\n alert( \"Default behavior is disabled!\" );\n });\n });\n </script>\n </head>\n\t\n <body>\n <span>Click the following link and it won't work:</span>\n <a href = \"https://www.google.com\">GOOGLE Inc.</a>\n </body>\n</html>" }, { "code": null, "e": 3525, "s": 3488, "text": "This will produce following result −" }, { "code": null, "e": 3558, "s": 3525, "text": "\n 27 Lectures \n 1 hours \n" }, { "code": null, "e": 3572, "s": 3558, "text": " Mahesh Kumar" }, { "code": null, "e": 3607, "s": 3572, "text": "\n 27 Lectures \n 1.5 hours \n" }, { "code": null, "e": 3621, "s": 3607, "text": " Pratik Singh" }, { "code": null, "e": 3656, "s": 3621, "text": "\n 72 Lectures \n 4.5 hours \n" }, { "code": null, "e": 3673, "s": 3656, "text": " Frahaan Hussain" }, { "code": null, "e": 3706, "s": 3673, "text": "\n 60 Lectures \n 9 hours \n" }, { "code": null, "e": 3734, "s": 3706, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 3767, "s": 3734, "text": "\n 17 Lectures \n 2 hours \n" }, { "code": null, "e": 3788, "s": 3767, "text": " Sandip Bhattacharya" }, { "code": null, "e": 3820, "s": 3788, "text": "\n 12 Lectures \n 53 mins\n" }, { "code": null, "e": 3837, "s": 3820, "text": " Laurence Svekis" }, { "code": null, "e": 3844, "s": 3837, "text": " Print" }, { "code": null, "e": 3855, "s": 3844, "text": " Add Notes" } ]
C# Example for Single Inheritance
The following is an example of Single Inheritance in C#. In the example, the base class is Father and declared like the following code snippet − class Father { public void Display() { Console.WriteLine("Display"); } } Our derived class is Son and is declared below − class Son : Father { public void DisplayOne() { Console.WriteLine("DisplayOne"); } } The following is the complete example to implement Single Inheritance in C#. Live Demo using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace MyAplication { class Demo { static void Main(string[] args) { // Father class Father f = new Father(); f.Display(); // Son class Son s = new Son(); s.Display(); s.DisplayOne(); Console.ReadKey(); } class Father { public void Display() { Console.WriteLine("Display"); } } class Son : Father { public void DisplayOne() { Console.WriteLine("DisplayOne"); } } } } Display Display DisplayOne
[ { "code": null, "e": 1207, "s": 1062, "text": "The following is an example of Single Inheritance in C#. In the example, the base class is Father and declared like the following code snippet −" }, { "code": null, "e": 1292, "s": 1207, "text": "class Father {\n public void Display() {\n Console.WriteLine(\"Display\");\n }\n}" }, { "code": null, "e": 1341, "s": 1292, "text": "Our derived class is Son and is declared below −" }, { "code": null, "e": 1438, "s": 1341, "text": "class Son : Father {\n public void DisplayOne() {\n Console.WriteLine(\"DisplayOne\");\n }\n}" }, { "code": null, "e": 1515, "s": 1438, "text": "The following is the complete example to implement Single Inheritance in C#." }, { "code": null, "e": 1525, "s": 1515, "text": "Live Demo" }, { "code": null, "e": 2156, "s": 1525, "text": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nnamespace MyAplication {\n class Demo {\n static void Main(string[] args) {\n // Father class\n Father f = new Father();\n f.Display();\n // Son class\n Son s = new Son();\n s.Display();\n s.DisplayOne();\n\n Console.ReadKey();\n }\n class Father {\n public void Display() {\n Console.WriteLine(\"Display\");\n }\n }\n class Son : Father {\n public void DisplayOne() {\n Console.WriteLine(\"DisplayOne\");\n }\n }\n }\n}" }, { "code": null, "e": 2183, "s": 2156, "text": "Display\nDisplay\nDisplayOne" } ]
What is the Punycode in Node.js ?
30 Jun, 2020 Punycode is a special encoding syntax that is specifically used to convert Unicode characters (UTF-8) to ASCII, which is nothing but the restricted string character set. Why this type of specific conversion needed ? The hostnames will understand only ASCII characters. Punycode is used by the International Domain Names(IDN) in order to encode/decode the URL which has been typed in the browser.For example: If you search mañana.com in the browser, your browser which has an inbuilt IDNA service convert that to xn--maana-pta.com with the help of Punycode converter embedded in the browser. Now let’s see, how-to-use Punycode with the help of Node.js. Punycode in Node.js: Punycode is bundled with node.js v0.6.2 and the later versions. If you want to use Punycode, you need to install Punycode module using npm installation. npm installation: npm install punycode --save Include punycode module: const punycode = require('punycode'); punycode.decode(string): It is used to convert Punycode strings of ASCII to Unicode symbols. Example: // Include punycode moduleconst punycode = require('punycode'); // Decode Punycode strings of ASCII// to Unicode symbolsconsole.log(punycode.decode('manama-pta'));console.log(punycode.decode('--dqo34k')); Output: punycode.encode(string): It is used to convert Unicode strings to Punycode strings of ASCII symbols. Example: // Include punycode moduleconst punycode = require('punycode'); // Encode Unicode symbols to// Punycode ASCII string console.log(punycode.encode('máanama'));console.log(punycode.encode('?-?')); Output: manama-pta --dqo34k punycode.toUnicode(input): It is used to convert Punycode strings that represent a domain name or an email address to Unicode symbols. It doesn’t matter you call it on an already converted Unicode. Example: // Include punycode moduleconst punycode = require('punycode'); console.log(punycode.toUnicode('xn--maana-pta.com'));console.log(punycode.toUnicode('xn----dqo34k.com')); Output: punycode.toASCII(input): It is used to convert lowercased Unicode strings that represent a domain name or an email address to Punycode symbols. It doesn’t matter you call it with a domain that’s already in ASCII. Example: // Include punycode moduleconst punycode = require('punycode'); console.log(punycode.toASCII('mañana.com'));console.log(punycode.toASCII('?-?.com')); Output: xn--maana-pta.com xn----dqo34k.com punycode.ucs2.decode(string): Creates an array of numeric code point values for each Unicode code symbols in the string.Behind the scenes in the browser which was built on Javascript internally, the UCS-2 function in it, will convert a pair of surrogate halves into a single coded point. Example: // Include punycode moduleconst punycode = require('punycode'); // Decoding strings console.log(punycode.ucs2.decode('abc'));console.log(punycode.ucs2.decode('\uD834\uDF06')); Output: [ 97, 98, 99 ] [ 119558 ] UCS-2: UCS-2 is a 2-byte Universal Character Set that produces a fixed-length format by suing 16-bit code unit. The code point ranges from 0 to 0xFFFF. Surrogate pairs: Characters that are outside BMP, e.g. U+1D306 TETRAGRAM FOR CENTRE:, can only be encoded by using two 16-bit code units. This is known as “surrogate pairs”. The Surrogate pairs only represent a single character alone. punycode.ucs2.encode(codePoints): It is used to create a string based on the array of numeric code point values. Example: // Include punycode moduleconst punycode = require('punycode'); console.log(punycode.ucs2.encode([0x61, 0x62, 0x63]));console.log(punycode.ucs2.encode([0x1D306])); Output: abc 𝌆 You can see thePunycode Converter to see the live result. Akanksha_Rai Node.js-Misc Picked Node.js Web Technologies Web technologies Questions Write From Home Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. JWT Authentication with Node.js Installation of Node.js on Windows Difference between dependencies, devDependencies and peerDependencies Mongoose Populate() Method Mongoose find() Function 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 ? Differences between Functional Components and Class Components in React
[ { "code": null, "e": 28, "s": 0, "text": "\n30 Jun, 2020" }, { "code": null, "e": 198, "s": 28, "text": "Punycode is a special encoding syntax that is specifically used to convert Unicode characters (UTF-8) to ASCII, which is nothing but the restricted string character set." }, { "code": null, "e": 620, "s": 198, "text": "Why this type of specific conversion needed ? The hostnames will understand only ASCII characters. Punycode is used by the International Domain Names(IDN) in order to encode/decode the URL which has been typed in the browser.For example: If you search mañana.com in the browser, your browser which has an inbuilt IDNA service convert that to xn--maana-pta.com with the help of Punycode converter embedded in the browser." }, { "code": null, "e": 681, "s": 620, "text": "Now let’s see, how-to-use Punycode with the help of Node.js." }, { "code": null, "e": 855, "s": 681, "text": "Punycode in Node.js: Punycode is bundled with node.js v0.6.2 and the later versions. If you want to use Punycode, you need to install Punycode module using npm installation." }, { "code": null, "e": 873, "s": 855, "text": "npm installation:" }, { "code": null, "e": 903, "s": 873, "text": " npm install punycode --save " }, { "code": null, "e": 928, "s": 903, "text": "Include punycode module:" }, { "code": null, "e": 966, "s": 928, "text": "const punycode = require('punycode');" }, { "code": null, "e": 1059, "s": 966, "text": "punycode.decode(string): It is used to convert Punycode strings of ASCII to Unicode symbols." }, { "code": null, "e": 1068, "s": 1059, "text": "Example:" }, { "code": "// Include punycode moduleconst punycode = require('punycode'); // Decode Punycode strings of ASCII// to Unicode symbolsconsole.log(punycode.decode('manama-pta'));console.log(punycode.decode('--dqo34k'));", "e": 1274, "s": 1068, "text": null }, { "code": null, "e": 1282, "s": 1274, "text": "Output:" }, { "code": null, "e": 1383, "s": 1282, "text": "punycode.encode(string): It is used to convert Unicode strings to Punycode strings of ASCII symbols." }, { "code": null, "e": 1392, "s": 1383, "text": "Example:" }, { "code": "// Include punycode moduleconst punycode = require('punycode'); // Encode Unicode symbols to// Punycode ASCII string console.log(punycode.encode('máanama'));console.log(punycode.encode('?-?'));", "e": 1588, "s": 1392, "text": null }, { "code": null, "e": 1596, "s": 1588, "text": "Output:" }, { "code": null, "e": 1616, "s": 1596, "text": "manama-pta\n--dqo34k" }, { "code": null, "e": 1814, "s": 1616, "text": "punycode.toUnicode(input): It is used to convert Punycode strings that represent a domain name or an email address to Unicode symbols. It doesn’t matter you call it on an already converted Unicode." }, { "code": null, "e": 1823, "s": 1814, "text": "Example:" }, { "code": "// Include punycode moduleconst punycode = require('punycode'); console.log(punycode.toUnicode('xn--maana-pta.com'));console.log(punycode.toUnicode('xn----dqo34k.com'));", "e": 1994, "s": 1823, "text": null }, { "code": null, "e": 2002, "s": 1994, "text": "Output:" }, { "code": null, "e": 2215, "s": 2002, "text": "punycode.toASCII(input): It is used to convert lowercased Unicode strings that represent a domain name or an email address to Punycode symbols. It doesn’t matter you call it with a domain that’s already in ASCII." }, { "code": null, "e": 2224, "s": 2215, "text": "Example:" }, { "code": "// Include punycode moduleconst punycode = require('punycode'); console.log(punycode.toASCII('mañana.com'));console.log(punycode.toASCII('?-?.com'));", "e": 2376, "s": 2224, "text": null }, { "code": null, "e": 2384, "s": 2376, "text": "Output:" }, { "code": null, "e": 2419, "s": 2384, "text": "xn--maana-pta.com\nxn----dqo34k.com" }, { "code": null, "e": 2707, "s": 2419, "text": "punycode.ucs2.decode(string): Creates an array of numeric code point values for each Unicode code symbols in the string.Behind the scenes in the browser which was built on Javascript internally, the UCS-2 function in it, will convert a pair of surrogate halves into a single coded point." }, { "code": null, "e": 2716, "s": 2707, "text": "Example:" }, { "code": "// Include punycode moduleconst punycode = require('punycode'); // Decoding strings console.log(punycode.ucs2.decode('abc'));console.log(punycode.ucs2.decode('\\uD834\\uDF06'));", "e": 2893, "s": 2716, "text": null }, { "code": null, "e": 2901, "s": 2893, "text": "Output:" }, { "code": null, "e": 2927, "s": 2901, "text": "[ 97, 98, 99 ]\n[ 119558 ]" }, { "code": null, "e": 3079, "s": 2927, "text": "UCS-2: UCS-2 is a 2-byte Universal Character Set that produces a fixed-length format by suing 16-bit code unit. The code point ranges from 0 to 0xFFFF." }, { "code": null, "e": 3314, "s": 3079, "text": "Surrogate pairs: Characters that are outside BMP, e.g. U+1D306 TETRAGRAM FOR CENTRE:, can only be encoded by using two 16-bit code units. This is known as “surrogate pairs”. The Surrogate pairs only represent a single character alone." }, { "code": null, "e": 3427, "s": 3314, "text": "punycode.ucs2.encode(codePoints): It is used to create a string based on the array of numeric code point values." }, { "code": null, "e": 3436, "s": 3427, "text": "Example:" }, { "code": "// Include punycode moduleconst punycode = require('punycode'); console.log(punycode.ucs2.encode([0x61, 0x62, 0x63]));console.log(punycode.ucs2.encode([0x1D306]));", "e": 3601, "s": 3436, "text": null }, { "code": null, "e": 3609, "s": 3601, "text": "Output:" }, { "code": null, "e": 3615, "s": 3609, "text": "abc\n𝌆" }, { "code": null, "e": 3673, "s": 3615, "text": "You can see thePunycode Converter to see the live result." }, { "code": null, "e": 3686, "s": 3673, "text": "Akanksha_Rai" }, { "code": null, "e": 3699, "s": 3686, "text": "Node.js-Misc" }, { "code": null, "e": 3706, "s": 3699, "text": "Picked" }, { "code": null, "e": 3714, "s": 3706, "text": "Node.js" }, { "code": null, "e": 3731, "s": 3714, "text": "Web Technologies" }, { "code": null, "e": 3758, "s": 3731, "text": "Web technologies Questions" }, { "code": null, "e": 3774, "s": 3758, "text": "Write From Home" }, { "code": null, "e": 3872, "s": 3774, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3904, "s": 3872, "text": "JWT Authentication with Node.js" }, { "code": null, "e": 3939, "s": 3904, "text": "Installation of Node.js on Windows" }, { "code": null, "e": 4009, "s": 3939, "text": "Difference between dependencies, devDependencies and peerDependencies" }, { "code": null, "e": 4036, "s": 4009, "text": "Mongoose Populate() Method" }, { "code": null, "e": 4061, "s": 4036, "text": "Mongoose find() Function" }, { "code": null, "e": 4123, "s": 4061, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 4184, "s": 4123, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 4234, "s": 4184, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 4277, "s": 4234, "text": "How to fetch data from an API in ReactJS ?" } ]
Python | Plotting charts in excel sheet using openpyxl module | Set 3
19 May, 2021 Prerequisite : Plotting charts in excel sheet using openpyxl module Set – 1 | Set – 2Openpyxl is a Python library using which one can perform multiple operations on excel files like reading, writing, arithmetic operations and plotting graphs. Charts are composed of at least one series of one or more data points. Series themselves are comprised of references to cell ranges. Let’s see how to plot Doughnot, Radar, Surface, 3D Surface Chart on an excel sheet using openpyxl.For plotting the charts on an excel sheet, firstly, create chart object of specific chart class( i.e SurfaceChart, RadarChart etc.). After creating chart objects, insert data in it and lastly, add that chart object in the sheet object. Let’s see how to plot different charts using realtime data.Code #1 : Plot the Doughnut ChartDoughnut charts are similar to pie charts except that they use a ring instead of a circle. They can also plot several series of data as concentric rings. For plotting the Doughnut chart on an excel sheet, use DoughnutChart class from openpyxl.chart submodule. Python3 # import Workbook from openpyxlfrom openpyxl import Workbook # import DoughnutChart, Reference from openpyxl.chart sub_module .from openpyxl.chart import DoughnutChart, Reference # import DataPoint from openpyxl.chart.series classfrom openpyxl.chart.series import DataPoint # Call a Workbook() function of openpyxl# to create a new blank Workbook objectwb = Workbook() # Get workbook active sheet# from the active attribute.ws = wb.active # data givendata = [ ['Pie', 2014], ['Plain', 40], ['Jam', 2], ['Lime', 20], ['Chocolate', 30],] # write content of each row in 1st and 2nd# column of the active sheet respectively .for row in data: ws.append(row) # Create object of DoughnutChart classchart = DoughnutChart() # create data for plottinglabels = Reference(ws, min_col = 1, min_row = 2, max_row = 5)data = Reference(ws, min_col = 2, min_row = 1, max_row = 5) # adding data to the Doughnut chart objectchart.add_data(data, titles_from_data = True) # set labels in the chart objectchart.set_categories(labels) # set the title of the chartchart.title = "Doughnuts Chart" # set style of the chartchart.style = 26 # add chart to the sheet# the top-left corner of a chart# is anchored to cell E1 .ws.add_chart(chart, "E1") # save the filewb.save("doughnut.xlsx") Output: Code #2: Plot the Radar ChartData that is arranged in columns or rows on a worksheet can be plotted in a radar chart. Radar charts compare the aggregate values of multiple data series. It is effectively a projection of an area chart on a circular x-axis. For plotting the Radar chart on an excel sheet, use RadarChart class from openpyxl.chart submodule. Python3 # import Workbook from openpyxlfrom openpyxl import Workbook # import RadarChart, Reference from openpyxl.chart sub_module .from openpyxl.chart import RadarChart, Reference # Call a Workbook() function of openpyxl# to create a new blank Workbook objectwb = Workbook() # Get workbook active sheet# from the active attribute.ws = wb.active # data givendata = [ ['Month', "Bulbs", "Seeds", "Flowers", "Trees & shrubs"], ['Jan', 0, 2500, 500, 0, ], ['Feb', 0, 5500, 750, 1500], ['Mar', 0, 9000, 1500, 2500], ['Apr', 0, 6500, 2000, 4000], ['May', 0, 3500, 5500, 3500], ['Jun', 0, 0, 7500, 1500], ['Jul', 0, 0, 8500, 800], ['Aug', 1500, 0, 7000, 550], ['Sep', 5000, 0, 3500, 2500], ['Oct', 8500, 0, 2500, 6000], ['Nov', 3500, 0, 500, 5500], ['Dec', 500, 0, 100, 3000 ],] # write content of each row in 1st and 2nd# column of the active sheet respectively .for row in data: ws.append(row) # Create object of RadarChart classchart = RadarChart() # filled type of radar chartchart.type = "filled" # create data for plottinglabels = Reference(ws, min_col = 1, min_row = 2, max_row = 13)data = Reference(ws, min_col = 2, max_col = 5, min_row = 2, max_row = 13) # adding data to the Radar chart objectchart.add_data(data, titles_from_data = True) # set labels in the chart objectchart.set_categories(labels) # set the title of the chartchart.title = "Radar Chart" # set style of the chartchart.style = 26 # delete y axis from the chartchart.y_axis.delete = True # add chart to the sheet# the top-left corner of a chart# is anchored to cell G2 .ws.add_chart(chart, "G2") # save the filewb.save("Radar.xlsx") Output: Code #3 : Plot The Surface ChartData that is arranged in columns or rows on a worksheet can be plotted in a surface chart. A surface chart is useful when you want to find optimum combinations between two sets of data. As in a topographic map, colors and patterns indicate areas that are in the same range of values. For plotting the Surface chart on an excel sheet, use SurfaceChart class from openpyxl.chart submodule. Python3 # import Workbook from openpyxlfrom openpyxl import Workbook # import SurfaceChart, Reference, Series from openpyxl.chart sub_module .from openpyxl.chart import SurfaceChart, Reference, Series # Call a Workbook() function of openpyxl# to create a new blank Workbook objectwb = Workbook() # Get workbook active sheet# from the active attribute.ws = wb.active # given datadata = [ [None, 10, 20, 30, 40, 50, ], [0.1, 15, 65, 105, 65, 15, ], [0.2, 35, 105, 170, 105, 35, ], [0.3, 55, 135, 215, 135, 55, ], [0.4, 75, 155, 240, 155, 75, ], [0.5, 80, 190, 245, 190, 80, ], [0.6, 75, 155, 240, 155, 75, ], [0.7, 55, 135, 215, 135, 55, ], [0.8, 35, 105, 170, 105, 35, ], [0.9, 15, 65, 105, 65, 15],] # write content of each row in 1st and 2nd# column of the active sheet respectively .for row in data: ws.append(row) # Create object of SurfaceChart classchart = SurfaceChart() # create data for plottinglabels = Reference(ws, min_col = 1, min_row = 2, max_row = 10)data = Reference(ws, min_col = 2, max_col = 6, min_row = 1, max_row = 10) # adding data to the Surface chart objectchart.add_data(data, titles_from_data = True) # set labels in the chart objectchart.set_categories(labels) # set the title of the chartchart.title = "Surface Chart" # set style of the chartchart.style = 26 # add chart to the sheet# the top-left corner of a chart# is anchored to cell H2 .ws.add_chart(chart, "H2") # save the filewb.save("Surface.xlsx") Output: Code #4 : Plot the Surface 3D chartFor plotting the 3D Surface chart on an excel sheet, use SurfaceChart3D class from openpyxl.chart submodule. Python3 # import Workbook from openpyxlfrom openpyxl import Workbook # import SurfaceChart3D, Reference, Series from openpyxl.chart sub_module .from openpyxl.chart import SurfaceChart3D, Reference, Series # Call a Workbook() function of openpyxl# to create a new blank Workbook objectwb = Workbook() # Get workbook active sheet# from the active attribute.ws = wb.active # given datadata = [ [None, 10, 20, 30, 40, 50, ], [0.1, 15, 65, 105, 65, 15, ], [0.2, 35, 105, 170, 105, 35, ], [0.3, 55, 135, 215, 135, 55, ], [0.4, 75, 155, 240, 155, 75, ], [0.5, 80, 190, 245, 190, 80, ], [0.6, 75, 155, 240, 155, 75, ], [0.7, 55, 135, 215, 135, 55, ], [0.8, 35, 105, 170, 105, 35, ], [0.9, 15, 65, 105, 65, 15],] # write content of each row in 1st and 2nd# column of the active sheet respectively .for row in data: ws.append(row) # Create object of SurfaceChart3D classchart = SurfaceChart3D() # create data for plottinglabels = Reference(ws, min_col = 1, min_row = 2, max_row = 10)data = Reference(ws, min_col = 2, max_col = 6, min_row = 1, max_row = 10) # adding data to the Surface chart 3D objectchart.add_data(data, titles_from_data = True) # set labels in the chart objectchart.set_categories(labels) # set the title of the chartchart.title = "Surface Chart 3D" # set style of the chartchart.style = 26 # add chart to the sheet# the top-left corner of a chart# is anchored to cell H2 .ws.add_chart(chart, "H2") # save the filewb.save("Surface3D.xlsx") Output : anikaseth98 python-modules Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n19 May, 2021" }, { "code": null, "e": 1115, "s": 52, "text": "Prerequisite : Plotting charts in excel sheet using openpyxl module Set – 1 | Set – 2Openpyxl is a Python library using which one can perform multiple operations on excel files like reading, writing, arithmetic operations and plotting graphs. Charts are composed of at least one series of one or more data points. Series themselves are comprised of references to cell ranges. Let’s see how to plot Doughnot, Radar, Surface, 3D Surface Chart on an excel sheet using openpyxl.For plotting the charts on an excel sheet, firstly, create chart object of specific chart class( i.e SurfaceChart, RadarChart etc.). After creating chart objects, insert data in it and lastly, add that chart object in the sheet object. Let’s see how to plot different charts using realtime data.Code #1 : Plot the Doughnut ChartDoughnut charts are similar to pie charts except that they use a ring instead of a circle. They can also plot several series of data as concentric rings. For plotting the Doughnut chart on an excel sheet, use DoughnutChart class from openpyxl.chart submodule. " }, { "code": null, "e": 1123, "s": 1115, "text": "Python3" }, { "code": "# import Workbook from openpyxlfrom openpyxl import Workbook # import DoughnutChart, Reference from openpyxl.chart sub_module .from openpyxl.chart import DoughnutChart, Reference # import DataPoint from openpyxl.chart.series classfrom openpyxl.chart.series import DataPoint # Call a Workbook() function of openpyxl# to create a new blank Workbook objectwb = Workbook() # Get workbook active sheet# from the active attribute.ws = wb.active # data givendata = [ ['Pie', 2014], ['Plain', 40], ['Jam', 2], ['Lime', 20], ['Chocolate', 30],] # write content of each row in 1st and 2nd# column of the active sheet respectively .for row in data: ws.append(row) # Create object of DoughnutChart classchart = DoughnutChart() # create data for plottinglabels = Reference(ws, min_col = 1, min_row = 2, max_row = 5)data = Reference(ws, min_col = 2, min_row = 1, max_row = 5) # adding data to the Doughnut chart objectchart.add_data(data, titles_from_data = True) # set labels in the chart objectchart.set_categories(labels) # set the title of the chartchart.title = \"Doughnuts Chart\" # set style of the chartchart.style = 26 # add chart to the sheet# the top-left corner of a chart# is anchored to cell E1 .ws.add_chart(chart, \"E1\") # save the filewb.save(\"doughnut.xlsx\")", "e": 2401, "s": 1123, "text": null }, { "code": null, "e": 2411, "s": 2401, "text": "Output: " }, { "code": null, "e": 2769, "s": 2411, "text": " Code #2: Plot the Radar ChartData that is arranged in columns or rows on a worksheet can be plotted in a radar chart. Radar charts compare the aggregate values of multiple data series. It is effectively a projection of an area chart on a circular x-axis. For plotting the Radar chart on an excel sheet, use RadarChart class from openpyxl.chart submodule. " }, { "code": null, "e": 2777, "s": 2769, "text": "Python3" }, { "code": "# import Workbook from openpyxlfrom openpyxl import Workbook # import RadarChart, Reference from openpyxl.chart sub_module .from openpyxl.chart import RadarChart, Reference # Call a Workbook() function of openpyxl# to create a new blank Workbook objectwb = Workbook() # Get workbook active sheet# from the active attribute.ws = wb.active # data givendata = [ ['Month', \"Bulbs\", \"Seeds\", \"Flowers\", \"Trees & shrubs\"], ['Jan', 0, 2500, 500, 0, ], ['Feb', 0, 5500, 750, 1500], ['Mar', 0, 9000, 1500, 2500], ['Apr', 0, 6500, 2000, 4000], ['May', 0, 3500, 5500, 3500], ['Jun', 0, 0, 7500, 1500], ['Jul', 0, 0, 8500, 800], ['Aug', 1500, 0, 7000, 550], ['Sep', 5000, 0, 3500, 2500], ['Oct', 8500, 0, 2500, 6000], ['Nov', 3500, 0, 500, 5500], ['Dec', 500, 0, 100, 3000 ],] # write content of each row in 1st and 2nd# column of the active sheet respectively .for row in data: ws.append(row) # Create object of RadarChart classchart = RadarChart() # filled type of radar chartchart.type = \"filled\" # create data for plottinglabels = Reference(ws, min_col = 1, min_row = 2, max_row = 13)data = Reference(ws, min_col = 2, max_col = 5, min_row = 2, max_row = 13) # adding data to the Radar chart objectchart.add_data(data, titles_from_data = True) # set labels in the chart objectchart.set_categories(labels) # set the title of the chartchart.title = \"Radar Chart\" # set style of the chartchart.style = 26 # delete y axis from the chartchart.y_axis.delete = True # add chart to the sheet# the top-left corner of a chart# is anchored to cell G2 .ws.add_chart(chart, \"G2\") # save the filewb.save(\"Radar.xlsx\")", "e": 4414, "s": 2777, "text": null }, { "code": null, "e": 4424, "s": 4414, "text": "Output: " }, { "code": null, "e": 4847, "s": 4424, "text": " Code #3 : Plot The Surface ChartData that is arranged in columns or rows on a worksheet can be plotted in a surface chart. A surface chart is useful when you want to find optimum combinations between two sets of data. As in a topographic map, colors and patterns indicate areas that are in the same range of values. For plotting the Surface chart on an excel sheet, use SurfaceChart class from openpyxl.chart submodule. " }, { "code": null, "e": 4855, "s": 4847, "text": "Python3" }, { "code": "# import Workbook from openpyxlfrom openpyxl import Workbook # import SurfaceChart, Reference, Series from openpyxl.chart sub_module .from openpyxl.chart import SurfaceChart, Reference, Series # Call a Workbook() function of openpyxl# to create a new blank Workbook objectwb = Workbook() # Get workbook active sheet# from the active attribute.ws = wb.active # given datadata = [ [None, 10, 20, 30, 40, 50, ], [0.1, 15, 65, 105, 65, 15, ], [0.2, 35, 105, 170, 105, 35, ], [0.3, 55, 135, 215, 135, 55, ], [0.4, 75, 155, 240, 155, 75, ], [0.5, 80, 190, 245, 190, 80, ], [0.6, 75, 155, 240, 155, 75, ], [0.7, 55, 135, 215, 135, 55, ], [0.8, 35, 105, 170, 105, 35, ], [0.9, 15, 65, 105, 65, 15],] # write content of each row in 1st and 2nd# column of the active sheet respectively .for row in data: ws.append(row) # Create object of SurfaceChart classchart = SurfaceChart() # create data for plottinglabels = Reference(ws, min_col = 1, min_row = 2, max_row = 10)data = Reference(ws, min_col = 2, max_col = 6, min_row = 1, max_row = 10) # adding data to the Surface chart objectchart.add_data(data, titles_from_data = True) # set labels in the chart objectchart.set_categories(labels) # set the title of the chartchart.title = \"Surface Chart\" # set style of the chartchart.style = 26 # add chart to the sheet# the top-left corner of a chart# is anchored to cell H2 .ws.add_chart(chart, \"H2\") # save the filewb.save(\"Surface.xlsx\")", "e": 6313, "s": 4855, "text": null }, { "code": null, "e": 6323, "s": 6313, "text": "Output: " }, { "code": null, "e": 6468, "s": 6323, "text": "Code #4 : Plot the Surface 3D chartFor plotting the 3D Surface chart on an excel sheet, use SurfaceChart3D class from openpyxl.chart submodule. " }, { "code": null, "e": 6476, "s": 6468, "text": "Python3" }, { "code": "# import Workbook from openpyxlfrom openpyxl import Workbook # import SurfaceChart3D, Reference, Series from openpyxl.chart sub_module .from openpyxl.chart import SurfaceChart3D, Reference, Series # Call a Workbook() function of openpyxl# to create a new blank Workbook objectwb = Workbook() # Get workbook active sheet# from the active attribute.ws = wb.active # given datadata = [ [None, 10, 20, 30, 40, 50, ], [0.1, 15, 65, 105, 65, 15, ], [0.2, 35, 105, 170, 105, 35, ], [0.3, 55, 135, 215, 135, 55, ], [0.4, 75, 155, 240, 155, 75, ], [0.5, 80, 190, 245, 190, 80, ], [0.6, 75, 155, 240, 155, 75, ], [0.7, 55, 135, 215, 135, 55, ], [0.8, 35, 105, 170, 105, 35, ], [0.9, 15, 65, 105, 65, 15],] # write content of each row in 1st and 2nd# column of the active sheet respectively .for row in data: ws.append(row) # Create object of SurfaceChart3D classchart = SurfaceChart3D() # create data for plottinglabels = Reference(ws, min_col = 1, min_row = 2, max_row = 10)data = Reference(ws, min_col = 2, max_col = 6, min_row = 1, max_row = 10) # adding data to the Surface chart 3D objectchart.add_data(data, titles_from_data = True) # set labels in the chart objectchart.set_categories(labels) # set the title of the chartchart.title = \"Surface Chart 3D\" # set style of the chartchart.style = 26 # add chart to the sheet# the top-left corner of a chart# is anchored to cell H2 .ws.add_chart(chart, \"H2\") # save the filewb.save(\"Surface3D.xlsx\")", "e": 7950, "s": 6476, "text": null }, { "code": null, "e": 7961, "s": 7950, "text": "Output : " }, { "code": null, "e": 7975, "s": 7963, "text": "anikaseth98" }, { "code": null, "e": 7990, "s": 7975, "text": "python-modules" }, { "code": null, "e": 7997, "s": 7990, "text": "Python" } ]
Search an element in a Doubly Linked List
28 Mar, 2022 Given a Doubly linked list(DLL) containing N nodes and an integer X, the task is to find the position of the integer X in the doubly linked list. If no such position found then print -1. Examples: Input: 15 <=> 16 <=> 8 <=> 7 <=> 13, X = 8 Output: 3 Explanation: X (= 8) is present at the 3rd node of the doubly linked list. Therefore, the required output is 3 Input: 5 <=> 3 <=> 4 <=> 2 <=> 9, X = 0 Output: -1 Explanation: X (= 0) is not present in the doubly linked list. Therefore, the required output is -1 Approach: Follow the steps below to solve the problem: Initialize a variable, say pos, to store the position of the node containing data value X in the doubly linked list. Initialize a pointer, say temp, to store the head node of the doubly linked list. Iterate over the linked list and for every node, check if data value of that node is equal to X or not. If found to be true, then print pos. Otherwise, print -1. Below is the implementation of the above approach C++ Java C# Javascript Python3 // C++ program to implement// the above approach #include <bits/stdc++.h>using namespace std; // Structure of a node of// the doubly linked liststruct Node { // Stores data value // of a node int data; // Stores pointer // to next node Node* next; // Stores pointer // to previous node Node* prev;}; // Function to insert a node at the// beginning of the Doubly Linked Listvoid push(Node** head_ref, int new_data){ // Allocate memory for new node Node* new_node = (Node*)malloc(sizeof(struct Node)); // Insert the data new_node->data = new_data; // Since node is added at the // beginning, prev is always NULL new_node->prev = NULL; // Link the old list to the new node new_node->next = (*head_ref); // If pointer to head is not NULL if ((*head_ref) != NULL) { // Change the prev of head // node to new node (*head_ref)->prev = new_node; } // Move the head to point to the new node (*head_ref) = new_node;} // Function to find the position of// an integer in doubly linked listint search(Node** head_ref, int x){ // Stores head Node Node* temp = *head_ref; // Stores position of the integer // in the doubly linked list int pos = 0; // Traverse the doubly linked list while (temp->data != x && temp->next != NULL) { // Update pos pos++; // Update temp temp = temp->next; } // If the integer not present // in the doubly linked list if (temp->data != x) return -1; // If the integer present in // the doubly linked list return (pos + 1);} // Driver Codeint main(){ Node* head = NULL; int X = 8; // Create the doubly linked list // 18 <-> 15 <-> 8 <-> 9 <-> 14 push(&head, 14); push(&head, 9); push(&head, 8); push(&head, 15); push(&head, 18); cout << search(&head, X); return 0;} // Java program to implement// the above approachimport java.util.*;class GFG{ // Structure of a node of // the doubly linked list static class Node { // Stores data value // of a node int data; // Stores pointer // to next node Node next; // Stores pointer // to previous node Node prev; }; // Function to insert a node at the // beginning of the Doubly Linked List static Node push(Node head_ref, int new_data) { // Allocate memory for new node Node new_node = new Node(); // Insert the data new_node.data = new_data; // Since node is added at the // beginning, prev is always null new_node.prev = null; // Link the old list to the new node new_node.next = head_ref; // If pointer to head is not null if (head_ref != null) { // Change the prev of head // node to new node head_ref.prev = new_node; } // Move the head to point to the new node head_ref = new_node; return head_ref; } // Function to find the position of // an integer in doubly linked list static int search(Node head_ref, int x) { // Stores head Node Node temp = head_ref; // Stores position of the integer // in the doubly linked list int pos = 0; // Traverse the doubly linked list while (temp.data != x && temp.next != null) { // Update pos pos++; // Update temp temp = temp.next; } // If the integer not present // in the doubly linked list if (temp.data != x) return -1; // If the integer present in // the doubly linked list return (pos + 1); } // Driver Code public static void main(String[] args) { Node head = null; int X = 8; // Create the doubly linked list // 18 <-> 15 <-> 8 <-> 9 <-> 14 head = push(head, 14); head = push(head, 9); head = push(head, 8); head = push(head, 15); head = push(head, 18); System.out.print(search(head, X)); }} // This code is contributed by Rajput-Ji // C# program to implement// the above approachusing System; class GFG{ // Structure of a node of// the doubly linked listpublic class Node{ // Stores data value // of a node public int data; // Stores pointer // to next node public Node next; // Stores pointer // to previous node public Node prev;}; // Function to insert a node at the// beginning of the Doubly Linked Liststatic Node push(Node head_ref, int new_data){ // Allocate memory for new node Node new_node = new Node(); // Insert the data new_node.data = new_data; // Since node is added at the // beginning, prev is always null new_node.prev = null; // Link the old list to the new node new_node.next = head_ref; // If pointer to head is not null if (head_ref != null) { // Change the prev of head // node to new node head_ref.prev = new_node; } // Move the head to point to the new node head_ref = new_node; return head_ref;} // Function to find the position of// an integer in doubly linked liststatic int search(Node head_ref, int x){ // Stores head Node Node temp = head_ref; // Stores position of the integer // in the doubly linked list int pos = 0; // Traverse the doubly linked list while (temp.data != x && temp.next != null) { // Update pos pos++; // Update temp temp = temp.next; } // If the integer not present // in the doubly linked list if (temp.data != x) return -1; // If the integer present in // the doubly linked list return (pos + 1);} // Driver Codepublic static void Main(String[] args){ Node head = null; int X = 8; // Create the doubly linked list // 18 <-> 15 <-> 8 <-> 9 <-> 14 head = push(head, 14); head = push(head, 9); head = push(head, 8); head = push(head, 15); head = push(head, 18); Console.Write(search(head, X));}} // This code is contributed by gauravrajput1 <script> // Javascript program to implement// the above approach // Structure of a node of// the doubly linked listclass Node { constructor() { // Stores data value // of a node this.data = 0; // Stores pointer // to next node this.next = null; // Stores pointer // to previous node this.prev = null; }}; // Function to insert a node at the// beginning of the Doubly Linked Listfunction push(head_ref, new_data){ // Allocate memory for new node var new_node = new Node(); // Insert the data new_node.data = new_data; // Since node is added at the // beginning, prev is always null new_node.prev = null; // Link the old list to the new node new_node.next = (head_ref); // If pointer to head is not null if ((head_ref) != null) { // Change the prev of head // node to new node (head_ref).prev = new_node; } // Move the head to point to the new node (head_ref) = new_node; return head_ref;} // Function to find the position of// an integer in doubly linked listfunction search( head_ref, x){ // Stores head Node var temp = head_ref; // Stores position of the integer // in the doubly linked list var pos = 0; // Traverse the doubly linked list while (temp.data != x && temp.next != null) { // Update pos pos++; // Update temp temp = temp.next; } // If the integer not present // in the doubly linked list if (temp.data != x) return -1; // If the integer present in // the doubly linked list return (pos + 1);} // Driver Codevar head = null;var X = 8; // Create the doubly linked list// 18 <. 15 <. 8 <. 9 <. 14head = push(head, 14);head = push(head, 9);head = push(head, 8);head = push(head, 15);head = push(head, 18);document.write( search(head, X)); // This code is contributed by rrrtnx.</script> # Python program to implement# the above approach # Structure of a Node of# the doubly linked listclass Node: def __init__(self): self.data = 0; self.next = None; self.prev = None; # Function to insert a Node at the# beginning of the Doubly Linked Listdef push(head_ref, new_data): # Allocate memory for new Node new_Node = Node(); # Insert the data new_Node.data = new_data; # Since Node is added at the # beginning, prev is always None new_Node.prev = None; # Link the old list to the new Node new_Node.next = head_ref; # If pointer to head is not None if (head_ref != None): # Change the prev of head # Node to new Node head_ref.prev = new_Node; # Move the head to point to the new Node head_ref = new_Node; return head_ref; # Function to find the position of# an integer in doubly linked listdef search(head_ref, x): # Stores head Node temp = head_ref; # Stores position of the integer # in the doubly linked list pos = 0; # Traverse the doubly linked list while (temp.data != x and temp.next != None): # Update pos pos+=1; # Update temp temp = temp.next; # If the integer not present # in the doubly linked list if (temp.data != x): return -1; # If the integer present in # the doubly linked list return (pos + 1); # Driver Codeif __name__ == '__main__': head = None; X = 8; # Create the doubly linked list # 18 <-> 15 <-> 8 <-> 9 <-> 14 head = push(head, 14); head = push(head, 9); head = push(head, 8); head = push(head, 15); head = push(head, 18); print(search(head, X)); # This code is contributed by Rajput-Ji 3 Time Complexity: O(N)Auxiliary Space: O(1) Rajput-Ji GauravRajput1 rrrtnx surinderdawra388 Algorithms-Searching doubly linked list Technical Scripter 2020 Linked List Searching Technical Scripter Linked List Searching Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n28 Mar, 2022" }, { "code": null, "e": 239, "s": 52, "text": "Given a Doubly linked list(DLL) containing N nodes and an integer X, the task is to find the position of the integer X in the doubly linked list. If no such position found then print -1." }, { "code": null, "e": 249, "s": 239, "text": "Examples:" }, { "code": null, "e": 413, "s": 249, "text": "Input: 15 <=> 16 <=> 8 <=> 7 <=> 13, X = 8 Output: 3 Explanation: X (= 8) is present at the 3rd node of the doubly linked list. Therefore, the required output is 3" }, { "code": null, "e": 564, "s": 413, "text": "Input: 5 <=> 3 <=> 4 <=> 2 <=> 9, X = 0 Output: -1 Explanation: X (= 0) is not present in the doubly linked list. Therefore, the required output is -1" }, { "code": null, "e": 619, "s": 564, "text": "Approach: Follow the steps below to solve the problem:" }, { "code": null, "e": 736, "s": 619, "text": "Initialize a variable, say pos, to store the position of the node containing data value X in the doubly linked list." }, { "code": null, "e": 818, "s": 736, "text": "Initialize a pointer, say temp, to store the head node of the doubly linked list." }, { "code": null, "e": 959, "s": 818, "text": "Iterate over the linked list and for every node, check if data value of that node is equal to X or not. If found to be true, then print pos." }, { "code": null, "e": 980, "s": 959, "text": "Otherwise, print -1." }, { "code": null, "e": 1030, "s": 980, "text": "Below is the implementation of the above approach" }, { "code": null, "e": 1034, "s": 1030, "text": "C++" }, { "code": null, "e": 1039, "s": 1034, "text": "Java" }, { "code": null, "e": 1042, "s": 1039, "text": "C#" }, { "code": null, "e": 1053, "s": 1042, "text": "Javascript" }, { "code": null, "e": 1061, "s": 1053, "text": "Python3" }, { "code": "// C++ program to implement// the above approach #include <bits/stdc++.h>using namespace std; // Structure of a node of// the doubly linked liststruct Node { // Stores data value // of a node int data; // Stores pointer // to next node Node* next; // Stores pointer // to previous node Node* prev;}; // Function to insert a node at the// beginning of the Doubly Linked Listvoid push(Node** head_ref, int new_data){ // Allocate memory for new node Node* new_node = (Node*)malloc(sizeof(struct Node)); // Insert the data new_node->data = new_data; // Since node is added at the // beginning, prev is always NULL new_node->prev = NULL; // Link the old list to the new node new_node->next = (*head_ref); // If pointer to head is not NULL if ((*head_ref) != NULL) { // Change the prev of head // node to new node (*head_ref)->prev = new_node; } // Move the head to point to the new node (*head_ref) = new_node;} // Function to find the position of// an integer in doubly linked listint search(Node** head_ref, int x){ // Stores head Node Node* temp = *head_ref; // Stores position of the integer // in the doubly linked list int pos = 0; // Traverse the doubly linked list while (temp->data != x && temp->next != NULL) { // Update pos pos++; // Update temp temp = temp->next; } // If the integer not present // in the doubly linked list if (temp->data != x) return -1; // If the integer present in // the doubly linked list return (pos + 1);} // Driver Codeint main(){ Node* head = NULL; int X = 8; // Create the doubly linked list // 18 <-> 15 <-> 8 <-> 9 <-> 14 push(&head, 14); push(&head, 9); push(&head, 8); push(&head, 15); push(&head, 18); cout << search(&head, X); return 0;}", "e": 2977, "s": 1061, "text": null }, { "code": "// Java program to implement// the above approachimport java.util.*;class GFG{ // Structure of a node of // the doubly linked list static class Node { // Stores data value // of a node int data; // Stores pointer // to next node Node next; // Stores pointer // to previous node Node prev; }; // Function to insert a node at the // beginning of the Doubly Linked List static Node push(Node head_ref, int new_data) { // Allocate memory for new node Node new_node = new Node(); // Insert the data new_node.data = new_data; // Since node is added at the // beginning, prev is always null new_node.prev = null; // Link the old list to the new node new_node.next = head_ref; // If pointer to head is not null if (head_ref != null) { // Change the prev of head // node to new node head_ref.prev = new_node; } // Move the head to point to the new node head_ref = new_node; return head_ref; } // Function to find the position of // an integer in doubly linked list static int search(Node head_ref, int x) { // Stores head Node Node temp = head_ref; // Stores position of the integer // in the doubly linked list int pos = 0; // Traverse the doubly linked list while (temp.data != x && temp.next != null) { // Update pos pos++; // Update temp temp = temp.next; } // If the integer not present // in the doubly linked list if (temp.data != x) return -1; // If the integer present in // the doubly linked list return (pos + 1); } // Driver Code public static void main(String[] args) { Node head = null; int X = 8; // Create the doubly linked list // 18 <-> 15 <-> 8 <-> 9 <-> 14 head = push(head, 14); head = push(head, 9); head = push(head, 8); head = push(head, 15); head = push(head, 18); System.out.print(search(head, X)); }} // This code is contributed by Rajput-Ji", "e": 5046, "s": 2977, "text": null }, { "code": "// C# program to implement// the above approachusing System; class GFG{ // Structure of a node of// the doubly linked listpublic class Node{ // Stores data value // of a node public int data; // Stores pointer // to next node public Node next; // Stores pointer // to previous node public Node prev;}; // Function to insert a node at the// beginning of the Doubly Linked Liststatic Node push(Node head_ref, int new_data){ // Allocate memory for new node Node new_node = new Node(); // Insert the data new_node.data = new_data; // Since node is added at the // beginning, prev is always null new_node.prev = null; // Link the old list to the new node new_node.next = head_ref; // If pointer to head is not null if (head_ref != null) { // Change the prev of head // node to new node head_ref.prev = new_node; } // Move the head to point to the new node head_ref = new_node; return head_ref;} // Function to find the position of// an integer in doubly linked liststatic int search(Node head_ref, int x){ // Stores head Node Node temp = head_ref; // Stores position of the integer // in the doubly linked list int pos = 0; // Traverse the doubly linked list while (temp.data != x && temp.next != null) { // Update pos pos++; // Update temp temp = temp.next; } // If the integer not present // in the doubly linked list if (temp.data != x) return -1; // If the integer present in // the doubly linked list return (pos + 1);} // Driver Codepublic static void Main(String[] args){ Node head = null; int X = 8; // Create the doubly linked list // 18 <-> 15 <-> 8 <-> 9 <-> 14 head = push(head, 14); head = push(head, 9); head = push(head, 8); head = push(head, 15); head = push(head, 18); Console.Write(search(head, X));}} // This code is contributed by gauravrajput1", "e": 7135, "s": 5046, "text": null }, { "code": "<script> // Javascript program to implement// the above approach // Structure of a node of// the doubly linked listclass Node { constructor() { // Stores data value // of a node this.data = 0; // Stores pointer // to next node this.next = null; // Stores pointer // to previous node this.prev = null; }}; // Function to insert a node at the// beginning of the Doubly Linked Listfunction push(head_ref, new_data){ // Allocate memory for new node var new_node = new Node(); // Insert the data new_node.data = new_data; // Since node is added at the // beginning, prev is always null new_node.prev = null; // Link the old list to the new node new_node.next = (head_ref); // If pointer to head is not null if ((head_ref) != null) { // Change the prev of head // node to new node (head_ref).prev = new_node; } // Move the head to point to the new node (head_ref) = new_node; return head_ref;} // Function to find the position of// an integer in doubly linked listfunction search( head_ref, x){ // Stores head Node var temp = head_ref; // Stores position of the integer // in the doubly linked list var pos = 0; // Traverse the doubly linked list while (temp.data != x && temp.next != null) { // Update pos pos++; // Update temp temp = temp.next; } // If the integer not present // in the doubly linked list if (temp.data != x) return -1; // If the integer present in // the doubly linked list return (pos + 1);} // Driver Codevar head = null;var X = 8; // Create the doubly linked list// 18 <. 15 <. 8 <. 9 <. 14head = push(head, 14);head = push(head, 9);head = push(head, 8);head = push(head, 15);head = push(head, 18);document.write( search(head, X)); // This code is contributed by rrrtnx.</script>", "e": 9091, "s": 7135, "text": null }, { "code": "# Python program to implement# the above approach # Structure of a Node of# the doubly linked listclass Node: def __init__(self): self.data = 0; self.next = None; self.prev = None; # Function to insert a Node at the# beginning of the Doubly Linked Listdef push(head_ref, new_data): # Allocate memory for new Node new_Node = Node(); # Insert the data new_Node.data = new_data; # Since Node is added at the # beginning, prev is always None new_Node.prev = None; # Link the old list to the new Node new_Node.next = head_ref; # If pointer to head is not None if (head_ref != None): # Change the prev of head # Node to new Node head_ref.prev = new_Node; # Move the head to point to the new Node head_ref = new_Node; return head_ref; # Function to find the position of# an integer in doubly linked listdef search(head_ref, x): # Stores head Node temp = head_ref; # Stores position of the integer # in the doubly linked list pos = 0; # Traverse the doubly linked list while (temp.data != x and temp.next != None): # Update pos pos+=1; # Update temp temp = temp.next; # If the integer not present # in the doubly linked list if (temp.data != x): return -1; # If the integer present in # the doubly linked list return (pos + 1); # Driver Codeif __name__ == '__main__': head = None; X = 8; # Create the doubly linked list # 18 <-> 15 <-> 8 <-> 9 <-> 14 head = push(head, 14); head = push(head, 9); head = push(head, 8); head = push(head, 15); head = push(head, 18); print(search(head, X)); # This code is contributed by Rajput-Ji", "e": 10834, "s": 9091, "text": null }, { "code": null, "e": 10836, "s": 10834, "text": "3" }, { "code": null, "e": 10881, "s": 10838, "text": "Time Complexity: O(N)Auxiliary Space: O(1)" }, { "code": null, "e": 10891, "s": 10881, "text": "Rajput-Ji" }, { "code": null, "e": 10905, "s": 10891, "text": "GauravRajput1" }, { "code": null, "e": 10912, "s": 10905, "text": "rrrtnx" }, { "code": null, "e": 10929, "s": 10912, "text": "surinderdawra388" }, { "code": null, "e": 10950, "s": 10929, "text": "Algorithms-Searching" }, { "code": null, "e": 10969, "s": 10950, "text": "doubly linked list" }, { "code": null, "e": 10993, "s": 10969, "text": "Technical Scripter 2020" }, { "code": null, "e": 11005, "s": 10993, "text": "Linked List" }, { "code": null, "e": 11015, "s": 11005, "text": "Searching" }, { "code": null, "e": 11034, "s": 11015, "text": "Technical Scripter" }, { "code": null, "e": 11046, "s": 11034, "text": "Linked List" }, { "code": null, "e": 11056, "s": 11046, "text": "Searching" } ]
Serializer Relations – Django REST Framework
16 Feb, 2021 Serialization is one of the most important concepts in RESTful Webservices. It facilitates the conversion of complex data (such as model instances) to native Python data types that can be rendered using JSON, XML, or other content types. In Django REST Framework, we have different types of serializers to serialize object instances, and the serializers have different serializer relations to represent model relationships. In this section, we will discuss the different serializer relations provided by Django REST Framework Serializers. Table of Contents Getting Started Creating Django Models and Views PrimaryKeyRelatedField StringRelatedField SlugRelatedField HyperlinkedIndetityField HyperlinkedRelatedField Nested Relationship Before working on Django REST Framework serializers, you should make sure that you already installed Django and Django REST Framework in your virtual environment. You can check the below tutorials: Create virtual environment using venv | Python Django Installation Django REST Framework Installation Next, you can create a project named emt (employee management tool) and an app named employees. Refer to the following articles to check how to create a project and an app in Django. How to Create a Basic Project using MVT in Django? How to Create an App in Django? In this section, we will be using PostgreSQL. You have to create a database named emt in PostgreSQL. You can check the below link for installation. Install PostgreSQL on Windows Note: if you need to work with SQLite, you can continue using the default database. To make use of PostgreSQL, we need to install a Python-PostgreSQL Database Adapter (psycopg2). This package helps Django to interact with a PostgreSQL database. You can use the below command to install the psycopg2 package. Make sure the PostgreSQL bin folder is included in the PATH environmental variables, and the virtual environment is activated before executing the command. pip install psycopg2 Now, you need to configure the PostgreSQL database in your Django project. By default, the database configuration has an SQLite database engine and database file name. You can check the setting.py Python file and replace the default database configuration with the PostgreSQL database configuration. DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'emt', 'USER': 'username', 'PASSWORD': 'password', 'HOST': '127.0.0.1', 'PORT': '5432', } } Here, the name refers to the database name, the user and the password refers to the Postgres username and password. At last, we need to install the httpie package in our virtual environment. We will be composing HTTPie commands for CRUD operation. You can activate the virtual environment and run the below command pip install –upgrade httpie In Django, Models are classes that deal with databases in an object-oriented way. Each model class refers to a database table and each attribute in the model class refers to a database column. Here, we will create an Employee model and EmployeeTask model in Django. The EmployeeTask model holds a ManyToOne relationship with the Employee model We require the following attributes for our Employee entity: emp_id name gender designation The attributes for our EmployeeTask model as follows: task_name employee (foreign key – Employee) task_desc created_date deadline Let’s get into the implementation of the Employee model in Django. You can replace the models.py Python file with the below code: Python3 GENDER_CHOICES = (('M','Male'), ('F','Female'),) class Employee(models.Model): emp_id = models.IntegerField() name = models.CharField(max_length=150) gender = models.CharField(max_length=1, choices=GENDER_CHOICES, default='M') designation = models.CharField(max_length=150) class Meta: ordering=('emp_id',) def __str__(self): return self.name The Employee model is a subclass of the django.db.models.Model class and defines the attributes and a Meta inner class. It has an ordering attribute that orders the result in an ascending order based on employee id. Next, let get into the implementation of EmployeeTask Model. You can add the below code to the models.py file. Python3 class EmployeeTask(models.Model): task_name = models.CharField(max_length=150) employee = models.ForeignKey(Employee, related_name='tasks', on_delete=models.CASCADE) task_desc = models.CharField(max_length=350) created_date = models.DateTimeField(auto_now_add=True) deadline = models.DateTimeField() class Meta: ordering = ('task_name',) def __str__(self): return self.task_name The EmployeeTask model is a subclass of the django.db.models.Model class and defines the attributes and a Meta inner class. It has an ordering attribute that orders the result in an ascending order based on task_name. It has an employee field that holds a many-to-one relationship with the Employee model. employee = models.ForeignKey(Employee, related_name='tasks', on_delete=models.CASCADE) The related_name helps in a reverse relationship. Reverse relationship means referring from Employee to EmployeeTask. The employee field represents the Employee model in the EmployeeTaks. Likewise, the related_name represents the EmployeeTask in the Employee model. Reverse relations are not automatically included by the serializer class. We must explicitly add it to the field list. If you set an appropriate related_name argument on the relationship, then you can use it as a field name (You will be able to understand reverse relation while serializing the Models). Let’s make the initial migrations using the below command. python manage.py makemigrations If the migration is a success then apply all generated migrations using the below command: python manage.py migrate If successful you can check your database entries. Now, let’s create the Django views. Django views facilitate processing the HTTP requests and providing HTTP responses. On receiving an HTTP request, Django creates an HttpRequest instance and it is passed as the first argument to the view function. The view function checks the value and executes the code based on the HTTP verb. Here the code uses @csrf_exempt decorator to set a CSRF (Cross-Site Request Forgery) cookie. This makes it possible to POST to this view from clients that won’t have a CSRF token. You can add the below code to your view.py file. Python3 from django.shortcuts import renderfrom django.http import HttpResponse, JsonResponsefrom django.views.decorators.csrf import csrf_exempt from rest_framework.renderers import JSONRendererfrom rest_framework.parsers import JSONParser from employees.models import Employee, EmployeeTaskfrom employees.serializers import EmployeeSerializer, EmployeeTaskSerializer @csrf_exemptdef employee_list(request): if request.method == 'GET': emp = Employee.objects.all() emp_serializer = EmployeeSerializer(emp, many=True) return JsonResponse(emp_serializer.data, safe=False) elif request.method == 'POST': emp_data = JSONParser().parse(request) emp_serializer = EmployeeSerializer(data=emp_data) if emp_serializer.is_valid(): emp_serializer.save() return JsonResponse(emp_serializer.data, status=201) return JsonResponse(emp_serializer.errors, status=400) @csrf_exemptdef employee_detail(request, pk): try: emp = Employee.objects.get(pk=pk) except Employee.DoesNotExist: return HttpResponse(status=404) if request.method == 'GET': emp_serializer = EmployeeSerializer(emp) return JsonResponse(emp_serializer.data) elif request.method == 'DELETE': emp.delete() return HttpResponse(status=204) @csrf_exemptdef employeetask_list(request): if request.method == 'GET': emptask = EmployeeTask.objects.all() emptask_serializer = EmployeeTaskSerializer(emptask, many=True) return JsonResponse(emptask_serializer.data, safe=False) elif request.method == 'POST': emptask_data = JSONParser().parse(request) emptask_serializer = EmployeeTaskSerializer(data=emptask_data) if emptask_serializer.is_valid(): emptask_serializer.save() return JsonResponse(emptask_serializer.data, status=201) return JsonResponse(emptask_serializer.errors, status=400) @csrf_exemptdef employeetask_detail(request, pk): try: emptask = EmployeeTask.objects.get(pk=pk) except EmployeeTask.DoesNotExist: return HTTPResponse(status=404) if request.method == 'GET': emptask_serializer = EmployeeTaskSerializer(emptask) return JsonResponse(emptask_serializer.data) elif request.method == 'DELETE': emptask.delete() return HttpResponse(status=204) Here, we have different functions to process requests related to the Employee model and EmployeeTask model — employee_list, employeetask_list, and employee_detail and employeetask_detail. The employee_list and employeetask_list functions are capable of processing requests to retrieve all employees and employee’s tasks or to create a new employee and create a new employee task. The employee_detail and employeetask_detail functions are capable of processing requests such as retrieve a particular entry and delete an entry. Now, it’s necessary to route URLs to view. You need to create a new Python file name urls.py in the app (employees) folder and add the below code. Python3 from django.urls import pathfrom employees import views urlpatterns = [ path('employees/', views.employee_list, name = 'employee-list'), path('employees/<int:pk>/', views.employee_detail, name='employee-detail'), path('task/', views.employeetask_list, name = 'employeetask-list'), path('task/<int:pk>/', views.employeetask_detail, name='employeetask-detail'), Based on the matching path the URLs are routed to corresponding views. Next, we have to replace the code in the urls.py file in the root folder (emt\emt\urls.py). At present, it has the root URL configurations. Update the urls.py file with the below code. Python3 from django.urls import path, include urlpatterns = [ path('', include('employees.urls')),] PrimaryKeyRelatedField represents the target of the relation using the primary key (pk). It can be achieved by generating the relationship using the rest_framework.serializers.PrimaryKeyRelatedField() field. By default, this field is read-write, but you can make it read-only by setting the read_only attribute to True. The PrimaryKeyRelatedField has the following arguments: queryset – It used for model instance lookups when validating the field input. Relationships must either set a queryset explicitly (serializers.PrimaryKeyRelatedField(queryset=Employee.objects.all(),many=False) ), or set read_only=True. many – Set this argument to True to serialize more than one relationship allow_null – If set to True, the field will accept values of None or the empty string for nullable relationships. Defaults to False. pk_field – Set to a field to control serialization/deserialization of the primary key’s value. For example, pk_field=UUIDField(format=’hex’) would serialize a UUID primary key into its compact hex representation. Now let’s get to our serializer code. Here we have two serializer classes — EmployeeSerializer and EmployeeTaskSerializer. The EmployeeSerializer class serializes the Employee model and the EmployeeTaskSerializer serializes the EmployeeTask model. The EmployeeTask Model holds a ManyToOne relationship with the Employee Model. employee = models.ForeignKey(Employee, related_name='tasks', on_delete=models.CASCADE) The same task will not be assigned to more than one employee, but one employee can have multiple tasks. Hence, the EmployeeTaskSerializer class should serialize only a single employee instance, whereas, EmployeeSerializer class should serialize one or more EmployeeTask instances (more than one task can be assigned to an employee). The relationship generator process in EmployeeTaskSerializer as follows: employee = serializers.PrimaryKeyRelatedField(queryset=Employee.objects.all(), many=False) By default, the PrimaryKeyRelatedField field has read-write permission. The queryset=Employee.objects.all() argument checks for the particular model instance in the Employee table. The many=False argument is set because there is only a single relationship to serialize. The relationship generator process in EmployeeSerializer class as follows: tasks = serializers.PrimaryKeyRelatedField(many=True, read_only=True) The tasks attribute is the related_name specified (ForeignKey relationship) in the EmployeeTask model. Since each employee can have more than one task we set many=True. The read_only=True only allows permission to retrieve the EmployeeTask. You can add the below code to the serializers.py file. (if you don’t have the file, you can create a file named serializers.py file in your app [employees] folder). Python3 from rest_framework import serializersfrom employees.models import Employee, EmployeeTask class EmployeeSerializer(serializers.ModelSerializer): # PrimaryKeyRelatedField tasks = serializers.PrimaryKeyRelatedField(many=True, read_only=True) class Meta: model = Employee fields = ( 'pk', 'emp_id', 'name', 'gender', 'designation', 'tasks') class EmployeeTaskSerializer(serializers.ModelSerializer): # PrimaryKeyRelatedField employee = serializers.PrimaryKeyRelatedField(queryset=Employee.objects.all(), many=False) class Meta: model = EmployeeTask fields = ( 'pk', 'task_name', 'employee', 'task_desc', 'created_date', 'deadline') Let’s populate the employee table. You can execute the below HTTPie command. http POST :8000/employees/ emp_id=128 name=”Mathew A” gender=”M” designation=”Software Engineer” Output HTTP/1.1 201 Created Content-Length: 140 Content-Type: application/json Date: Thu, 21 Jan 2021 09:16:50 GMT Referrer-Policy: same-origin Server: WSGIServer/0.2 CPython/3.7.5 X-Content-Type-Options: nosniff X-Frame-Options: DENY { "designation": "Software Engineer", "emp_id": 128, "gender": "M", "name": "Mathew A", "pk": 8, "tasks": [] } You can notice the pk value of the employee. Now, let’s create an employee task and map it to the employee using PrimaryKeyRelatedField. Here the primary key value of the employee named Mathew A is 8. You have to pass it to the field name employee. Execute the below HTTPie command. http :8000/task/ task_name=”Interchange first and last elements in a list” employee=8 task_desc=”Write a Python program to interchange first and last element in a list” deadline=”2021-01-25 00:00:00.000000+00:00′′ Output HTTP/1.1 201 Created Content-Length: 285 Content-Type: application/json Date: Thu, 21 Jan 2021 09:42:39 GMT Referrer-Policy: same-origin Server: WSGIServer/0.2 CPython/3.7.5 X-Content-Type-Options: nosniff X-Frame-Options: DENY { "created_date": "2021-01-21T09:42:39.792788Z", "deadline": "2021-01-25T00:00:00Z", "employee": 8, "task_desc": "Write a Python program to interchange first and last element in a list", "task_name": "Interchange first and last elements in a list" } You can create one more task and assign it to the same employee and process the request to retrieve the employee details. The HTTPie command is http :8000/employees/ Output HTTP/1.1 200 OK Content-Length: 219 Content-Type: application/json Date: Fri, 22 Jan 2021 03:58:01 GMT Referrer-Policy: same-origin Server: WSGIServer/0.2 CPython/3.7.5 X-Content-Type-Options: nosniff X-Frame-Options: DENY [ { "designation": "Software Engineer", "emp_id": 128, "gender": "M", "name": "Mathew A", "pk": 8, "tasks": [ 2, 1 ] }, { "designation": "Test Engineer", "emp_id": 129, "gender": "F", "name": "Jeena R", "pk": 9, "tasks": [] } ] Sharing the command prompt screenshot for your reference You can notice the tasks field for the employee named Mathew A. It displays the pk of the task model and the many=True argument serialized multiple task instance id. Let’s retrieve the task details using the below HTTPie command http :8000/task/ Output HTTP/1.1 200 OK Content-Length: 454 Content-Type: application/json Date: Fri, 22 Jan 2021 03:59:40 GMT Referrer-Policy: same-origin Server: WSGIServer/0.2 CPython/3.7.5 X-Content-Type-Options: nosniff X-Frame-Options: DENY [ { "created_date": "2021-01-21T09:48:47.710707Z", "deadline": "2021-01-27T00:00:00Z", "employee": 8, "pk": 2, "task_desc": "Write a Python program for Binary Search", "task_name": "Binary Search" }, { "created_date": "2021-01-21T09:42:39.792788Z", "deadline": "2021-01-25T00:00:00Z", "employee": 8, "pk": 1, "task_desc": "Write a Python program to interchange first and last element in a list", "task_name": "Interchange first and last elements in a list" } ] Sharing the command prompt screenshot for your reference Let’s look at the HTTPie command to create a new task. http :8000/task/ task_name=”PrimaryKeyRelatedField” employee=8 task_desc=”Serialize relationship using PrimaryKeyRelateField” deadline=”2021-01-27 00:00:00.000000+00:00′′ Output HTTP/1.1 201 Created Content-Length: 213 Content-Type: application/json Date: Fri, 22 Jan 2021 04:33:15 GMT Referrer-Policy: same-origin Server: WSGIServer/0.2 CPython/3.7.5 X-Content-Type-Options: nosniff X-Frame-Options: DENY { "created_date": "2021-01-22T04:33:15.855264Z", "deadline": "2021-01-27T00:00:00Z", "employee": 8, "pk": 6, "task_desc": "Serialize relationship using PrimaryKeyRelateField", "task_name": "PrimaryKeyRelatedField" } Sharing the command prompt screenshot for your reference: Now let’s explore how StringRelatedField represents a relationship. The StringRelatedField represents the target of the relationship using its __str__ method. This field is read-only and set the ‘many’ argument to true If more than one instance to serialize. Let’s make use of StringRelatedField for tasks filed in EmployeeSerializer class. The relationship generator process as follows: tasks = serializers.StringRelatedField(many=True) The EmployeeSerializer class as follows: Python3 class EmployeeSerializer(serializers.ModelSerializer): # StringRelatedField tasks = serializers.StringRelatedField(many=True) class Meta: model = Employee fields = ( 'pk', 'emp_id', 'name', 'gender', 'designation', 'tasks') Let’s retrieve the employee details to understand how the StringRelatedField displays the relationship field values. The HTTPie command to retrieve the employee values is: http :8000/employees/ Output HTTP/1.1 200 OK Content-Length: 279 Content-Type: application/json Date: Fri, 22 Jan 2021 04:04:08 GMT Referrer-Policy: same-origin Server: WSGIServer/0.2 CPython/3.7.5 X-Content-Type-Options: nosniff X-Frame-Options: DENY [ { "designation": "Software Engineer", "emp_id": 128, "gender": "M", "name": "Mathew A", "pk": 8, "tasks": [ "Binary Search", "Interchange first and last elements in a list" ] }, { "designation": "Test Engineer", "emp_id": 129, "gender": "F", "name": "Jeena R", "pk": 9, "tasks": [] } ] Sharing the command prompt screenshot for your reference Here you can notice that the tasks field displays the string value from the function def __str__(self): in the EmployeeTask model. def __str__(self): return self.task_name The SlugRelatedField represents the target of the relationship using a field on the target. By default, the field permits read-write operation. For write operations, the slug field that represents a model field should be unique. The SlugRelatedField has the following arguments: slug_field – A field on the target and it should uniquely identify any given instance. queryset – It facilitates model instance lookups when validating the field input. Relationships must either set a queryset explicitly, or set read_only=True. many – Set this argument to True to serialize more than one relationship allow_null – If set to True, the field will accept values of None or the empty string for nullable relationships. Defaults to False. In the EmployeeTaskSerializer class, you can replace the employee field representation with the below code: employee = serializers.SlugRelatedField( queryset=Employee.objects.all(), slug_field='name') The EmployeeTaskSerializer code as follows: Python3 class EmployeeTaskSerializer(serializers.ModelSerializer): # SlugRelatedField employee = serializers.SlugRelatedField( queryset=Employee.objects.all(), slug_field='name') class Meta: model = EmployeeTask fields = ( 'pk', 'task_name', 'employee', 'task_desc', 'created_date', 'deadline') The HTTPie command to create a new employee task is http :8000/task/ task_name=”SlugRelatedField” employee=”Mathew A” task_desc=”Serialize relationship using SlugRelateField” deadline=”2021-01-27 00:00:00.000000+00:00′′ Output HTTP/1.1 201 Created Content-Length: 210 Content-Type: application/json Date: Fri, 22 Jan 2021 04:41:12 GMT Referrer-Policy: same-origin Server: WSGIServer/0.2 CPython/3.7.5 X-Content-Type-Options: nosniff X-Frame-Options: DENY { "created_date": "2021-01-22T04:41:12.424001Z", "deadline": "2021-01-27T00:00:00Z", "employee": "Mathew A", "pk": 7, "task_desc": "Serialize relationship using SlugRelateField", "task_name": "SlugRelatedField" } Sharing the command prompt screenshot for your reference Here, while creating a new task, we have given the employee name in the employee field rather than the primary key. You can also mention employee id while representing SlugRelatedField. You should make sure that it satisfies the unique constraint. For Hyperlinking the API, the serializer class should extend HyperlinkedModelSerializer. The HyperlinkedModelSerializer class makes use of hyperlinks to represent relationships, instead of primary keys. By default, the serializer class that is inherited from HyperlinkedModelSerializer class will include a url field instead of a primary key field. The url field will be represented using a HyperlinkedIdentityField serializer field. It can also be used for an attribute on the object. The HyperlinkedIdentityField is always read-only. The arguments of HyperlinkedIdentitField are: view_name – The view name is used as the target of the relationship. In standard router classes, this will be a string with the format <model_name>-detail. lookup_field – The field on the target, which is used for the lookup. It corresponds to a URL keyword argument on the referenced view. Default is ‘pk’. lookup_url_kwarg – The name of the keyword argument defined in the URL conf that corresponds to the lookup field. Defaults to using the same value as lookup_field. format – If using format suffixes, hyperlinked fields will use the same format suffix for the target unless overridden by using the format argument. In the EmployeeTaskSerializer class, you can use represent the url field as shown below: url = serializers.HyperlinkedIdentityField( view_name='employeetask-detail', lookup_field='pk' ) Note: By default, the serializer class that is inherited from HyperlinkedModelSerializer class will include a url field, and the view name will be a string with the format <model_name>-detail. The EmployeeTaskSerializer class as follows: Python3 class EmployeeTaskSerializer(serializers.HyperlinkedModelSerializer): url = serializers.HyperlinkedIdentityField( view_name='employeetask-detail', lookup_field='pk' ) employee = serializers.SlugRelatedField( queryset=Employee.objects.all(), slug_field='name') class Meta: model = EmployeeTask fields = '__all__' When instantiating a HyperlinkedModelSerializer, it is a must to include the current request in the serializer context. You need to pass context={‘request’:request} as an argument when instantiating your EmployeeTaskSerializer. For example: emp_serializer = EmployeeSerializer(emp, many=True, context={'request':request}) Make sure you edit your employee_list and employee_detail function in the views.py file with the above code. You should add context={‘request’:request} argument while instantiating EmployeeTaskSerializer (GET, POST, PUT and PATCH). Note: Note: This context along with the lookup_field is used for generating a fully qualified url by HyperlinkedIdentityField Let’s retrieve the EmployeeTask values to understand how the values are displayed. The HTTPie command is http GET :8000/task/1/ Output HTTP/1.1 200 OK Content-Length: 296 Content-Type: application/json Date: Fri, 22 Jan 2021 16:16:42 GMT Referrer-Policy: same-origin Server: WSGIServer/0.2 CPython/3.7.5 X-Content-Type-Options: nosniff X-Frame-Options: DENY { "created_date": "2021-01-21T09:42:39.792788Z", "deadline": "2021-01-25T00:00:00Z", "employee": "Mathew A", "task_desc": "Write a Python program to interchange first and last element in a list", "task_name": "Interchange first and last elements in a list", "url": "http://localhost:8000/task/1/" } Sharing the command prompt screenshot for your reference If we analyze the output, we can notice that instead of the primary key it displays url field. "url": "http://localhost:8000/task/1/" HyperlinkedRelatedField is used to represent the target of the relationship using a Hyperlink. By default, this field is a read-write, but we can make it read-only by setting the read-only flag True. The arguments of HyperlinkedRelatedField are as follows: view_name – The view name is used as the target of the relationship. For standard router classes, this will be a string with the format <modelname>-detail. queryset – It facilitates model instance lookups when validating the field input. Relationships must either set a queryset explicitly or set read_only=True. many – To serialize more than one relation, you should set this argument to True. allow_null – If set to True, the field will accept None values or the empty string for nullable relationships. Defaults to False. lookup_field – The field on the target is used for the lookup. It corresponds to a URL keyword argument on the referenced view. Default is ‘pk’. lookup_url_kwarg – The name of the keyword argument defined in the URL conf that corresponds to the lookup field. By default, it uses the same value as lookup_field. format – If using format suffixes, hyperlinked fields will use the same format suffix for the target unless overridden by using the format argument. In our reverse relationship (Employee to EmployeeTask) we have seen that by default the serializer (EmployeeSerializer) uses the primary key to represent the target of a relationship (to include a reverse relationship, you must explicitly add it to the field list). We have also explored other representations such as StringRelatedField and SlugRelatedField. Here, we will make use of HyperlinkedRelatedField. In the EmployeeSerializer class, you can use represent the tasks field as shown below: tasks = serializers.HyperlinkedRelatedField(many=True, read_only=True, view_name='employeetask-detail') You can replace the existing EmployeeSerializer class with the below one: Python3 class EmployeeSerializer(serializers.HyperlinkedModelSerializer): url = serializers.HyperlinkedIdentityField( view_name='employee-detail', lookup_field='pk' ) tasks = serializers.HyperlinkedRelatedField(many=True, read_only=True, view_name='employeetask-detail') class Meta: model = Employee fields = ( 'url', 'pk', 'emp_id', 'name', 'gender', 'designation', 'tasks') The HTTPie command is: http GET :8000/employees/8/ Output HTTP/1.1 200 OK Content-Length: 283 Content-Type: application/json Date: Fri, 22 Jan 2021 16:18:59 GMT Referrer-Policy: same-origin Server: WSGIServer/0.2 CPython/3.7.5 X-Content-Type-Options: nosniff X-Frame-Options: DENY { "designation": "Software Engineer", "emp_id": 128, "gender": "M", "name": "Mathew A", "pk": 8, "tasks": [ "http://localhost:8000/task/2/", "http://localhost:8000/task/1/", "http://localhost:8000/task/6/", "http://localhost:8000/task/7/" ], "url": "http://localhost:8000/employees/8/" } Sharing the command prompt screenshot for your reference If we analyze the output, we can notice that the tasks field displays a set, or hyperlinks. "tasks": [ "http://localhost:8000/task/2/", "http://localhost:8000/task/1/", "http://localhost:8000/task/6/", "http://localhost:8000/task/7/" ] Next, let’s understand how the nested relationship can be expressed by using serializers as fields. A nested relationship makes it possible to embed the referred entity. If we look at the case of EmployeeTask, it refers to the Employee. Let’s serialize the EmployeeTask using a nested relationship. You can use the below code to refer to the employee field in the EmployeeTaskSerializer: employee = EmployeeSerializer(read_only=True) You can replace the EmployeeTaskSerializer with the below code: Python3 class EmployeeTaskSerializer(serializers.HyperlinkedModelSerializer): url = serializers.HyperlinkedIdentityField( view_name='employeetask-detail', lookup_field='pk' ) employee = EmployeeSerializer(read_only=True) class Meta: model = EmployeeTask fields = '__all__' Let’s retrieve an EmployeeTask entry. The HTTPie command is http GET :8000/task/1/ Output HTTP/1.1 200 OK Content-Length: 569 Content-Type: application/json Date: Fri, 22 Jan 2021 16:33:51 GMT Referrer-Policy: same-origin Server: WSGIServer/0.2 CPython/3.7.5 X-Content-Type-Options: nosniff X-Frame-Options: DENY { "created_date": "2021-01-21T09:42:39.792788Z", "deadline": "2021-01-25T00:00:00Z", "employee": { "designation": "Software Engineer", "emp_id": 128, "gender": "M", "name": "Mathew A", "pk": 8, "tasks": [ "http://localhost:8000/task/2/", "http://localhost:8000/task/1/", "http://localhost:8000/task/6/", "http://localhost:8000/task/7/" ], "url": "http://localhost:8000/employees/8/" }, "task_desc": "Write a Python program to interchange first and last element in a list", "task_name": "Interchange first and last elements in a list", "url": "http://localhost:8000/task/1/" } Sharing the command prompt screenshot for your reference You can notice that the employee field displays the complete employee details rather than just the primary key or slug. "employee": { "designation": "Software Engineer", "emp_id": 128, "gender": "M", "name": "Mathew A", "pk": 8, "tasks": [ "http://localhost:8000/task/2/", "http://localhost:8000/task/1/", "http://localhost:8000/task/6/", "http://localhost:8000/task/7/" ], "url": "http://localhost:8000/employees/8/" }, In this section, we explored various types of relational fields provided by DRF serializer relations. We understood how each relational fields represent the relationship with the target. The PrimaryKeyRelatedField represents the target of the relationship using its primary key whereas, the StringRelatedField uses the __str__ method of the target. In the case of SlugRelatedField, it represents the target of the relationship using a target field. Finally, the HyperlinkedIdentityField is used as an identity relationship, and the HyperlinkedRealtedField represents the target of the relationship using a hyperlink. Django-REST Python Django Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n16 Feb, 2021" }, { "code": null, "e": 569, "s": 28, "text": "Serialization is one of the most important concepts in RESTful Webservices. It facilitates the conversion of complex data (such as model instances) to native Python data types that can be rendered using JSON, XML, or other content types. In Django REST Framework, we have different types of serializers to serialize object instances, and the serializers have different serializer relations to represent model relationships. In this section, we will discuss the different serializer relations provided by Django REST Framework Serializers. " }, { "code": null, "e": 587, "s": 569, "text": "Table of Contents" }, { "code": null, "e": 603, "s": 587, "text": "Getting Started" }, { "code": null, "e": 636, "s": 603, "text": "Creating Django Models and Views" }, { "code": null, "e": 659, "s": 636, "text": "PrimaryKeyRelatedField" }, { "code": null, "e": 678, "s": 659, "text": "StringRelatedField" }, { "code": null, "e": 695, "s": 678, "text": "SlugRelatedField" }, { "code": null, "e": 720, "s": 695, "text": "HyperlinkedIndetityField" }, { "code": null, "e": 744, "s": 720, "text": "HyperlinkedRelatedField" }, { "code": null, "e": 764, "s": 744, "text": "Nested Relationship" }, { "code": null, "e": 962, "s": 764, "text": "Before working on Django REST Framework serializers, you should make sure that you already installed Django and Django REST Framework in your virtual environment. You can check the below tutorials:" }, { "code": null, "e": 1009, "s": 962, "text": "Create virtual environment using venv | Python" }, { "code": null, "e": 1029, "s": 1009, "text": "Django Installation" }, { "code": null, "e": 1064, "s": 1029, "text": "Django REST Framework Installation" }, { "code": null, "e": 1247, "s": 1064, "text": "Next, you can create a project named emt (employee management tool) and an app named employees. Refer to the following articles to check how to create a project and an app in Django." }, { "code": null, "e": 1298, "s": 1247, "text": "How to Create a Basic Project using MVT in Django?" }, { "code": null, "e": 1330, "s": 1298, "text": "How to Create an App in Django?" }, { "code": null, "e": 1478, "s": 1330, "text": "In this section, we will be using PostgreSQL. You have to create a database named emt in PostgreSQL. You can check the below link for installation." }, { "code": null, "e": 1508, "s": 1478, "text": "Install PostgreSQL on Windows" }, { "code": null, "e": 1592, "s": 1508, "text": "Note: if you need to work with SQLite, you can continue using the default database." }, { "code": null, "e": 1972, "s": 1592, "text": "To make use of PostgreSQL, we need to install a Python-PostgreSQL Database Adapter (psycopg2). This package helps Django to interact with a PostgreSQL database. You can use the below command to install the psycopg2 package. Make sure the PostgreSQL bin folder is included in the PATH environmental variables, and the virtual environment is activated before executing the command." }, { "code": null, "e": 1993, "s": 1972, "text": "pip install psycopg2" }, { "code": null, "e": 2293, "s": 1993, "text": "Now, you need to configure the PostgreSQL database in your Django project. By default, the database configuration has an SQLite database engine and database file name. You can check the setting.py Python file and replace the default database configuration with the PostgreSQL database configuration." }, { "code": null, "e": 2511, "s": 2293, "text": "DATABASES = {\n 'default': {\n 'ENGINE': 'django.db.backends.postgresql',\n 'NAME': 'emt',\n 'USER': 'username',\n 'PASSWORD': 'password',\n 'HOST': '127.0.0.1',\n 'PORT': '5432',\n }\n}" }, { "code": null, "e": 2627, "s": 2511, "text": "Here, the name refers to the database name, the user and the password refers to the Postgres username and password." }, { "code": null, "e": 2826, "s": 2627, "text": "At last, we need to install the httpie package in our virtual environment. We will be composing HTTPie commands for CRUD operation. You can activate the virtual environment and run the below command" }, { "code": null, "e": 2854, "s": 2826, "text": "pip install –upgrade httpie" }, { "code": null, "e": 3260, "s": 2854, "text": "In Django, Models are classes that deal with databases in an object-oriented way. Each model class refers to a database table and each attribute in the model class refers to a database column. Here, we will create an Employee model and EmployeeTask model in Django. The EmployeeTask model holds a ManyToOne relationship with the Employee model We require the following attributes for our Employee entity:" }, { "code": null, "e": 3267, "s": 3260, "text": "emp_id" }, { "code": null, "e": 3272, "s": 3267, "text": "name" }, { "code": null, "e": 3279, "s": 3272, "text": "gender" }, { "code": null, "e": 3291, "s": 3279, "text": "designation" }, { "code": null, "e": 3345, "s": 3291, "text": "The attributes for our EmployeeTask model as follows:" }, { "code": null, "e": 3355, "s": 3345, "text": "task_name" }, { "code": null, "e": 3389, "s": 3355, "text": "employee (foreign key – Employee)" }, { "code": null, "e": 3399, "s": 3389, "text": "task_desc" }, { "code": null, "e": 3412, "s": 3399, "text": "created_date" }, { "code": null, "e": 3421, "s": 3412, "text": "deadline" }, { "code": null, "e": 3551, "s": 3421, "text": "Let’s get into the implementation of the Employee model in Django. You can replace the models.py Python file with the below code:" }, { "code": null, "e": 3559, "s": 3551, "text": "Python3" }, { "code": "GENDER_CHOICES = (('M','Male'), ('F','Female'),) class Employee(models.Model): emp_id = models.IntegerField() name = models.CharField(max_length=150) gender = models.CharField(max_length=1, choices=GENDER_CHOICES, default='M') designation = models.CharField(max_length=150) class Meta: ordering=('emp_id',) def __str__(self): return self.name", "e": 4018, "s": 3559, "text": null }, { "code": null, "e": 4235, "s": 4018, "text": "The Employee model is a subclass of the django.db.models.Model class and defines the attributes and a Meta inner class. It has an ordering attribute that orders the result in an ascending order based on employee id." }, { "code": null, "e": 4346, "s": 4235, "text": "Next, let get into the implementation of EmployeeTask Model. You can add the below code to the models.py file." }, { "code": null, "e": 4354, "s": 4346, "text": "Python3" }, { "code": "class EmployeeTask(models.Model): task_name = models.CharField(max_length=150) employee = models.ForeignKey(Employee, related_name='tasks', on_delete=models.CASCADE) task_desc = models.CharField(max_length=350) created_date = models.DateTimeField(auto_now_add=True) deadline = models.DateTimeField() class Meta: ordering = ('task_name',) def __str__(self): return self.task_name", "e": 4838, "s": 4354, "text": null }, { "code": null, "e": 5145, "s": 4838, "text": "The EmployeeTask model is a subclass of the django.db.models.Model class and defines the attributes and a Meta inner class. It has an ordering attribute that orders the result in an ascending order based on task_name. It has an employee field that holds a many-to-one relationship with the Employee model." }, { "code": null, "e": 5300, "s": 5145, "text": "employee = models.ForeignKey(Employee,\n related_name='tasks',\n on_delete=models.CASCADE)" }, { "code": null, "e": 5567, "s": 5300, "text": "The related_name helps in a reverse relationship. Reverse relationship means referring from Employee to EmployeeTask. The employee field represents the Employee model in the EmployeeTaks. Likewise, the related_name represents the EmployeeTask in the Employee model." }, { "code": null, "e": 5872, "s": 5567, "text": "Reverse relations are not automatically included by the serializer class. We must explicitly add it to the field list. If you set an appropriate related_name argument on the relationship, then you can use it as a field name (You will be able to understand reverse relation while serializing the Models). " }, { "code": null, "e": 5931, "s": 5872, "text": "Let’s make the initial migrations using the below command." }, { "code": null, "e": 5963, "s": 5931, "text": "python manage.py makemigrations" }, { "code": null, "e": 6054, "s": 5963, "text": "If the migration is a success then apply all generated migrations using the below command:" }, { "code": null, "e": 6079, "s": 6054, "text": "python manage.py migrate" }, { "code": null, "e": 6166, "s": 6079, "text": "If successful you can check your database entries. Now, let’s create the Django views." }, { "code": null, "e": 6640, "s": 6166, "text": "Django views facilitate processing the HTTP requests and providing HTTP responses. On receiving an HTTP request, Django creates an HttpRequest instance and it is passed as the first argument to the view function. The view function checks the value and executes the code based on the HTTP verb. Here the code uses @csrf_exempt decorator to set a CSRF (Cross-Site Request Forgery) cookie. This makes it possible to POST to this view from clients that won’t have a CSRF token." }, { "code": null, "e": 6690, "s": 6640, "text": "You can add the below code to your view.py file. " }, { "code": null, "e": 6698, "s": 6690, "text": "Python3" }, { "code": "from django.shortcuts import renderfrom django.http import HttpResponse, JsonResponsefrom django.views.decorators.csrf import csrf_exempt from rest_framework.renderers import JSONRendererfrom rest_framework.parsers import JSONParser from employees.models import Employee, EmployeeTaskfrom employees.serializers import EmployeeSerializer, EmployeeTaskSerializer @csrf_exemptdef employee_list(request): if request.method == 'GET': emp = Employee.objects.all() emp_serializer = EmployeeSerializer(emp, many=True) return JsonResponse(emp_serializer.data, safe=False) elif request.method == 'POST': emp_data = JSONParser().parse(request) emp_serializer = EmployeeSerializer(data=emp_data) if emp_serializer.is_valid(): emp_serializer.save() return JsonResponse(emp_serializer.data, status=201) return JsonResponse(emp_serializer.errors, status=400) @csrf_exemptdef employee_detail(request, pk): try: emp = Employee.objects.get(pk=pk) except Employee.DoesNotExist: return HttpResponse(status=404) if request.method == 'GET': emp_serializer = EmployeeSerializer(emp) return JsonResponse(emp_serializer.data) elif request.method == 'DELETE': emp.delete() return HttpResponse(status=204) @csrf_exemptdef employeetask_list(request): if request.method == 'GET': emptask = EmployeeTask.objects.all() emptask_serializer = EmployeeTaskSerializer(emptask, many=True) return JsonResponse(emptask_serializer.data, safe=False) elif request.method == 'POST': emptask_data = JSONParser().parse(request) emptask_serializer = EmployeeTaskSerializer(data=emptask_data) if emptask_serializer.is_valid(): emptask_serializer.save() return JsonResponse(emptask_serializer.data, status=201) return JsonResponse(emptask_serializer.errors, status=400) @csrf_exemptdef employeetask_detail(request, pk): try: emptask = EmployeeTask.objects.get(pk=pk) except EmployeeTask.DoesNotExist: return HTTPResponse(status=404) if request.method == 'GET': emptask_serializer = EmployeeTaskSerializer(emptask) return JsonResponse(emptask_serializer.data) elif request.method == 'DELETE': emptask.delete() return HttpResponse(status=204)", "e": 9201, "s": 6698, "text": null }, { "code": null, "e": 9727, "s": 9201, "text": "Here, we have different functions to process requests related to the Employee model and EmployeeTask model — employee_list, employeetask_list, and employee_detail and employeetask_detail. The employee_list and employeetask_list functions are capable of processing requests to retrieve all employees and employee’s tasks or to create a new employee and create a new employee task. The employee_detail and employeetask_detail functions are capable of processing requests such as retrieve a particular entry and delete an entry." }, { "code": null, "e": 9874, "s": 9727, "text": "Now, it’s necessary to route URLs to view. You need to create a new Python file name urls.py in the app (employees) folder and add the below code." }, { "code": null, "e": 9882, "s": 9874, "text": "Python3" }, { "code": "from django.urls import pathfrom employees import views urlpatterns = [ path('employees/', views.employee_list, name = 'employee-list'), path('employees/<int:pk>/', views.employee_detail, name='employee-detail'), path('task/', views.employeetask_list, name = 'employeetask-list'), path('task/<int:pk>/', views.employeetask_detail, name='employeetask-detail'),", "e": 10311, "s": 9882, "text": null }, { "code": null, "e": 10567, "s": 10311, "text": "Based on the matching path the URLs are routed to corresponding views. Next, we have to replace the code in the urls.py file in the root folder (emt\\emt\\urls.py). At present, it has the root URL configurations. Update the urls.py file with the below code." }, { "code": null, "e": 10575, "s": 10567, "text": "Python3" }, { "code": "from django.urls import path, include urlpatterns = [ path('', include('employees.urls')),]", "e": 10671, "s": 10575, "text": null }, { "code": null, "e": 11047, "s": 10671, "text": "PrimaryKeyRelatedField represents the target of the relation using the primary key (pk). It can be achieved by generating the relationship using the rest_framework.serializers.PrimaryKeyRelatedField() field. By default, this field is read-write, but you can make it read-only by setting the read_only attribute to True. The PrimaryKeyRelatedField has the following arguments:" }, { "code": null, "e": 11284, "s": 11047, "text": "queryset – It used for model instance lookups when validating the field input. Relationships must either set a queryset explicitly (serializers.PrimaryKeyRelatedField(queryset=Employee.objects.all(),many=False) ), or set read_only=True." }, { "code": null, "e": 11357, "s": 11284, "text": "many – Set this argument to True to serialize more than one relationship" }, { "code": null, "e": 11490, "s": 11357, "text": "allow_null – If set to True, the field will accept values of None or the empty string for nullable relationships. Defaults to False." }, { "code": null, "e": 11703, "s": 11490, "text": "pk_field – Set to a field to control serialization/deserialization of the primary key’s value. For example, pk_field=UUIDField(format=’hex’) would serialize a UUID primary key into its compact hex representation." }, { "code": null, "e": 12031, "s": 11703, "text": "Now let’s get to our serializer code. Here we have two serializer classes — EmployeeSerializer and EmployeeTaskSerializer. The EmployeeSerializer class serializes the Employee model and the EmployeeTaskSerializer serializes the EmployeeTask model. The EmployeeTask Model holds a ManyToOne relationship with the Employee Model. " }, { "code": null, "e": 12186, "s": 12031, "text": "employee = models.ForeignKey(Employee,\n related_name='tasks',\n on_delete=models.CASCADE)" }, { "code": null, "e": 12519, "s": 12186, "text": "The same task will not be assigned to more than one employee, but one employee can have multiple tasks. Hence, the EmployeeTaskSerializer class should serialize only a single employee instance, whereas, EmployeeSerializer class should serialize one or more EmployeeTask instances (more than one task can be assigned to an employee)." }, { "code": null, "e": 12592, "s": 12519, "text": "The relationship generator process in EmployeeTaskSerializer as follows:" }, { "code": null, "e": 12734, "s": 12592, "text": "employee = serializers.PrimaryKeyRelatedField(queryset=Employee.objects.all(),\n many=False) " }, { "code": null, "e": 13004, "s": 12734, "text": "By default, the PrimaryKeyRelatedField field has read-write permission. The queryset=Employee.objects.all() argument checks for the particular model instance in the Employee table. The many=False argument is set because there is only a single relationship to serialize." }, { "code": null, "e": 13079, "s": 13004, "text": "The relationship generator process in EmployeeSerializer class as follows:" }, { "code": null, "e": 13149, "s": 13079, "text": "tasks = serializers.PrimaryKeyRelatedField(many=True, read_only=True)" }, { "code": null, "e": 13391, "s": 13149, "text": "The tasks attribute is the related_name specified (ForeignKey relationship) in the EmployeeTask model. Since each employee can have more than one task we set many=True. The read_only=True only allows permission to retrieve the EmployeeTask. " }, { "code": null, "e": 13556, "s": 13391, "text": "You can add the below code to the serializers.py file. (if you don’t have the file, you can create a file named serializers.py file in your app [employees] folder)." }, { "code": null, "e": 13564, "s": 13556, "text": "Python3" }, { "code": "from rest_framework import serializersfrom employees.models import Employee, EmployeeTask class EmployeeSerializer(serializers.ModelSerializer): # PrimaryKeyRelatedField tasks = serializers.PrimaryKeyRelatedField(many=True, read_only=True) class Meta: model = Employee fields = ( 'pk', 'emp_id', 'name', 'gender', 'designation', 'tasks') class EmployeeTaskSerializer(serializers.ModelSerializer): # PrimaryKeyRelatedField employee = serializers.PrimaryKeyRelatedField(queryset=Employee.objects.all(), many=False) class Meta: model = EmployeeTask fields = ( 'pk', 'task_name', 'employee', 'task_desc', 'created_date', 'deadline')", "e": 14433, "s": 13564, "text": null }, { "code": null, "e": 14510, "s": 14433, "text": "Let’s populate the employee table. You can execute the below HTTPie command." }, { "code": null, "e": 14607, "s": 14510, "text": "http POST :8000/employees/ emp_id=128 name=”Mathew A” gender=”M” designation=”Software Engineer”" }, { "code": null, "e": 14614, "s": 14607, "text": "Output" }, { "code": null, "e": 14978, "s": 14614, "text": "HTTP/1.1 201 Created\nContent-Length: 140\nContent-Type: application/json\nDate: Thu, 21 Jan 2021 09:16:50 GMT\nReferrer-Policy: same-origin\nServer: WSGIServer/0.2 CPython/3.7.5\nX-Content-Type-Options: nosniff\nX-Frame-Options: DENY\n\n{\n \"designation\": \"Software Engineer\",\n \"emp_id\": 128,\n \"gender\": \"M\",\n \"name\": \"Mathew A\",\n \"pk\": 8,\n \"tasks\": []\n}" }, { "code": null, "e": 15262, "s": 14978, "text": "You can notice the pk value of the employee. Now, let’s create an employee task and map it to the employee using PrimaryKeyRelatedField. Here the primary key value of the employee named Mathew A is 8. You have to pass it to the field name employee. Execute the below HTTPie command." }, { "code": null, "e": 15477, "s": 15262, "text": "http :8000/task/ task_name=”Interchange first and last elements in a list” employee=8 task_desc=”Write a Python program to interchange first and last element in a list” deadline=”2021-01-25 00:00:00.000000+00:00′′ " }, { "code": null, "e": 15484, "s": 15477, "text": "Output" }, { "code": null, "e": 15983, "s": 15484, "text": "HTTP/1.1 201 Created\nContent-Length: 285\nContent-Type: application/json\nDate: Thu, 21 Jan 2021 09:42:39 GMT\nReferrer-Policy: same-origin\nServer: WSGIServer/0.2 CPython/3.7.5\nX-Content-Type-Options: nosniff\nX-Frame-Options: DENY\n\n{\n \"created_date\": \"2021-01-21T09:42:39.792788Z\",\n \"deadline\": \"2021-01-25T00:00:00Z\",\n \"employee\": 8,\n \"task_desc\": \"Write a Python program to interchange first and last element in a list\",\n \"task_name\": \"Interchange first and last elements in a list\"\n}" }, { "code": null, "e": 16128, "s": 15983, "text": "You can create one more task and assign it to the same employee and process the request to retrieve the employee details. The HTTPie command is " }, { "code": null, "e": 16150, "s": 16128, "text": "http :8000/employees/" }, { "code": null, "e": 16157, "s": 16150, "text": "Output" }, { "code": null, "e": 16753, "s": 16157, "text": "HTTP/1.1 200 OK\nContent-Length: 219\nContent-Type: application/json\nDate: Fri, 22 Jan 2021 03:58:01 GMT\nReferrer-Policy: same-origin\nServer: WSGIServer/0.2 CPython/3.7.5\nX-Content-Type-Options: nosniff\nX-Frame-Options: DENY\n\n[\n {\n \"designation\": \"Software Engineer\",\n \"emp_id\": 128,\n \"gender\": \"M\",\n \"name\": \"Mathew A\",\n \"pk\": 8,\n \"tasks\": [\n 2,\n 1\n ]\n },\n {\n \"designation\": \"Test Engineer\",\n \"emp_id\": 129,\n \"gender\": \"F\",\n \"name\": \"Jeena R\",\n \"pk\": 9,\n \"tasks\": []\n }\n]" }, { "code": null, "e": 16810, "s": 16753, "text": "Sharing the command prompt screenshot for your reference" }, { "code": null, "e": 16976, "s": 16810, "text": "You can notice the tasks field for the employee named Mathew A. It displays the pk of the task model and the many=True argument serialized multiple task instance id." }, { "code": null, "e": 17039, "s": 16976, "text": "Let’s retrieve the task details using the below HTTPie command" }, { "code": null, "e": 17056, "s": 17039, "text": "http :8000/task/" }, { "code": null, "e": 17063, "s": 17056, "text": "Output" }, { "code": null, "e": 17860, "s": 17063, "text": "HTTP/1.1 200 OK\nContent-Length: 454\nContent-Type: application/json\nDate: Fri, 22 Jan 2021 03:59:40 GMT\nReferrer-Policy: same-origin\nServer: WSGIServer/0.2 CPython/3.7.5\nX-Content-Type-Options: nosniff\nX-Frame-Options: DENY\n\n[\n {\n \"created_date\": \"2021-01-21T09:48:47.710707Z\",\n \"deadline\": \"2021-01-27T00:00:00Z\",\n \"employee\": 8,\n \"pk\": 2,\n \"task_desc\": \"Write a Python program for Binary Search\",\n \"task_name\": \"Binary Search\"\n },\n {\n \"created_date\": \"2021-01-21T09:42:39.792788Z\",\n \"deadline\": \"2021-01-25T00:00:00Z\",\n \"employee\": 8,\n \"pk\": 1,\n \"task_desc\": \"Write a Python program to interchange first and last element in a list\",\n \"task_name\": \"Interchange first and last elements in a list\"\n }\n]" }, { "code": null, "e": 17917, "s": 17860, "text": "Sharing the command prompt screenshot for your reference" }, { "code": null, "e": 17973, "s": 17917, "text": " Let’s look at the HTTPie command to create a new task." }, { "code": null, "e": 18144, "s": 17973, "text": "http :8000/task/ task_name=”PrimaryKeyRelatedField” employee=8 task_desc=”Serialize relationship using PrimaryKeyRelateField” deadline=”2021-01-27 00:00:00.000000+00:00′′" }, { "code": null, "e": 18151, "s": 18144, "text": "Output" }, { "code": null, "e": 18620, "s": 18151, "text": "HTTP/1.1 201 Created\nContent-Length: 213\nContent-Type: application/json\nDate: Fri, 22 Jan 2021 04:33:15 GMT\nReferrer-Policy: same-origin\nServer: WSGIServer/0.2 CPython/3.7.5\nX-Content-Type-Options: nosniff\nX-Frame-Options: DENY\n\n{\n \"created_date\": \"2021-01-22T04:33:15.855264Z\",\n \"deadline\": \"2021-01-27T00:00:00Z\",\n \"employee\": 8,\n \"pk\": 6,\n \"task_desc\": \"Serialize relationship using PrimaryKeyRelateField\",\n \"task_name\": \"PrimaryKeyRelatedField\"\n}" }, { "code": null, "e": 18678, "s": 18620, "text": "Sharing the command prompt screenshot for your reference:" }, { "code": null, "e": 18748, "s": 18678, "text": " Now let’s explore how StringRelatedField represents a relationship. " }, { "code": null, "e": 19069, "s": 18748, "text": "The StringRelatedField represents the target of the relationship using its __str__ method. This field is read-only and set the ‘many’ argument to true If more than one instance to serialize. Let’s make use of StringRelatedField for tasks filed in EmployeeSerializer class. The relationship generator process as follows:" }, { "code": null, "e": 19119, "s": 19069, "text": "tasks = serializers.StringRelatedField(many=True)" }, { "code": null, "e": 19160, "s": 19119, "text": "The EmployeeSerializer class as follows:" }, { "code": null, "e": 19168, "s": 19160, "text": "Python3" }, { "code": "class EmployeeSerializer(serializers.ModelSerializer): # StringRelatedField tasks = serializers.StringRelatedField(many=True) class Meta: model = Employee fields = ( 'pk', 'emp_id', 'name', 'gender', 'designation', 'tasks')", "e": 19487, "s": 19168, "text": null }, { "code": null, "e": 19659, "s": 19487, "text": "Let’s retrieve the employee details to understand how the StringRelatedField displays the relationship field values. The HTTPie command to retrieve the employee values is:" }, { "code": null, "e": 19681, "s": 19659, "text": "http :8000/employees/" }, { "code": null, "e": 19688, "s": 19681, "text": "Output" }, { "code": null, "e": 20344, "s": 19688, "text": "HTTP/1.1 200 OK\nContent-Length: 279\nContent-Type: application/json\nDate: Fri, 22 Jan 2021 04:04:08 GMT\nReferrer-Policy: same-origin\nServer: WSGIServer/0.2 CPython/3.7.5\nX-Content-Type-Options: nosniff\nX-Frame-Options: DENY\n\n[\n {\n \"designation\": \"Software Engineer\",\n \"emp_id\": 128,\n \"gender\": \"M\",\n \"name\": \"Mathew A\",\n \"pk\": 8,\n \"tasks\": [\n \"Binary Search\",\n \"Interchange first and last elements in a list\"\n ]\n },\n {\n \"designation\": \"Test Engineer\",\n \"emp_id\": 129,\n \"gender\": \"F\",\n \"name\": \"Jeena R\",\n \"pk\": 9,\n \"tasks\": []\n }\n]" }, { "code": null, "e": 20401, "s": 20344, "text": "Sharing the command prompt screenshot for your reference" }, { "code": null, "e": 20532, "s": 20401, "text": "Here you can notice that the tasks field displays the string value from the function def __str__(self): in the EmployeeTask model." }, { "code": null, "e": 20585, "s": 20532, "text": " def __str__(self):\n return self.task_name" }, { "code": null, "e": 20866, "s": 20585, "text": "The SlugRelatedField represents the target of the relationship using a field on the target. By default, the field permits read-write operation. For write operations, the slug field that represents a model field should be unique. The SlugRelatedField has the following arguments: " }, { "code": null, "e": 20953, "s": 20866, "text": "slug_field – A field on the target and it should uniquely identify any given instance." }, { "code": null, "e": 21111, "s": 20953, "text": "queryset – It facilitates model instance lookups when validating the field input. Relationships must either set a queryset explicitly, or set read_only=True." }, { "code": null, "e": 21184, "s": 21111, "text": "many – Set this argument to True to serialize more than one relationship" }, { "code": null, "e": 21317, "s": 21184, "text": "allow_null – If set to True, the field will accept values of None or the empty string for nullable relationships. Defaults to False." }, { "code": null, "e": 21425, "s": 21317, "text": "In the EmployeeTaskSerializer class, you can replace the employee field representation with the below code:" }, { "code": null, "e": 21534, "s": 21425, "text": "employee = serializers.SlugRelatedField(\n queryset=Employee.objects.all(),\n slug_field='name')" }, { "code": null, "e": 21578, "s": 21534, "text": "The EmployeeTaskSerializer code as follows:" }, { "code": null, "e": 21586, "s": 21578, "text": "Python3" }, { "code": "class EmployeeTaskSerializer(serializers.ModelSerializer): # SlugRelatedField employee = serializers.SlugRelatedField( queryset=Employee.objects.all(), slug_field='name') class Meta: model = EmployeeTask fields = ( 'pk', 'task_name', 'employee', 'task_desc', 'created_date', 'deadline')", "e": 21989, "s": 21586, "text": null }, { "code": null, "e": 22041, "s": 21989, "text": "The HTTPie command to create a new employee task is" }, { "code": null, "e": 22209, "s": 22041, "text": "http :8000/task/ task_name=”SlugRelatedField” employee=”Mathew A” task_desc=”Serialize relationship using SlugRelateField” deadline=”2021-01-27 00:00:00.000000+00:00′′" }, { "code": null, "e": 22216, "s": 22209, "text": "Output" }, { "code": null, "e": 22682, "s": 22216, "text": "HTTP/1.1 201 Created\nContent-Length: 210\nContent-Type: application/json\nDate: Fri, 22 Jan 2021 04:41:12 GMT\nReferrer-Policy: same-origin\nServer: WSGIServer/0.2 CPython/3.7.5\nX-Content-Type-Options: nosniff\nX-Frame-Options: DENY\n\n{\n \"created_date\": \"2021-01-22T04:41:12.424001Z\",\n \"deadline\": \"2021-01-27T00:00:00Z\",\n \"employee\": \"Mathew A\",\n \"pk\": 7,\n \"task_desc\": \"Serialize relationship using SlugRelateField\",\n \"task_name\": \"SlugRelatedField\"\n}" }, { "code": null, "e": 22739, "s": 22682, "text": "Sharing the command prompt screenshot for your reference" }, { "code": null, "e": 22990, "s": 22739, "text": "Here, while creating a new task, we have given the employee name in the employee field rather than the primary key. You can also mention employee id while representing SlugRelatedField. You should make sure that it satisfies the unique constraint. " }, { "code": null, "e": 23476, "s": 22990, "text": "For Hyperlinking the API, the serializer class should extend HyperlinkedModelSerializer. The HyperlinkedModelSerializer class makes use of hyperlinks to represent relationships, instead of primary keys. By default, the serializer class that is inherited from HyperlinkedModelSerializer class will include a url field instead of a primary key field. The url field will be represented using a HyperlinkedIdentityField serializer field. It can also be used for an attribute on the object." }, { "code": null, "e": 23572, "s": 23476, "text": "The HyperlinkedIdentityField is always read-only. The arguments of HyperlinkedIdentitField are:" }, { "code": null, "e": 23728, "s": 23572, "text": "view_name – The view name is used as the target of the relationship. In standard router classes, this will be a string with the format <model_name>-detail." }, { "code": null, "e": 23880, "s": 23728, "text": "lookup_field – The field on the target, which is used for the lookup. It corresponds to a URL keyword argument on the referenced view. Default is ‘pk’." }, { "code": null, "e": 24044, "s": 23880, "text": "lookup_url_kwarg – The name of the keyword argument defined in the URL conf that corresponds to the lookup field. Defaults to using the same value as lookup_field." }, { "code": null, "e": 24193, "s": 24044, "text": "format – If using format suffixes, hyperlinked fields will use the same format suffix for the target unless overridden by using the format argument." }, { "code": null, "e": 24282, "s": 24193, "text": "In the EmployeeTaskSerializer class, you can use represent the url field as shown below:" }, { "code": null, "e": 24399, "s": 24282, "text": "url = serializers.HyperlinkedIdentityField(\n view_name='employeetask-detail',\n lookup_field='pk'\n )" }, { "code": null, "e": 24592, "s": 24399, "text": "Note: By default, the serializer class that is inherited from HyperlinkedModelSerializer class will include a url field, and the view name will be a string with the format <model_name>-detail." }, { "code": null, "e": 24637, "s": 24592, "text": "The EmployeeTaskSerializer class as follows:" }, { "code": null, "e": 24645, "s": 24637, "text": "Python3" }, { "code": "class EmployeeTaskSerializer(serializers.HyperlinkedModelSerializer): url = serializers.HyperlinkedIdentityField( view_name='employeetask-detail', lookup_field='pk' ) employee = serializers.SlugRelatedField( queryset=Employee.objects.all(), slug_field='name') class Meta: model = EmployeeTask fields = '__all__'", "e": 25008, "s": 24645, "text": null }, { "code": null, "e": 25250, "s": 25008, "text": "When instantiating a HyperlinkedModelSerializer, it is a must to include the current request in the serializer context. You need to pass context={‘request’:request} as an argument when instantiating your EmployeeTaskSerializer. For example:" }, { "code": null, "e": 25403, "s": 25250, "text": "emp_serializer = EmployeeSerializer(emp,\n many=True,\n context={'request':request})" }, { "code": null, "e": 25635, "s": 25403, "text": "Make sure you edit your employee_list and employee_detail function in the views.py file with the above code. You should add context={‘request’:request} argument while instantiating EmployeeTaskSerializer (GET, POST, PUT and PATCH)." }, { "code": null, "e": 25761, "s": 25635, "text": "Note: Note: This context along with the lookup_field is used for generating a fully qualified url by HyperlinkedIdentityField" }, { "code": null, "e": 25867, "s": 25761, "text": "Let’s retrieve the EmployeeTask values to understand how the values are displayed. The HTTPie command is " }, { "code": null, "e": 25890, "s": 25867, "text": "http GET :8000/task/1/" }, { "code": null, "e": 25897, "s": 25890, "text": "Output" }, { "code": null, "e": 26444, "s": 25897, "text": "HTTP/1.1 200 OK\nContent-Length: 296\nContent-Type: application/json\nDate: Fri, 22 Jan 2021 16:16:42 GMT\nReferrer-Policy: same-origin\nServer: WSGIServer/0.2 CPython/3.7.5\nX-Content-Type-Options: nosniff\nX-Frame-Options: DENY\n\n{\n \"created_date\": \"2021-01-21T09:42:39.792788Z\",\n \"deadline\": \"2021-01-25T00:00:00Z\",\n \"employee\": \"Mathew A\",\n \"task_desc\": \"Write a Python program to interchange first and last element in a list\",\n \"task_name\": \"Interchange first and last elements in a list\",\n \"url\": \"http://localhost:8000/task/1/\"\n}" }, { "code": null, "e": 26501, "s": 26444, "text": "Sharing the command prompt screenshot for your reference" }, { "code": null, "e": 26597, "s": 26501, "text": "If we analyze the output, we can notice that instead of the primary key it displays url field. " }, { "code": null, "e": 26636, "s": 26597, "text": "\"url\": \"http://localhost:8000/task/1/\"" }, { "code": null, "e": 26893, "s": 26636, "text": "HyperlinkedRelatedField is used to represent the target of the relationship using a Hyperlink. By default, this field is a read-write, but we can make it read-only by setting the read-only flag True. The arguments of HyperlinkedRelatedField are as follows:" }, { "code": null, "e": 27049, "s": 26893, "text": "view_name – The view name is used as the target of the relationship. For standard router classes, this will be a string with the format <modelname>-detail." }, { "code": null, "e": 27206, "s": 27049, "text": "queryset – It facilitates model instance lookups when validating the field input. Relationships must either set a queryset explicitly or set read_only=True." }, { "code": null, "e": 27288, "s": 27206, "text": "many – To serialize more than one relation, you should set this argument to True." }, { "code": null, "e": 27418, "s": 27288, "text": "allow_null – If set to True, the field will accept None values or the empty string for nullable relationships. Defaults to False." }, { "code": null, "e": 27563, "s": 27418, "text": "lookup_field – The field on the target is used for the lookup. It corresponds to a URL keyword argument on the referenced view. Default is ‘pk’." }, { "code": null, "e": 27729, "s": 27563, "text": "lookup_url_kwarg – The name of the keyword argument defined in the URL conf that corresponds to the lookup field. By default, it uses the same value as lookup_field." }, { "code": null, "e": 27878, "s": 27729, "text": "format – If using format suffixes, hyperlinked fields will use the same format suffix for the target unless overridden by using the format argument." }, { "code": null, "e": 28288, "s": 27878, "text": "In our reverse relationship (Employee to EmployeeTask) we have seen that by default the serializer (EmployeeSerializer) uses the primary key to represent the target of a relationship (to include a reverse relationship, you must explicitly add it to the field list). We have also explored other representations such as StringRelatedField and SlugRelatedField. Here, we will make use of HyperlinkedRelatedField." }, { "code": null, "e": 28375, "s": 28288, "text": "In the EmployeeSerializer class, you can use represent the tasks field as shown below:" }, { "code": null, "e": 28567, "s": 28375, "text": "tasks = serializers.HyperlinkedRelatedField(many=True,\n read_only=True,\n view_name='employeetask-detail')" }, { "code": null, "e": 28641, "s": 28567, "text": "You can replace the existing EmployeeSerializer class with the below one:" }, { "code": null, "e": 28649, "s": 28641, "text": "Python3" }, { "code": "class EmployeeSerializer(serializers.HyperlinkedModelSerializer): url = serializers.HyperlinkedIdentityField( view_name='employee-detail', lookup_field='pk' ) tasks = serializers.HyperlinkedRelatedField(many=True, read_only=True, view_name='employeetask-detail') class Meta: model = Employee fields = ( 'url', 'pk', 'emp_id', 'name', 'gender', 'designation', 'tasks')", "e": 29244, "s": 28649, "text": null }, { "code": null, "e": 29267, "s": 29244, "text": "The HTTPie command is:" }, { "code": null, "e": 29295, "s": 29267, "text": "http GET :8000/employees/8/" }, { "code": null, "e": 29302, "s": 29295, "text": "Output" }, { "code": null, "e": 29878, "s": 29302, "text": "HTTP/1.1 200 OK\nContent-Length: 283\nContent-Type: application/json\nDate: Fri, 22 Jan 2021 16:18:59 GMT\nReferrer-Policy: same-origin\nServer: WSGIServer/0.2 CPython/3.7.5\nX-Content-Type-Options: nosniff\nX-Frame-Options: DENY\n\n{\n \"designation\": \"Software Engineer\",\n \"emp_id\": 128,\n \"gender\": \"M\",\n \"name\": \"Mathew A\",\n \"pk\": 8,\n \"tasks\": [\n \"http://localhost:8000/task/2/\",\n \"http://localhost:8000/task/1/\",\n \"http://localhost:8000/task/6/\",\n \"http://localhost:8000/task/7/\"\n ],\n \"url\": \"http://localhost:8000/employees/8/\"\n}" }, { "code": null, "e": 29935, "s": 29878, "text": "Sharing the command prompt screenshot for your reference" }, { "code": null, "e": 30027, "s": 29935, "text": "If we analyze the output, we can notice that the tasks field displays a set, or hyperlinks." }, { "code": null, "e": 30207, "s": 30027, "text": "\"tasks\": [\n \"http://localhost:8000/task/2/\",\n \"http://localhost:8000/task/1/\",\n \"http://localhost:8000/task/6/\",\n \"http://localhost:8000/task/7/\"\n ]" }, { "code": null, "e": 30308, "s": 30207, "text": "Next, let’s understand how the nested relationship can be expressed by using serializers as fields. " }, { "code": null, "e": 30507, "s": 30308, "text": "A nested relationship makes it possible to embed the referred entity. If we look at the case of EmployeeTask, it refers to the Employee. Let’s serialize the EmployeeTask using a nested relationship." }, { "code": null, "e": 30596, "s": 30507, "text": "You can use the below code to refer to the employee field in the EmployeeTaskSerializer:" }, { "code": null, "e": 30642, "s": 30596, "text": "employee = EmployeeSerializer(read_only=True)" }, { "code": null, "e": 30706, "s": 30642, "text": "You can replace the EmployeeTaskSerializer with the below code:" }, { "code": null, "e": 30714, "s": 30706, "text": "Python3" }, { "code": "class EmployeeTaskSerializer(serializers.HyperlinkedModelSerializer): url = serializers.HyperlinkedIdentityField( view_name='employeetask-detail', lookup_field='pk' ) employee = EmployeeSerializer(read_only=True) class Meta: model = EmployeeTask fields = '__all__'", "e": 31021, "s": 30714, "text": null }, { "code": null, "e": 31081, "s": 31021, "text": "Let’s retrieve an EmployeeTask entry. The HTTPie command is" }, { "code": null, "e": 31104, "s": 31081, "text": "http GET :8000/task/1/" }, { "code": null, "e": 31111, "s": 31104, "text": "Output" }, { "code": null, "e": 32051, "s": 31111, "text": "HTTP/1.1 200 OK\nContent-Length: 569\nContent-Type: application/json\nDate: Fri, 22 Jan 2021 16:33:51 GMT\nReferrer-Policy: same-origin\nServer: WSGIServer/0.2 CPython/3.7.5\nX-Content-Type-Options: nosniff\nX-Frame-Options: DENY\n\n{\n \"created_date\": \"2021-01-21T09:42:39.792788Z\",\n \"deadline\": \"2021-01-25T00:00:00Z\",\n \"employee\": {\n \"designation\": \"Software Engineer\",\n \"emp_id\": 128,\n \"gender\": \"M\",\n \"name\": \"Mathew A\",\n \"pk\": 8,\n \"tasks\": [\n \"http://localhost:8000/task/2/\",\n \"http://localhost:8000/task/1/\",\n \"http://localhost:8000/task/6/\",\n \"http://localhost:8000/task/7/\"\n ],\n \"url\": \"http://localhost:8000/employees/8/\"\n },\n \"task_desc\": \"Write a Python program to interchange first and last element in a list\",\n \"task_name\": \"Interchange first and last elements in a list\",\n \"url\": \"http://localhost:8000/task/1/\"\n}" }, { "code": null, "e": 32108, "s": 32051, "text": "Sharing the command prompt screenshot for your reference" }, { "code": null, "e": 32228, "s": 32108, "text": "You can notice that the employee field displays the complete employee details rather than just the primary key or slug." }, { "code": null, "e": 32645, "s": 32228, "text": "\"employee\": {\n \"designation\": \"Software Engineer\",\n \"emp_id\": 128,\n \"gender\": \"M\",\n \"name\": \"Mathew A\",\n \"pk\": 8,\n \"tasks\": [\n \"http://localhost:8000/task/2/\",\n \"http://localhost:8000/task/1/\",\n \"http://localhost:8000/task/6/\",\n \"http://localhost:8000/task/7/\"\n ],\n \"url\": \"http://localhost:8000/employees/8/\"\n }," }, { "code": null, "e": 33263, "s": 32645, "text": "In this section, we explored various types of relational fields provided by DRF serializer relations. We understood how each relational fields represent the relationship with the target. The PrimaryKeyRelatedField represents the target of the relationship using its primary key whereas, the StringRelatedField uses the __str__ method of the target. In the case of SlugRelatedField, it represents the target of the relationship using a target field. Finally, the HyperlinkedIdentityField is used as an identity relationship, and the HyperlinkedRealtedField represents the target of the relationship using a hyperlink. " }, { "code": null, "e": 33275, "s": 33263, "text": "Django-REST" }, { "code": null, "e": 33289, "s": 33275, "text": "Python Django" }, { "code": null, "e": 33296, "s": 33289, "text": "Python" } ]
MouseListener and MouseMotionListener in Java
14 Apr, 2021 MouseListener and MouseMotionListener is an interface in java.awt.event package . Mouse events are of two types. MouseListener handles the events when the mouse is not in motion. While MouseMotionListener handles the events when mouse is in motion.There are five types of events that MouseListener can generate. There are five abstract functions that represent these five events. The abstract functions are : void mouseReleased(MouseEvent e) : Mouse key is releasedvoid mouseClicked(MouseEvent e) : Mouse key is pressed/releasedvoid mouseExited(MouseEvent e) : Mouse exited the componentvoid mouseEntered(MouseEvent e) : Mouse entered the componentvoid mousepressed(MouseEvent e) : Mouse key is pressed void mouseReleased(MouseEvent e) : Mouse key is released void mouseClicked(MouseEvent e) : Mouse key is pressed/released void mouseExited(MouseEvent e) : Mouse exited the component void mouseEntered(MouseEvent e) : Mouse entered the component void mousepressed(MouseEvent e) : Mouse key is pressed There are two types of events that MouseMotionListener can generate. There are two abstract functions that represent these five events. The abstract functions are : void mouseDragged(MouseEvent e) : Invoked when a mouse button is pressed in the component and dragged. Events are passed until the user releases the mouse button.void mouseMoved(MouseEvent e) : invoked when the mouse cursor is moved from one point to another within the component, without pressing any mouse buttons. void mouseDragged(MouseEvent e) : Invoked when a mouse button is pressed in the component and dragged. Events are passed until the user releases the mouse button. void mouseMoved(MouseEvent e) : invoked when the mouse cursor is moved from one point to another within the component, without pressing any mouse buttons. The following programs are a illustration of MouseListener and MouseMotionListener.1. Program to handle MouseListener events Java // Java program to handle MouseListener eventsimport java.awt.*;import java.awt.event.*;import javax.swing.*;class Mouse extends Frame implements MouseListener { // Jlabels to display the actions of events of mouseListener // static JLabel label1, label2, label3; // default constructor Mouse() { } // main class public static void main(String[] args) { // create a frame JFrame f = new JFrame("MouseListener"); // set the size of the frame f.setSize(600, 100); // close the frame when close button is pressed f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // create anew panel JPanel p = new JPanel(); // set the layout of the panel p.setLayout(new FlowLayout()); // initialize the labels label1 = new JLabel("no event "); label2 = new JLabel("no event "); label3 = new JLabel("no event "); // create an object of mouse class Mouse m = new Mouse(); // add mouseListener to the frame f.addMouseListener(m); // add labels to the panel p.add(label1); p.add(label2); p.add(label3); // add panel to the frame f.add(p); f.show(); } // getX() and getY() functions return the // x and y coordinates of the current // mouse position // getClickCount() returns the number of // quick consecutive clicks made by the user // this function is invoked when the mouse is pressed public void mousePressed(MouseEvent e) { // show the point where the user pressed the mouse label1.setText("mouse pressed at point:" + e.getX() + " " + e.getY()); } // this function is invoked when the mouse is released public void mouseReleased(MouseEvent e) { // show the point where the user released the mouse click label1.setText("mouse released at point:" + e.getX() + " " + e.getY()); } // this function is invoked when the mouse exits the component public void mouseExited(MouseEvent e) { // show the point through which the mouse exited the frame label2.setText("mouse exited through point:" + e.getX() + " " + e.getY()); } // this function is invoked when the mouse enters the component public void mouseEntered(MouseEvent e) { // show the point through which the mouse entered the frame label2.setText("mouse entered at point:" + e.getX() + " " + e.getY()); } // this function is invoked when the mouse is pressed or released public void mouseClicked(MouseEvent e) { // getClickCount gives the number of quick, // consecutive clicks made by the user // show the point where the mouse is i.e // the x and y coordinates label3.setText("mouse clicked at point:" + e.getX() + " " + e.getY() + "mouse clicked :" + e.getClickCount()); }} Output : Note : The following program might not run in an online compiler please use an offline IDELet’s take another example on MouseListener,the question is: Q. Write an applet which displays x and y co-ordinate in it’s status bar whenever the user click anywhere in the Applet window. Ans. Note: This code is with respect to Netbeans IDE. Java //Program of an applet which//displays x and y co-ordinate//in it's status bar,whenever//the user click anywhere in//the applet window. import java.awt.*;import java.awt.event.*;import java.applet.*;public class GFG extends Applet implements MouseListener{public void init(){this.addMouseListener (this);//first "this" represent source//(in this case it is applet which//is current calling object) and//second "this" represent//listener(in this case it is GFG) }public void mouseClicked(MouseEvent m){ int x = m.getX(); int y = m.getY(); String str = "x =" +x+",y = "+y; showStatus(str);} @Override public void mousePressed(MouseEvent e) { } @Override public void mouseReleased(MouseEvent e) { } @Override public void mouseEntered(MouseEvent e) { } @Override public void mouseExited(MouseEvent e) { }} Output: Output showing (x,y) in status bar Modification: Now our aim is to improve above program so that co-ordinates should display at that point only where click has been madeNote: This code is with respect to Netbeans IDE. Java //Co-ordinates should display//at that point only wherever//their is click on canvas import java.awt.*;import java.awt.event.*;import java.applet.*;public class GFG extends Applet implements MouseListener{private int x,y;private String str = " ";public void init(){this.addMouseListener (this);//first "this" represent source//(in this case it is applet which// is current calling object) and// second "this" represent listener//(in this case it is GFG) }public void paint(Graphics g){g.drawString(str,x,y);}public void mouseClicked(MouseEvent m){ x = m.getX(); y = m.getY(); str = "x =" +x+",y = "+y;repaint(); // we have made this//call because repaint() will//call paint() method for us.//If we comment out this line,//then we will see output//only when focus is on the applet//i.e on maximising the applet window//because paint() method is called//when applet screen gets the focus.//repaint() is a method of Component//class and prototype for this method is://public void repaint() } public void mouseEntered(MouseEvent m)//over-riding all the methods given by// MouseListener{} public void mouseExited(MouseEvent m){} public void mousePressed(MouseEvent m){} public void mouseReleased(MouseEvent m){}} Output Output showing (x,y) in canvas Now one more unusual thing will come in output which is that, we will not able to see previous co-ordinates.But why? In Java, before calling paint() method, it calls one more method which is update() and it do the following things: it repaints the applet background with current color.it then calls paint(). it repaints the applet background with current color. it then calls paint(). Now to see previous co-ordinates as well: we have to over-ride update() method also and it’s prototype is similar to paint().Further Modification To see previous co-ordinates as well:Note: This code is with respect to Netbeans IDE. Java //Co-ordinates should display//at that point only wherever//their is click on canvas and also//able to see the previous coordinates import java.awt.*;import java.awt.event.*;import java.applet.*;public class GFG extends Applet implements MouseListener{private int x,y;private String str = " ";public void init(){this.addMouseListener (this);}public void paint(Graphics g){g.drawString(str,x,y);}public void update(Graphics g){paint(g);}public void mouseClicked(MouseEvent m){ x = m.getX(); y = m.getY(); str = "x =" +x+",y = "+y;repaint();} public void mouseEntered(MouseEvent m){} public void mouseExited(MouseEvent m){} public void mousePressed(MouseEvent m){} public void mouseReleased(MouseEvent m) { }} Output Output showing previous co-ordinate as well 2. Program to handle MouseMotionListener events Java // Java Program to illustrate MouseMotionListener eventsimport java.awt.*;import java.awt.event.*;import javax.swing.*;class Mouse extends Frame implements MouseMotionListener { // Jlabels to display the actions of events of MouseMotionListener static JLabel label1, label2; // default constructor Mouse() { } // main class public static void main(String[] args) { // create a frame JFrame f = new JFrame("MouseMotionListener"); // set the size of the frame f.setSize(600, 400); // close the frame when close button is pressed f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // create anew panel JPanel p = new JPanel(); // set the layout of the panel p.setLayout(new FlowLayout()); // initialize the labels label1 = new JLabel("no event "); label2 = new JLabel("no event "); // create an object of mouse class Mouse m = new Mouse(); // add mouseListener to the frame f.addMouseMotionListener(m); // add labels to the panel p.add(label1); p.add(label2); // add panel to the frame f.add(p); f.show(); } // getX() and getY() functions return the // x and y coordinates of the current // mouse position // invoked when mouse button is pressed // and dragged from one point to another // in a component public void mouseDragged(MouseEvent e) { // update the label to show the point // through which point mouse is dragged label1.setText("mouse is dragged through point " + e.getX() + " " + e.getY()); } // invoked when the cursor is moved from // one point to another within the component public void mouseMoved(MouseEvent e) { // update the label to show the point to which the cursor moved label2.setText("mouse is moved to point " + e.getX() + " " + e.getY()); }} Output : 3. Java program to illustrate MouseListener and MouseMotionListener events simultaneously Java // Java program to illustrate MouseListener// and MouseMotionListener events// simultaneously import java.awt.*;import java.awt.event.*;import javax.swing.*;class Mouse extends Frame implements MouseMotionListener, MouseListener { // Jlabels to display the actions of events of MouseMotionListener and MouseListener static JLabel label1, label2, label3, label4, label5; // default constructor Mouse() { } // main class public static void main(String[] args) { // create a frame JFrame f = new JFrame("MouseListener and MouseMotionListener"); // set the size of the frame f.setSize(900, 300); // close the frame when close button is pressed f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // create anew panel JPanel p = new JPanel(); JPanel p1 = new JPanel(); // set the layout of the frame f.setLayout(new FlowLayout()); JLabel l1, l2; l1 = new JLabel("MouseMotionListener events :"); l2 = new JLabel("MouseLIstener events :"); // initialize the labels label1 = new JLabel("no event "); label2 = new JLabel("no event "); label3 = new JLabel("no event "); label4 = new JLabel("no event "); label5 = new JLabel("no event "); // create an object of mouse class Mouse m = new Mouse(); // add mouseListener and MouseMotionListenerto the frame f.addMouseMotionListener(m); f.addMouseListener(m); // add labels to the panel p.add(l1); p.add(label1); p.add(label2); p1.add(l2); p1.add(label3); p1.add(label4); p1.add(label5); // add panel to the frame f.add(p); f.add(p1); f.show(); } // getX() and getY() functions return the // x and y coordinates of the current // mouse position // getClickCount() returns the number of // quick consecutive clicks made by the user // MouseMotionListener events // invoked when mouse button is pressed // and dragged from one point to another // in a component public void mouseDragged(MouseEvent e) { // update the label to show the point // through which point mouse is dragged label1.setText("mouse is dragged through point " + e.getX() + " " + e.getY()); } // invoked when the cursor is moved from // one point to another within the component public void mouseMoved(MouseEvent e) { // update the label to show the point to which the cursor moved label2.setText("mouse is moved to point " + e.getX() + " " + e.getY()); } // MouseListener events // this function is invoked when the mouse is pressed public void mousePressed(MouseEvent e) { // show the point where the user pressed the mouse label3.setText("mouse pressed at point:" + e.getX() + " " + e.getY()); } // this function is invoked when the mouse is released public void mouseReleased(MouseEvent e) { // show the point where the user released the mouse click label3.setText("mouse released at point:" + e.getX() + " " + e.getY()); } // this function is invoked when the mouse exits the component public void mouseExited(MouseEvent e) { // show the point through which the mouse exited the frame label4.setText("mouse exited through point:" + e.getX() + " " + e.getY()); } // this function is invoked when the mouse enters the component public void mouseEntered(MouseEvent e) { // show the point through which the mouse entered the frame label4.setText("mouse entered at point:" + e.getX() + " " + e.getY()); } // this function is invoked when the mouse is pressed or released public void mouseClicked(MouseEvent e) { // getClickCount gives the number of quick, // consecutive clicks made by the user // show the point where the mouse is i.e // the x and y coordinates label5.setText("mouse clicked at point:" + e.getX() + " " + e.getY() + "mouse clicked :" + e.getClickCount()); }} output : MouseListener vs MouseMotionListener MouseListener: MouseListener events are invoked when the mouse is not in motion and is stable . It generates events such as mousePressed, mouseReleased, mouseClicked, mouseExited and mouseEntered (i.e when the mouse buttons are pressed or the mouse enters or exits the component). The object of this class must be registered with the component and they are registered using addMouseListener() method. MouseMotionListener: MouseMotionListener events are invoked when the mouse is in motion . It generates events such as mouseMoved and mouseDragged (i.e when the mouse is moved from one point to another within the component or the mouse button is pressed and dragged from one point to another ). The object of this class must be registered with the component and they are registered using addMouseMotionListener() method. AnshulVaidya Akanksha_Rai sweetyty Java Java Programs Misc Misc Misc Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Object Oriented Programming (OOPs) Concept in Java How to iterate any Map in Java Interfaces in Java HashMap in Java with Examples Stream In Java Initializing a List in Java Java Programming Examples Convert a String to Character Array in Java Convert Double to Integer in Java Implementing a Linked List in Java using Class
[ { "code": null, "e": 52, "s": 24, "text": "\n14 Apr, 2021" }, { "code": null, "e": 463, "s": 52, "text": "MouseListener and MouseMotionListener is an interface in java.awt.event package . Mouse events are of two types. MouseListener handles the events when the mouse is not in motion. While MouseMotionListener handles the events when mouse is in motion.There are five types of events that MouseListener can generate. There are five abstract functions that represent these five events. The abstract functions are : " }, { "code": null, "e": 757, "s": 463, "text": "void mouseReleased(MouseEvent e) : Mouse key is releasedvoid mouseClicked(MouseEvent e) : Mouse key is pressed/releasedvoid mouseExited(MouseEvent e) : Mouse exited the componentvoid mouseEntered(MouseEvent e) : Mouse entered the componentvoid mousepressed(MouseEvent e) : Mouse key is pressed" }, { "code": null, "e": 814, "s": 757, "text": "void mouseReleased(MouseEvent e) : Mouse key is released" }, { "code": null, "e": 878, "s": 814, "text": "void mouseClicked(MouseEvent e) : Mouse key is pressed/released" }, { "code": null, "e": 938, "s": 878, "text": "void mouseExited(MouseEvent e) : Mouse exited the component" }, { "code": null, "e": 1000, "s": 938, "text": "void mouseEntered(MouseEvent e) : Mouse entered the component" }, { "code": null, "e": 1055, "s": 1000, "text": "void mousepressed(MouseEvent e) : Mouse key is pressed" }, { "code": null, "e": 1222, "s": 1055, "text": "There are two types of events that MouseMotionListener can generate. There are two abstract functions that represent these five events. The abstract functions are : " }, { "code": null, "e": 1539, "s": 1222, "text": "void mouseDragged(MouseEvent e) : Invoked when a mouse button is pressed in the component and dragged. Events are passed until the user releases the mouse button.void mouseMoved(MouseEvent e) : invoked when the mouse cursor is moved from one point to another within the component, without pressing any mouse buttons." }, { "code": null, "e": 1702, "s": 1539, "text": "void mouseDragged(MouseEvent e) : Invoked when a mouse button is pressed in the component and dragged. Events are passed until the user releases the mouse button." }, { "code": null, "e": 1857, "s": 1702, "text": "void mouseMoved(MouseEvent e) : invoked when the mouse cursor is moved from one point to another within the component, without pressing any mouse buttons." }, { "code": null, "e": 1984, "s": 1857, "text": "The following programs are a illustration of MouseListener and MouseMotionListener.1. Program to handle MouseListener events " }, { "code": null, "e": 1989, "s": 1984, "text": "Java" }, { "code": "// Java program to handle MouseListener eventsimport java.awt.*;import java.awt.event.*;import javax.swing.*;class Mouse extends Frame implements MouseListener { // Jlabels to display the actions of events of mouseListener // static JLabel label1, label2, label3; // default constructor Mouse() { } // main class public static void main(String[] args) { // create a frame JFrame f = new JFrame(\"MouseListener\"); // set the size of the frame f.setSize(600, 100); // close the frame when close button is pressed f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // create anew panel JPanel p = new JPanel(); // set the layout of the panel p.setLayout(new FlowLayout()); // initialize the labels label1 = new JLabel(\"no event \"); label2 = new JLabel(\"no event \"); label3 = new JLabel(\"no event \"); // create an object of mouse class Mouse m = new Mouse(); // add mouseListener to the frame f.addMouseListener(m); // add labels to the panel p.add(label1); p.add(label2); p.add(label3); // add panel to the frame f.add(p); f.show(); } // getX() and getY() functions return the // x and y coordinates of the current // mouse position // getClickCount() returns the number of // quick consecutive clicks made by the user // this function is invoked when the mouse is pressed public void mousePressed(MouseEvent e) { // show the point where the user pressed the mouse label1.setText(\"mouse pressed at point:\" + e.getX() + \" \" + e.getY()); } // this function is invoked when the mouse is released public void mouseReleased(MouseEvent e) { // show the point where the user released the mouse click label1.setText(\"mouse released at point:\" + e.getX() + \" \" + e.getY()); } // this function is invoked when the mouse exits the component public void mouseExited(MouseEvent e) { // show the point through which the mouse exited the frame label2.setText(\"mouse exited through point:\" + e.getX() + \" \" + e.getY()); } // this function is invoked when the mouse enters the component public void mouseEntered(MouseEvent e) { // show the point through which the mouse entered the frame label2.setText(\"mouse entered at point:\" + e.getX() + \" \" + e.getY()); } // this function is invoked when the mouse is pressed or released public void mouseClicked(MouseEvent e) { // getClickCount gives the number of quick, // consecutive clicks made by the user // show the point where the mouse is i.e // the x and y coordinates label3.setText(\"mouse clicked at point:\" + e.getX() + \" \" + e.getY() + \"mouse clicked :\" + e.getClickCount()); }}", "e": 5032, "s": 1989, "text": null }, { "code": null, "e": 5043, "s": 5032, "text": "Output : " }, { "code": null, "e": 5379, "s": 5045, "text": "Note : The following program might not run in an online compiler please use an offline IDELet’s take another example on MouseListener,the question is: Q. Write an applet which displays x and y co-ordinate in it’s status bar whenever the user click anywhere in the Applet window. Ans. Note: This code is with respect to Netbeans IDE. " }, { "code": null, "e": 5384, "s": 5379, "text": "Java" }, { "code": "//Program of an applet which//displays x and y co-ordinate//in it's status bar,whenever//the user click anywhere in//the applet window. import java.awt.*;import java.awt.event.*;import java.applet.*;public class GFG extends Applet implements MouseListener{public void init(){this.addMouseListener (this);//first \"this\" represent source//(in this case it is applet which//is current calling object) and//second \"this\" represent//listener(in this case it is GFG) }public void mouseClicked(MouseEvent m){ int x = m.getX(); int y = m.getY(); String str = \"x =\" +x+\",y = \"+y; showStatus(str);} @Override public void mousePressed(MouseEvent e) { } @Override public void mouseReleased(MouseEvent e) { } @Override public void mouseEntered(MouseEvent e) { } @Override public void mouseExited(MouseEvent e) { }}", "e": 6256, "s": 5384, "text": null }, { "code": null, "e": 6265, "s": 6256, "text": "Output: " }, { "code": null, "e": 6300, "s": 6265, "text": "Output showing (x,y) in status bar" }, { "code": null, "e": 6484, "s": 6300, "text": "Modification: Now our aim is to improve above program so that co-ordinates should display at that point only where click has been madeNote: This code is with respect to Netbeans IDE. " }, { "code": null, "e": 6489, "s": 6484, "text": "Java" }, { "code": "//Co-ordinates should display//at that point only wherever//their is click on canvas import java.awt.*;import java.awt.event.*;import java.applet.*;public class GFG extends Applet implements MouseListener{private int x,y;private String str = \" \";public void init(){this.addMouseListener (this);//first \"this\" represent source//(in this case it is applet which// is current calling object) and// second \"this\" represent listener//(in this case it is GFG) }public void paint(Graphics g){g.drawString(str,x,y);}public void mouseClicked(MouseEvent m){ x = m.getX(); y = m.getY(); str = \"x =\" +x+\",y = \"+y;repaint(); // we have made this//call because repaint() will//call paint() method for us.//If we comment out this line,//then we will see output//only when focus is on the applet//i.e on maximising the applet window//because paint() method is called//when applet screen gets the focus.//repaint() is a method of Component//class and prototype for this method is://public void repaint() } public void mouseEntered(MouseEvent m)//over-riding all the methods given by// MouseListener{} public void mouseExited(MouseEvent m){} public void mousePressed(MouseEvent m){} public void mouseReleased(MouseEvent m){}}", "e": 7701, "s": 6489, "text": null }, { "code": null, "e": 7709, "s": 7701, "text": "Output " }, { "code": null, "e": 7740, "s": 7709, "text": "Output showing (x,y) in canvas" }, { "code": null, "e": 7974, "s": 7740, "text": "Now one more unusual thing will come in output which is that, we will not able to see previous co-ordinates.But why? In Java, before calling paint() method, it calls one more method which is update() and it do the following things: " }, { "code": null, "e": 8050, "s": 7974, "text": "it repaints the applet background with current color.it then calls paint()." }, { "code": null, "e": 8104, "s": 8050, "text": "it repaints the applet background with current color." }, { "code": null, "e": 8127, "s": 8104, "text": "it then calls paint()." }, { "code": null, "e": 8361, "s": 8127, "text": "Now to see previous co-ordinates as well: we have to over-ride update() method also and it’s prototype is similar to paint().Further Modification To see previous co-ordinates as well:Note: This code is with respect to Netbeans IDE. " }, { "code": null, "e": 8366, "s": 8361, "text": "Java" }, { "code": "//Co-ordinates should display//at that point only wherever//their is click on canvas and also//able to see the previous coordinates import java.awt.*;import java.awt.event.*;import java.applet.*;public class GFG extends Applet implements MouseListener{private int x,y;private String str = \" \";public void init(){this.addMouseListener (this);}public void paint(Graphics g){g.drawString(str,x,y);}public void update(Graphics g){paint(g);}public void mouseClicked(MouseEvent m){ x = m.getX(); y = m.getY(); str = \"x =\" +x+\",y = \"+y;repaint();} public void mouseEntered(MouseEvent m){} public void mouseExited(MouseEvent m){} public void mousePressed(MouseEvent m){} public void mouseReleased(MouseEvent m) { }}", "e": 9081, "s": 8366, "text": null }, { "code": null, "e": 9089, "s": 9081, "text": "Output " }, { "code": null, "e": 9133, "s": 9089, "text": "Output showing previous co-ordinate as well" }, { "code": null, "e": 9183, "s": 9133, "text": "2. Program to handle MouseMotionListener events " }, { "code": null, "e": 9188, "s": 9183, "text": "Java" }, { "code": "// Java Program to illustrate MouseMotionListener eventsimport java.awt.*;import java.awt.event.*;import javax.swing.*;class Mouse extends Frame implements MouseMotionListener { // Jlabels to display the actions of events of MouseMotionListener static JLabel label1, label2; // default constructor Mouse() { } // main class public static void main(String[] args) { // create a frame JFrame f = new JFrame(\"MouseMotionListener\"); // set the size of the frame f.setSize(600, 400); // close the frame when close button is pressed f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // create anew panel JPanel p = new JPanel(); // set the layout of the panel p.setLayout(new FlowLayout()); // initialize the labels label1 = new JLabel(\"no event \"); label2 = new JLabel(\"no event \"); // create an object of mouse class Mouse m = new Mouse(); // add mouseListener to the frame f.addMouseMotionListener(m); // add labels to the panel p.add(label1); p.add(label2); // add panel to the frame f.add(p); f.show(); } // getX() and getY() functions return the // x and y coordinates of the current // mouse position // invoked when mouse button is pressed // and dragged from one point to another // in a component public void mouseDragged(MouseEvent e) { // update the label to show the point // through which point mouse is dragged label1.setText(\"mouse is dragged through point \" + e.getX() + \" \" + e.getY()); } // invoked when the cursor is moved from // one point to another within the component public void mouseMoved(MouseEvent e) { // update the label to show the point to which the cursor moved label2.setText(\"mouse is moved to point \" + e.getX() + \" \" + e.getY()); }}", "e": 11185, "s": 9188, "text": null }, { "code": null, "e": 11196, "s": 11185, "text": "Output : " }, { "code": null, "e": 11290, "s": 11198, "text": "3. Java program to illustrate MouseListener and MouseMotionListener events simultaneously " }, { "code": null, "e": 11295, "s": 11290, "text": "Java" }, { "code": "// Java program to illustrate MouseListener// and MouseMotionListener events// simultaneously import java.awt.*;import java.awt.event.*;import javax.swing.*;class Mouse extends Frame implements MouseMotionListener, MouseListener { // Jlabels to display the actions of events of MouseMotionListener and MouseListener static JLabel label1, label2, label3, label4, label5; // default constructor Mouse() { } // main class public static void main(String[] args) { // create a frame JFrame f = new JFrame(\"MouseListener and MouseMotionListener\"); // set the size of the frame f.setSize(900, 300); // close the frame when close button is pressed f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // create anew panel JPanel p = new JPanel(); JPanel p1 = new JPanel(); // set the layout of the frame f.setLayout(new FlowLayout()); JLabel l1, l2; l1 = new JLabel(\"MouseMotionListener events :\"); l2 = new JLabel(\"MouseLIstener events :\"); // initialize the labels label1 = new JLabel(\"no event \"); label2 = new JLabel(\"no event \"); label3 = new JLabel(\"no event \"); label4 = new JLabel(\"no event \"); label5 = new JLabel(\"no event \"); // create an object of mouse class Mouse m = new Mouse(); // add mouseListener and MouseMotionListenerto the frame f.addMouseMotionListener(m); f.addMouseListener(m); // add labels to the panel p.add(l1); p.add(label1); p.add(label2); p1.add(l2); p1.add(label3); p1.add(label4); p1.add(label5); // add panel to the frame f.add(p); f.add(p1); f.show(); } // getX() and getY() functions return the // x and y coordinates of the current // mouse position // getClickCount() returns the number of // quick consecutive clicks made by the user // MouseMotionListener events // invoked when mouse button is pressed // and dragged from one point to another // in a component public void mouseDragged(MouseEvent e) { // update the label to show the point // through which point mouse is dragged label1.setText(\"mouse is dragged through point \" + e.getX() + \" \" + e.getY()); } // invoked when the cursor is moved from // one point to another within the component public void mouseMoved(MouseEvent e) { // update the label to show the point to which the cursor moved label2.setText(\"mouse is moved to point \" + e.getX() + \" \" + e.getY()); } // MouseListener events // this function is invoked when the mouse is pressed public void mousePressed(MouseEvent e) { // show the point where the user pressed the mouse label3.setText(\"mouse pressed at point:\" + e.getX() + \" \" + e.getY()); } // this function is invoked when the mouse is released public void mouseReleased(MouseEvent e) { // show the point where the user released the mouse click label3.setText(\"mouse released at point:\" + e.getX() + \" \" + e.getY()); } // this function is invoked when the mouse exits the component public void mouseExited(MouseEvent e) { // show the point through which the mouse exited the frame label4.setText(\"mouse exited through point:\" + e.getX() + \" \" + e.getY()); } // this function is invoked when the mouse enters the component public void mouseEntered(MouseEvent e) { // show the point through which the mouse entered the frame label4.setText(\"mouse entered at point:\" + e.getX() + \" \" + e.getY()); } // this function is invoked when the mouse is pressed or released public void mouseClicked(MouseEvent e) { // getClickCount gives the number of quick, // consecutive clicks made by the user // show the point where the mouse is i.e // the x and y coordinates label5.setText(\"mouse clicked at point:\" + e.getX() + \" \" + e.getY() + \"mouse clicked :\" + e.getClickCount()); }}", "e": 15620, "s": 11295, "text": null }, { "code": null, "e": 15631, "s": 15620, "text": "output : " }, { "code": null, "e": 15672, "s": 15635, "text": "MouseListener vs MouseMotionListener" }, { "code": null, "e": 16077, "s": 15674, "text": "MouseListener: MouseListener events are invoked when the mouse is not in motion and is stable . It generates events such as mousePressed, mouseReleased, mouseClicked, mouseExited and mouseEntered (i.e when the mouse buttons are pressed or the mouse enters or exits the component). The object of this class must be registered with the component and they are registered using addMouseListener() method. " }, { "code": null, "e": 16497, "s": 16077, "text": "MouseMotionListener: MouseMotionListener events are invoked when the mouse is in motion . It generates events such as mouseMoved and mouseDragged (i.e when the mouse is moved from one point to another within the component or the mouse button is pressed and dragged from one point to another ). The object of this class must be registered with the component and they are registered using addMouseMotionListener() method." }, { "code": null, "e": 16512, "s": 16499, "text": "AnshulVaidya" }, { "code": null, "e": 16525, "s": 16512, "text": "Akanksha_Rai" }, { "code": null, "e": 16534, "s": 16525, "text": "sweetyty" }, { "code": null, "e": 16539, "s": 16534, "text": "Java" }, { "code": null, "e": 16553, "s": 16539, "text": "Java Programs" }, { "code": null, "e": 16558, "s": 16553, "text": "Misc" }, { "code": null, "e": 16563, "s": 16558, "text": "Misc" }, { "code": null, "e": 16568, "s": 16563, "text": "Misc" }, { "code": null, "e": 16573, "s": 16568, "text": "Java" }, { "code": null, "e": 16671, "s": 16573, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 16722, "s": 16671, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 16753, "s": 16722, "text": "How to iterate any Map in Java" }, { "code": null, "e": 16772, "s": 16753, "text": "Interfaces in Java" }, { "code": null, "e": 16802, "s": 16772, "text": "HashMap in Java with Examples" }, { "code": null, "e": 16817, "s": 16802, "text": "Stream In Java" }, { "code": null, "e": 16845, "s": 16817, "text": "Initializing a List in Java" }, { "code": null, "e": 16871, "s": 16845, "text": "Java Programming Examples" }, { "code": null, "e": 16915, "s": 16871, "text": "Convert a String to Character Array in Java" }, { "code": null, "e": 16949, "s": 16915, "text": "Convert Double to Integer in Java" } ]
Maximum number of groups of size 3 containing two type of items
20 Aug, 2021 Given n instance of item A and m instance of item B. Find the maximum number of groups of size 3 that can be formed using these items such that all groups contain items of both types, i.e., a group should not have either all items of type A or all items of type B. Total number of items of type A in the formed groups must be less than or equal to n. Total number of items of type B in the formed groups must be less than or equal to m.Examples : Input : n = 2 and m = 6. Output : 2 In group 1, one item of type A and two items of type B. Similarly, in the group 2, one item of type A and two items of type B. We have used 2 (<= n) items of type A and 4 (<= m) items of type B. Input : n = 4 and m = 5. Output : 3 In group 1, one item of type A and two items of type B. In group 2, one item of type B and two items of type A. In group 3, one item of type A and two items of type B. We have used 4 (<= n) items of type A and 5 (<= 5) items of type B. Observation: 1. There will be n groups possible if m >= 2n. Or there will be m groups possible, if n >= 2m. 2. Suppose n = 3 and m = 3, so one instance of item A will make a group with the two instance of item B and one instance of item B will make a group with the two instance of item A. So, maximum two groups are possible. So find the total number of such conditions with given n and m by dividing m and m by 3. After this, there can be 0, 1, 2 instances of each type can be left. For finding the number of groups for the left instances: a) If n = 0 or m = 0, 0 group is possible. b) If n + m >= 3, only 1 group is possible.Algorithm for solving this problem: 1. If n >= 2m, maximum number of groups = n. 2. Else if m >= 2n, maximum number of groups = m. 3. Else If (m + n) % 3 == 0, maximum number of group = (m + n)/3; 4. Else maximum number of group = (n + m)/3. And set n = n%3 and m = m%3. a) If n != 0 && m != 0 && (n + m) >= 3, add one to maximum number of groups.Below is implementation of the above idea : C++ Java Python3 C# PHP Javascript // C++ program to calculate// maximum number of groups#include<bits/stdc++.h> using namespace std; // Implements above mentioned steps.int maxGroup(int n, int m){ if (n >= 2 * m) return n; if (m >= 2 * n) return m; if ((m + n) % 3 == 0) return (m + n)/3; int ans = (m + n)/3; m %= 3; n %= 3; if (m && n && (m + n) >= 3) ans++; return ans;} // Driver codeint main(){ int n = 4, m = 5; cout << maxGroup(n, m) << endl; return 0;} // Java program to calculate// maximum number of groupsimport java.io.*; public class GFG{ // Implements above mentioned steps.static int maxGroup(int n, int m){ if (n >= 2 * m) return n; if (m >= 2 * n) return m; if ((m + n) % 3 == 0) return (m + n) / 3; int ans = (m + n) / 3; m %= 3; n %= 3; if (m > 0 && n > 0 && (m + n) >= 3) ans++; return ans;} // Driver code static public void main (String[] args) { int n = 4, m = 5; System.out.println(maxGroup(n, m)); }} // This code is contributed by vt_m. # Python3 program to calculate maximum# number of groups # Implements above mentioned stepsdef maxGroup(n, m): if n >= 2 * m: return n if m >= 2 * n: return m if (m + n) % 3 == 0: return (m + n) // 3 ans = (m + n) // 3 m = m % 3 n = n % 3 if m and n and (m + n) >= 3: ans += 1 return ans # Driver Coden, m = 4, 5print(maxGroup(n, m)) # This code is contributed# by Mohit kumar 29 // C# program to calculate// maximum number of groupsusing System; public class GFG{ // Implements above mentioned steps.static int maxGroup(int n, int m){ if (n >= 2 * m) return n; if (m >= 2 * n) return m; if ((m + n) % 3 == 0) return (m + n) / 3; int ans = (m + n) / 3; m %= 3; n %= 3; if (m > 0 && n > 0 && (m + n) >= 3) ans++; return ans;} // Driver code static public void Main () { int n = 4, m = 5; Console.WriteLine(maxGroup(n, m)); }} // This code is contributed by vt_m. <?php// PHP program to calculate// maximum number of groups // Implements above mentioned steps.function maxGroup($n, $m){ if ($n >= 2 * $m) return n; if ($m >= 2 * $n) return m; if ((($m + $n) % 3) == 0) return ($m + $n) / 3; $ans = ($m + $n) / 3; $m %= 3; $n %= 3; if ($m && $n && ($m + $n) >= 3) $ans++; return $ans;} // Driver code$n = 4; $m = 5;echo maxGroup($n, $m) ; // This code is contributed// by nitin mittal.?> <script> // JavaScript program to find Cullen number // Implements above mentioned steps.function maxGroup(n, m){ if (n >= 2 * m) return n; if (m >= 2 * n) return m; if ((m + n) % 3 == 0) return (m + n) / 3; let ans = (m + n) / 3; m %= 3; n %= 3; if (m > 0 && n > 0 && (m + n) >= 3) ans++; return ans;} // Driver Code let n = 4, m = 5; document.write(maxGroup(n, m)); // This code is contributed by chinmoy1997pal.</script> Output : 3 Time Complexity: O(1)Auxiliary Space: O(1) This article is contributed by Anuj Chauhan(anuj0503). 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. vt_m nitin mittal mohit kumar 29 chinmoy1997pal pankajsharmagfg simmytarika5 Algorithms Algorithms Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. What is Hashing | A Complete Tutorial Find if there is a path between two vertices in an undirected graph How to Start Learning DSA? Complete Roadmap To Learn DSA From Scratch Types of Complexity Classes | P, NP, CoNP, NP hard and NP complete Difference between NP hard and NP complete problem What Should I Learn First: Data Structures or Algorithms? Ternary Search K means Clustering - Introduction Find maximum meetings in one room
[ { "code": null, "e": 52, "s": 24, "text": "\n20 Aug, 2021" }, { "code": null, "e": 501, "s": 52, "text": "Given n instance of item A and m instance of item B. Find the maximum number of groups of size 3 that can be formed using these items such that all groups contain items of both types, i.e., a group should not have either all items of type A or all items of type B. Total number of items of type A in the formed groups must be less than or equal to n. Total number of items of type B in the formed groups must be less than or equal to m.Examples : " }, { "code": null, "e": 1006, "s": 501, "text": "Input : n = 2 and m = 6.\nOutput : 2\nIn group 1, one item of type A and two items of\ntype B. Similarly, in the group 2, one item of \ntype A and two items of type B.\nWe have used 2 (<= n) items of type A and 4 (<= m)\nitems of type B.\n\nInput : n = 4 and m = 5.\nOutput : 3\nIn group 1, one item of type A and two items of type B.\nIn group 2, one item of type B and two items of type A.\nIn group 3, one item of type A and two items of type B.\nWe have used 4 (<= n) items of type A and 5 (<= 5)\nitems of type B." }, { "code": null, "e": 2044, "s": 1008, "text": "Observation: 1. There will be n groups possible if m >= 2n. Or there will be m groups possible, if n >= 2m. 2. Suppose n = 3 and m = 3, so one instance of item A will make a group with the two instance of item B and one instance of item B will make a group with the two instance of item A. So, maximum two groups are possible. So find the total number of such conditions with given n and m by dividing m and m by 3. After this, there can be 0, 1, 2 instances of each type can be left. For finding the number of groups for the left instances: a) If n = 0 or m = 0, 0 group is possible. b) If n + m >= 3, only 1 group is possible.Algorithm for solving this problem: 1. If n >= 2m, maximum number of groups = n. 2. Else if m >= 2n, maximum number of groups = m. 3. Else If (m + n) % 3 == 0, maximum number of group = (m + n)/3; 4. Else maximum number of group = (n + m)/3. And set n = n%3 and m = m%3. a) If n != 0 && m != 0 && (n + m) >= 3, add one to maximum number of groups.Below is implementation of the above idea : " }, { "code": null, "e": 2048, "s": 2044, "text": "C++" }, { "code": null, "e": 2053, "s": 2048, "text": "Java" }, { "code": null, "e": 2061, "s": 2053, "text": "Python3" }, { "code": null, "e": 2064, "s": 2061, "text": "C#" }, { "code": null, "e": 2068, "s": 2064, "text": "PHP" }, { "code": null, "e": 2079, "s": 2068, "text": "Javascript" }, { "code": "// C++ program to calculate// maximum number of groups#include<bits/stdc++.h> using namespace std; // Implements above mentioned steps.int maxGroup(int n, int m){ if (n >= 2 * m) return n; if (m >= 2 * n) return m; if ((m + n) % 3 == 0) return (m + n)/3; int ans = (m + n)/3; m %= 3; n %= 3; if (m && n && (m + n) >= 3) ans++; return ans;} // Driver codeint main(){ int n = 4, m = 5; cout << maxGroup(n, m) << endl; return 0;}", "e": 2570, "s": 2079, "text": null }, { "code": "// Java program to calculate// maximum number of groupsimport java.io.*; public class GFG{ // Implements above mentioned steps.static int maxGroup(int n, int m){ if (n >= 2 * m) return n; if (m >= 2 * n) return m; if ((m + n) % 3 == 0) return (m + n) / 3; int ans = (m + n) / 3; m %= 3; n %= 3; if (m > 0 && n > 0 && (m + n) >= 3) ans++; return ans;} // Driver code static public void main (String[] args) { int n = 4, m = 5; System.out.println(maxGroup(n, m)); }} // This code is contributed by vt_m.", "e": 3158, "s": 2570, "text": null }, { "code": "# Python3 program to calculate maximum# number of groups # Implements above mentioned stepsdef maxGroup(n, m): if n >= 2 * m: return n if m >= 2 * n: return m if (m + n) % 3 == 0: return (m + n) // 3 ans = (m + n) // 3 m = m % 3 n = n % 3 if m and n and (m + n) >= 3: ans += 1 return ans # Driver Coden, m = 4, 5print(maxGroup(n, m)) # This code is contributed# by Mohit kumar 29", "e": 3604, "s": 3158, "text": null }, { "code": "// C# program to calculate// maximum number of groupsusing System; public class GFG{ // Implements above mentioned steps.static int maxGroup(int n, int m){ if (n >= 2 * m) return n; if (m >= 2 * n) return m; if ((m + n) % 3 == 0) return (m + n) / 3; int ans = (m + n) / 3; m %= 3; n %= 3; if (m > 0 && n > 0 && (m + n) >= 3) ans++; return ans;} // Driver code static public void Main () { int n = 4, m = 5; Console.WriteLine(maxGroup(n, m)); }} // This code is contributed by vt_m.", "e": 4172, "s": 3604, "text": null }, { "code": "<?php// PHP program to calculate// maximum number of groups // Implements above mentioned steps.function maxGroup($n, $m){ if ($n >= 2 * $m) return n; if ($m >= 2 * $n) return m; if ((($m + $n) % 3) == 0) return ($m + $n) / 3; $ans = ($m + $n) / 3; $m %= 3; $n %= 3; if ($m && $n && ($m + $n) >= 3) $ans++; return $ans;} // Driver code$n = 4; $m = 5;echo maxGroup($n, $m) ; // This code is contributed// by nitin mittal.?>", "e": 4650, "s": 4172, "text": null }, { "code": "<script> // JavaScript program to find Cullen number // Implements above mentioned steps.function maxGroup(n, m){ if (n >= 2 * m) return n; if (m >= 2 * n) return m; if ((m + n) % 3 == 0) return (m + n) / 3; let ans = (m + n) / 3; m %= 3; n %= 3; if (m > 0 && n > 0 && (m + n) >= 3) ans++; return ans;} // Driver Code let n = 4, m = 5; document.write(maxGroup(n, m)); // This code is contributed by chinmoy1997pal.</script>", "e": 5141, "s": 4650, "text": null }, { "code": null, "e": 5152, "s": 5141, "text": "Output : " }, { "code": null, "e": 5154, "s": 5152, "text": "3" }, { "code": null, "e": 5628, "s": 5154, "text": "Time Complexity: O(1)Auxiliary Space: O(1) This article is contributed by Anuj Chauhan(anuj0503). 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": 5633, "s": 5628, "text": "vt_m" }, { "code": null, "e": 5646, "s": 5633, "text": "nitin mittal" }, { "code": null, "e": 5661, "s": 5646, "text": "mohit kumar 29" }, { "code": null, "e": 5676, "s": 5661, "text": "chinmoy1997pal" }, { "code": null, "e": 5692, "s": 5676, "text": "pankajsharmagfg" }, { "code": null, "e": 5705, "s": 5692, "text": "simmytarika5" }, { "code": null, "e": 5716, "s": 5705, "text": "Algorithms" }, { "code": null, "e": 5727, "s": 5716, "text": "Algorithms" }, { "code": null, "e": 5825, "s": 5727, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 5863, "s": 5825, "text": "What is Hashing | A Complete Tutorial" }, { "code": null, "e": 5931, "s": 5863, "text": "Find if there is a path between two vertices in an undirected graph" }, { "code": null, "e": 5958, "s": 5931, "text": "How to Start Learning DSA?" }, { "code": null, "e": 6001, "s": 5958, "text": "Complete Roadmap To Learn DSA From Scratch" }, { "code": null, "e": 6068, "s": 6001, "text": "Types of Complexity Classes | P, NP, CoNP, NP hard and NP complete" }, { "code": null, "e": 6119, "s": 6068, "text": "Difference between NP hard and NP complete problem" }, { "code": null, "e": 6177, "s": 6119, "text": "What Should I Learn First: Data Structures or Algorithms?" }, { "code": null, "e": 6192, "s": 6177, "text": "Ternary Search" }, { "code": null, "e": 6226, "s": 6192, "text": "K means Clustering - Introduction" } ]
How to make object eligible for garbage collection in Java?
30 May, 2018 An object is eligible to be garbage collected if its reference variable is lost from the program during execution.Sometimes they are also called unreachable objects. What is reference of an object? The new operator dynamically allocates memory for an object and returns a reference to it. This reference is the address in memory of the object allocated by new. A reference is an address that indicates where an object’s variables, methods etc. are stored. The objects are not actually used when assigned to a variable or passed as an argument to a method . The references to objects are used everywhere. Example: Box mybox = new Box(); //referencing to object Role of an unreachable objects in java In java, the memory allocated at runtime i.e. heap area can be made free by the process of garbage collection. It is nothing but just a method of making the memory free which is not being used by the programmer. Only the objects who have no longer reference to them are eligible for garbage collection in java. Ways to make an object eligible for garbage collection: Please note that the object can not become a candidate for garbage collection until all references to it are discarded. Object created inside a method : When a method is called it goes inside the stack frame. When the method is popped from the stack, all its members dies and if some objects were created inside it then these objects becomes unreachable or anonymous after method execution and thus becomes eligible for garbage collection.Example:/* Java program to demonstrate that objects created inside a method will becomeseligible for gc after method execution terminate */ class Test{ // to store object name String obj_name; public Test(String obj_name) { this.obj_name = obj_name; } static void show() { //object t1 inside method becomes unreachable when show() removed Test t1 = new Test("t1"); display(); } static void display() { //object t2 inside method becomes unreachable when display() removed Test t2 = new Test("t2"); } // Driver method public static void main(String args[]) { // calling show() show(); // calling garbage collector System.gc(); } @Override /* Overriding finalize method to check which object is garbage collected */ protected void finalize() throws Throwable { // will print name of object System.out.println(this.obj_name + " successfully garbage collected"); }}Output:t2 successfully garbage collected t1 successfully garbage collected Note : If a method returns the object created inside it and we store this object reference by using a reference-type variable than it is no longer eligible for garbage collection.Reassigning the reference variable: When reference id of one object is referenced to reference id of some other object then the previous object has no any longer reference to it and becomes unreachable and thus becomes eligible for garbage collection.Example:/* Java program to demonstrate gc when one object referred to other object */ class Test{ // to store object name String obj_name; public Test(String obj_name) { this.obj_name = obj_name; } // Driver method public static void main(String args[]) { Test t1 = new Test("t1"); Test t2 = new Test("t2"); //t1 now referred to t2 t1 = t2; // calling garbage collector System.gc(); } @Override /* Overriding finalize method to check which object is garbage collected */ protected void finalize() throws Throwable { // will print name of object System.out.println(this.obj_name + " successfully garbage collected"); }}Output:t1 successfully garbage collected Nullifying the reference variable : When all the reference variables of an object are changed to NULL, it becomes unreachable and thus becomes eligible for garbage collection.Example:/* Java program to demonstrate gc when object reference changed to NULL */ class Test{ // to store object name String obj_name; public Test(String obj_name) { this.obj_name = obj_name; } // Driver method public static void main(String args[]) { Test t1 = new Test("t1"); /* t1 being used for some purpose in program */ /* When there is no more use of t1, make the object referred by t1 eligible for garbage collection */ t1 = null; // calling garbage collector System.gc(); } @Override /* Overriding finalize method to check which object is garbage collected */ protected void finalize() throws Throwable { // will print name of object System.out.println(this.obj_name + " successfully garbage collected"); }}Output:t1 successfully garbage collected Anonymous object : The reference id of an anonymous object is not stored anywhere. Hence, it becomes unreachable.Example:/* Java program to demonstrate gc of anonymous objects */ class Test{ // to store object name String obj_name; public Test(String obj_name) { this.obj_name = obj_name; } // Driver method public static void main(String args[]) { //anonymous object without reference id new Test("t1"); // calling garbage collector System.gc(); } @Override /* Overriding finalize method to check which object is garbage collected */ protected void finalize() throws Throwable { // will print name of object System.out.println(this.obj_name + " successfully garbage collected"); }}Output:t1 successfully garbage collected Object created inside a method : When a method is called it goes inside the stack frame. When the method is popped from the stack, all its members dies and if some objects were created inside it then these objects becomes unreachable or anonymous after method execution and thus becomes eligible for garbage collection.Example:/* Java program to demonstrate that objects created inside a method will becomeseligible for gc after method execution terminate */ class Test{ // to store object name String obj_name; public Test(String obj_name) { this.obj_name = obj_name; } static void show() { //object t1 inside method becomes unreachable when show() removed Test t1 = new Test("t1"); display(); } static void display() { //object t2 inside method becomes unreachable when display() removed Test t2 = new Test("t2"); } // Driver method public static void main(String args[]) { // calling show() show(); // calling garbage collector System.gc(); } @Override /* Overriding finalize method to check which object is garbage collected */ protected void finalize() throws Throwable { // will print name of object System.out.println(this.obj_name + " successfully garbage collected"); }}Output:t2 successfully garbage collected t1 successfully garbage collected Note : If a method returns the object created inside it and we store this object reference by using a reference-type variable than it is no longer eligible for garbage collection. /* Java program to demonstrate that objects created inside a method will becomeseligible for gc after method execution terminate */ class Test{ // to store object name String obj_name; public Test(String obj_name) { this.obj_name = obj_name; } static void show() { //object t1 inside method becomes unreachable when show() removed Test t1 = new Test("t1"); display(); } static void display() { //object t2 inside method becomes unreachable when display() removed Test t2 = new Test("t2"); } // Driver method public static void main(String args[]) { // calling show() show(); // calling garbage collector System.gc(); } @Override /* Overriding finalize method to check which object is garbage collected */ protected void finalize() throws Throwable { // will print name of object System.out.println(this.obj_name + " successfully garbage collected"); }} Output: t2 successfully garbage collected t1 successfully garbage collected Note : If a method returns the object created inside it and we store this object reference by using a reference-type variable than it is no longer eligible for garbage collection. Reassigning the reference variable: When reference id of one object is referenced to reference id of some other object then the previous object has no any longer reference to it and becomes unreachable and thus becomes eligible for garbage collection.Example:/* Java program to demonstrate gc when one object referred to other object */ class Test{ // to store object name String obj_name; public Test(String obj_name) { this.obj_name = obj_name; } // Driver method public static void main(String args[]) { Test t1 = new Test("t1"); Test t2 = new Test("t2"); //t1 now referred to t2 t1 = t2; // calling garbage collector System.gc(); } @Override /* Overriding finalize method to check which object is garbage collected */ protected void finalize() throws Throwable { // will print name of object System.out.println(this.obj_name + " successfully garbage collected"); }}Output:t1 successfully garbage collected /* Java program to demonstrate gc when one object referred to other object */ class Test{ // to store object name String obj_name; public Test(String obj_name) { this.obj_name = obj_name; } // Driver method public static void main(String args[]) { Test t1 = new Test("t1"); Test t2 = new Test("t2"); //t1 now referred to t2 t1 = t2; // calling garbage collector System.gc(); } @Override /* Overriding finalize method to check which object is garbage collected */ protected void finalize() throws Throwable { // will print name of object System.out.println(this.obj_name + " successfully garbage collected"); }} Output: t1 successfully garbage collected Nullifying the reference variable : When all the reference variables of an object are changed to NULL, it becomes unreachable and thus becomes eligible for garbage collection.Example:/* Java program to demonstrate gc when object reference changed to NULL */ class Test{ // to store object name String obj_name; public Test(String obj_name) { this.obj_name = obj_name; } // Driver method public static void main(String args[]) { Test t1 = new Test("t1"); /* t1 being used for some purpose in program */ /* When there is no more use of t1, make the object referred by t1 eligible for garbage collection */ t1 = null; // calling garbage collector System.gc(); } @Override /* Overriding finalize method to check which object is garbage collected */ protected void finalize() throws Throwable { // will print name of object System.out.println(this.obj_name + " successfully garbage collected"); }}Output:t1 successfully garbage collected /* Java program to demonstrate gc when object reference changed to NULL */ class Test{ // to store object name String obj_name; public Test(String obj_name) { this.obj_name = obj_name; } // Driver method public static void main(String args[]) { Test t1 = new Test("t1"); /* t1 being used for some purpose in program */ /* When there is no more use of t1, make the object referred by t1 eligible for garbage collection */ t1 = null; // calling garbage collector System.gc(); } @Override /* Overriding finalize method to check which object is garbage collected */ protected void finalize() throws Throwable { // will print name of object System.out.println(this.obj_name + " successfully garbage collected"); }} Output: t1 successfully garbage collected Anonymous object : The reference id of an anonymous object is not stored anywhere. Hence, it becomes unreachable.Example:/* Java program to demonstrate gc of anonymous objects */ class Test{ // to store object name String obj_name; public Test(String obj_name) { this.obj_name = obj_name; } // Driver method public static void main(String args[]) { //anonymous object without reference id new Test("t1"); // calling garbage collector System.gc(); } @Override /* Overriding finalize method to check which object is garbage collected */ protected void finalize() throws Throwable { // will print name of object System.out.println(this.obj_name + " successfully garbage collected"); }}Output:t1 successfully garbage collected /* Java program to demonstrate gc of anonymous objects */ class Test{ // to store object name String obj_name; public Test(String obj_name) { this.obj_name = obj_name; } // Driver method public static void main(String args[]) { //anonymous object without reference id new Test("t1"); // calling garbage collector System.gc(); } @Override /* Overriding finalize method to check which object is garbage collected */ protected void finalize() throws Throwable { // will print name of object System.out.println(this.obj_name + " successfully garbage collected"); }} Output: t1 successfully garbage collected Related Article: Island of Isolation This article is contributed by Apoorva Singh and Gaurav Miglani. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.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. java-garbage-collection 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 Collections in Java Stream In Java Multidimensional Arrays in Java Singleton Class in Java Set in Java Stack Class in Java
[ { "code": null, "e": 52, "s": 24, "text": "\n30 May, 2018" }, { "code": null, "e": 218, "s": 52, "text": "An object is eligible to be garbage collected if its reference variable is lost from the program during execution.Sometimes they are also called unreachable objects." }, { "code": null, "e": 250, "s": 218, "text": "What is reference of an object?" }, { "code": null, "e": 508, "s": 250, "text": "The new operator dynamically allocates memory for an object and returns a reference to it. This reference is the address in memory of the object allocated by new. A reference is an address that indicates where an object’s variables, methods etc. are stored." }, { "code": null, "e": 665, "s": 508, "text": "The objects are not actually used when assigned to a variable or passed as an argument to a method . The references to objects are used everywhere. Example:" }, { "code": null, "e": 716, "s": 665, "text": "Box mybox = new Box(); //referencing to object\n" }, { "code": null, "e": 755, "s": 716, "text": "Role of an unreachable objects in java" }, { "code": null, "e": 1066, "s": 755, "text": "In java, the memory allocated at runtime i.e. heap area can be made free by the process of garbage collection. It is nothing but just a method of making the memory free which is not being used by the programmer. Only the objects who have no longer reference to them are eligible for garbage collection in java." }, { "code": null, "e": 1122, "s": 1066, "text": "Ways to make an object eligible for garbage collection:" }, { "code": null, "e": 1242, "s": 1122, "text": "Please note that the object can not become a candidate for garbage collection until all references to it are discarded." }, { "code": null, "e": 5879, "s": 1242, "text": "Object created inside a method : When a method is called it goes inside the stack frame. When the method is popped from the stack, all its members dies and if some objects were created inside it then these objects becomes unreachable or anonymous after method execution and thus becomes eligible for garbage collection.Example:/* Java program to demonstrate that objects created inside a method will becomeseligible for gc after method execution terminate */ class Test{ // to store object name String obj_name; public Test(String obj_name) { this.obj_name = obj_name; } static void show() { //object t1 inside method becomes unreachable when show() removed Test t1 = new Test(\"t1\"); display(); } static void display() { //object t2 inside method becomes unreachable when display() removed Test t2 = new Test(\"t2\"); } // Driver method public static void main(String args[]) { // calling show() show(); // calling garbage collector System.gc(); } @Override /* Overriding finalize method to check which object is garbage collected */ protected void finalize() throws Throwable { // will print name of object System.out.println(this.obj_name + \" successfully garbage collected\"); }}Output:t2 successfully garbage collected\nt1 successfully garbage collected\nNote : If a method returns the object created inside it and we store this object reference by using a reference-type variable than it is no longer eligible for garbage collection.Reassigning the reference variable: When reference id of one object is referenced to reference id of some other object then the previous object has no any longer reference to it and becomes unreachable and thus becomes eligible for garbage collection.Example:/* Java program to demonstrate gc when one object referred to other object */ class Test{ // to store object name String obj_name; public Test(String obj_name) { this.obj_name = obj_name; } // Driver method public static void main(String args[]) { Test t1 = new Test(\"t1\"); Test t2 = new Test(\"t2\"); //t1 now referred to t2 t1 = t2; // calling garbage collector System.gc(); } @Override /* Overriding finalize method to check which object is garbage collected */ protected void finalize() throws Throwable { // will print name of object System.out.println(this.obj_name + \" successfully garbage collected\"); }}Output:t1 successfully garbage collected\nNullifying the reference variable : When all the reference variables of an object are changed to NULL, it becomes unreachable and thus becomes eligible for garbage collection.Example:/* Java program to demonstrate gc when object reference changed to NULL */ class Test{ // to store object name String obj_name; public Test(String obj_name) { this.obj_name = obj_name; } // Driver method public static void main(String args[]) { Test t1 = new Test(\"t1\"); /* t1 being used for some purpose in program */ /* When there is no more use of t1, make the object referred by t1 eligible for garbage collection */ t1 = null; // calling garbage collector System.gc(); } @Override /* Overriding finalize method to check which object is garbage collected */ protected void finalize() throws Throwable { // will print name of object System.out.println(this.obj_name + \" successfully garbage collected\"); }}Output:t1 successfully garbage collected\nAnonymous object : The reference id of an anonymous object is not stored anywhere. Hence, it becomes unreachable.Example:/* Java program to demonstrate gc of anonymous objects */ class Test{ // to store object name String obj_name; public Test(String obj_name) { this.obj_name = obj_name; } // Driver method public static void main(String args[]) { //anonymous object without reference id new Test(\"t1\"); // calling garbage collector System.gc(); } @Override /* Overriding finalize method to check which object is garbage collected */ protected void finalize() throws Throwable { // will print name of object System.out.println(this.obj_name + \" successfully garbage collected\"); }}Output:t1 successfully garbage collected\n" }, { "code": null, "e": 7515, "s": 5879, "text": "Object created inside a method : When a method is called it goes inside the stack frame. When the method is popped from the stack, all its members dies and if some objects were created inside it then these objects becomes unreachable or anonymous after method execution and thus becomes eligible for garbage collection.Example:/* Java program to demonstrate that objects created inside a method will becomeseligible for gc after method execution terminate */ class Test{ // to store object name String obj_name; public Test(String obj_name) { this.obj_name = obj_name; } static void show() { //object t1 inside method becomes unreachable when show() removed Test t1 = new Test(\"t1\"); display(); } static void display() { //object t2 inside method becomes unreachable when display() removed Test t2 = new Test(\"t2\"); } // Driver method public static void main(String args[]) { // calling show() show(); // calling garbage collector System.gc(); } @Override /* Overriding finalize method to check which object is garbage collected */ protected void finalize() throws Throwable { // will print name of object System.out.println(this.obj_name + \" successfully garbage collected\"); }}Output:t2 successfully garbage collected\nt1 successfully garbage collected\nNote : If a method returns the object created inside it and we store this object reference by using a reference-type variable than it is no longer eligible for garbage collection." }, { "code": "/* Java program to demonstrate that objects created inside a method will becomeseligible for gc after method execution terminate */ class Test{ // to store object name String obj_name; public Test(String obj_name) { this.obj_name = obj_name; } static void show() { //object t1 inside method becomes unreachable when show() removed Test t1 = new Test(\"t1\"); display(); } static void display() { //object t2 inside method becomes unreachable when display() removed Test t2 = new Test(\"t2\"); } // Driver method public static void main(String args[]) { // calling show() show(); // calling garbage collector System.gc(); } @Override /* Overriding finalize method to check which object is garbage collected */ protected void finalize() throws Throwable { // will print name of object System.out.println(this.obj_name + \" successfully garbage collected\"); }}", "e": 8570, "s": 7515, "text": null }, { "code": null, "e": 8578, "s": 8570, "text": "Output:" }, { "code": null, "e": 8647, "s": 8578, "text": "t2 successfully garbage collected\nt1 successfully garbage collected\n" }, { "code": null, "e": 8827, "s": 8647, "text": "Note : If a method returns the object created inside it and we store this object reference by using a reference-type variable than it is no longer eligible for garbage collection." }, { "code": null, "e": 9888, "s": 8827, "text": "Reassigning the reference variable: When reference id of one object is referenced to reference id of some other object then the previous object has no any longer reference to it and becomes unreachable and thus becomes eligible for garbage collection.Example:/* Java program to demonstrate gc when one object referred to other object */ class Test{ // to store object name String obj_name; public Test(String obj_name) { this.obj_name = obj_name; } // Driver method public static void main(String args[]) { Test t1 = new Test(\"t1\"); Test t2 = new Test(\"t2\"); //t1 now referred to t2 t1 = t2; // calling garbage collector System.gc(); } @Override /* Overriding finalize method to check which object is garbage collected */ protected void finalize() throws Throwable { // will print name of object System.out.println(this.obj_name + \" successfully garbage collected\"); }}Output:t1 successfully garbage collected\n" }, { "code": "/* Java program to demonstrate gc when one object referred to other object */ class Test{ // to store object name String obj_name; public Test(String obj_name) { this.obj_name = obj_name; } // Driver method public static void main(String args[]) { Test t1 = new Test(\"t1\"); Test t2 = new Test(\"t2\"); //t1 now referred to t2 t1 = t2; // calling garbage collector System.gc(); } @Override /* Overriding finalize method to check which object is garbage collected */ protected void finalize() throws Throwable { // will print name of object System.out.println(this.obj_name + \" successfully garbage collected\"); }}", "e": 10649, "s": 9888, "text": null }, { "code": null, "e": 10657, "s": 10649, "text": "Output:" }, { "code": null, "e": 10692, "s": 10657, "text": "t1 successfully garbage collected\n" }, { "code": null, "e": 11791, "s": 10692, "text": "Nullifying the reference variable : When all the reference variables of an object are changed to NULL, it becomes unreachable and thus becomes eligible for garbage collection.Example:/* Java program to demonstrate gc when object reference changed to NULL */ class Test{ // to store object name String obj_name; public Test(String obj_name) { this.obj_name = obj_name; } // Driver method public static void main(String args[]) { Test t1 = new Test(\"t1\"); /* t1 being used for some purpose in program */ /* When there is no more use of t1, make the object referred by t1 eligible for garbage collection */ t1 = null; // calling garbage collector System.gc(); } @Override /* Overriding finalize method to check which object is garbage collected */ protected void finalize() throws Throwable { // will print name of object System.out.println(this.obj_name + \" successfully garbage collected\"); }}Output:t1 successfully garbage collected\n" }, { "code": "/* Java program to demonstrate gc when object reference changed to NULL */ class Test{ // to store object name String obj_name; public Test(String obj_name) { this.obj_name = obj_name; } // Driver method public static void main(String args[]) { Test t1 = new Test(\"t1\"); /* t1 being used for some purpose in program */ /* When there is no more use of t1, make the object referred by t1 eligible for garbage collection */ t1 = null; // calling garbage collector System.gc(); } @Override /* Overriding finalize method to check which object is garbage collected */ protected void finalize() throws Throwable { // will print name of object System.out.println(this.obj_name + \" successfully garbage collected\"); }}", "e": 12666, "s": 11791, "text": null }, { "code": null, "e": 12674, "s": 12666, "text": "Output:" }, { "code": null, "e": 12709, "s": 12674, "text": "t1 successfully garbage collected\n" }, { "code": null, "e": 13553, "s": 12709, "text": "Anonymous object : The reference id of an anonymous object is not stored anywhere. Hence, it becomes unreachable.Example:/* Java program to demonstrate gc of anonymous objects */ class Test{ // to store object name String obj_name; public Test(String obj_name) { this.obj_name = obj_name; } // Driver method public static void main(String args[]) { //anonymous object without reference id new Test(\"t1\"); // calling garbage collector System.gc(); } @Override /* Overriding finalize method to check which object is garbage collected */ protected void finalize() throws Throwable { // will print name of object System.out.println(this.obj_name + \" successfully garbage collected\"); }}Output:t1 successfully garbage collected\n" }, { "code": "/* Java program to demonstrate gc of anonymous objects */ class Test{ // to store object name String obj_name; public Test(String obj_name) { this.obj_name = obj_name; } // Driver method public static void main(String args[]) { //anonymous object without reference id new Test(\"t1\"); // calling garbage collector System.gc(); } @Override /* Overriding finalize method to check which object is garbage collected */ protected void finalize() throws Throwable { // will print name of object System.out.println(this.obj_name + \" successfully garbage collected\"); }}", "e": 14235, "s": 13553, "text": null }, { "code": null, "e": 14243, "s": 14235, "text": "Output:" }, { "code": null, "e": 14278, "s": 14243, "text": "t1 successfully garbage collected\n" }, { "code": null, "e": 14315, "s": 14278, "text": "Related Article: Island of Isolation" }, { "code": null, "e": 14635, "s": 14315, "text": "This article is contributed by Apoorva Singh and Gaurav Miglani. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.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": 14760, "s": 14635, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 14784, "s": 14760, "text": "java-garbage-collection" }, { "code": null, "e": 14789, "s": 14784, "text": "Java" }, { "code": null, "e": 14794, "s": 14789, "text": "Java" }, { "code": null, "e": 14892, "s": 14794, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 14923, "s": 14892, "text": "How to iterate any Map in Java" }, { "code": null, "e": 14942, "s": 14923, "text": "Interfaces in Java" }, { "code": null, "e": 14972, "s": 14942, "text": "HashMap in Java with Examples" }, { "code": null, "e": 14990, "s": 14972, "text": "ArrayList in Java" }, { "code": null, "e": 15010, "s": 14990, "text": "Collections in Java" }, { "code": null, "e": 15025, "s": 15010, "text": "Stream In Java" }, { "code": null, "e": 15057, "s": 15025, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 15081, "s": 15057, "text": "Singleton Class in Java" }, { "code": null, "e": 15093, "s": 15081, "text": "Set in Java" } ]
sort() vs. partial_sort() vs. nth_element() + sort() in C++ STL
21 Jun, 2020 In this article, we will discuss the difference between sort(), partial_sort(), and nth_element()+sort(). Below is the illustration of the above functions: sort(): C++ STL provides a function sort() that sorts a list of element in O(N*log N) time. By default, sort() sorts an array in ascending order. Below is the program to illustrate sort():// C++ program to illustrate the default behaviour// of sort() in STL#include <bits/stdc++.h>using namespace std; // Driver Codeint main(){ // Given array of elements int arr[] = { 1, 5, 8, 9, 6, 7, 3, 4, 2, 0 }; int n = sizeof(arr) / sizeof(arr[0]); // Function sort() to sort the element of // the array in increasing order sort(arr, arr + n); // Print the array elements after sorting cout << "\nArray after sorting using " "default sort is: \n"; for (int i = 0; i < n; ++i) { cout << arr[i] << " "; } return 0;}Output:Array after sorting using default sort is : 0 1 2 3 4 5 6 7 8 9 partial_sort(): One of the variants of std::sort() is std::partial_sort(), which is used for sorting not the entire range, but only a sub-part of it. It rearranges the elements in the range [first, last), in such a way that the elements before middle are sorted in ascending order, whereas the elements after middle are left without any specific order.Below is the program to illustrate partial_sort():// C++ program to demonstrate the use of// partial_sort()#include <bits/stdc++.h>using namespace std; // Driver Codeint main(){ // Given array of elements vector<int> v = { 1, 3, 1, 10, 3, 3, 7, 7, 8 }; // Using std::partial_sort() to sort // first 3 elements partial_sort(v.begin(), v.begin() + 3, v.end()); // Displaying the vector after applying // partial_sort() for (int ip : v) { cout << ip << " "; } return 0;}Output:1 1 3 10 3 3 7 7 8 The complexity of partial_sort() is O(N*log K) where N is the number of elements in array and K is the number of elements between middle and start. The partial_sort() is faster than sort() if K is significantly smaller than N as partial_sort() will sort first K elements whereas sort() will sort all the N elements.The worst-case O(N*log K) running time of partial_sort() doesn’t tell the whole story. Its average-case running time on random input is O(N + K*log K + K*(log K)*(log Nk)).Because very little work is done to ignore each element that isn’t among the smallest K seen so far just a single comparison, the constant factor turns out to be difficult to beat for small K, even with an asymptotically better algorithm.nth_element(): The nth_element() is an STL algorithm which rearranges the list in such a way such that the element at the nth position is the one which should be at that position if we sort the list.It does not sort the list, just that all the elements, which precede the nth element are not greater than it, and all the elements which succeed it are not less than it.Below is the program to illustrate nth_element():// C++ program to demonstrate the use// of std::nth_element#include <bits/stdc++.h>using namespace std; // Driver Codeint main(){ // Given array v[] int v[] = { 3, 2, 10, 45, 33, 56, 23, 47 }; // Using nth_element with n as 5 nth_element(v, v + 4, v + 8); // Since, n is 5 so 5th element // should be sorted for (int i = 0; i < 8; i++) cout << v[i] << " "; return 0;}Output:3 2 10 23 33 56 45 47 sort(): C++ STL provides a function sort() that sorts a list of element in O(N*log N) time. By default, sort() sorts an array in ascending order. Below is the program to illustrate sort():// C++ program to illustrate the default behaviour// of sort() in STL#include <bits/stdc++.h>using namespace std; // Driver Codeint main(){ // Given array of elements int arr[] = { 1, 5, 8, 9, 6, 7, 3, 4, 2, 0 }; int n = sizeof(arr) / sizeof(arr[0]); // Function sort() to sort the element of // the array in increasing order sort(arr, arr + n); // Print the array elements after sorting cout << "\nArray after sorting using " "default sort is: \n"; for (int i = 0; i < n; ++i) { cout << arr[i] << " "; } return 0;}Output:Array after sorting using default sort is : 0 1 2 3 4 5 6 7 8 9 // C++ program to illustrate the default behaviour// of sort() in STL#include <bits/stdc++.h>using namespace std; // Driver Codeint main(){ // Given array of elements int arr[] = { 1, 5, 8, 9, 6, 7, 3, 4, 2, 0 }; int n = sizeof(arr) / sizeof(arr[0]); // Function sort() to sort the element of // the array in increasing order sort(arr, arr + n); // Print the array elements after sorting cout << "\nArray after sorting using " "default sort is: \n"; for (int i = 0; i < n; ++i) { cout << arr[i] << " "; } return 0;} Array after sorting using default sort is : 0 1 2 3 4 5 6 7 8 9 partial_sort(): One of the variants of std::sort() is std::partial_sort(), which is used for sorting not the entire range, but only a sub-part of it. It rearranges the elements in the range [first, last), in such a way that the elements before middle are sorted in ascending order, whereas the elements after middle are left without any specific order.Below is the program to illustrate partial_sort():// C++ program to demonstrate the use of// partial_sort()#include <bits/stdc++.h>using namespace std; // Driver Codeint main(){ // Given array of elements vector<int> v = { 1, 3, 1, 10, 3, 3, 7, 7, 8 }; // Using std::partial_sort() to sort // first 3 elements partial_sort(v.begin(), v.begin() + 3, v.end()); // Displaying the vector after applying // partial_sort() for (int ip : v) { cout << ip << " "; } return 0;}Output:1 1 3 10 3 3 7 7 8 The complexity of partial_sort() is O(N*log K) where N is the number of elements in array and K is the number of elements between middle and start. The partial_sort() is faster than sort() if K is significantly smaller than N as partial_sort() will sort first K elements whereas sort() will sort all the N elements.The worst-case O(N*log K) running time of partial_sort() doesn’t tell the whole story. Its average-case running time on random input is O(N + K*log K + K*(log K)*(log Nk)).Because very little work is done to ignore each element that isn’t among the smallest K seen so far just a single comparison, the constant factor turns out to be difficult to beat for small K, even with an asymptotically better algorithm. // C++ program to demonstrate the use of// partial_sort()#include <bits/stdc++.h>using namespace std; // Driver Codeint main(){ // Given array of elements vector<int> v = { 1, 3, 1, 10, 3, 3, 7, 7, 8 }; // Using std::partial_sort() to sort // first 3 elements partial_sort(v.begin(), v.begin() + 3, v.end()); // Displaying the vector after applying // partial_sort() for (int ip : v) { cout << ip << " "; } return 0;} 1 1 3 10 3 3 7 7 8 The complexity of partial_sort() is O(N*log K) where N is the number of elements in array and K is the number of elements between middle and start. The partial_sort() is faster than sort() if K is significantly smaller than N as partial_sort() will sort first K elements whereas sort() will sort all the N elements.The worst-case O(N*log K) running time of partial_sort() doesn’t tell the whole story. Its average-case running time on random input is O(N + K*log K + K*(log K)*(log Nk)).Because very little work is done to ignore each element that isn’t among the smallest K seen so far just a single comparison, the constant factor turns out to be difficult to beat for small K, even with an asymptotically better algorithm. nth_element(): The nth_element() is an STL algorithm which rearranges the list in such a way such that the element at the nth position is the one which should be at that position if we sort the list.It does not sort the list, just that all the elements, which precede the nth element are not greater than it, and all the elements which succeed it are not less than it.Below is the program to illustrate nth_element():// C++ program to demonstrate the use// of std::nth_element#include <bits/stdc++.h>using namespace std; // Driver Codeint main(){ // Given array v[] int v[] = { 3, 2, 10, 45, 33, 56, 23, 47 }; // Using nth_element with n as 5 nth_element(v, v + 4, v + 8); // Since, n is 5 so 5th element // should be sorted for (int i = 0; i < 8; i++) cout << v[i] << " "; return 0;}Output:3 2 10 23 33 56 45 47 // C++ program to demonstrate the use// of std::nth_element#include <bits/stdc++.h>using namespace std; // Driver Codeint main(){ // Given array v[] int v[] = { 3, 2, 10, 45, 33, 56, 23, 47 }; // Using nth_element with n as 5 nth_element(v, v + 4, v + 8); // Since, n is 5 so 5th element // should be sorted for (int i = 0; i < 8; i++) cout << v[i] << " "; return 0;} 3 2 10 23 33 56 45 47 Below is the benchmark comparison between three algorithms, varying N from 0 to 107(X-axis in the graph): The nth_element() + sort() solution is asymptotically fastest, and performs better results for larger K(which is most of them note the logarithmic scale). But it does lose to partial_sort() on random input for K < 70000, by up to a factor of 6. CPP-Functions Competitive Programming Difference Between Sorting Write From Home Sorting Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Most important type of Algorithms The Ultimate Beginner's Guide For DSA Find two numbers from their sum and XOR Equal Sum and XOR of three Numbers C++: Methods of code shortening in competitive programming Class method vs Static method in Python Difference between BFS and DFS Difference between var, let and const keywords in JavaScript Difference Between Method Overloading and Method Overriding in Java Differences between JDK, JRE and JVM
[ { "code": null, "e": 52, "s": 24, "text": "\n21 Jun, 2020" }, { "code": null, "e": 158, "s": 52, "text": "In this article, we will discuss the difference between sort(), partial_sort(), and nth_element()+sort()." }, { "code": null, "e": 208, "s": 158, "text": "Below is the illustration of the above functions:" }, { "code": null, "e": 3507, "s": 208, "text": "sort(): C++ STL provides a function sort() that sorts a list of element in O(N*log N) time. By default, sort() sorts an array in ascending order. Below is the program to illustrate sort():// C++ program to illustrate the default behaviour// of sort() in STL#include <bits/stdc++.h>using namespace std; // Driver Codeint main(){ // Given array of elements int arr[] = { 1, 5, 8, 9, 6, 7, 3, 4, 2, 0 }; int n = sizeof(arr) / sizeof(arr[0]); // Function sort() to sort the element of // the array in increasing order sort(arr, arr + n); // Print the array elements after sorting cout << \"\\nArray after sorting using \" \"default sort is: \\n\"; for (int i = 0; i < n; ++i) { cout << arr[i] << \" \"; } return 0;}Output:Array after sorting using default sort is : \n0 1 2 3 4 5 6 7 8 9\npartial_sort(): One of the variants of std::sort() is std::partial_sort(), which is used for sorting not the entire range, but only a sub-part of it. It rearranges the elements in the range [first, last), in such a way that the elements before middle are sorted in ascending order, whereas the elements after middle are left without any specific order.Below is the program to illustrate partial_sort():// C++ program to demonstrate the use of// partial_sort()#include <bits/stdc++.h>using namespace std; // Driver Codeint main(){ // Given array of elements vector<int> v = { 1, 3, 1, 10, 3, 3, 7, 7, 8 }; // Using std::partial_sort() to sort // first 3 elements partial_sort(v.begin(), v.begin() + 3, v.end()); // Displaying the vector after applying // partial_sort() for (int ip : v) { cout << ip << \" \"; } return 0;}Output:1 1 3 10 3 3 7 7 8\nThe complexity of partial_sort() is O(N*log K) where N is the number of elements in array and K is the number of elements between middle and start. The partial_sort() is faster than sort() if K is significantly smaller than N as partial_sort() will sort first K elements whereas sort() will sort all the N elements.The worst-case O(N*log K) running time of partial_sort() doesn’t tell the whole story. Its average-case running time on random input is O(N + K*log K + K*(log K)*(log Nk)).Because very little work is done to ignore each element that isn’t among the smallest K seen so far just a single comparison, the constant factor turns out to be difficult to beat for small K, even with an asymptotically better algorithm.nth_element(): The nth_element() is an STL algorithm which rearranges the list in such a way such that the element at the nth position is the one which should be at that position if we sort the list.It does not sort the list, just that all the elements, which precede the nth element are not greater than it, and all the elements which succeed it are not less than it.Below is the program to illustrate nth_element():// C++ program to demonstrate the use// of std::nth_element#include <bits/stdc++.h>using namespace std; // Driver Codeint main(){ // Given array v[] int v[] = { 3, 2, 10, 45, 33, 56, 23, 47 }; // Using nth_element with n as 5 nth_element(v, v + 4, v + 8); // Since, n is 5 so 5th element // should be sorted for (int i = 0; i < 8; i++) cout << v[i] << \" \"; return 0;}Output:3 2 10 23 33 56 45 47\n" }, { "code": null, "e": 4341, "s": 3507, "text": "sort(): C++ STL provides a function sort() that sorts a list of element in O(N*log N) time. By default, sort() sorts an array in ascending order. Below is the program to illustrate sort():// C++ program to illustrate the default behaviour// of sort() in STL#include <bits/stdc++.h>using namespace std; // Driver Codeint main(){ // Given array of elements int arr[] = { 1, 5, 8, 9, 6, 7, 3, 4, 2, 0 }; int n = sizeof(arr) / sizeof(arr[0]); // Function sort() to sort the element of // the array in increasing order sort(arr, arr + n); // Print the array elements after sorting cout << \"\\nArray after sorting using \" \"default sort is: \\n\"; for (int i = 0; i < n; ++i) { cout << arr[i] << \" \"; } return 0;}Output:Array after sorting using default sort is : \n0 1 2 3 4 5 6 7 8 9\n" }, { "code": "// C++ program to illustrate the default behaviour// of sort() in STL#include <bits/stdc++.h>using namespace std; // Driver Codeint main(){ // Given array of elements int arr[] = { 1, 5, 8, 9, 6, 7, 3, 4, 2, 0 }; int n = sizeof(arr) / sizeof(arr[0]); // Function sort() to sort the element of // the array in increasing order sort(arr, arr + n); // Print the array elements after sorting cout << \"\\nArray after sorting using \" \"default sort is: \\n\"; for (int i = 0; i < n; ++i) { cout << arr[i] << \" \"; } return 0;}", "e": 4915, "s": 4341, "text": null }, { "code": null, "e": 4981, "s": 4915, "text": "Array after sorting using default sort is : \n0 1 2 3 4 5 6 7 8 9\n" }, { "code": null, "e": 6596, "s": 4981, "text": "partial_sort(): One of the variants of std::sort() is std::partial_sort(), which is used for sorting not the entire range, but only a sub-part of it. It rearranges the elements in the range [first, last), in such a way that the elements before middle are sorted in ascending order, whereas the elements after middle are left without any specific order.Below is the program to illustrate partial_sort():// C++ program to demonstrate the use of// partial_sort()#include <bits/stdc++.h>using namespace std; // Driver Codeint main(){ // Given array of elements vector<int> v = { 1, 3, 1, 10, 3, 3, 7, 7, 8 }; // Using std::partial_sort() to sort // first 3 elements partial_sort(v.begin(), v.begin() + 3, v.end()); // Displaying the vector after applying // partial_sort() for (int ip : v) { cout << ip << \" \"; } return 0;}Output:1 1 3 10 3 3 7 7 8\nThe complexity of partial_sort() is O(N*log K) where N is the number of elements in array and K is the number of elements between middle and start. The partial_sort() is faster than sort() if K is significantly smaller than N as partial_sort() will sort first K elements whereas sort() will sort all the N elements.The worst-case O(N*log K) running time of partial_sort() doesn’t tell the whole story. Its average-case running time on random input is O(N + K*log K + K*(log K)*(log Nk)).Because very little work is done to ignore each element that isn’t among the smallest K seen so far just a single comparison, the constant factor turns out to be difficult to beat for small K, even with an asymptotically better algorithm." }, { "code": "// C++ program to demonstrate the use of// partial_sort()#include <bits/stdc++.h>using namespace std; // Driver Codeint main(){ // Given array of elements vector<int> v = { 1, 3, 1, 10, 3, 3, 7, 7, 8 }; // Using std::partial_sort() to sort // first 3 elements partial_sort(v.begin(), v.begin() + 3, v.end()); // Displaying the vector after applying // partial_sort() for (int ip : v) { cout << ip << \" \"; } return 0;}", "e": 7058, "s": 6596, "text": null }, { "code": null, "e": 7078, "s": 7058, "text": "1 1 3 10 3 3 7 7 8\n" }, { "code": null, "e": 7804, "s": 7078, "text": "The complexity of partial_sort() is O(N*log K) where N is the number of elements in array and K is the number of elements between middle and start. The partial_sort() is faster than sort() if K is significantly smaller than N as partial_sort() will sort first K elements whereas sort() will sort all the N elements.The worst-case O(N*log K) running time of partial_sort() doesn’t tell the whole story. Its average-case running time on random input is O(N + K*log K + K*(log K)*(log Nk)).Because very little work is done to ignore each element that isn’t among the smallest K seen so far just a single comparison, the constant factor turns out to be difficult to beat for small K, even with an asymptotically better algorithm." }, { "code": null, "e": 8656, "s": 7804, "text": "nth_element(): The nth_element() is an STL algorithm which rearranges the list in such a way such that the element at the nth position is the one which should be at that position if we sort the list.It does not sort the list, just that all the elements, which precede the nth element are not greater than it, and all the elements which succeed it are not less than it.Below is the program to illustrate nth_element():// C++ program to demonstrate the use// of std::nth_element#include <bits/stdc++.h>using namespace std; // Driver Codeint main(){ // Given array v[] int v[] = { 3, 2, 10, 45, 33, 56, 23, 47 }; // Using nth_element with n as 5 nth_element(v, v + 4, v + 8); // Since, n is 5 so 5th element // should be sorted for (int i = 0; i < 8; i++) cout << v[i] << \" \"; return 0;}Output:3 2 10 23 33 56 45 47\n" }, { "code": "// C++ program to demonstrate the use// of std::nth_element#include <bits/stdc++.h>using namespace std; // Driver Codeint main(){ // Given array v[] int v[] = { 3, 2, 10, 45, 33, 56, 23, 47 }; // Using nth_element with n as 5 nth_element(v, v + 4, v + 8); // Since, n is 5 so 5th element // should be sorted for (int i = 0; i < 8; i++) cout << v[i] << \" \"; return 0;}", "e": 9062, "s": 8656, "text": null }, { "code": null, "e": 9085, "s": 9062, "text": "3 2 10 23 33 56 45 47\n" }, { "code": null, "e": 9191, "s": 9085, "text": "Below is the benchmark comparison between three algorithms, varying N from 0 to 107(X-axis in the graph):" }, { "code": null, "e": 9436, "s": 9191, "text": "The nth_element() + sort() solution is asymptotically fastest, and performs better results for larger K(which is most of them note the logarithmic scale). But it does lose to partial_sort() on random input for K < 70000, by up to a factor of 6." }, { "code": null, "e": 9450, "s": 9436, "text": "CPP-Functions" }, { "code": null, "e": 9474, "s": 9450, "text": "Competitive Programming" }, { "code": null, "e": 9493, "s": 9474, "text": "Difference Between" }, { "code": null, "e": 9501, "s": 9493, "text": "Sorting" }, { "code": null, "e": 9517, "s": 9501, "text": "Write From Home" }, { "code": null, "e": 9525, "s": 9517, "text": "Sorting" }, { "code": null, "e": 9623, "s": 9525, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 9657, "s": 9623, "text": "Most important type of Algorithms" }, { "code": null, "e": 9695, "s": 9657, "text": "The Ultimate Beginner's Guide For DSA" }, { "code": null, "e": 9735, "s": 9695, "text": "Find two numbers from their sum and XOR" }, { "code": null, "e": 9770, "s": 9735, "text": "Equal Sum and XOR of three Numbers" }, { "code": null, "e": 9829, "s": 9770, "text": "C++: Methods of code shortening in competitive programming" }, { "code": null, "e": 9869, "s": 9829, "text": "Class method vs Static method in Python" }, { "code": null, "e": 9900, "s": 9869, "text": "Difference between BFS and DFS" }, { "code": null, "e": 9961, "s": 9900, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 10029, "s": 9961, "text": "Difference Between Method Overloading and Method Overriding in Java" } ]
How to Use Logical Operator Within If Statements in MATLAB?
30 Jun, 2022 Logical Operators are used to combining two or more conditions/constraints or to complement the evaluation of the original condition in consideration. The result of the operation of a logical operator is a boolean value either true or false. Like any other programming language, logical operators in MATLAB are beneficial, and in this article, we will demonstrate one of its uses. Element-wise: These operators function on corresponding factors of logical arrays. Element-wise logical operators function detail-by-detail on logical arrays. The symbols &, |, and ~ are the logical array operators AND, OR, and NOT. Short-circuit: These operators function on scalar, logical expressions. Short-circuit logical operators permit short-circuiting on logical operations. The symbols && and || are the logical short-circuit operators AND and OR. But before we learn how to use logical operators with conditional statements, we should have a quick look at logical operators. Logical AND(&): True if both the operands are true. Logical OR( | ): True if either of the operands is true. Logical XOR(xor): The result of XOR is true if the two bits are different. Logical NOT( ~ ): True if the operand is false. Now, here is a MATLAB example that illustrating logical operators with conditional statements. Example 1: Matlab % MATLAB code for Logicl Operators% in use, 1 - True, 0 - False% logical and operatorandResult = 1 & 0; % logical or operatororResult = 1 | 0; % logical xor operatorxorResult = xor(1,0); % logical not operatornotResult = ~1; % logical all()allResult = all([1 2 3 4 5]); % logical()logicalResult = logical(76); % islogical()isLogicalResult = islogical([true false true]); % logical find()findResult = find([1 2 0 0 0 3 4 2]); % logical any()anyResult = any([1 0 2 3]); disp("1 & 0 = " + andResult);disp("1 | 0 = " + orResult);disp("1 XOR 0 = " + xorResult);disp("~1 = " + notResult);disp("all([1 2 3 4 5]) = " + allResult);disp("logical(87) = " + logicalResult);disp("isLogical([true false true]) = " + isLogicalResult);disp("find([1 2 0 0 0 3 4 2])");findResultdisp("any([1 0 2 3]) = " + anyResult); Output: So now that we have a rudimentary understanding of the logical operator, we can use them in our conditional statements. Now we are going to use the logical operators in conditional statements. Example 2: Matlab % MATLAB script is used to determine% the nature of the product (positive,% negative or zero) of the two% numbers given by the usernum1 = input('Enter the first number:- ');num2 = input('Enter the second number:- '); % here we are using && instead of & and ||% instead of | because it makes the code% execution faster as if the condition fails% in the first operand the second operand is not tested% If the both the numbers are greater that% zero or both the numbers are less than zero% their product will be positiveif((num1 > 0 && num2 > 0) || (num1 < 0 && num2 < 0))disp('The product of the two numbers will be positive'); % If the numbers have opposite sign then% their product will be negativeelseif((num1 > 0 && num2 < 0) || (num1 < 0 && num2 > 0))disp('The product of the two numbers will be negative');elsedisp('The product of the two numbers will be zero');end Output: The above MATLAB script outputs the nature of the product of the two numbers given by the user and, while doing so, also illustrates how to use logical operators in conditional statements(like the If statement) So, logical operators are convenient when working with conditional statements. all(): This determines if all array elements are nonzero or true. In this logical operation if all the elements of the array are non-zero then the output will be 1 (true) and If at least one of the elements is zero then the output will be 0 (false). logical(): This function converts the non-zero elements to 1 and the zero elements to 0. isLogical(): In this function If the input is logical i.e. true or false then the output will be 1, and if the input is anything apart from logical then the output will be 0. find(): Finds and returns the indices of non-zero elements in the array. any(): If any element in an array is non-zero the output is 1 if not then the output is 0. sweetyty surinderdawra388 MATLAB-Basic Picked MATLAB Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n30 Jun, 2022" }, { "code": null, "e": 409, "s": 28, "text": "Logical Operators are used to combining two or more conditions/constraints or to complement the evaluation of the original condition in consideration. The result of the operation of a logical operator is a boolean value either true or false. Like any other programming language, logical operators in MATLAB are beneficial, and in this article, we will demonstrate one of its uses." }, { "code": null, "e": 642, "s": 409, "text": "Element-wise: These operators function on corresponding factors of logical arrays. Element-wise logical operators function detail-by-detail on logical arrays. The symbols &, |, and ~ are the logical array operators AND, OR, and NOT." }, { "code": null, "e": 867, "s": 642, "text": "Short-circuit: These operators function on scalar, logical expressions. Short-circuit logical operators permit short-circuiting on logical operations. The symbols && and || are the logical short-circuit operators AND and OR." }, { "code": null, "e": 995, "s": 867, "text": "But before we learn how to use logical operators with conditional statements, we should have a quick look at logical operators." }, { "code": null, "e": 1047, "s": 995, "text": "Logical AND(&): True if both the operands are true." }, { "code": null, "e": 1104, "s": 1047, "text": "Logical OR( | ): True if either of the operands is true." }, { "code": null, "e": 1179, "s": 1104, "text": "Logical XOR(xor): The result of XOR is true if the two bits are different." }, { "code": null, "e": 1227, "s": 1179, "text": "Logical NOT( ~ ): True if the operand is false." }, { "code": null, "e": 1322, "s": 1227, "text": "Now, here is a MATLAB example that illustrating logical operators with conditional statements." }, { "code": null, "e": 1333, "s": 1322, "text": "Example 1:" }, { "code": null, "e": 1340, "s": 1333, "text": "Matlab" }, { "code": "% MATLAB code for Logicl Operators% in use, 1 - True, 0 - False% logical and operatorandResult = 1 & 0; % logical or operatororResult = 1 | 0; % logical xor operatorxorResult = xor(1,0); % logical not operatornotResult = ~1; % logical all()allResult = all([1 2 3 4 5]); % logical()logicalResult = logical(76); % islogical()isLogicalResult = islogical([true false true]); % logical find()findResult = find([1 2 0 0 0 3 4 2]); % logical any()anyResult = any([1 0 2 3]); disp(\"1 & 0 = \" + andResult);disp(\"1 | 0 = \" + orResult);disp(\"1 XOR 0 = \" + xorResult);disp(\"~1 = \" + notResult);disp(\"all([1 2 3 4 5]) = \" + allResult);disp(\"logical(87) = \" + logicalResult);disp(\"isLogical([true false true]) = \" + isLogicalResult);disp(\"find([1 2 0 0 0 3 4 2])\");findResultdisp(\"any([1 0 2 3]) = \" + anyResult);", "e": 2143, "s": 1340, "text": null }, { "code": null, "e": 2154, "s": 2146, "text": "Output:" }, { "code": null, "e": 2349, "s": 2156, "text": "So now that we have a rudimentary understanding of the logical operator, we can use them in our conditional statements. Now we are going to use the logical operators in conditional statements." }, { "code": null, "e": 2362, "s": 2351, "text": "Example 2:" }, { "code": null, "e": 2371, "s": 2364, "text": "Matlab" }, { "code": "% MATLAB script is used to determine% the nature of the product (positive,% negative or zero) of the two% numbers given by the usernum1 = input('Enter the first number:- ');num2 = input('Enter the second number:- '); % here we are using && instead of & and ||% instead of | because it makes the code% execution faster as if the condition fails% in the first operand the second operand is not tested% If the both the numbers are greater that% zero or both the numbers are less than zero% their product will be positiveif((num1 > 0 && num2 > 0) || (num1 < 0 && num2 < 0))disp('The product of the two numbers will be positive'); % If the numbers have opposite sign then% their product will be negativeelseif((num1 > 0 && num2 < 0) || (num1 < 0 && num2 > 0))disp('The product of the two numbers will be negative');elsedisp('The product of the two numbers will be zero');end", "e": 3242, "s": 2371, "text": null }, { "code": null, "e": 3253, "s": 3245, "text": "Output:" }, { "code": null, "e": 3545, "s": 3255, "text": "The above MATLAB script outputs the nature of the product of the two numbers given by the user and, while doing so, also illustrates how to use logical operators in conditional statements(like the If statement) So, logical operators are convenient when working with conditional statements." }, { "code": null, "e": 3797, "s": 3547, "text": "all(): This determines if all array elements are nonzero or true. In this logical operation if all the elements of the array are non-zero then the output will be 1 (true) and If at least one of the elements is zero then the output will be 0 (false)." }, { "code": null, "e": 3886, "s": 3797, "text": "logical(): This function converts the non-zero elements to 1 and the zero elements to 0." }, { "code": null, "e": 4061, "s": 3886, "text": "isLogical(): In this function If the input is logical i.e. true or false then the output will be 1, and if the input is anything apart from logical then the output will be 0." }, { "code": null, "e": 4134, "s": 4061, "text": "find(): Finds and returns the indices of non-zero elements in the array." }, { "code": null, "e": 4225, "s": 4134, "text": "any(): If any element in an array is non-zero the output is 1 if not then the output is 0." }, { "code": null, "e": 4236, "s": 4227, "text": "sweetyty" }, { "code": null, "e": 4253, "s": 4236, "text": "surinderdawra388" }, { "code": null, "e": 4266, "s": 4253, "text": "MATLAB-Basic" }, { "code": null, "e": 4273, "s": 4266, "text": "Picked" }, { "code": null, "e": 4280, "s": 4273, "text": "MATLAB" } ]
HTML | <textarea> rows Attribute
16 Oct, 2019 The HTML textarea rows Attribute is used to specify the number of visible text lines for the control i.e the number of rows to display. It also specifies the visible height of the Textarea. Syntax: <textarea rows = "value"> Attribute Values: number: It specify the height of the Textarea. Its Default value is 2. Example: <!DOCTYPE html><html> <head> <title> HTML Textarea rows Attribute </title></head> <body> <center> <h1 style="color: green;"> GeeksforGeeks </h1> <h2> HTML Textarea rows Attribute </h2> <!-- Below textarea element has rows attribute assigned to 5 --> <textarea rows="5" cols="23"> This paragraph has number of rows equal to 5. </textarea> </center></body> </html> Output: Supported Browsers: The browsers supported by HTML textarea rows Attribute are listed below: Google Chrome Internet Explorer Firefox Apple Safari Opera shubham_singh HTML-Attributes HTML Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n16 Oct, 2019" }, { "code": null, "e": 218, "s": 28, "text": "The HTML textarea rows Attribute is used to specify the number of visible text lines for the control i.e the number of rows to display. It also specifies the visible height of the Textarea." }, { "code": null, "e": 226, "s": 218, "text": "Syntax:" }, { "code": null, "e": 252, "s": 226, "text": "<textarea rows = \"value\">" }, { "code": null, "e": 270, "s": 252, "text": "Attribute Values:" }, { "code": null, "e": 341, "s": 270, "text": "number: It specify the height of the Textarea. Its Default value is 2." }, { "code": null, "e": 350, "s": 341, "text": "Example:" }, { "code": "<!DOCTYPE html><html> <head> <title> HTML Textarea rows Attribute </title></head> <body> <center> <h1 style=\"color: green;\"> GeeksforGeeks </h1> <h2> HTML Textarea rows Attribute </h2> <!-- Below textarea element has rows attribute assigned to 5 --> <textarea rows=\"5\" cols=\"23\"> This paragraph has number of rows equal to 5. </textarea> </center></body> </html>", "e": 847, "s": 350, "text": null }, { "code": null, "e": 855, "s": 847, "text": "Output:" }, { "code": null, "e": 948, "s": 855, "text": "Supported Browsers: The browsers supported by HTML textarea rows Attribute are listed below:" }, { "code": null, "e": 962, "s": 948, "text": "Google Chrome" }, { "code": null, "e": 980, "s": 962, "text": "Internet Explorer" }, { "code": null, "e": 988, "s": 980, "text": "Firefox" }, { "code": null, "e": 1001, "s": 988, "text": "Apple Safari" }, { "code": null, "e": 1007, "s": 1001, "text": "Opera" }, { "code": null, "e": 1021, "s": 1007, "text": "shubham_singh" }, { "code": null, "e": 1037, "s": 1021, "text": "HTML-Attributes" }, { "code": null, "e": 1042, "s": 1037, "text": "HTML" }, { "code": null, "e": 1059, "s": 1042, "text": "Web Technologies" }, { "code": null, "e": 1064, "s": 1059, "text": "HTML" } ]
HTML | DOM Input Password pattern Property
08 Mar, 2019 The Input password pattern Property in HTML DOM is used to set or return the value of pattern attribute of a Password Field. This attribute is used to specify the regular expression on which the input elements value is checked against. Use the Global title attribute to describe the pattern for helping the user. Syntax: It returns the Input password pattern Property.passwordObject.pattern passwordObject.pattern It is used to set the Input password pattern Property.passwordObject.pattern = regexp passwordObject.pattern = regexp Property Values: It accepts single value regexp which is used to specify the regular expression that a password field value is checked against. Return Value: It returns a string value which represents the regular expression that a password field value is checked against. Example: This example describes the use of Input password pattern Property. <!DOCTYPE html> <html> <head> <title> HTML DOM Input Password pattern Property </title></head> <body style="text-align:center;"> <h1 style="color:green;"> GeeksForGeeks </h1> <h2>DOM Input Password pattern Property</h2> <form id="myGeeks"> Password: <input type="password" id="myPsw" name="Geeks" pattern="[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2, 3}$" > </form> <br><br> <button onclick="myFunction()"> Click Here! </button> <p id="demo" style="color:green;font-size:25px;"></p> <!-- Script to use Input Password pattern Property --> <script> function myFunction() { var x = document.getElementById( "myPsw").pattern; document.getElementById( "demo").innerHTML = x; } </script> </body> </html> Output:Before Clicking the Button:After Clicking the Button: Supported Browsers: The browser supported by DOM input Password pattern Property are listed below: Google Chrome Internet Explorer 10.0 Firefox Opera Safari HTML-DOM HTML Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. REST API (Introduction) Design a Tribute Page using HTML & CSS Build a Survey Form using HTML and CSS Angular File Upload Form validation using jQuery Installation of Node.js on Linux Difference between var, let and const keywords in JavaScript How to fetch data from an API in ReactJS ? Differences between Functional Components and Class Components in React Remove elements from a JavaScript Array
[ { "code": null, "e": 53, "s": 25, "text": "\n08 Mar, 2019" }, { "code": null, "e": 366, "s": 53, "text": "The Input password pattern Property in HTML DOM is used to set or return the value of pattern attribute of a Password Field. This attribute is used to specify the regular expression on which the input elements value is checked against. Use the Global title attribute to describe the pattern for helping the user." }, { "code": null, "e": 374, "s": 366, "text": "Syntax:" }, { "code": null, "e": 444, "s": 374, "text": "It returns the Input password pattern Property.passwordObject.pattern" }, { "code": null, "e": 467, "s": 444, "text": "passwordObject.pattern" }, { "code": null, "e": 553, "s": 467, "text": "It is used to set the Input password pattern Property.passwordObject.pattern = regexp" }, { "code": null, "e": 585, "s": 553, "text": "passwordObject.pattern = regexp" }, { "code": null, "e": 729, "s": 585, "text": "Property Values: It accepts single value regexp which is used to specify the regular expression that a password field value is checked against." }, { "code": null, "e": 857, "s": 729, "text": "Return Value: It returns a string value which represents the regular expression that a password field value is checked against." }, { "code": null, "e": 933, "s": 857, "text": "Example: This example describes the use of Input password pattern Property." }, { "code": "<!DOCTYPE html> <html> <head> <title> HTML DOM Input Password pattern Property </title></head> <body style=\"text-align:center;\"> <h1 style=\"color:green;\"> GeeksForGeeks </h1> <h2>DOM Input Password pattern Property</h2> <form id=\"myGeeks\"> Password: <input type=\"password\" id=\"myPsw\" name=\"Geeks\" pattern=\"[a-z0-9._%+-]+@[a-z0-9.-]+\\.[a-z]{2, 3}$\" > </form> <br><br> <button onclick=\"myFunction()\"> Click Here! </button> <p id=\"demo\" style=\"color:green;font-size:25px;\"></p> <!-- Script to use Input Password pattern Property --> <script> function myFunction() { var x = document.getElementById( \"myPsw\").pattern; document.getElementById( \"demo\").innerHTML = x; } </script> </body> </html> ", "e": 1873, "s": 933, "text": null }, { "code": null, "e": 1934, "s": 1873, "text": "Output:Before Clicking the Button:After Clicking the Button:" }, { "code": null, "e": 2033, "s": 1934, "text": "Supported Browsers: The browser supported by DOM input Password pattern Property are listed below:" }, { "code": null, "e": 2047, "s": 2033, "text": "Google Chrome" }, { "code": null, "e": 2070, "s": 2047, "text": "Internet Explorer 10.0" }, { "code": null, "e": 2078, "s": 2070, "text": "Firefox" }, { "code": null, "e": 2084, "s": 2078, "text": "Opera" }, { "code": null, "e": 2091, "s": 2084, "text": "Safari" }, { "code": null, "e": 2100, "s": 2091, "text": "HTML-DOM" }, { "code": null, "e": 2105, "s": 2100, "text": "HTML" }, { "code": null, "e": 2122, "s": 2105, "text": "Web Technologies" }, { "code": null, "e": 2127, "s": 2122, "text": "HTML" }, { "code": null, "e": 2225, "s": 2127, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2249, "s": 2225, "text": "REST API (Introduction)" }, { "code": null, "e": 2288, "s": 2249, "text": "Design a Tribute Page using HTML & CSS" }, { "code": null, "e": 2327, "s": 2288, "text": "Build a Survey Form using HTML and CSS" }, { "code": null, "e": 2347, "s": 2327, "text": "Angular File Upload" }, { "code": null, "e": 2376, "s": 2347, "text": "Form validation using jQuery" }, { "code": null, "e": 2409, "s": 2376, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 2470, "s": 2409, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 2513, "s": 2470, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 2585, "s": 2513, "text": "Differences between Functional Components and Class Components in React" } ]
JavaScript performance.now() Method
29 Oct, 2021 In JavaScript performance.now() method can be used to check the performance of your code. You can check the execution time of your code using this method. It returns the value of time (of type double) in milliseconds. The returned value represents the time elapsed since the execution started. Syntax: let t = performance.now(); The code below will give you a brief idea of how this code performs. Example 1: Javascript <script> const t0 = performance.now(); for (let i = 0; i < 10; i++) { console.log(i); } const t1 = performance.now(); console.log(`Call to doSomething took ${t1 - t0} milliseconds.`);</script> Output: In the above code, variables t0 and t1 are used to store starting time and ending time respectively, and while printing we subtracted t0 from t1 to print the time required in the execution of the code. 0 1 2 3 4 5 6 7 8 9 "Call to doSomething took 1.7899998929351568 milliseconds." Example 2: Javascript <script> const t0 = performance.now(); for (let i = 0; i < 5; i++) { console.log(i); } const t1 = performance.now(); console.log(`Call to doSomething took ${t1 - t0} milliseconds.`);</script> Output: 0 1 2 3 4 "Call to doSomething took 0.7100000511854887 milliseconds." prachisoda1234 JavaScript-Methods JavaScript Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Difference between var, let and const keywords in JavaScript Remove elements from a JavaScript Array Difference Between PUT and PATCH Request Roadmap to Learn JavaScript For Beginners JavaScript | Promises How to filter object array based on attributes? Lodash _.debounce() Method JavaScript String includes() Method JavaScript | fetch() Method Lodash _.groupBy() Method
[ { "code": null, "e": 28, "s": 0, "text": "\n29 Oct, 2021" }, { "code": null, "e": 183, "s": 28, "text": "In JavaScript performance.now() method can be used to check the performance of your code. You can check the execution time of your code using this method." }, { "code": null, "e": 322, "s": 183, "text": "It returns the value of time (of type double) in milliseconds. The returned value represents the time elapsed since the execution started." }, { "code": null, "e": 330, "s": 322, "text": "Syntax:" }, { "code": null, "e": 357, "s": 330, "text": "let t = performance.now();" }, { "code": null, "e": 426, "s": 357, "text": "The code below will give you a brief idea of how this code performs." }, { "code": null, "e": 437, "s": 426, "text": "Example 1:" }, { "code": null, "e": 448, "s": 437, "text": "Javascript" }, { "code": "<script> const t0 = performance.now(); for (let i = 0; i < 10; i++) { console.log(i); } const t1 = performance.now(); console.log(`Call to doSomething took ${t1 - t0} milliseconds.`);</script>", "e": 649, "s": 448, "text": null }, { "code": null, "e": 859, "s": 649, "text": "Output: In the above code, variables t0 and t1 are used to store starting time and ending time respectively, and while printing we subtracted t0 from t1 to print the time required in the execution of the code." }, { "code": null, "e": 939, "s": 859, "text": "0\n1\n2\n3\n4\n5\n6\n7\n8\n9\n\"Call to doSomething took 1.7899998929351568 milliseconds.\"" }, { "code": null, "e": 950, "s": 939, "text": "Example 2:" }, { "code": null, "e": 961, "s": 950, "text": "Javascript" }, { "code": "<script> const t0 = performance.now(); for (let i = 0; i < 5; i++) { console.log(i); } const t1 = performance.now(); console.log(`Call to doSomething took ${t1 - t0} milliseconds.`);</script>", "e": 1161, "s": 961, "text": null }, { "code": null, "e": 1169, "s": 1161, "text": "Output:" }, { "code": null, "e": 1239, "s": 1169, "text": "0\n1\n2\n3\n4\n\"Call to doSomething took 0.7100000511854887 milliseconds.\"" }, { "code": null, "e": 1254, "s": 1239, "text": "prachisoda1234" }, { "code": null, "e": 1273, "s": 1254, "text": "JavaScript-Methods" }, { "code": null, "e": 1284, "s": 1273, "text": "JavaScript" }, { "code": null, "e": 1382, "s": 1284, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1443, "s": 1382, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 1483, "s": 1443, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 1524, "s": 1483, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 1566, "s": 1524, "text": "Roadmap to Learn JavaScript For Beginners" }, { "code": null, "e": 1588, "s": 1566, "text": "JavaScript | Promises" }, { "code": null, "e": 1636, "s": 1588, "text": "How to filter object array based on attributes?" }, { "code": null, "e": 1663, "s": 1636, "text": "Lodash _.debounce() Method" }, { "code": null, "e": 1699, "s": 1663, "text": "JavaScript String includes() Method" }, { "code": null, "e": 1727, "s": 1699, "text": "JavaScript | fetch() Method" } ]
Working with Images in Python?
One of the most popular and considered as default library of python for image processing is Pillow. Pillow is an updated version of the Python Image Library or PIL and supports a range of simple and advanced image manipulation functionality. It is also the basis for simple image support in other Python libraries such as sciPy and Matplotlib. Before we start, we need python and pillow. Incase of Linux, pillow will probably be there already, since major flavour of linux including Fedora, Debian/Ubuntu and ArchLinux includes Pillow in packages that previously contained PIL. The easiest way to install it is to use pip: pip install pillow First we need a test image to demonstrate some important features of using the python Pillow library. I’ve used the statue_of_unity photo as a sample image. Download the image and save it in your current working directory. #Load and show an image with Pillow from PIL import Image #Load the image img = Image.open('statue_of_unity.jpg') #Get basic details about the image print(img.format) print(img.mode) print(img.size) #show the image img.show() JPEG RGB (400, 260) Above the image is loaded directely using the open() function on Image class. This returns an image object that contains the pixel data for the image as well as details about the image. The format property on the image will report the image format(e.g png, jpeg), the mode will report the pixel channel format (e.g. CMYK or RGB) and the size will report the dimensions of the image in pixels (e.g. 400*260) The show() function will display the image using operating systems default application. To convert an image to grayscale, display it and then save it is very easy, just do the following: #Import required library from PIL import Image #Read an image & convert it to gray-scale image = Image.open('statue_of_unity.jpg').convert('L') #Display image image.show() #Save image image.save('statue_of_unity_gs.jpg') After running above program, a file “statue_of_unity_gs.jpg” is created in your current working directory. Converting an image of one type (jpeg) to another(say, png) is also very easy. from PIL import Image image = Image.open('statue_of_unity.jpg') image.save('statue_of_unity.png') A new image file is created and save in our default directory. The size(dimensions) of our current image file is 400 * 260px. Incase we want to resize it, and make it of size 440 * 600px, can be done by: image = Image.open('statue_of_unity.jpg') newImage = image.resize((440, 600)) newImage.save('statue_of_unity_440&600.jpg') A new file ‘statue_of_unit_440*600.jpg’ of size 440 *600px is created and save in your current working directory. As you can see, this enlarges our original image into desired dimensions rather than cropping it, which you may not want. Incase you want to crop the existing image, you can do it using, image.crop(box=None) Below program loads an image, rotates it 45 degrees and display it using an external viewer. from PIL import Image image = Image.open('statue_of_unity.jpg') image.rotate(45).show() Below program will create 128*128 thumbnails of all jpeg images in your current working directory. from PIL import Image import glob, os size = 128, 128 for infile in glob.glob("*.jpg"): file, ext = os.path.splitext(infile) image = Image.open(infile) image.thumbnail(size, Image.ANTIALIAS) image.save(file + ".thumbnail", "JPEG") Will return the thumbnails of all jpeg file in my current directory(c:\python\python361) including the ‘statue_of_unity.jpg’ image.
[ { "code": null, "e": 1531, "s": 1187, "text": "One of the most popular and considered as default library of python for image processing is Pillow. Pillow is an updated version of the Python Image Library or PIL and supports a range of simple and advanced image manipulation functionality. It is also the basis for simple image support in other Python libraries such as sciPy and Matplotlib." }, { "code": null, "e": 1765, "s": 1531, "text": "Before we start, we need python and pillow. Incase of Linux, pillow will probably be there already, since major flavour of linux including Fedora, Debian/Ubuntu and ArchLinux includes Pillow in packages that previously contained PIL." }, { "code": null, "e": 1810, "s": 1765, "text": "The easiest way to install it is to use pip:" }, { "code": null, "e": 1829, "s": 1810, "text": "pip install pillow" }, { "code": null, "e": 1931, "s": 1829, "text": "First we need a test image to demonstrate some important features of using the python Pillow library." }, { "code": null, "e": 2052, "s": 1931, "text": "I’ve used the statue_of_unity photo as a sample image. Download the image and save it in your current working directory." }, { "code": null, "e": 2281, "s": 2052, "text": "#Load and show an image with Pillow\nfrom PIL import Image\n\n#Load the image\nimg = Image.open('statue_of_unity.jpg')\n\n#Get basic details about the image\nprint(img.format)\nprint(img.mode)\nprint(img.size)\n\n#show the image\nimg.show()" }, { "code": null, "e": 2303, "s": 2281, "text": "JPEG\nRGB\n(400, 260)\n\n" }, { "code": null, "e": 2489, "s": 2303, "text": "Above the image is loaded directely using the open() function on Image class. This returns an image object that contains the pixel data for the image as well as details about the image." }, { "code": null, "e": 2710, "s": 2489, "text": "The format property on the image will report the image format(e.g png, jpeg), the mode will report the pixel channel format (e.g. CMYK or RGB) and the size will report the dimensions of the image in pixels (e.g. 400*260)" }, { "code": null, "e": 2798, "s": 2710, "text": "The show() function will display the image using operating systems default application." }, { "code": null, "e": 2897, "s": 2798, "text": "To convert an image to grayscale, display it and then save it is very easy, just do the following:" }, { "code": null, "e": 3118, "s": 2897, "text": "#Import required library\nfrom PIL import Image\n#Read an image & convert it to gray-scale\nimage = Image.open('statue_of_unity.jpg').convert('L')\n#Display image\nimage.show()\n#Save image\nimage.save('statue_of_unity_gs.jpg')" }, { "code": null, "e": 3225, "s": 3118, "text": "After running above program, a file “statue_of_unity_gs.jpg” is created in your current working directory." }, { "code": null, "e": 3304, "s": 3225, "text": "Converting an image of one type (jpeg) to another(say, png) is also very easy." }, { "code": null, "e": 3403, "s": 3304, "text": "from PIL import Image\n\nimage = Image.open('statue_of_unity.jpg')\nimage.save('statue_of_unity.png')" }, { "code": null, "e": 3466, "s": 3403, "text": "A new image file is created and save in our default directory." }, { "code": null, "e": 3607, "s": 3466, "text": "The size(dimensions) of our current image file is 400 * 260px. Incase we want to resize it, and make it of size 440 * 600px, can be done by:" }, { "code": null, "e": 3730, "s": 3607, "text": "image = Image.open('statue_of_unity.jpg')\nnewImage = image.resize((440, 600))\nnewImage.save('statue_of_unity_440&600.jpg')" }, { "code": null, "e": 3844, "s": 3730, "text": "A new file ‘statue_of_unit_440*600.jpg’ of size 440 *600px is created and save in your current working directory." }, { "code": null, "e": 3966, "s": 3844, "text": "As you can see, this enlarges our original image into desired dimensions rather than cropping it, which you may not want." }, { "code": null, "e": 4031, "s": 3966, "text": "Incase you want to crop the existing image, you can do it using," }, { "code": null, "e": 4052, "s": 4031, "text": "image.crop(box=None)" }, { "code": null, "e": 4145, "s": 4052, "text": "Below program loads an image, rotates it 45 degrees and display it using an external viewer." }, { "code": null, "e": 4234, "s": 4145, "text": "from PIL import Image\n\nimage = Image.open('statue_of_unity.jpg')\nimage.rotate(45).show()" }, { "code": null, "e": 4333, "s": 4234, "text": "Below program will create 128*128 thumbnails of all jpeg images in your current working directory." }, { "code": null, "e": 4566, "s": 4333, "text": "from PIL import Image\nimport glob, os\n\nsize = 128, 128\n\nfor infile in glob.glob(\"*.jpg\"):\nfile, ext = os.path.splitext(infile)\nimage = Image.open(infile)\nimage.thumbnail(size, Image.ANTIALIAS)\nimage.save(file + \".thumbnail\", \"JPEG\")" }, { "code": null, "e": 4698, "s": 4566, "text": "Will return the thumbnails of all jpeg file in my current directory(c:\\python\\python361) including the ‘statue_of_unity.jpg’ image." } ]
What is #if DEBUG and How to use it in C#?
In Visual Studio Debug mode and Release mode are different configurations for building your .Net project. Select the Debug mode for debugging step by step their .Net project and select the Release mode for the final build of Assembly file (.dll or .exe). The Debug mode does not optimize the binary it produces because the relationship between source code and generated instructions is more complex. This allows breakpoints to be set accurately and allows a programmer to step through the code one line at a time. The Debug configuration of your program is compiled with full symbolic debug information which help the debugger figure out where it is in the source code The release configuration of your program has no symbolic debug information and is fully optimized. From the Build menu, select Configuration Manager, then select Debug or Release. or On the toolbar, choose either Debug or Release from the Solution Configurations list The code which is written inside the #if debug will be executed only if the code is running inside the debug mode If the code is running in the release mode then the #if Debug will be false and it will not execute the code present inside this class Program { static void Main() { #if DEBUG Console.WriteLine("You are in debug"); #endif Console.ReadKey(); } } If the Program is running in the debug mode then the If bloc will return true And prints "You are in debug" If the program is not in the debug mode then If Debug return false
[ { "code": null, "e": 1293, "s": 1187, "text": "In Visual Studio Debug mode and Release mode are different configurations for building your .Net project." }, { "code": null, "e": 1442, "s": 1293, "text": "Select the Debug mode for debugging step by step their .Net project and select the Release mode for the final build of Assembly file (.dll or .exe)." }, { "code": null, "e": 1587, "s": 1442, "text": "The Debug mode does not optimize the binary it produces because the relationship between source code and generated instructions is more complex." }, { "code": null, "e": 1701, "s": 1587, "text": "This allows breakpoints to be set accurately and allows a programmer to step through the code one line at a time." }, { "code": null, "e": 1856, "s": 1701, "text": "The Debug configuration of your program is compiled with full symbolic debug information which help the debugger figure out where it is in the source code" }, { "code": null, "e": 1956, "s": 1856, "text": "The release configuration of your program has no symbolic debug information and is fully optimized." }, { "code": null, "e": 2037, "s": 1956, "text": "From the Build menu, select Configuration Manager, then select Debug or Release." }, { "code": null, "e": 2040, "s": 2037, "text": "or" }, { "code": null, "e": 2125, "s": 2040, "text": "On the toolbar, choose either Debug or Release from the Solution Configurations list" }, { "code": null, "e": 2239, "s": 2125, "text": "The code which is written inside the #if debug will be executed only if the code is running inside the debug mode" }, { "code": null, "e": 2368, "s": 2239, "text": "If the code is running in the release mode then the #if Debug will be false and it will not execute the code present inside this" }, { "code": null, "e": 2514, "s": 2368, "text": "class Program {\n static void Main() {\n #if DEBUG\n Console.WriteLine(\"You are in debug\");\n #endif\n Console.ReadKey();\n }\n}" }, { "code": null, "e": 2592, "s": 2514, "text": "If the Program is running in the debug mode then the If bloc will return true" }, { "code": null, "e": 2622, "s": 2592, "text": "And prints \"You are in debug\"" }, { "code": null, "e": 2689, "s": 2622, "text": "If the program is not in the debug mode then If Debug return false" } ]
How to Set an Image as Wallpaper Programmatically in Android?
23 Feb, 2021 Setting wallpaper in Android programmatically is helpful when the application is fetching wallpapers from the API library and asking the user whether to set the wallpaper for the home screen or not. In this article, it’s been discussed how to set a sample image as the home screen wallpaper programmatically. Have a look at the following image to get an idea of how that is going to be work after implementation. Note that we are going to implement this project using the Java language. Step 1: Create a New Project To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language. Step 2: Now add the permission to the AndroidManifest.xml file Invoke the following code in the AndroidMainfest.xml file. XML <?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.adityamshidlyali.setimageaswallpaper"> <!--access permission to set the wallpaper--> <uses-permission android:name="android.permission.SET_WALLPAPER" /> <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> Refer to the following image if unable to locate the AndroidManifest.xml file to invoke the permission. Step 3: Now import some images to the drawable folder Import some images to the drawable folder or can fetch the images from the API libraries. In this case, a sample GeeksforGeeks logo image has been imported to the drawable folder. The drawable folder can be got under the app > src > main > res > drawable If unable to locate the drawable folder refer to the following image. Step 4: Working with the activity_main.xml file Invoke the simple layout given below in the activity_main.xml file. Comments are added inside the code to understand the code in more detail. XML <?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context=".MainActivity" tools:ignore="HardcodedText"> <!--layout to bound the width and height of the wallpaper preview--> <LinearLayout android:layout_width="match_parent" android:layout_height="400dp"> <!--a sample image view for the preview purpose--> <ImageView android:id="@+id/wallpaper_image" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="16dp" android:scaleType="centerCrop" android:src="@drawable/wallpaper" /> </LinearLayout> <!--button which sets the image as wallpaper--> <Button android:id="@+id/set_wallpaper_button" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="16dp" android:text="Set As Wallpaper" /> </LinearLayout> Following Output UI is Produced: Step 5: Working with the MainActivity.java file Handle the button to set the desired wallpaper using WallpaperManager. Invoke the following code in the MainActivity.java file. Comments are added inside the code to understand the code in more detail. Java import androidx.appcompat.app.AppCompatActivity;import android.annotation.SuppressLint;import android.app.WallpaperManager;import android.os.Bundle;import android.view.View;import android.widget.Button;import java.io.IOException; public class MainActivity extends AppCompatActivity { // button to set the home screen wallpaper when clicked Button bSetWallpaper; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // creating the instance of the WallpaperManager final WallpaperManager wallpaperManager = WallpaperManager.getInstance(getApplicationContext()); // handle the set wallpaper button to set the desired wallpaper for home screen bSetWallpaper = findViewById(R.id.set_wallpaper_button); bSetWallpaper.setOnClickListener(new View.OnClickListener() { @SuppressLint("ResourceType") @Override public void onClick(View v) { try { // set the wallpaper by calling the setResource function and // passing the drawable file wallpaperManager.setResource(R.drawable.wallpaper); } catch (IOException e) { // here the errors can be logged instead of printStackTrace e.printStackTrace(); } } }); }} adityamshidlyali Android-Misc Technical Scripter 2020 Android Java Technical Scripter Java Android Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n23 Feb, 2021" }, { "code": null, "e": 516, "s": 28, "text": "Setting wallpaper in Android programmatically is helpful when the application is fetching wallpapers from the API library and asking the user whether to set the wallpaper for the home screen or not. In this article, it’s been discussed how to set a sample image as the home screen wallpaper programmatically. Have a look at the following image to get an idea of how that is going to be work after implementation. Note that we are going to implement this project using the Java language. " }, { "code": null, "e": 545, "s": 516, "text": "Step 1: Create a New Project" }, { "code": null, "e": 656, "s": 545, "text": "To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio." }, { "code": null, "e": 707, "s": 656, "text": "Note that select Java as the programming language." }, { "code": null, "e": 770, "s": 707, "text": "Step 2: Now add the permission to the AndroidManifest.xml file" }, { "code": null, "e": 829, "s": 770, "text": "Invoke the following code in the AndroidMainfest.xml file." }, { "code": null, "e": 833, "s": 829, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><manifest xmlns:android=\"http://schemas.android.com/apk/res/android\" package=\"com.adityamshidlyali.setimageaswallpaper\"> <!--access permission to set the wallpaper--> <uses-permission android:name=\"android.permission.SET_WALLPAPER\" /> <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>", "e": 1676, "s": 833, "text": null }, { "code": null, "e": 1780, "s": 1676, "text": "Refer to the following image if unable to locate the AndroidManifest.xml file to invoke the permission." }, { "code": null, "e": 1834, "s": 1780, "text": "Step 3: Now import some images to the drawable folder" }, { "code": null, "e": 1924, "s": 1834, "text": "Import some images to the drawable folder or can fetch the images from the API libraries." }, { "code": null, "e": 2014, "s": 1924, "text": "In this case, a sample GeeksforGeeks logo image has been imported to the drawable folder." }, { "code": null, "e": 2089, "s": 2014, "text": "The drawable folder can be got under the app > src > main > res > drawable" }, { "code": null, "e": 2159, "s": 2089, "text": "If unable to locate the drawable folder refer to the following image." }, { "code": null, "e": 2207, "s": 2159, "text": "Step 4: Working with the activity_main.xml file" }, { "code": null, "e": 2349, "s": 2207, "text": "Invoke the simple layout given below in the activity_main.xml file. Comments are added inside the code to understand the code in more detail." }, { "code": null, "e": 2353, "s": 2349, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:orientation=\"vertical\" tools:context=\".MainActivity\" tools:ignore=\"HardcodedText\"> <!--layout to bound the width and height of the wallpaper preview--> <LinearLayout android:layout_width=\"match_parent\" android:layout_height=\"400dp\"> <!--a sample image view for the preview purpose--> <ImageView android:id=\"@+id/wallpaper_image\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_margin=\"16dp\" android:scaleType=\"centerCrop\" android:src=\"@drawable/wallpaper\" /> </LinearLayout> <!--button which sets the image as wallpaper--> <Button android:id=\"@+id/set_wallpaper_button\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_margin=\"16dp\" android:text=\"Set As Wallpaper\" /> </LinearLayout>", "e": 3526, "s": 2353, "text": null }, { "code": null, "e": 3560, "s": 3526, "text": "Following Output UI is Produced: " }, { "code": null, "e": 3609, "s": 3560, "text": "Step 5: Working with the MainActivity.java file " }, { "code": null, "e": 3680, "s": 3609, "text": "Handle the button to set the desired wallpaper using WallpaperManager." }, { "code": null, "e": 3811, "s": 3680, "text": "Invoke the following code in the MainActivity.java file. Comments are added inside the code to understand the code in more detail." }, { "code": null, "e": 3816, "s": 3811, "text": "Java" }, { "code": "import androidx.appcompat.app.AppCompatActivity;import android.annotation.SuppressLint;import android.app.WallpaperManager;import android.os.Bundle;import android.view.View;import android.widget.Button;import java.io.IOException; public class MainActivity extends AppCompatActivity { // button to set the home screen wallpaper when clicked Button bSetWallpaper; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // creating the instance of the WallpaperManager final WallpaperManager wallpaperManager = WallpaperManager.getInstance(getApplicationContext()); // handle the set wallpaper button to set the desired wallpaper for home screen bSetWallpaper = findViewById(R.id.set_wallpaper_button); bSetWallpaper.setOnClickListener(new View.OnClickListener() { @SuppressLint(\"ResourceType\") @Override public void onClick(View v) { try { // set the wallpaper by calling the setResource function and // passing the drawable file wallpaperManager.setResource(R.drawable.wallpaper); } catch (IOException e) { // here the errors can be logged instead of printStackTrace e.printStackTrace(); } } }); }}", "e": 5265, "s": 3816, "text": null }, { "code": null, "e": 5282, "s": 5265, "text": "adityamshidlyali" }, { "code": null, "e": 5295, "s": 5282, "text": "Android-Misc" }, { "code": null, "e": 5319, "s": 5295, "text": "Technical Scripter 2020" }, { "code": null, "e": 5327, "s": 5319, "text": "Android" }, { "code": null, "e": 5332, "s": 5327, "text": "Java" }, { "code": null, "e": 5351, "s": 5332, "text": "Technical Scripter" }, { "code": null, "e": 5356, "s": 5351, "text": "Java" }, { "code": null, "e": 5364, "s": 5356, "text": "Android" } ]
SQL | SELECT data from Multiple Tables
17 Aug, 2020 Below statement could be used to get data from multiple tables, so, we need to use join to get data from multiple tables. Syntax : SELECT tablenmae1.colunmname, tablename2.columnnmae FROM tablenmae1 JOIN tablename2 ON tablenmae1.colunmnam = tablename2.columnnmae ORDER BY columnname; Let us take three tables, two tables of customers named Geeks1, Geeks2 and Geeks3. Geeks1 table : Geeks2 table : Geeks3 table : Example to select from multiple tables : SELECT Geeks3.GID, Geeks3.PID, Geeks3.Asset, Geeks1.FirstName, Geeks2.LastName FROM Geeks3 LEFT JOIN Geeks1 ON Geeks3.GID = Geeks1.ID LEFT JOIN Geeks2 ON Geeks3.GID = Geeks2.ID Output : DBMS-SQL DBMS SQL DBMS SQL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. CTE in SQL Introduction of DBMS (Database Management System) | Set 1 Difference between Clustered and Non-clustered index SQL Trigger | Student Database Introduction of B-Tree SQL | DDL, DQL, DML, DCL and TCL Commands How to find Nth highest salary from a table CTE in SQL SQL | ALTER (RENAME) SQL Trigger | Student Database
[ { "code": null, "e": 53, "s": 25, "text": "\n17 Aug, 2020" }, { "code": null, "e": 175, "s": 53, "text": "Below statement could be used to get data from multiple tables, so, we need to use join to get data from multiple tables." }, { "code": null, "e": 184, "s": 175, "text": "Syntax :" }, { "code": null, "e": 348, "s": 184, "text": "SELECT tablenmae1.colunmname, tablename2.columnnmae \nFROM tablenmae1 \nJOIN tablename2 \nON tablenmae1.colunmnam = tablename2.columnnmae\nORDER BY columnname; \n" }, { "code": null, "e": 431, "s": 348, "text": "Let us take three tables, two tables of customers named Geeks1, Geeks2 and Geeks3." }, { "code": null, "e": 446, "s": 431, "text": "Geeks1 table :" }, { "code": null, "e": 461, "s": 446, "text": "Geeks2 table :" }, { "code": null, "e": 476, "s": 461, "text": "Geeks3 table :" }, { "code": null, "e": 517, "s": 476, "text": "Example to select from multiple tables :" }, { "code": null, "e": 716, "s": 517, "text": "SELECT Geeks3.GID, Geeks3.PID, \n Geeks3.Asset, Geeks1.FirstName, \n Geeks2.LastName \nFROM Geeks3\nLEFT JOIN Geeks1 \nON Geeks3.GID = Geeks1.ID\nLEFT JOIN Geeks2 \nON Geeks3.GID = Geeks2.ID " }, { "code": null, "e": 725, "s": 716, "text": "Output :" }, { "code": null, "e": 734, "s": 725, "text": "DBMS-SQL" }, { "code": null, "e": 739, "s": 734, "text": "DBMS" }, { "code": null, "e": 743, "s": 739, "text": "SQL" }, { "code": null, "e": 748, "s": 743, "text": "DBMS" }, { "code": null, "e": 752, "s": 748, "text": "SQL" }, { "code": null, "e": 850, "s": 752, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 861, "s": 850, "text": "CTE in SQL" }, { "code": null, "e": 919, "s": 861, "text": "Introduction of DBMS (Database Management System) | Set 1" }, { "code": null, "e": 972, "s": 919, "text": "Difference between Clustered and Non-clustered index" }, { "code": null, "e": 1003, "s": 972, "text": "SQL Trigger | Student Database" }, { "code": null, "e": 1026, "s": 1003, "text": "Introduction of B-Tree" }, { "code": null, "e": 1068, "s": 1026, "text": "SQL | DDL, DQL, DML, DCL and TCL Commands" }, { "code": null, "e": 1112, "s": 1068, "text": "How to find Nth highest salary from a table" }, { "code": null, "e": 1123, "s": 1112, "text": "CTE in SQL" }, { "code": null, "e": 1144, "s": 1123, "text": "SQL | ALTER (RENAME)" } ]
Kali Linux – Vulnerability Analysis Tools
20 Nov, 2021 Vulnerability Analysis is one of the most important phases of Hacking. It is done after Information Gathering and is one of the crucial steps to be done while designing an application. The cyber-world is filled with a lot of vulnerabilities which are the loopholes in a program through which hacker executes an attack. These vulnerabilities act as an injection point or a point that could be used by an attacker as a launchpad to execute the attack. Kali Linux comes packed with 300+ tools out of which many are used for vulnerability analysis. Though there are many tools in Kali Linux for vulnerability analysis here is the list of most used tools. Nikto is an Open Source software written in Perl language that is used to scan a web-server for vulnerability that can be exploited and can compromise the server. It can also check for outdated version details of 1200 servers and can detect problems with specific version details of over 200 servers. It comes packed with many features, a few of them are listed below. Full support for SSL Looks for subdomains Supports full HTTP Proxy Outdated component report Username Guessing To use Nikto, download nikto, and enter the following command: perl nikto.pl -H Burp Suite is one of the most popular web application security testing software. It is used as a proxy, so all the requests from the browser with the proxy pass through it. And as the request passes through the burp suite, it allows us to make changes to those requests as per our need which is good for testing vulnerabilities like XSS or SQLi or even any vulnerability related to the web. Kali Linux comes with burp suite community edition which is free but there is a paid edition of this tool known as burp suite professional which has a lot many functions as compared to burp suite community edition. To use burp suite: Read this to learn how to setup burp suite. Open terminal and type “burpsuite” there. Go to the Proxy tab and turn the interceptor switch to on. Now visit any URL and it could be seen that the request is captured. SQLMap is an open-source tool that is used to automate the process of manual SQL injection over a parameter on a website. It detects and exploits the SQL injection parameters itself all we have to do is to provide it with an appropriate request or URL. It supports 34 databases including MySQL, Oracle, PostgreSQL, etc. To use sqlmap tool: sqlmap comes pre-installed in Kali Linux Just type sqlmap in the terminal to use the tool. It is another useful tool for the scanning phase of Ethical Hacking in Kali Linux. It uses the Graphical User Interface. It is a great tool for network discovery and security auditing. It does the same functions as that of the Nmap tool or in other words, it is the graphical Interface version of the Nmap tool. It uses command line Interface. It is a free utility tool for network discovery and security auditing. Tasks such as network inventory, managing service upgrade schedules, and monitoring host or service uptime are considered really useful by systems and network administrators. To use Zenmap, enter the target URL in the target field to scan the target. Nmap is an open-source network scanner that is used to recon/scan networks. It is used to discover hosts, ports, and services along with their versions over a network. It sends packets to the host and then analyzes the responses in order to produce the desired results. It could even be used for host discovery, operating system detection, or scanning for open ports. It is one of the most popular reconnaissance tools. To use Nmap: Ping the host with ping command to get the IP address ping hostname Open the terminal and enter the following command there: nmap -sV ipaddress Replace the IP address with the IP address of the host you want to scan. It will display all the captured details of the host. abhishek0719kadiyan Kali-Linux Linux-Unix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 53, "s": 25, "text": "\n20 Nov, 2021" }, { "code": null, "e": 504, "s": 53, "text": "Vulnerability Analysis is one of the most important phases of Hacking. It is done after Information Gathering and is one of the crucial steps to be done while designing an application. The cyber-world is filled with a lot of vulnerabilities which are the loopholes in a program through which hacker executes an attack. These vulnerabilities act as an injection point or a point that could be used by an attacker as a launchpad to execute the attack. " }, { "code": null, "e": 707, "s": 504, "text": "Kali Linux comes packed with 300+ tools out of which many are used for vulnerability analysis. Though there are many tools in Kali Linux for vulnerability analysis here is the list of most used tools. " }, { "code": null, "e": 1078, "s": 707, "text": "Nikto is an Open Source software written in Perl language that is used to scan a web-server for vulnerability that can be exploited and can compromise the server. It can also check for outdated version details of 1200 servers and can detect problems with specific version details of over 200 servers. It comes packed with many features, a few of them are listed below. " }, { "code": null, "e": 1099, "s": 1078, "text": "Full support for SSL" }, { "code": null, "e": 1120, "s": 1099, "text": "Looks for subdomains" }, { "code": null, "e": 1145, "s": 1120, "text": "Supports full HTTP Proxy" }, { "code": null, "e": 1171, "s": 1145, "text": "Outdated component report" }, { "code": null, "e": 1189, "s": 1171, "text": "Username Guessing" }, { "code": null, "e": 1253, "s": 1189, "text": "To use Nikto, download nikto, and enter the following command: " }, { "code": null, "e": 1270, "s": 1253, "text": "perl nikto.pl -H" }, { "code": null, "e": 1877, "s": 1270, "text": "Burp Suite is one of the most popular web application security testing software. It is used as a proxy, so all the requests from the browser with the proxy pass through it. And as the request passes through the burp suite, it allows us to make changes to those requests as per our need which is good for testing vulnerabilities like XSS or SQLi or even any vulnerability related to the web. Kali Linux comes with burp suite community edition which is free but there is a paid edition of this tool known as burp suite professional which has a lot many functions as compared to burp suite community edition. " }, { "code": null, "e": 1897, "s": 1877, "text": "To use burp suite: " }, { "code": null, "e": 1941, "s": 1897, "text": "Read this to learn how to setup burp suite." }, { "code": null, "e": 1983, "s": 1941, "text": "Open terminal and type “burpsuite” there." }, { "code": null, "e": 2042, "s": 1983, "text": "Go to the Proxy tab and turn the interceptor switch to on." }, { "code": null, "e": 2111, "s": 2042, "text": "Now visit any URL and it could be seen that the request is captured." }, { "code": null, "e": 2432, "s": 2111, "text": "SQLMap is an open-source tool that is used to automate the process of manual SQL injection over a parameter on a website. It detects and exploits the SQL injection parameters itself all we have to do is to provide it with an appropriate request or URL. It supports 34 databases including MySQL, Oracle, PostgreSQL, etc. " }, { "code": null, "e": 2453, "s": 2432, "text": "To use sqlmap tool: " }, { "code": null, "e": 2494, "s": 2453, "text": "sqlmap comes pre-installed in Kali Linux" }, { "code": null, "e": 2544, "s": 2494, "text": "Just type sqlmap in the terminal to use the tool." }, { "code": null, "e": 3135, "s": 2544, "text": "It is another useful tool for the scanning phase of Ethical Hacking in Kali Linux. It uses the Graphical User Interface. It is a great tool for network discovery and security auditing. It does the same functions as that of the Nmap tool or in other words, it is the graphical Interface version of the Nmap tool. It uses command line Interface. It is a free utility tool for network discovery and security auditing. Tasks such as network inventory, managing service upgrade schedules, and monitoring host or service uptime are considered really useful by systems and network administrators. " }, { "code": null, "e": 3212, "s": 3135, "text": "To use Zenmap, enter the target URL in the target field to scan the target. " }, { "code": null, "e": 3633, "s": 3212, "text": "Nmap is an open-source network scanner that is used to recon/scan networks. It is used to discover hosts, ports, and services along with their versions over a network. It sends packets to the host and then analyzes the responses in order to produce the desired results. It could even be used for host discovery, operating system detection, or scanning for open ports. It is one of the most popular reconnaissance tools. " }, { "code": null, "e": 3647, "s": 3633, "text": "To use Nmap: " }, { "code": null, "e": 3701, "s": 3647, "text": "Ping the host with ping command to get the IP address" }, { "code": null, "e": 3715, "s": 3701, "text": "ping hostname" }, { "code": null, "e": 3772, "s": 3715, "text": "Open the terminal and enter the following command there:" }, { "code": null, "e": 3791, "s": 3772, "text": "nmap -sV ipaddress" }, { "code": null, "e": 3864, "s": 3791, "text": "Replace the IP address with the IP address of the host you want to scan." }, { "code": null, "e": 3918, "s": 3864, "text": "It will display all the captured details of the host." }, { "code": null, "e": 3940, "s": 3920, "text": "abhishek0719kadiyan" }, { "code": null, "e": 3951, "s": 3940, "text": "Kali-Linux" }, { "code": null, "e": 3962, "s": 3951, "text": "Linux-Unix" } ]
Minimum time required to fill given N slots - GeeksforGeeks
31 May, 2021 Given an integer N which denotes the number of slots, and an array arr[] consisting of K integers in the range [1, N] repreand. Each element of the array are in the range [1, N] which represents the indices of the filled slots. At each unit of time, the index with filled slot fills the adjacent empty slots. The task is to find the minimum time taken to fill all the N slots. Examples: Input: N = 6, K = 2, arr[] = {2, 6}Output: 2Explanation:Initially there are 6 slots and the indices of the filled slots are slots[] = {0, 2, 0, 0, 0, 6}, where 0 represents unfilled.After 1 unit of time, slots[] = {1, 2, 3, 0, 5, 6}After 2 units of time, slots[] = {1, 2, 3, 4, 5, 6}Therefore, the minimum time required is 2. Input: N = 5, K = 5, arr[] = {1, 2, 3, 4, 5}Output: 1 Approach: To solve the given problem, the idea is to perform Level Order Traversal on the given N slots using a Queue. Follow the steps below to solve the problem: Initialize a variable, say time as 0, and an auxiliary array visited[] to mark the filled indices in each iteration. Now, push the indices of filled slots given in array arr[] in a queue and mark them as visited. Now, iterate until the queue is not empty and perform the following steps:Remove the front index i from the queue and if the adjacent slots (i – 1) and (i + 1) are in the range [1, N] and are unvisited, then mark them as visited and push them into the queue.Increment the time by 1. Remove the front index i from the queue and if the adjacent slots (i – 1) and (i + 1) are in the range [1, N] and are unvisited, then mark them as visited and push them into the queue. Increment the time by 1. After completing the above steps, print the value of (time – 1) as the minimum time required to fill all the slots. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ program for the above approach#include <bits/stdc++.h> using namespace std; // Function to return the minimum// time to fill all the slotsvoid minTime(vector<int> arr, int N, int K){ // Stores visited slots queue<int> q; // Checks if a slot is visited or not vector<bool> vis(N + 1, false); int time = 0; // Insert all filled slots for (int i = 0; i < K; i++) { q.push(arr[i]); vis[arr[i]] = true; } // Iterate until queue is // not empty while (q.size() > 0) { // Iterate through all slots // in the queue for (int i = 0; i < q.size(); i++) { // Front index int curr = q.front(); q.pop(); // If previous slot is // present and not visited if (curr - 1 >= 1 && !vis[curr - 1]) { vis[curr - 1] = true; q.push(curr - 1); } // If next slot is present // and not visited if (curr + 1 <= N && !vis[curr + 1]) { vis[curr + 1] = true; q.push(curr + 1); } } // Increment the time // at each level time++; } // Print the answer cout << (time - 1);} // Driver Codeint main(){ int N = 6; vector<int> arr = { 2, 6 }; int K = arr.size(); // Function Call minTime(arr, N, K);} // Java program for the above approach import java.io.*;import java.util.*;class GFG { // Function to return the minimum // time to fill all the slots public static void minTime(int arr[], int N, int K) { // Stores visited slots Queue<Integer> q = new LinkedList<>(); // Checks if a slot is visited or not boolean vis[] = new boolean[N + 1]; int time = 0; // Insert all filled slots for (int i = 0; i < K; i++) { q.add(arr[i]); vis[arr[i]] = true; } // Iterate until queue is // not empty while (q.size() > 0) { // Iterate through all slots // in the queue for (int i = 0; i < q.size(); i++) { // Front index int curr = q.poll(); // If previous slot is // present and not visited if (curr - 1 >= 1 && !vis[curr - 1]) { vis[curr - 1] = true; q.add(curr - 1); } // If next slot is present // and not visited if (curr + 1 <= N && !vis[curr + 1]) { vis[curr + 1] = true; q.add(curr + 1); } } // Increment the time // at each level time++; } // Print the answer System.out.println(time - 1); } // Driver Code public static void main(String[] args) { int N = 6; int arr[] = { 2, 6 }; int K = arr.length; // Function Call minTime(arr, N, K); }} # Python3 program for the above approach # Function to return the minimum# time to fill all the slotsdef minTime(arr, N, K): # Stores visited slots q = [] # Checks if a slot is visited or not vis = [False] * (N + 1) time = 0 # Insert all filled slots for i in range(K): q.append(arr[i]) vis[arr[i]] = True # Iterate until queue is # not empty while (len(q) > 0): # Iterate through all slots # in the queue for i in range(len(q)): # Front index curr = q[0] q.pop(0) # If previous slot is # present and not visited if (curr - 1 >= 1 and vis[curr - 1] == 0): vis[curr - 1] = True q.append(curr - 1) # If next slot is present # and not visited if (curr + 1 <= N and vis[curr + 1] == 0): vis[curr + 1] = True q.append(curr + 1) # Increment the time # at each level time += 1 # Print the answer print(time - 1) # Driver CodeN = 6arr = [ 2, 6 ]K = len(arr) # Function CallminTime(arr, N, K) # This code is contributed by susmitakundugoaldanga // C# program for the above approachusing System;using System.Collections.Generic;class GFG{ // Function to return the minimum// time to fill all the slotsstatic void minTime(List<int> arr, int N, int K){ // Stores visited slots Queue<int> q = new Queue<int>(); // Checks if a slot is visited or not int []vis = new int[N + 1]; Array.Clear(vis, 0, vis.Length); int time = 0; // Insert all filled slots for (int i = 0; i < K; i++) { q.Enqueue(arr[i]); vis[arr[i]] = 1; } // Iterate until queue is // not empty while (q.Count > 0) { // Iterate through all slots // in the queue for (int i = 0; i < q.Count; i++) { // Front index int curr = q.Peek(); q.Dequeue(); // If previous slot is // present and not visited if (curr - 1 >= 1 && vis[curr - 1]==0) { vis[curr - 1] = 1; q.Enqueue(curr - 1); } // If next slot is present // and not visited if (curr + 1 <= N && vis[curr + 1] == 0) { vis[curr + 1] = 1; q.Enqueue(curr + 1); } } // Increment the time // at each level time++; } // Print the answer Console.WriteLine(time-1);} // Driver Codepublic static void Main(){ int N = 6; List<int> arr = new List<int>() { 2, 6 }; int K = arr.Count; // Function Call minTime(arr, N, K);}} // THIS CODE IS CONTRIBUTED BY SURENDRA_GANGWAR. <script> // Javascript program for the above approach // Function to return the minimum// time to fill all the slotsfunction minTime(arr, N, K){ // Stores visited slots var q = []; // Checks if a slot is visited or not var vis = Array(N + 1).fill(false); var time = 0; // Insert all filled slots for (var i = 0; i < K; i++) { q.push(arr[i]); vis[arr[i]] = true; } // Iterate until queue is // not empty while (q.length > 0) { // Iterate through all slots // in the queue for (var i = 0; i < q.length; i++) { // Front index var curr = q[0]; q.pop(); // If previous slot is // present and not visited if (curr - 1 >= 1 && !vis[curr - 1]) { vis[curr - 1] = true; q.push(curr - 1); } // If next slot is present // and not visited if (curr + 1 <= N && !vis[curr + 1]) { vis[curr + 1] = true; q.push(curr + 1); } } // Increment the time // at each level time++; } // Print the answer document.write(time - 1);} // Driver Codevar N = 6;var arr = [2, 6];var K = arr.length; // Function CallminTime(arr, N, K); // This code is contributed by noob2000.</script> 2 Time Complexity: O(N)Auxiliary Space: O(N) mohit kumar 29 susmitakundugoaldanga SURENDRA_GANGWAR noob2000 BFS cpp-queue tree-level-order Arrays Queue Searching Arrays Searching Queue BFS Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Maximum and minimum of an array using minimum number of comparisons Top 50 Array Coding Problems for Interviews Stack Data Structure (Introduction and Program) Introduction to Arrays Multidimensional Arrays in Java Breadth First Search or BFS for a Graph Level Order Binary Tree Traversal Queue Interface In Java Queue in Python Queue | Set 1 (Introduction and Array Implementation)
[ { "code": null, "e": 26933, "s": 26905, "text": "\n31 May, 2021" }, { "code": null, "e": 27310, "s": 26933, "text": "Given an integer N which denotes the number of slots, and an array arr[] consisting of K integers in the range [1, N] repreand. Each element of the array are in the range [1, N] which represents the indices of the filled slots. At each unit of time, the index with filled slot fills the adjacent empty slots. The task is to find the minimum time taken to fill all the N slots." }, { "code": null, "e": 27320, "s": 27310, "text": "Examples:" }, { "code": null, "e": 27646, "s": 27320, "text": "Input: N = 6, K = 2, arr[] = {2, 6}Output: 2Explanation:Initially there are 6 slots and the indices of the filled slots are slots[] = {0, 2, 0, 0, 0, 6}, where 0 represents unfilled.After 1 unit of time, slots[] = {1, 2, 3, 0, 5, 6}After 2 units of time, slots[] = {1, 2, 3, 4, 5, 6}Therefore, the minimum time required is 2." }, { "code": null, "e": 27700, "s": 27646, "text": "Input: N = 5, K = 5, arr[] = {1, 2, 3, 4, 5}Output: 1" }, { "code": null, "e": 27864, "s": 27700, "text": "Approach: To solve the given problem, the idea is to perform Level Order Traversal on the given N slots using a Queue. Follow the steps below to solve the problem:" }, { "code": null, "e": 27981, "s": 27864, "text": "Initialize a variable, say time as 0, and an auxiliary array visited[] to mark the filled indices in each iteration." }, { "code": null, "e": 28077, "s": 27981, "text": "Now, push the indices of filled slots given in array arr[] in a queue and mark them as visited." }, { "code": null, "e": 28360, "s": 28077, "text": "Now, iterate until the queue is not empty and perform the following steps:Remove the front index i from the queue and if the adjacent slots (i – 1) and (i + 1) are in the range [1, N] and are unvisited, then mark them as visited and push them into the queue.Increment the time by 1." }, { "code": null, "e": 28545, "s": 28360, "text": "Remove the front index i from the queue and if the adjacent slots (i – 1) and (i + 1) are in the range [1, N] and are unvisited, then mark them as visited and push them into the queue." }, { "code": null, "e": 28570, "s": 28545, "text": "Increment the time by 1." }, { "code": null, "e": 28686, "s": 28570, "text": "After completing the above steps, print the value of (time – 1) as the minimum time required to fill all the slots." }, { "code": null, "e": 28737, "s": 28686, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 28741, "s": 28737, "text": "C++" }, { "code": null, "e": 28746, "s": 28741, "text": "Java" }, { "code": null, "e": 28754, "s": 28746, "text": "Python3" }, { "code": null, "e": 28757, "s": 28754, "text": "C#" }, { "code": null, "e": 28768, "s": 28757, "text": "Javascript" }, { "code": "// C++ program for the above approach#include <bits/stdc++.h> using namespace std; // Function to return the minimum// time to fill all the slotsvoid minTime(vector<int> arr, int N, int K){ // Stores visited slots queue<int> q; // Checks if a slot is visited or not vector<bool> vis(N + 1, false); int time = 0; // Insert all filled slots for (int i = 0; i < K; i++) { q.push(arr[i]); vis[arr[i]] = true; } // Iterate until queue is // not empty while (q.size() > 0) { // Iterate through all slots // in the queue for (int i = 0; i < q.size(); i++) { // Front index int curr = q.front(); q.pop(); // If previous slot is // present and not visited if (curr - 1 >= 1 && !vis[curr - 1]) { vis[curr - 1] = true; q.push(curr - 1); } // If next slot is present // and not visited if (curr + 1 <= N && !vis[curr + 1]) { vis[curr + 1] = true; q.push(curr + 1); } } // Increment the time // at each level time++; } // Print the answer cout << (time - 1);} // Driver Codeint main(){ int N = 6; vector<int> arr = { 2, 6 }; int K = arr.size(); // Function Call minTime(arr, N, K);}", "e": 30191, "s": 28768, "text": null }, { "code": "// Java program for the above approach import java.io.*;import java.util.*;class GFG { // Function to return the minimum // time to fill all the slots public static void minTime(int arr[], int N, int K) { // Stores visited slots Queue<Integer> q = new LinkedList<>(); // Checks if a slot is visited or not boolean vis[] = new boolean[N + 1]; int time = 0; // Insert all filled slots for (int i = 0; i < K; i++) { q.add(arr[i]); vis[arr[i]] = true; } // Iterate until queue is // not empty while (q.size() > 0) { // Iterate through all slots // in the queue for (int i = 0; i < q.size(); i++) { // Front index int curr = q.poll(); // If previous slot is // present and not visited if (curr - 1 >= 1 && !vis[curr - 1]) { vis[curr - 1] = true; q.add(curr - 1); } // If next slot is present // and not visited if (curr + 1 <= N && !vis[curr + 1]) { vis[curr + 1] = true; q.add(curr + 1); } } // Increment the time // at each level time++; } // Print the answer System.out.println(time - 1); } // Driver Code public static void main(String[] args) { int N = 6; int arr[] = { 2, 6 }; int K = arr.length; // Function Call minTime(arr, N, K); }}", "e": 31905, "s": 30191, "text": null }, { "code": "# Python3 program for the above approach # Function to return the minimum# time to fill all the slotsdef minTime(arr, N, K): # Stores visited slots q = [] # Checks if a slot is visited or not vis = [False] * (N + 1) time = 0 # Insert all filled slots for i in range(K): q.append(arr[i]) vis[arr[i]] = True # Iterate until queue is # not empty while (len(q) > 0): # Iterate through all slots # in the queue for i in range(len(q)): # Front index curr = q[0] q.pop(0) # If previous slot is # present and not visited if (curr - 1 >= 1 and vis[curr - 1] == 0): vis[curr - 1] = True q.append(curr - 1) # If next slot is present # and not visited if (curr + 1 <= N and vis[curr + 1] == 0): vis[curr + 1] = True q.append(curr + 1) # Increment the time # at each level time += 1 # Print the answer print(time - 1) # Driver CodeN = 6arr = [ 2, 6 ]K = len(arr) # Function CallminTime(arr, N, K) # This code is contributed by susmitakundugoaldanga", "e": 33167, "s": 31905, "text": null }, { "code": "// C# program for the above approachusing System;using System.Collections.Generic;class GFG{ // Function to return the minimum// time to fill all the slotsstatic void minTime(List<int> arr, int N, int K){ // Stores visited slots Queue<int> q = new Queue<int>(); // Checks if a slot is visited or not int []vis = new int[N + 1]; Array.Clear(vis, 0, vis.Length); int time = 0; // Insert all filled slots for (int i = 0; i < K; i++) { q.Enqueue(arr[i]); vis[arr[i]] = 1; } // Iterate until queue is // not empty while (q.Count > 0) { // Iterate through all slots // in the queue for (int i = 0; i < q.Count; i++) { // Front index int curr = q.Peek(); q.Dequeue(); // If previous slot is // present and not visited if (curr - 1 >= 1 && vis[curr - 1]==0) { vis[curr - 1] = 1; q.Enqueue(curr - 1); } // If next slot is present // and not visited if (curr + 1 <= N && vis[curr + 1] == 0) { vis[curr + 1] = 1; q.Enqueue(curr + 1); } } // Increment the time // at each level time++; } // Print the answer Console.WriteLine(time-1);} // Driver Codepublic static void Main(){ int N = 6; List<int> arr = new List<int>() { 2, 6 }; int K = arr.Count; // Function Call minTime(arr, N, K);}} // THIS CODE IS CONTRIBUTED BY SURENDRA_GANGWAR.", "e": 34783, "s": 33167, "text": null }, { "code": "<script> // Javascript program for the above approach // Function to return the minimum// time to fill all the slotsfunction minTime(arr, N, K){ // Stores visited slots var q = []; // Checks if a slot is visited or not var vis = Array(N + 1).fill(false); var time = 0; // Insert all filled slots for (var i = 0; i < K; i++) { q.push(arr[i]); vis[arr[i]] = true; } // Iterate until queue is // not empty while (q.length > 0) { // Iterate through all slots // in the queue for (var i = 0; i < q.length; i++) { // Front index var curr = q[0]; q.pop(); // If previous slot is // present and not visited if (curr - 1 >= 1 && !vis[curr - 1]) { vis[curr - 1] = true; q.push(curr - 1); } // If next slot is present // and not visited if (curr + 1 <= N && !vis[curr + 1]) { vis[curr + 1] = true; q.push(curr + 1); } } // Increment the time // at each level time++; } // Print the answer document.write(time - 1);} // Driver Codevar N = 6;var arr = [2, 6];var K = arr.length; // Function CallminTime(arr, N, K); // This code is contributed by noob2000.</script>", "e": 36172, "s": 34783, "text": null }, { "code": null, "e": 36174, "s": 36172, "text": "2" }, { "code": null, "e": 36219, "s": 36176, "text": "Time Complexity: O(N)Auxiliary Space: O(N)" }, { "code": null, "e": 36234, "s": 36219, "text": "mohit kumar 29" }, { "code": null, "e": 36256, "s": 36234, "text": "susmitakundugoaldanga" }, { "code": null, "e": 36273, "s": 36256, "text": "SURENDRA_GANGWAR" }, { "code": null, "e": 36282, "s": 36273, "text": "noob2000" }, { "code": null, "e": 36286, "s": 36282, "text": "BFS" }, { "code": null, "e": 36296, "s": 36286, "text": "cpp-queue" }, { "code": null, "e": 36313, "s": 36296, "text": "tree-level-order" }, { "code": null, "e": 36320, "s": 36313, "text": "Arrays" }, { "code": null, "e": 36326, "s": 36320, "text": "Queue" }, { "code": null, "e": 36336, "s": 36326, "text": "Searching" }, { "code": null, "e": 36343, "s": 36336, "text": "Arrays" }, { "code": null, "e": 36353, "s": 36343, "text": "Searching" }, { "code": null, "e": 36359, "s": 36353, "text": "Queue" }, { "code": null, "e": 36363, "s": 36359, "text": "BFS" }, { "code": null, "e": 36461, "s": 36363, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 36529, "s": 36461, "text": "Maximum and minimum of an array using minimum number of comparisons" }, { "code": null, "e": 36573, "s": 36529, "text": "Top 50 Array Coding Problems for Interviews" }, { "code": null, "e": 36621, "s": 36573, "text": "Stack Data Structure (Introduction and Program)" }, { "code": null, "e": 36644, "s": 36621, "text": "Introduction to Arrays" }, { "code": null, "e": 36676, "s": 36644, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 36716, "s": 36676, "text": "Breadth First Search or BFS for a Graph" }, { "code": null, "e": 36750, "s": 36716, "text": "Level Order Binary Tree Traversal" }, { "code": null, "e": 36774, "s": 36750, "text": "Queue Interface In Java" }, { "code": null, "e": 36790, "s": 36774, "text": "Queue in Python" } ]
Check if a given year is leap year in PL/SQL - GeeksforGeeks
02 Jul, 2018 Prerequisite – PL/SQL introduction In PL/SQL code groups of commands are arranged within a block. A block group related declarations or statements. In declare part, we declare variables and between begin and end part, we perform the operations. Given a year, the task is to check that given year is a leap year or not. Examples: Input: 1500 Output: 1500 is not leap year. Input: 1600 Output: 1600 is a leap year A year is a leap year if following conditions are satisfied:1) Year is multiple of 4002) Year is multiple of 4 and not multiple of 100 -- To check if a-- given year is leap year or notDECLARE year NUMBER := 1600;BEGIN -- true if the year is a multiple -- of 4 and not multiple of 100. -- OR year is multiple of 400. IF MOD(year, 4)=0 AND MOD(year, 100)!=0 OR MOD(year, 400)=0 THEN dbms_output.Put_line(year || ' is a leap year '); ELSE dbms_output.Put_line(year || ' is not a leap year.'); END IF;END; Output: 1600 is a leap year. SQL-PL/SQL SQL SQL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. SQL Interview Questions CTE in SQL How to Update Multiple Columns in Single Update Statement in SQL? Difference between SQL and NoSQL Difference between DELETE, DROP and TRUNCATE MySQL | Group_CONCAT() Function Difference between DELETE and TRUNCATE SQL - ORDER BY SQL | Subquery How to Create a Table With Multiple Foreign Keys in SQL?
[ { "code": null, "e": 25622, "s": 25594, "text": "\n02 Jul, 2018" }, { "code": null, "e": 25657, "s": 25622, "text": "Prerequisite – PL/SQL introduction" }, { "code": null, "e": 25867, "s": 25657, "text": "In PL/SQL code groups of commands are arranged within a block. A block group related declarations or statements. In declare part, we declare variables and between begin and end part, we perform the operations." }, { "code": null, "e": 25941, "s": 25867, "text": "Given a year, the task is to check that given year is a leap year or not." }, { "code": null, "e": 25951, "s": 25941, "text": "Examples:" }, { "code": null, "e": 26036, "s": 25951, "text": "Input: 1500\nOutput: 1500 is not leap year.\n\nInput: 1600\nOutput: 1600 is a leap year\n" }, { "code": null, "e": 26171, "s": 26036, "text": "A year is a leap year if following conditions are satisfied:1) Year is multiple of 4002) Year is multiple of 4 and not multiple of 100" }, { "code": "-- To check if a-- given year is leap year or notDECLARE year NUMBER := 1600;BEGIN -- true if the year is a multiple -- of 4 and not multiple of 100. -- OR year is multiple of 400. IF MOD(year, 4)=0 AND MOD(year, 100)!=0 OR MOD(year, 400)=0 THEN dbms_output.Put_line(year || ' is a leap year '); ELSE dbms_output.Put_line(year || ' is not a leap year.'); END IF;END; ", "e": 26571, "s": 26171, "text": null }, { "code": null, "e": 26579, "s": 26571, "text": "Output:" }, { "code": null, "e": 26601, "s": 26579, "text": "1600 is a leap year.\n" }, { "code": null, "e": 26612, "s": 26601, "text": "SQL-PL/SQL" }, { "code": null, "e": 26616, "s": 26612, "text": "SQL" }, { "code": null, "e": 26620, "s": 26616, "text": "SQL" }, { "code": null, "e": 26718, "s": 26620, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26742, "s": 26718, "text": "SQL Interview Questions" }, { "code": null, "e": 26753, "s": 26742, "text": "CTE in SQL" }, { "code": null, "e": 26819, "s": 26753, "text": "How to Update Multiple Columns in Single Update Statement in SQL?" }, { "code": null, "e": 26852, "s": 26819, "text": "Difference between SQL and NoSQL" }, { "code": null, "e": 26897, "s": 26852, "text": "Difference between DELETE, DROP and TRUNCATE" }, { "code": null, "e": 26929, "s": 26897, "text": "MySQL | Group_CONCAT() Function" }, { "code": null, "e": 26968, "s": 26929, "text": "Difference between DELETE and TRUNCATE" }, { "code": null, "e": 26983, "s": 26968, "text": "SQL - ORDER BY" }, { "code": null, "e": 26998, "s": 26983, "text": "SQL | Subquery" } ]
How to Clear RAM Memory Cache, Buffer and Swap Space on Linux - GeeksforGeeks
30 May, 2021 In this article, we will see How to Clear RAM Memory Cache, Buffer, and Swap Space on Linux. In every system we do come across caches that have unwanted files and can harm our system, the same thing happens in Linux cache and if you want to clear the cache and free some memory then Linux has many commands to do that. In all the Linux systems we have three options to clear cache without interrupting any services or processes. Example 1: To Clear PageCache only Syntax : sudo sh -c 'echo 1 > /proc/sys/vm/drop_caches' The command # free -h will give us the status of the memory drop_caches is used a clean cache without killing any application, you can run the # free -h command to see the difference between used and free memory before and after clearing the cache Example 2: To Clear dentries and inodes Syntax: sudo sh -c 'echo 2 > /proc/sys/vm/drop_caches' Example 3: To Clear PageCache, dentries and inodes Syntax: sudo sh -c 'echo 3 > /proc/sys/vm/drop_caches' Now using Linux Kernel, to free Buffer and Cache in Linux we will Create a shell script to auto clear RAM cache daily, through a cron scheduler task., the command vim script.sh is used to create a shell script “script.sh” Now in script, you have to add the below syntax: echo " echo 3 > /proc/sys/vm/drop_caches" Now to set run permission, to clear ram cache, you have to call the script whenever required, setting a cron to clear RAM caches every day for 3 hours. # chmod 755 script.sh # crontab -e Example 4: To Clear Swap Space in Linux You can clear the swap space by running the below command Syntax : sudo swapoff -a sudo swapon -a You can run the # free -h command to see the difference between used and free memory before and after clearing the swap space Add the above command to a cron script, Here we are going to combine this two different command into one single command, to form a proper script which will help us to clear Swap Space and RAM Cache. echo 3 > /proc/sys/vm/drop_caches & & swapoff -a & & swapon -a & & printf ‘\n%s\n’ ‘ ‘ Ram-cache and the swap get cleared’ Now Ram cache and swap will be cleared you can run # free -h command to see After running the command you will get output like this linux-command Picked Linux-Unix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. ZIP command in Linux with examples TCP Server-Client implementation in C tar command in Linux with examples curl command in Linux with Examples Conditional Statements | Shell Script diff command in Linux with examples UDP Server-Client implementation in C Tail command in Linux with examples echo command in Linux with Examples Compiling with g++
[ { "code": null, "e": 25731, "s": 25703, "text": "\n30 May, 2021" }, { "code": null, "e": 26050, "s": 25731, "text": "In this article, we will see How to Clear RAM Memory Cache, Buffer, and Swap Space on Linux. In every system we do come across caches that have unwanted files and can harm our system, the same thing happens in Linux cache and if you want to clear the cache and free some memory then Linux has many commands to do that." }, { "code": null, "e": 26160, "s": 26050, "text": "In all the Linux systems we have three options to clear cache without interrupting any services or processes." }, { "code": null, "e": 26195, "s": 26160, "text": "Example 1: To Clear PageCache only" }, { "code": null, "e": 26204, "s": 26195, "text": "Syntax :" }, { "code": null, "e": 26252, "s": 26204, "text": "sudo sh -c 'echo 1 > /proc/sys/vm/drop_caches'" }, { "code": null, "e": 26313, "s": 26252, "text": "The command # free -h will give us the status of the memory " }, { "code": null, "e": 26501, "s": 26313, "text": "drop_caches is used a clean cache without killing any application, you can run the # free -h command to see the difference between used and free memory before and after clearing the cache" }, { "code": null, "e": 26541, "s": 26501, "text": "Example 2: To Clear dentries and inodes" }, { "code": null, "e": 26549, "s": 26541, "text": "Syntax:" }, { "code": null, "e": 26598, "s": 26549, "text": "sudo sh -c 'echo 2 > /proc/sys/vm/drop_caches' " }, { "code": null, "e": 26649, "s": 26598, "text": "Example 3: To Clear PageCache, dentries and inodes" }, { "code": null, "e": 26657, "s": 26649, "text": "Syntax:" }, { "code": null, "e": 26707, "s": 26657, "text": "sudo sh -c 'echo 3 > /proc/sys/vm/drop_caches' " }, { "code": null, "e": 26929, "s": 26707, "text": "Now using Linux Kernel, to free Buffer and Cache in Linux we will Create a shell script to auto clear RAM cache daily, through a cron scheduler task., the command vim script.sh is used to create a shell script “script.sh”" }, { "code": null, "e": 26978, "s": 26929, "text": "Now in script, you have to add the below syntax:" }, { "code": null, "e": 27021, "s": 26978, "text": "echo \" echo 3 > /proc/sys/vm/drop_caches\"" }, { "code": null, "e": 27173, "s": 27021, "text": "Now to set run permission, to clear ram cache, you have to call the script whenever required, setting a cron to clear RAM caches every day for 3 hours." }, { "code": null, "e": 27208, "s": 27173, "text": "# chmod 755 script.sh\n# crontab -e" }, { "code": null, "e": 27248, "s": 27208, "text": "Example 4: To Clear Swap Space in Linux" }, { "code": null, "e": 27307, "s": 27248, "text": "You can clear the swap space by running the below command " }, { "code": null, "e": 27316, "s": 27307, "text": "Syntax :" }, { "code": null, "e": 27348, "s": 27316, "text": "sudo swapoff -a\n\nsudo swapon -a" }, { "code": null, "e": 27474, "s": 27348, "text": "You can run the # free -h command to see the difference between used and free memory before and after clearing the swap space" }, { "code": null, "e": 27673, "s": 27474, "text": "Add the above command to a cron script, Here we are going to combine this two different command into one single command, to form a proper script which will help us to clear Swap Space and RAM Cache." }, { "code": null, "e": 27802, "s": 27673, "text": "echo 3 > /proc/sys/vm/drop_caches & & swapoff -a & & swapon -a & & printf ‘\\n%s\\n’ ‘ ‘ Ram-cache and the swap get cleared’" }, { "code": null, "e": 27879, "s": 27802, "text": "Now Ram cache and swap will be cleared you can run # free -h command to see" }, { "code": null, "e": 27936, "s": 27879, "text": "After running the command you will get output like this " }, { "code": null, "e": 27950, "s": 27936, "text": "linux-command" }, { "code": null, "e": 27957, "s": 27950, "text": "Picked" }, { "code": null, "e": 27968, "s": 27957, "text": "Linux-Unix" }, { "code": null, "e": 28066, "s": 27968, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28101, "s": 28066, "text": "ZIP command in Linux with examples" }, { "code": null, "e": 28139, "s": 28101, "text": "TCP Server-Client implementation in C" }, { "code": null, "e": 28174, "s": 28139, "text": "tar command in Linux with examples" }, { "code": null, "e": 28210, "s": 28174, "text": "curl command in Linux with Examples" }, { "code": null, "e": 28248, "s": 28210, "text": "Conditional Statements | Shell Script" }, { "code": null, "e": 28284, "s": 28248, "text": "diff command in Linux with examples" }, { "code": null, "e": 28322, "s": 28284, "text": "UDP Server-Client implementation in C" }, { "code": null, "e": 28358, "s": 28322, "text": "Tail command in Linux with examples" }, { "code": null, "e": 28394, "s": 28358, "text": "echo command in Linux with Examples" } ]
Implement Search Autocomplete For Input Fields in Django - GeeksforGeeks
16 Feb, 2021 Django is a high-level Python based Web Framework that allows rapid development and clean, pragmatic design. It is also called batteries included framework because Django provides built-in features for everything including Django Admin Interface, default database – SQLlite3, etc. Today we will create joke app in django. In this article we will learn how to fetch data from django models and give it feature like autocomplete. We will be using jquery for autocompletion. Installation : Ubuntu pip3 install django First we will create new project django-admin startproject AutoC cd AutoC Then we will create new app python3 manage.py startapp main Then add the app name in settings.py inside the INSTALLED_APPS models.py Python3 from django.db import models # Create your models here.class Language(models.Model): name = models.CharField(max_length=20) def __str__(self): return f"{self.name}" Then to create database table we have to makemigrations python3 manage.py makemigrations python3 manage.py migrate I have added this languages in the table. Python3 from django.shortcuts import renderfrom .models import Language # Create your views here.def home(request): languages = Language.objects.all() return render(request,'main/index.html',{"languages":languages}) Then create new directory inside app template inside that create another directory main Then create new file index.html HTML <!DOCTYPE html><html><head> <title>AutoComplete</title> <script src= "https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.js"> </script> <script src= "https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.16/jquery-ui.js"> </script> <link href= "http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.16/themes/ui-lightness/jquery-ui.css" rel="stylesheet" type="text/css" /> </head><body> <h1>Welcome to GFG</h1> <input type="text" id="tags"> <script> $( function() { var availableTags = [ {% for language in languages %} "{{language.name}}", {% endfor %} ]; $( "#tags" ).autocomplete({ source: availableTags }); } ); </script></body></html> Then create new file urls.py Python3 from django.urls import pathfrom .views import * urlpatterns = [ path('', home,name="home")] Then add the app/urls inside our project/urls AutoC/urls.py Python3 from django.contrib import adminfrom django.urls import path,include urlpatterns = [ path('admin/', admin.site.urls), path('',include("main.urls"))] Then to run this app Windows python manage.py runserver Ubuntu python3 manage.py runserver Python Django Python Framework Python Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Read a file line by line in Python How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe Remove elements from a JavaScript Array Installation of Node.js on Linux Convert a string to an integer in JavaScript How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 26025, "s": 25997, "text": "\n16 Feb, 2021" }, { "code": null, "e": 26349, "s": 26025, "text": "Django is a high-level Python based Web Framework that allows rapid development and clean, pragmatic design. It is also called batteries included framework because Django provides built-in features for everything including Django Admin Interface, default database – SQLlite3, etc. Today we will create joke app in django." }, { "code": null, "e": 26499, "s": 26349, "text": "In this article we will learn how to fetch data from django models and give it feature like autocomplete. We will be using jquery for autocompletion." }, { "code": null, "e": 26514, "s": 26499, "text": "Installation :" }, { "code": null, "e": 26521, "s": 26514, "text": "Ubuntu" }, { "code": null, "e": 26541, "s": 26521, "text": "pip3 install django" }, { "code": null, "e": 26574, "s": 26541, "text": "First we will create new project" }, { "code": null, "e": 26606, "s": 26574, "text": "django-admin startproject AutoC" }, { "code": null, "e": 26615, "s": 26606, "text": "cd AutoC" }, { "code": null, "e": 26643, "s": 26615, "text": "Then we will create new app" }, { "code": null, "e": 26675, "s": 26643, "text": "python3 manage.py startapp main" }, { "code": null, "e": 26738, "s": 26675, "text": "Then add the app name in settings.py inside the INSTALLED_APPS" }, { "code": null, "e": 26749, "s": 26738, "text": " models.py" }, { "code": null, "e": 26757, "s": 26749, "text": "Python3" }, { "code": "from django.db import models # Create your models here.class Language(models.Model): name = models.CharField(max_length=20) def __str__(self): return f\"{self.name}\"", "e": 26938, "s": 26757, "text": null }, { "code": null, "e": 26994, "s": 26938, "text": "Then to create database table we have to makemigrations" }, { "code": null, "e": 27027, "s": 26994, "text": "python3 manage.py makemigrations" }, { "code": null, "e": 27053, "s": 27027, "text": "python3 manage.py migrate" }, { "code": null, "e": 27095, "s": 27053, "text": "I have added this languages in the table." }, { "code": null, "e": 27103, "s": 27095, "text": "Python3" }, { "code": "from django.shortcuts import renderfrom .models import Language # Create your views here.def home(request): languages = Language.objects.all() return render(request,'main/index.html',{\"languages\":languages})", "e": 27318, "s": 27103, "text": null }, { "code": null, "e": 27407, "s": 27318, "text": "Then create new directory inside app template inside that create another directory main" }, { "code": null, "e": 27439, "s": 27407, "text": "Then create new file index.html" }, { "code": null, "e": 27444, "s": 27439, "text": "HTML" }, { "code": "<!DOCTYPE html><html><head> <title>AutoComplete</title> <script src= \"https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.js\"> </script> <script src= \"https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.16/jquery-ui.js\"> </script> <link href= \"http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.16/themes/ui-lightness/jquery-ui.css\" rel=\"stylesheet\" type=\"text/css\" /> </head><body> <h1>Welcome to GFG</h1> <input type=\"text\" id=\"tags\"> <script> $( function() { var availableTags = [ {% for language in languages %} \"{{language.name}}\", {% endfor %} ]; $( \"#tags\" ).autocomplete({ source: availableTags }); } ); </script></body></html>", "e": 28183, "s": 27444, "text": null }, { "code": null, "e": 28212, "s": 28183, "text": "Then create new file urls.py" }, { "code": null, "e": 28220, "s": 28212, "text": "Python3" }, { "code": "from django.urls import pathfrom .views import * urlpatterns = [ path('', home,name=\"home\")]", "e": 28318, "s": 28220, "text": null }, { "code": null, "e": 28364, "s": 28318, "text": "Then add the app/urls inside our project/urls" }, { "code": null, "e": 28378, "s": 28364, "text": "AutoC/urls.py" }, { "code": null, "e": 28386, "s": 28378, "text": "Python3" }, { "code": "from django.contrib import adminfrom django.urls import path,include urlpatterns = [ path('admin/', admin.site.urls), path('',include(\"main.urls\"))]", "e": 28542, "s": 28386, "text": null }, { "code": null, "e": 28564, "s": 28542, "text": "Then to run this app " }, { "code": null, "e": 28572, "s": 28564, "text": "Windows" }, { "code": null, "e": 28599, "s": 28572, "text": "python manage.py runserver" }, { "code": null, "e": 28606, "s": 28599, "text": "Ubuntu" }, { "code": null, "e": 28634, "s": 28606, "text": "python3 manage.py runserver" }, { "code": null, "e": 28648, "s": 28634, "text": "Python Django" }, { "code": null, "e": 28665, "s": 28648, "text": "Python Framework" }, { "code": null, "e": 28672, "s": 28665, "text": "Python" }, { "code": null, "e": 28689, "s": 28672, "text": "Web Technologies" }, { "code": null, "e": 28787, "s": 28689, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28805, "s": 28787, "text": "Python Dictionary" }, { "code": null, "e": 28840, "s": 28805, "text": "Read a file line by line in Python" }, { "code": null, "e": 28872, "s": 28840, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 28894, "s": 28872, "text": "Enumerate() in Python" }, { "code": null, "e": 28936, "s": 28894, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 28976, "s": 28936, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 29009, "s": 28976, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 29054, "s": 29009, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 29097, "s": 29054, "text": "How to fetch data from an API in ReactJS ?" } ]
Maximum number of edges that N-vertex graph can have such that graph is Triangle free | Mantel's Theorem - GeeksforGeeks
23 Apr, 2021 Given a number N which is the number of nodes in a graph, the task is to find the maximum number of edges that N-vertex graph can have such that graph is triangle-free (which means there should not be any three edges A, B, C in the graph such that A is connected to B, B is connected to C and C is connected to A). The graph cannot contain a self-loop or multi edges. Examples: Input: N = 4 Output: 4 Explanation: Input: N = 3 Output: 2 Explanation: If there are three edges in 3-vertex graph then it will have a triangle. Approach: This Problem can be solved using Mantel’s Theorem which states that the maximum number of edges in a graph without containing any triangle is floor(n2/4). In other words, one must delete nearly half of the edges to obtain a triangle-free graph. How Mantel’s Theorem Works ? For any Graph, such that the graph is Triangle free then for any vertex Z can only be connected to any of one vertex from x and y, i.e. For any edge connected between x and y, d(x) + d(y) ≤ N, where d(x) and d(y) is the degree of the vertex x and y. Then, the Degree of all vertex – By Cauchy-Schwarz inequality – Therefore, 4m2 / n ≤ mn, which implies m ≤ n2 / 4 Below is the implementation of above approach: C++ Java C# Python3 Javascript // C++ implementation to find the maximum// number of edges for triangle free graph #include <bits/stdc++.h>using namespace std; // Function to find the maximum number of// edges in a N-vertex graph.int solve(int n){ // According to the Mantel's theorem // the maximum number of edges will be // floor of [(n^2)/4] int ans = (n * n / 4); return ans;} // Driver Functionint main(){ int n = 10; cout << solve(n) << endl; return 0;} // Java implementation to find the maximum// number of edges for triangle free graphclass GFG{ // Function to find the maximum number of // edges in a N-vertex graph. public static int solve(int n) { // According to the Mantel's theorem // the maximum number of edges will be // floor of [(n^2)/4] int ans = (n * n / 4); return ans; } // Driver code public static void main(String args[]) { int n = 10; System.out.println(solve(n)); }} // This code is contributed by divyamohan123 // C# implementation to find the maximum// number of edges for triangle free graphusing System; class GFG{ // Function to find the maximum number of // edges in a N-vertex graph. public static int solve(int n) { // According to the Mantel's theorem // the maximum number of edges will be // floor of [(n^2)/4] int ans = (n * n / 4); return ans; } // Driver code public static void Main() { int n = 10; Console.WriteLine(solve(n)); }} // This code is contributed by AnkitRai01 # Python3 implementation to find the maximum# number of edges for triangle free graph # Function to find the maximum number of# edges in a N-vertex graph.def solve(n): # According to the Mantel's theorem # the maximum number of edges will be # floor of [(n^2)/4] ans = (n * n // 4) return ans # Driver Functionif __name__ == '__main__': n = 10 print(solve(n)) # This code is contributed by mohit kumar 29 <script> // Javascript implementation to find the maximum// number of edges for triangle free graph // Function to find the maximum number of// edges in a N-vertex graph.function solve(n){ // According to the Mantel's theorem // the maximum number of edges will be // floor of [(n^2)/4] var ans = (n * n / 4); return ans;} // Driver codevar n = 10; document.write(solve(n)); // This code is contributed by aashish1995 </script> 25 Time Complexity: O(1) mohit kumar 29 divyamohan123 ankthon aashish1995 Technical Scripter 2019 Graph Mathematical Technical Scripter Mathematical Graph Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Longest Path in a Directed Acyclic Graph Best First Search (Informed Search) Graph Coloring | Set 2 (Greedy Algorithm) Maximum Bipartite Matching Graph Coloring | Set 1 (Introduction and Applications) Program for Fibonacci numbers Write a program to print all permutations of a given string C++ Data Types Set in C++ Standard Template Library (STL) Coin Change | DP-7
[ { "code": null, "e": 26311, "s": 26283, "text": "\n23 Apr, 2021" }, { "code": null, "e": 26679, "s": 26311, "text": "Given a number N which is the number of nodes in a graph, the task is to find the maximum number of edges that N-vertex graph can have such that graph is triangle-free (which means there should not be any three edges A, B, C in the graph such that A is connected to B, B is connected to C and C is connected to A). The graph cannot contain a self-loop or multi edges." }, { "code": null, "e": 26690, "s": 26679, "text": "Examples: " }, { "code": null, "e": 26728, "s": 26690, "text": "Input: N = 4 Output: 4 Explanation: " }, { "code": null, "e": 26839, "s": 26728, "text": "Input: N = 3 Output: 2 Explanation: If there are three edges in 3-vertex graph then it will have a triangle. " }, { "code": null, "e": 27094, "s": 26839, "text": "Approach: This Problem can be solved using Mantel’s Theorem which states that the maximum number of edges in a graph without containing any triangle is floor(n2/4). In other words, one must delete nearly half of the edges to obtain a triangle-free graph." }, { "code": null, "e": 27375, "s": 27094, "text": "How Mantel’s Theorem Works ? For any Graph, such that the graph is Triangle free then for any vertex Z can only be connected to any of one vertex from x and y, i.e. For any edge connected between x and y, d(x) + d(y) ≤ N, where d(x) and d(y) is the degree of the vertex x and y. " }, { "code": null, "e": 27410, "s": 27375, "text": "Then, the Degree of all vertex – " }, { "code": null, "e": 27443, "s": 27410, "text": "By Cauchy-Schwarz inequality – " }, { "code": null, "e": 27494, "s": 27443, "text": "Therefore, 4m2 / n ≤ mn, which implies m ≤ n2 / 4 " }, { "code": null, "e": 27542, "s": 27494, "text": "Below is the implementation of above approach: " }, { "code": null, "e": 27546, "s": 27542, "text": "C++" }, { "code": null, "e": 27551, "s": 27546, "text": "Java" }, { "code": null, "e": 27554, "s": 27551, "text": "C#" }, { "code": null, "e": 27562, "s": 27554, "text": "Python3" }, { "code": null, "e": 27573, "s": 27562, "text": "Javascript" }, { "code": "// C++ implementation to find the maximum// number of edges for triangle free graph #include <bits/stdc++.h>using namespace std; // Function to find the maximum number of// edges in a N-vertex graph.int solve(int n){ // According to the Mantel's theorem // the maximum number of edges will be // floor of [(n^2)/4] int ans = (n * n / 4); return ans;} // Driver Functionint main(){ int n = 10; cout << solve(n) << endl; return 0;}", "e": 28028, "s": 27573, "text": null }, { "code": "// Java implementation to find the maximum// number of edges for triangle free graphclass GFG{ // Function to find the maximum number of // edges in a N-vertex graph. public static int solve(int n) { // According to the Mantel's theorem // the maximum number of edges will be // floor of [(n^2)/4] int ans = (n * n / 4); return ans; } // Driver code public static void main(String args[]) { int n = 10; System.out.println(solve(n)); }} // This code is contributed by divyamohan123", "e": 28597, "s": 28028, "text": null }, { "code": "// C# implementation to find the maximum// number of edges for triangle free graphusing System; class GFG{ // Function to find the maximum number of // edges in a N-vertex graph. public static int solve(int n) { // According to the Mantel's theorem // the maximum number of edges will be // floor of [(n^2)/4] int ans = (n * n / 4); return ans; } // Driver code public static void Main() { int n = 10; Console.WriteLine(solve(n)); }} // This code is contributed by AnkitRai01", "e": 29161, "s": 28597, "text": null }, { "code": "# Python3 implementation to find the maximum# number of edges for triangle free graph # Function to find the maximum number of# edges in a N-vertex graph.def solve(n): # According to the Mantel's theorem # the maximum number of edges will be # floor of [(n^2)/4] ans = (n * n // 4) return ans # Driver Functionif __name__ == '__main__': n = 10 print(solve(n)) # This code is contributed by mohit kumar 29", "e": 29593, "s": 29161, "text": null }, { "code": "<script> // Javascript implementation to find the maximum// number of edges for triangle free graph // Function to find the maximum number of// edges in a N-vertex graph.function solve(n){ // According to the Mantel's theorem // the maximum number of edges will be // floor of [(n^2)/4] var ans = (n * n / 4); return ans;} // Driver codevar n = 10; document.write(solve(n)); // This code is contributed by aashish1995 </script>", "e": 30042, "s": 29593, "text": null }, { "code": null, "e": 30045, "s": 30042, "text": "25" }, { "code": null, "e": 30070, "s": 30047, "text": "Time Complexity: O(1) " }, { "code": null, "e": 30085, "s": 30070, "text": "mohit kumar 29" }, { "code": null, "e": 30099, "s": 30085, "text": "divyamohan123" }, { "code": null, "e": 30107, "s": 30099, "text": "ankthon" }, { "code": null, "e": 30119, "s": 30107, "text": "aashish1995" }, { "code": null, "e": 30143, "s": 30119, "text": "Technical Scripter 2019" }, { "code": null, "e": 30149, "s": 30143, "text": "Graph" }, { "code": null, "e": 30162, "s": 30149, "text": "Mathematical" }, { "code": null, "e": 30181, "s": 30162, "text": "Technical Scripter" }, { "code": null, "e": 30194, "s": 30181, "text": "Mathematical" }, { "code": null, "e": 30200, "s": 30194, "text": "Graph" }, { "code": null, "e": 30298, "s": 30200, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30339, "s": 30298, "text": "Longest Path in a Directed Acyclic Graph" }, { "code": null, "e": 30375, "s": 30339, "text": "Best First Search (Informed Search)" }, { "code": null, "e": 30417, "s": 30375, "text": "Graph Coloring | Set 2 (Greedy Algorithm)" }, { "code": null, "e": 30444, "s": 30417, "text": "Maximum Bipartite Matching" }, { "code": null, "e": 30499, "s": 30444, "text": "Graph Coloring | Set 1 (Introduction and Applications)" }, { "code": null, "e": 30529, "s": 30499, "text": "Program for Fibonacci numbers" }, { "code": null, "e": 30589, "s": 30529, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 30604, "s": 30589, "text": "C++ Data Types" }, { "code": null, "e": 30647, "s": 30604, "text": "Set in C++ Standard Template Library (STL)" } ]
GATE | GATE CS 2013 | Question 47 - GeeksforGeeks
28 Jun, 2021 (A) A(B) B(C) C(D) DAnswer: (A) (D)Explanation: Given statement is : ¬ ∃ x ( ∀y(α) ∧ ∀z(β) ) where ¬ is a negation operator, ∃ is Existential Quantifier with the meaning of "there Exists", and ∀ is a Universal Quantifier with the meaning " for all " , and α, β can be treated as predicates. here we can apply some of the standard results of Propositional and 1st order logic on the given statement, which are as follows : [ Result 1 : ¬(∀x P(x)) <=> ∃ x¬P(x), i.e. negation of "for all" gives "there exists" and negation also gets applied to scope of quantifier, which is P(x) here. And also negation of "there exists" gives "for all", and negation also gets applied to scope of quantifier ] [ Result 2 : ¬ ( A ∧ B ) = ( ¬A ∨ ¬B ) ] [ Result 3 : ¬P ∨ Q <=> P -> Q ] [ Result 4 : If P ->Q, then by Result of Contrapositive, ¬Q -> ¬P ] Now we need to use these results as shown below: ¬ ∃ x ( ∀y(α) ∧ ∀z(β) ) [ Given ] => ∀ x (¬∀y(α) ∨ ¬∀z(β) ) [ after applying Result 1 & Result 2 ] => ∀ x ( ∀y(α) -> ¬∀z(β) ) [after applying Result 3 ] => ∀ x ( ∀y(α) -> ∃z(¬β) ) [after applying Result 1] which is same as the statement C. Hence the Given Statement is logically Equivalent to the statement C. Now, we can also prove that given statement is logically equivalent to the statement in option B. Let's see how ! The above derived statement is : ∀ x ( ∀y(α) -> ∃z(¬β) ) Now this statement can be written as (or equivalent to) : => ∀ x ( ∀z(β) -> ∃y(¬α) ) [after applying Result 4 ] And this statement is same as statement B. Hence the Given statement is also logically equivalent to the statement B. So, we can conclude that the Given statement is NOT logically equivalent to the statements A and D. Hence, the correct answer is Option A and Option D. But in GATE 2013, markswere given to all for this question.Quiz of this Question GATE-CS-2013 GATE-GATE CS 2013 GATE Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. GATE | Gate IT 2007 | Question 25 GATE | GATE-CS-2001 | Question 39 GATE | GATE-CS-2000 | Question 41 GATE | GATE-CS-2005 | Question 6 GATE | GATE MOCK 2017 | Question 21 GATE | GATE MOCK 2017 | Question 24 GATE | GATE-CS-2006 | Question 47 GATE | Gate IT 2008 | Question 43 GATE | GATE-CS-2009 | Question 38 GATE | GATE-CS-2003 | Question 90
[ { "code": null, "e": 25657, "s": 25629, "text": "\n28 Jun, 2021" }, { "code": null, "e": 25707, "s": 25657, "text": "(A) A(B) B(C) C(D) DAnswer: (A) (D)Explanation: " }, { "code": null, "e": 25728, "s": 25707, "text": "Given statement is :" }, { "code": null, "e": 25752, "s": 25728, "text": "¬ ∃ x ( ∀y(α) ∧ ∀z(β) )" }, { "code": null, "e": 26517, "s": 25752, "text": "where ¬ is a negation operator, ∃ is Existential Quantifier with the \nmeaning of \"there Exists\", and ∀ is a Universal Quantifier \nwith the meaning \" for all \" , and α, β can be treated as predicates.\n\nhere we can apply some of the standard \nresults of Propositional and 1st order logic on the given statement, \nwhich are as follows :\n\n[ Result 1 : ¬(∀x P(x)) <=> ∃ x¬P(x), i.e. negation \nof \"for all\" gives \"there exists\" and negation also gets applied to scope of \nquantifier, which is P(x) here. And also negation of \"there exists\" gives \"for all\", \nand negation also gets applied to scope of quantifier ]\n\n[ Result 2 : ¬ ( A ∧ B ) = ( ¬A ∨ ¬B ) ]\n\n[ Result 3 : ¬P ∨ Q <=> P -> Q ]\n\n[ Result 4 : If P ->Q, then by Result of Contrapositive, ¬Q -> ¬P ]\n\n" }, { "code": null, "e": 26566, "s": 26517, "text": "Now we need to use these results as shown below:" }, { "code": null, "e": 27439, "s": 26566, "text": "\n \n\n¬ ∃ x ( ∀y(α) ∧ ∀z(β) ) [ Given ]\n\n=> ∀ x (¬∀y(α) ∨ ¬∀z(β) ) [ after applying Result 1 & Result 2 ]\n\n=> ∀ x ( ∀y(α) -> ¬∀z(β) ) [after applying Result 3 ]\n\n=> ∀ x ( ∀y(α) -> ∃z(¬β) ) [after applying Result 1]\n\nwhich is same as the statement C. \n\nHence the Given Statement is logically Equivalent\nto the statement C.\n\nNow, we can also prove that given statement is logically equivalent to the statement\n in option B.\n\nLet's see how !\n\nThe above derived statement is :\n\n∀ x ( ∀y(α) -> ∃z(¬β) )\n\nNow this statement can be written as (or equivalent to) :\n\n=> ∀ x ( ∀z(β) -> ∃y(¬α) ) [after applying Result 4 ]\n\nAnd this statement is same as statement B. \nHence the Given statement is also logically equivalent \nto the statement B.\n\nSo, we can conclude that the Given statement is NOT logically equivalent to the \nstatements A and D.\n" }, { "code": null, "e": 27572, "s": 27439, "text": "Hence, the correct answer is Option A and Option D. But in GATE 2013, markswere given to all for this question.Quiz of this Question" }, { "code": null, "e": 27585, "s": 27572, "text": "GATE-CS-2013" }, { "code": null, "e": 27603, "s": 27585, "text": "GATE-GATE CS 2013" }, { "code": null, "e": 27608, "s": 27603, "text": "GATE" }, { "code": null, "e": 27706, "s": 27608, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27740, "s": 27706, "text": "GATE | Gate IT 2007 | Question 25" }, { "code": null, "e": 27774, "s": 27740, "text": "GATE | GATE-CS-2001 | Question 39" }, { "code": null, "e": 27808, "s": 27774, "text": "GATE | GATE-CS-2000 | Question 41" }, { "code": null, "e": 27841, "s": 27808, "text": "GATE | GATE-CS-2005 | Question 6" }, { "code": null, "e": 27877, "s": 27841, "text": "GATE | GATE MOCK 2017 | Question 21" }, { "code": null, "e": 27913, "s": 27877, "text": "GATE | GATE MOCK 2017 | Question 24" }, { "code": null, "e": 27947, "s": 27913, "text": "GATE | GATE-CS-2006 | Question 47" }, { "code": null, "e": 27981, "s": 27947, "text": "GATE | Gate IT 2008 | Question 43" }, { "code": null, "e": 28015, "s": 27981, "text": "GATE | GATE-CS-2009 | Question 38" } ]
Full Subtractor in Digital Logic - GeeksforGeeks
25 Nov, 2019 A full subtractor is a combinational circuit that performs subtraction of two bits, one is minuend and other is subtrahend, taking into account borrow of the previous adjacent lower minuend bit. This circuit has three inputs and two outputs. The three inputs A, B and Bin, denote the minuend, subtrahend, and previous borrow, respectively. The two outputs, D and Bout represent the difference and output borrow, respectively. Truth Table – From above table we can draw the K-Map as shown for “difference” and “borrow”. Logical expression for difference – D = A’B’Bin + A’BBin’ + AB’Bin’ + ABBin = Bin(A’B’ + AB) + Bin’(AB’ + A’B) = Bin( A XNOR B) + Bin’(A XOR B) = Bin (A XOR B)’ + Bin’(A XOR B) = Bin XOR (A XOR B) = (A XOR B) XOR Bin Logical expression for borrow – Bout = A’B’Bin + A’BBin’ + A’BBin + ABBin = A’B’Bin +A’BBin’ + A’BBin + A’BBin + A’BBin + ABBin = A’Bin(B + B’) + A’B(Bin + Bin’) + BBin(A + A’) = A’Bin + A’B + BBin OR Bout = A’B’Bin + A’BBin’ + A’BBin + ABBin = Bin(AB + A’B’) + A’B(Bin + Bin’) = Bin( A XNOR B) + A’B = Bin (A XOR B)’ + A’B Logic Circuit for Full Subtractor – Implementation of Full Subtractor using Half Subtractors –2 Half Subtractors and an OR gate is required to implement a Full Subtractor. Reference – Full Subtractor – Wikipedia This article is contributed by Harshita Pandey. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.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. Digital Electronics & Logic Design GATE CS Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. IEEE Standard 754 Floating Point Numbers 4-bit binary Adder-Subtractor Difference between Unipolar, Polar and Bipolar Line Coding Schemes Difference between RAM and ROM Introduction to memory and memory units Layers of OSI Model ACID Properties in DBMS TCP/IP Model Types of Operating Systems Normal Forms in DBMS
[ { "code": null, "e": 28079, "s": 28051, "text": "\n25 Nov, 2019" }, { "code": null, "e": 28505, "s": 28079, "text": "A full subtractor is a combinational circuit that performs subtraction of two bits, one is minuend and other is subtrahend, taking into account borrow of the previous adjacent lower minuend bit. This circuit has three inputs and two outputs. The three inputs A, B and Bin, denote the minuend, subtrahend, and previous borrow, respectively. The two outputs, D and Bout represent the difference and output borrow, respectively." }, { "code": null, "e": 28519, "s": 28505, "text": "Truth Table –" }, { "code": null, "e": 28598, "s": 28519, "text": "From above table we can draw the K-Map as shown for “difference” and “borrow”." }, { "code": null, "e": 28634, "s": 28598, "text": "Logical expression for difference –" }, { "code": null, "e": 28841, "s": 28634, "text": "D = A’B’Bin + A’BBin’ + AB’Bin’ + ABBin\n = Bin(A’B’ + AB) + Bin’(AB’ + A’B)\n = Bin( A XNOR B) + Bin’(A XOR B)\n = Bin (A XOR B)’ + Bin’(A XOR B)\n = Bin XOR (A XOR B)\n = (A XOR B) XOR Bin\n" }, { "code": null, "e": 28873, "s": 28841, "text": "Logical expression for borrow –" }, { "code": null, "e": 29210, "s": 28873, "text": "Bout = A’B’Bin + A’BBin’ + A’BBin + ABBin \n = A’B’Bin +A’BBin’ + A’BBin + A’BBin + A’BBin + ABBin\n = A’Bin(B + B’) + A’B(Bin + Bin’) + BBin(A + A’)\n = A’Bin + A’B + BBin\n\nOR\n\nBout = A’B’Bin + A’BBin’ + A’BBin + ABBin \n = Bin(AB + A’B’) + A’B(Bin + Bin’)\n = Bin( A XNOR B) + A’B\n = Bin (A XOR B)’ + A’B\n" }, { "code": null, "e": 29246, "s": 29210, "text": "Logic Circuit for Full Subtractor –" }, { "code": null, "e": 29382, "s": 29246, "text": "Implementation of Full Subtractor using Half Subtractors –2 Half Subtractors and an OR gate is required to implement a Full Subtractor." }, { "code": null, "e": 29422, "s": 29382, "text": "Reference – Full Subtractor – Wikipedia" }, { "code": null, "e": 29725, "s": 29422, "text": "This article is contributed by Harshita Pandey. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.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": 29850, "s": 29725, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 29885, "s": 29850, "text": "Digital Electronics & Logic Design" }, { "code": null, "e": 29893, "s": 29885, "text": "GATE CS" }, { "code": null, "e": 29991, "s": 29893, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30032, "s": 29991, "text": "IEEE Standard 754 Floating Point Numbers" }, { "code": null, "e": 30062, "s": 30032, "text": "4-bit binary Adder-Subtractor" }, { "code": null, "e": 30129, "s": 30062, "text": "Difference between Unipolar, Polar and Bipolar Line Coding Schemes" }, { "code": null, "e": 30160, "s": 30129, "text": "Difference between RAM and ROM" }, { "code": null, "e": 30200, "s": 30160, "text": "Introduction to memory and memory units" }, { "code": null, "e": 30220, "s": 30200, "text": "Layers of OSI Model" }, { "code": null, "e": 30244, "s": 30220, "text": "ACID Properties in DBMS" }, { "code": null, "e": 30257, "s": 30244, "text": "TCP/IP Model" }, { "code": null, "e": 30284, "s": 30257, "text": "Types of Operating Systems" } ]
How div class and id is useful in HTML ? - GeeksforGeeks
14 May, 2020 In this article, we will discuss how the id, div, and class is useful in HTML. Id, Div, and class are important concepts of structuring the HTML page. let’s discuss one by one. Id attributes in HTML Div tag in HTML Class attributes in HTML Now, consider a use case where you want to implement a table of contents of any book and want to go directly to the topics which you want to read. In this case, you can implement the Id attribute in HTML5 and can link all the topics with a table of contents. Now, you can directly click and can directly go to the topics which you want to read. <!DOCTYPE html><html> <head> <title>Id Div and Class</title></head> <body> <div> <ul> <div> <strong>Table of contents</strong> <li> <a href="#T1"> <strong> Example Topic-1 </strong> </a> </li> <li> <a href="#T2"> <strong> Example Topic-2 </strong> </a> </li> <li> <a href="#T3"> <strong> Example Topic-3 </strong> </a> </li> <li> <a href="#T4"> <strong> Example Topic-4 </strong> </a> </li> <li> <a href="#T5"> <strong> Example Topic-5 </strong> </a> </li> </div> </ul> <hr /> <div id="T1"> <ol> <li> <strong>Example Topic-1</strong> <br /> Example Heading 1 <p> Hi, This is an example of Example Heading 1. </p> </li> </ol> </div> <div id="T2"> <ol> <li> <strong>Example Topic-2</strong> <br /> Example Heading 2 <p> Hi, This is an example of Example Heading 2. </p> </li> </ol> </div> <div id="T3"> <ol> <li> <strong>Example Topic-3</strong> <br /> Example Heading 3 <p> Hi, This is an example of Example Heading 3. </p> </li> </ol> </div> <div id="T4"> <ol> <li> <strong>Example Topic-4</strong> <br /> Example Heading 4 <p> Hi, This is an example of Example Heading 4. </p> </li> </ol> </div> <div id="T5"> <ol> <li> <strong>Example Topic-5</strong> <br /> Example Heading 5 <p> Hi, This is an example of Example Heading 5. </p> </li> </ol> </div> </div></body> </html> You can verify the results by executing the above code. Now, let’s see the output with the page structure.Output: In the above output screen, you can directly see how Id and Div works, and also you can see that how Div is useful to structure your webpage. Now, here you will see how you can add more functionality to your webpage by using CSS with the help of Id and Div and class. <!DOCTYPE html><html> <head> <title>Id Div and Class</title> <style> #TOC { background-color: white; color: #009900; font-size: 30px; font-weight: bold; text-align: left; } .T1 { background-color: SILVER; color: #009900; font-weight: bold; } .T2 { background-color: DARKSALMON; color: #009900; font-weight: bold; } .T3 { background-color: NAVY; color: #009900; font-weight: bold; } .T4 { background-color: red; color: #009900; font-weight: bold; } .T5 { background-color: #daf7a6; color: #009900; font-weight: bold; } </style></head> <body> <div> <div> <ul> <div id="TOC"> <strong>Table of contents</strong> </div> <li> <a href="#T1"><strong> Example Topic-1</strong></a> </li> <li> <a href="#T2"><strong> Example Topic-2</strong></a> </li> <li> <a href="#T3"><strong> Example Topic-3</strong></a> </li> <li> <a href="#T4"><strong> Example Topic-4</strong></a> </li> <li> <a href="#T5"><strong> Example Topic-5</strong></a> </li> </ul> <hr /> <div class="T1"> <div id="T1"> <ol> <li> <strong> Example Topic-1</strong> <br /> Example Heading 1 <p> Hi, This is an example of Example Heading 1. </p> </li> </ol> </div> </div> <div class="T2"> <div id="T2"> <ol> <li> <strong>Example Topic-2</strong> <br /> Example Heading 2 <p> Hi, This is an example of Example Heading 2. </p> </li> </ol> </div> </div> <div class="T3"> <div id="T3"> <ol> <li> <strong>Example Topic-3</strong> <br /> Example Heading 3 <p> Hi, This is an example of Example Heading 3. </p> </li> </ol> </div> </div> <div class="T4"> <div id="T4"> <ol> <li> <strong>Example Topic-4</strong> <br /> Example Heading 4 <p> Hi, This is an example of Example Heading 4. </p> </li> </ol> </div> </div> <div class="T5"> <div id="T5"> <ol> <li> <strong>Example Topic-5</strong> <br /> Example Heading 5 <p> Hi, This is an example of Example Heading 5. </p> </li> </ol> </div> </div> </div> </div></body> </html> You can verify the results by executing the above code. Now, let’s see the output with the page structure.Output: In the above example, you can directly see that by using Id we can add individual functionality to different headings, and class is for common we can write the CSS script once and can use it anywhere and it is also useful for reusability. 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 CSS HTML Web Technologies Web technologies Questions HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to apply style to parent if it has child with CSS? Types of CSS (Cascading Style Sheet) How to position a div at the bottom of its container using CSS? Design a web page using HTML and CSS How to Upload Image into Database and Display it using PHP ? How to set the default value for an HTML <select> element ? Hide or show elements in HTML using display property How to set input type date in dd-mm-yyyy format using HTML ? How to Insert Form Data into Database using PHP ? REST API (Introduction)
[ { "code": null, "e": 25347, "s": 25319, "text": "\n14 May, 2020" }, { "code": null, "e": 25524, "s": 25347, "text": "In this article, we will discuss how the id, div, and class is useful in HTML. Id, Div, and class are important concepts of structuring the HTML page. let’s discuss one by one." }, { "code": null, "e": 25546, "s": 25524, "text": "Id attributes in HTML" }, { "code": null, "e": 25562, "s": 25546, "text": "Div tag in HTML" }, { "code": null, "e": 25587, "s": 25562, "text": "Class attributes in HTML" }, { "code": null, "e": 25932, "s": 25587, "text": "Now, consider a use case where you want to implement a table of contents of any book and want to go directly to the topics which you want to read. In this case, you can implement the Id attribute in HTML5 and can link all the topics with a table of contents. Now, you can directly click and can directly go to the topics which you want to read." }, { "code": "<!DOCTYPE html><html> <head> <title>Id Div and Class</title></head> <body> <div> <ul> <div> <strong>Table of contents</strong> <li> <a href=\"#T1\"> <strong> Example Topic-1 </strong> </a> </li> <li> <a href=\"#T2\"> <strong> Example Topic-2 </strong> </a> </li> <li> <a href=\"#T3\"> <strong> Example Topic-3 </strong> </a> </li> <li> <a href=\"#T4\"> <strong> Example Topic-4 </strong> </a> </li> <li> <a href=\"#T5\"> <strong> Example Topic-5 </strong> </a> </li> </div> </ul> <hr /> <div id=\"T1\"> <ol> <li> <strong>Example Topic-1</strong> <br /> Example Heading 1 <p> Hi, This is an example of Example Heading 1. </p> </li> </ol> </div> <div id=\"T2\"> <ol> <li> <strong>Example Topic-2</strong> <br /> Example Heading 2 <p> Hi, This is an example of Example Heading 2. </p> </li> </ol> </div> <div id=\"T3\"> <ol> <li> <strong>Example Topic-3</strong> <br /> Example Heading 3 <p> Hi, This is an example of Example Heading 3. </p> </li> </ol> </div> <div id=\"T4\"> <ol> <li> <strong>Example Topic-4</strong> <br /> Example Heading 4 <p> Hi, This is an example of Example Heading 4. </p> </li> </ol> </div> <div id=\"T5\"> <ol> <li> <strong>Example Topic-5</strong> <br /> Example Heading 5 <p> Hi, This is an example of Example Heading 5. </p> </li> </ol> </div> </div></body> </html>", "e": 29039, "s": 25932, "text": null }, { "code": null, "e": 29153, "s": 29039, "text": "You can verify the results by executing the above code. Now, let’s see the output with the page structure.Output:" }, { "code": null, "e": 29295, "s": 29153, "text": "In the above output screen, you can directly see how Id and Div works, and also you can see that how Div is useful to structure your webpage." }, { "code": null, "e": 29421, "s": 29295, "text": "Now, here you will see how you can add more functionality to your webpage by using CSS with the help of Id and Div and class." }, { "code": "<!DOCTYPE html><html> <head> <title>Id Div and Class</title> <style> #TOC { background-color: white; color: #009900; font-size: 30px; font-weight: bold; text-align: left; } .T1 { background-color: SILVER; color: #009900; font-weight: bold; } .T2 { background-color: DARKSALMON; color: #009900; font-weight: bold; } .T3 { background-color: NAVY; color: #009900; font-weight: bold; } .T4 { background-color: red; color: #009900; font-weight: bold; } .T5 { background-color: #daf7a6; color: #009900; font-weight: bold; } </style></head> <body> <div> <div> <ul> <div id=\"TOC\"> <strong>Table of contents</strong> </div> <li> <a href=\"#T1\"><strong> Example Topic-1</strong></a> </li> <li> <a href=\"#T2\"><strong> Example Topic-2</strong></a> </li> <li> <a href=\"#T3\"><strong> Example Topic-3</strong></a> </li> <li> <a href=\"#T4\"><strong> Example Topic-4</strong></a> </li> <li> <a href=\"#T5\"><strong> Example Topic-5</strong></a> </li> </ul> <hr /> <div class=\"T1\"> <div id=\"T1\"> <ol> <li> <strong> Example Topic-1</strong> <br /> Example Heading 1 <p> Hi, This is an example of Example Heading 1. </p> </li> </ol> </div> </div> <div class=\"T2\"> <div id=\"T2\"> <ol> <li> <strong>Example Topic-2</strong> <br /> Example Heading 2 <p> Hi, This is an example of Example Heading 2. </p> </li> </ol> </div> </div> <div class=\"T3\"> <div id=\"T3\"> <ol> <li> <strong>Example Topic-3</strong> <br /> Example Heading 3 <p> Hi, This is an example of Example Heading 3. </p> </li> </ol> </div> </div> <div class=\"T4\"> <div id=\"T4\"> <ol> <li> <strong>Example Topic-4</strong> <br /> Example Heading 4 <p> Hi, This is an example of Example Heading 4. </p> </li> </ol> </div> </div> <div class=\"T5\"> <div id=\"T5\"> <ol> <li> <strong>Example Topic-5</strong> <br /> Example Heading 5 <p> Hi, This is an example of Example Heading 5. </p> </li> </ol> </div> </div> </div> </div></body> </html>", "e": 33810, "s": 29421, "text": null }, { "code": null, "e": 33924, "s": 33810, "text": "You can verify the results by executing the above code. Now, let’s see the output with the page structure.Output:" }, { "code": null, "e": 34163, "s": 33924, "text": "In the above example, you can directly see that by using Id we can add individual functionality to different headings, and class is for common we can write the CSS script once and can use it anywhere and it is also useful for reusability." }, { "code": null, "e": 34300, "s": 34163, "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": 34309, "s": 34300, "text": "CSS-Misc" }, { "code": null, "e": 34319, "s": 34309, "text": "HTML-Misc" }, { "code": null, "e": 34323, "s": 34319, "text": "CSS" }, { "code": null, "e": 34328, "s": 34323, "text": "HTML" }, { "code": null, "e": 34345, "s": 34328, "text": "Web Technologies" }, { "code": null, "e": 34372, "s": 34345, "text": "Web technologies Questions" }, { "code": null, "e": 34377, "s": 34372, "text": "HTML" }, { "code": null, "e": 34475, "s": 34377, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 34530, "s": 34475, "text": "How to apply style to parent if it has child with CSS?" }, { "code": null, "e": 34567, "s": 34530, "text": "Types of CSS (Cascading Style Sheet)" }, { "code": null, "e": 34631, "s": 34567, "text": "How to position a div at the bottom of its container using CSS?" }, { "code": null, "e": 34668, "s": 34631, "text": "Design a web page using HTML and CSS" }, { "code": null, "e": 34729, "s": 34668, "text": "How to Upload Image into Database and Display it using PHP ?" }, { "code": null, "e": 34789, "s": 34729, "text": "How to set the default value for an HTML <select> element ?" }, { "code": null, "e": 34842, "s": 34789, "text": "Hide or show elements in HTML using display property" }, { "code": null, "e": 34903, "s": 34842, "text": "How to set input type date in dd-mm-yyyy format using HTML ?" }, { "code": null, "e": 34953, "s": 34903, "text": "How to Insert Form Data into Database using PHP ?" } ]
Perfect Binary Tree | Practice | GeeksforGeeks
Given a Binary Tree, write a function to check whether the given Binary Tree is a prefect Binary Tree or not. A Binary tree is Perfect Binary Tree in which all internal nodes have two children and all leaves are at same level. Example 1: Input: 7 / \ 4 9 Output: YES Explanation: As the root node 7 has two children and two leaf nodes 4 and 9 are at same level so it is a perfect binary tree. Example 2: Input: 7 / \ 3 8 / \ \ 2 5 10 / 1 Output: NO Your task: You don't need to read input or print anything. Your task is to complete the function isPerfect() which takes root node of the tree as input parameter and returns a boolean value.If the tree is a perfect binary tree return true other wise return false. Expected Time Complexity: O(N) Expected Auxiliary Space: O(N) Constraints: 1<=T<=10^5 1<=N<=10^5 1<=data of node<=10^5 0 bansallakshay0812 days ago int height(Node* root){ if(root==NULL) return 0; if(root->left==NULL&&root->right==NULL) return 1; return 1+max(height(root->left),height(root->right)); } int totalnode(Node* root){ if(root==NULL) return 0; if(root->left==NULL&&root->right==NULL) return 1; return 1+totalnode(root->left)+totalnode(root->right); } bool isPerfect(Node *root) { //code here int n=height(root); int nodes=totalnode(root); // cout<<n<<" "<<nodes<<endl; if(nodes==pow(2,n)-1) return true; return false; } 0 vrajeshmodi992 months ago int btHeight(Node*root){ if(!root)return 0; return 1+max(btHeight(root->left),btHeight(root->right)); } int btNodes(Node*root){ if(!root)return 0; int l= btNodes(root->left); int r = btNodes(root->right); return l+r+1; } bool isPerfect(Node *root) { int bth = btHeight(root); int btn = btNodes(root); //Note: Perfect-BT no. Nodes=2^H-1;(where H is height of tree) if(pow(2,bth)-1 == btn)return true; return false; } 0 feyza2 months ago class Solution{ public boolean isPerfect(Node root){ int d = depth(root); return is_Perfect(root,d,0); } public boolean is_Perfect(Node root, int d,int l){ if(root == null) return true; if(root.left ==null && root.right == null) return (d==l+1); if(root.left ==null || root.right == null) return false; return (is_Perfect(root.left, d,l+1) && is_Perfect(root.right,d,l+1)); } static int depth(Node node){ int d = 0; while(node != null){ d++; node = node.left; } return d; } } 0 dattatraygujar773 months ago Queue<Node>q=new LinkedList<>(); q.add(root); while(!q.isEmpty()) { int n=q.size(); for(int i=0;i<n;i++) { Node temp=q.poll(); if(temp.left!=null) q.add(temp.left); if(temp.right!=null) q.add(temp.right); } if(q.size()!=2*n && q.size()>0) return false; } return true; 0 19euee0683 months ago simple java solution class Solution{ class Bool{ boolean isPerfect=true; } public int getHeight( Node root , Bool flag){ if( flag.isPerfect==false || root == null ) return 0; int left=getHeight(root.left,flag); int right=getHeight(root.right,flag); if( left!=right ) flag.isPerfect = false; return 1+Math.max( left , right ); } public boolean isPerfect(Node root){ Bool bool = new Bool(); getHeight( root , bool ); return bool.isPerfect; } } 0 yadavkapil23363 months ago bool f(struct Node* root, int i,int v) { if(root==NULL) return(true); if(root->left==NULL && root->right!=NULL||root->left!=NULL && root->right==NULL) return(false); if(root->left==NULL && root->right==NULL) if(v!=i) return(false); bool x=f(root->left,i+1,v); bool y=f(root->right,i+1,v); if(x&&y) return(true); else return(false); } bool isPerfect(struct Node *root) { int v=0; struct Node* temp=root; while(temp->left!=NULL) { temp=temp->left; v++; } int i=0; return(f(root,i,v)); } 0 mayank20214 months ago C++bool isPerfect(Node *root) { int lvar=INT_MIN; level(root, 1, &lvar); return (lvar==-1)?0:1; } void level(Node *root, int l, int* lvar) { if(root && !root->left && !root->right ) { if(*lvar==INT_MIN) *lvar=l; else if (*lvar !=l ) { *lvar=-1; return; } } else if(root->left && root->right) { level(root->left, l+1, lvar ); level(root->right, l+1, lvar); } else { *lvar=-1; return; } } 0 sk77887754 months ago class Solution{ public boolean isPerfect(Node root){ //code here return (solve(root)==-1)?false:true; } int solve(Node root) { if(root.left==null && root.right==null) return 1; if(root.left==null || root.right==null) return -1; int c1=solve(root.left); int c2=solve(root.right); if(c1==-1 || c2==-1 || c1!=c2) return -1; else return 1+Math.max(c1,c2); } } 0 nekhatperveen4 months ago JAVA class Solution{ int depth = -1; public boolean isPerfect(Node root) { int count=1; boolean is_perfectBinary = getTreeStatus(root, count); return is_perfectBinary; } boolean getTreeStatus(Node root, int count) { int c= count; if(root==null) return true; else if(root.left==null && root.right!=null) return false; else if(root.left!=null && root.right==null) return false; else if(root.left==null && root.right==null) { if (depth == -1) { depth = c; return true; } else if(c != depth) { return false; } else return true; } else if(root.left!=null && root.right!=null) { c++; boolean leftTree = getTreeStatus(root.left, c); boolean rightTree = getTreeStatus(root.right, c); return (leftTree && rightTree); } return true; }} +1 deepuyadavze4 months ago // check if minimum height and maximum height are same then return true else return false class Solution { int mx(Node* root){ if(root == NULL){ return 0; } if(root->left==NULL && root->right==NULL){ return 1; } return max(mx(root->left), mx(root->right))+1; } int mn(Node* root){ if(root==NULL){ return 0; } if(root->left==NULL && root->right==NULL){ return 1; } return min(mn(root->left), mn(root->right))+1; } public: bool isPerfect(Node *root) { //code here // if max height and min height are same than tree is perfect int maxHeight=mx(root); int minHeight=mn(root); return maxHeight==minHeight; } }; 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 a Binary Tree, write a function to check whether the given Binary Tree is a prefect Binary Tree or not. A Binary tree is Perfect Binary Tree in which all internal nodes have two children and all leaves are at same level." }, { "code": null, "e": 476, "s": 465, "text": "Example 1:" }, { "code": null, "e": 661, "s": 476, "text": "Input: \n 7\n / \\\n 4 9\nOutput: YES\nExplanation: \nAs the root node 7 has two children and \ntwo leaf nodes 4 and 9 are at same level \nso it is a perfect binary tree.\n" }, { "code": null, "e": 672, "s": 661, "text": "Example 2:" }, { "code": null, "e": 821, "s": 672, "text": "Input: \n 7\n / \\\n 3 8\n / \\ \\\n 2 5 10\n /\n 1\nOutput: NO\n" }, { "code": null, "e": 832, "s": 821, "text": "Your task:" }, { "code": null, "e": 1085, "s": 832, "text": "You don't need to read input or print anything. Your task is to complete the function isPerfect() which takes root node of the tree as input parameter and returns a boolean value.If the tree is a perfect binary tree return true other wise return false." }, { "code": null, "e": 1147, "s": 1085, "text": "Expected Time Complexity: O(N)\nExpected Auxiliary Space: O(N)" }, { "code": null, "e": 1204, "s": 1147, "text": "Constraints:\n1<=T<=10^5\n1<=N<=10^5\n1<=data of node<=10^5" }, { "code": null, "e": 1206, "s": 1204, "text": "0" }, { "code": null, "e": 1233, "s": 1206, "text": "bansallakshay0812 days ago" }, { "code": null, "e": 1803, "s": 1233, "text": "int height(Node* root){ if(root==NULL) return 0; if(root->left==NULL&&root->right==NULL) return 1; return 1+max(height(root->left),height(root->right)); } int totalnode(Node* root){ if(root==NULL) return 0; if(root->left==NULL&&root->right==NULL) return 1; return 1+totalnode(root->left)+totalnode(root->right); } bool isPerfect(Node *root) { //code here int n=height(root); int nodes=totalnode(root); // cout<<n<<\" \"<<nodes<<endl; if(nodes==pow(2,n)-1) return true; return false; }" }, { "code": null, "e": 1805, "s": 1803, "text": "0" }, { "code": null, "e": 1831, "s": 1805, "text": "vrajeshmodi992 months ago" }, { "code": null, "e": 2357, "s": 1831, "text": "int btHeight(Node*root){ \n if(!root)return 0; \n return 1+max(btHeight(root->left),btHeight(root->right)); \n }\n \n int btNodes(Node*root){\n if(!root)return 0;\n int l= btNodes(root->left);\n int r = btNodes(root->right);\n return l+r+1; \n }\n bool isPerfect(Node *root)\n {\n int bth = btHeight(root);\n int btn = btNodes(root);\n//Note: Perfect-BT no. Nodes=2^H-1;(where H is height of tree)\n if(pow(2,bth)-1 == btn)return true;\n return false;\n }" }, { "code": null, "e": 2359, "s": 2357, "text": "0" }, { "code": null, "e": 2377, "s": 2359, "text": "feyza2 months ago" }, { "code": null, "e": 3032, "s": 2377, "text": "class Solution{\n public boolean isPerfect(Node root){\n int d = depth(root);\n return is_Perfect(root,d,0); \n }\n \n public boolean is_Perfect(Node root, int d,int l){\n if(root == null) return true;\n \n if(root.left ==null && root.right == null) return (d==l+1);\n if(root.left ==null || root.right == null) return false;\n \n return (is_Perfect(root.left, d,l+1) && is_Perfect(root.right,d,l+1)); \n \n }\n \n static int depth(Node node){\n int d = 0;\n while(node != null){\n d++;\n node = node.left;\n }\n return d;\n }\n}" }, { "code": null, "e": 3034, "s": 3032, "text": "0" }, { "code": null, "e": 3063, "s": 3034, "text": "dattatraygujar773 months ago" }, { "code": null, "e": 3466, "s": 3063, "text": " Queue<Node>q=new LinkedList<>();\n q.add(root);\n while(!q.isEmpty())\n {\n int n=q.size();\n for(int i=0;i<n;i++)\n {\n Node temp=q.poll();\n if(temp.left!=null) q.add(temp.left);\n if(temp.right!=null) q.add(temp.right);\n }\n if(q.size()!=2*n && q.size()>0) return false;\n }\n return true;" }, { "code": null, "e": 3468, "s": 3466, "text": "0" }, { "code": null, "e": 3490, "s": 3468, "text": "19euee0683 months ago" }, { "code": null, "e": 3511, "s": 3490, "text": "simple java solution" }, { "code": null, "e": 4089, "s": 3513, "text": "class Solution{\n class Bool{\n boolean isPerfect=true;\n }\n public int getHeight( Node root , \n \t\t\t\t\t Bool flag){\n if( flag.isPerfect==false || \n \troot == null ) return 0;\n \n int left=getHeight(root.left,flag);\n int right=getHeight(root.right,flag);\n \n if( left!=right ) \n \tflag.isPerfect = false;\n \n return 1+Math.max( left , right );\n }\n public boolean isPerfect(Node root){\n Bool bool = new Bool();\n getHeight( root , bool );\n return bool.isPerfect;\n }\n}" }, { "code": null, "e": 4091, "s": 4089, "text": "0" }, { "code": null, "e": 4118, "s": 4091, "text": "yadavkapil23363 months ago" }, { "code": null, "e": 4537, "s": 4118, "text": " bool f(struct Node* root, int i,int v) { if(root==NULL) return(true); if(root->left==NULL && root->right!=NULL||root->left!=NULL && root->right==NULL) return(false); if(root->left==NULL && root->right==NULL) if(v!=i) return(false); bool x=f(root->left,i+1,v); bool y=f(root->right,i+1,v); if(x&&y) return(true); else return(false); }" }, { "code": null, "e": 4781, "s": 4537, "text": " bool isPerfect(struct Node *root) { int v=0; struct Node* temp=root; while(temp->left!=NULL) { temp=temp->left; v++; } int i=0; return(f(root,i,v)); }" }, { "code": null, "e": 4783, "s": 4781, "text": "0" }, { "code": null, "e": 4806, "s": 4783, "text": "mayank20214 months ago" }, { "code": null, "e": 5445, "s": 4806, "text": "C++bool isPerfect(Node *root) { int lvar=INT_MIN; level(root, 1, &lvar); return (lvar==-1)?0:1; } void level(Node *root, int l, int* lvar) { if(root && !root->left && !root->right ) { if(*lvar==INT_MIN) *lvar=l; else if (*lvar !=l ) { *lvar=-1; return; } } else if(root->left && root->right) { level(root->left, l+1, lvar ); level(root->right, l+1, lvar); } else { *lvar=-1; return; } }" }, { "code": null, "e": 5447, "s": 5445, "text": "0" }, { "code": null, "e": 5469, "s": 5447, "text": "sk77887754 months ago" }, { "code": null, "e": 5958, "s": 5469, "text": "class Solution{\n public boolean isPerfect(Node root){\n //code here\n return (solve(root)==-1)?false:true;\n }\n \n int solve(Node root) {\n if(root.left==null && root.right==null)\n return 1;\n if(root.left==null || root.right==null)\n return -1;\n int c1=solve(root.left);\n int c2=solve(root.right);\n if(c1==-1 || c2==-1 || c1!=c2)\n return -1;\n else\n return 1+Math.max(c1,c2);\n }\n}" }, { "code": null, "e": 5960, "s": 5958, "text": "0" }, { "code": null, "e": 5986, "s": 5960, "text": "nekhatperveen4 months ago" }, { "code": null, "e": 5991, "s": 5986, "text": "JAVA" }, { "code": null, "e": 6063, "s": 5991, "text": "class Solution{ int depth = -1; public boolean isPerfect(Node root)" }, { "code": null, "e": 6732, "s": 6063, "text": " { int count=1; boolean is_perfectBinary = getTreeStatus(root, count); return is_perfectBinary; } boolean getTreeStatus(Node root, int count) { int c= count; if(root==null) return true; else if(root.left==null && root.right!=null) return false; else if(root.left!=null && root.right==null) return false; else if(root.left==null && root.right==null) { if (depth == -1) { depth = c; return true; } else if(c != depth) { return false; } else return true;" }, { "code": null, "e": 6995, "s": 6732, "text": " } else if(root.left!=null && root.right!=null) { c++; boolean leftTree = getTreeStatus(root.left, c); boolean rightTree = getTreeStatus(root.right, c); return (leftTree && rightTree);" }, { "code": null, "e": 7032, "s": 6995, "text": " } return true; }}" }, { "code": null, "e": 7035, "s": 7032, "text": "+1" }, { "code": null, "e": 7060, "s": 7035, "text": "deepuyadavze4 months ago" }, { "code": null, "e": 7877, "s": 7060, "text": "// check if minimum height and maximum height are same then return true else return false\n\nclass Solution\n{\n int mx(Node* root){\n if(root == NULL){\n return 0;\n }\n if(root->left==NULL && root->right==NULL){\n return 1;\n }\n return max(mx(root->left), mx(root->right))+1;\n }\n \n int mn(Node* root){\n if(root==NULL){\n return 0;\n }\n if(root->left==NULL && root->right==NULL){\n return 1;\n }\n return min(mn(root->left), mn(root->right))+1;\n }\npublic:\n bool isPerfect(Node *root)\n {\n //code here\n // if max height and min height are same than tree is perfect\n int maxHeight=mx(root);\n int minHeight=mn(root);\n \n return maxHeight==minHeight;\n }\n};" }, { "code": null, "e": 8023, "s": 7877, "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": 8059, "s": 8023, "text": " Login to access your submissions. " }, { "code": null, "e": 8069, "s": 8059, "text": "\nProblem\n" }, { "code": null, "e": 8079, "s": 8069, "text": "\nContest\n" }, { "code": null, "e": 8142, "s": 8079, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 8290, "s": 8142, "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": 8498, "s": 8290, "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": 8604, "s": 8498, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
ReactJS UI Ant Design Switch Component - GeeksforGeeks
21 May, 2021 Ant Design Library has this component pre-built, and it is very easy to integrate as well. Switch components are used to toggle the state of a single setting on or off. We can use the following approach in ReactJS to use the Ant Design Switch Component. Switch Methods: blur(): This method is used to remove the focus from the element. focus(): This method is used to get the focus on the element. Switch Props: autoFocus: It is used to get focus when the component is mounted. checked: It indicates whether the switch is checked or not. checkedChildren: It is the content that is to be shown when the state is checked. className: It is used to pass the class name for this switch. defaultChecked: It indicates whether to set the initial state or not. disabled: It is used to disable the switch. loading: It is used to show to loading state of the switch. size: It is used to denote the size of the switch. unCheckedChildren: It is the content that is to be shown when the state is unchecked. onChange: It is the callback function which is triggered when state changes. onClick: It is the callback function which is triggered on click event. Creating React Application And Installing Module: Step 1: Create a React application using the following command:npx create-react-app foldername Step 1: Create a React application using the following command: npx create-react-app foldername Step 2: After creating your project folder i.e. foldername, move to it using the following command:cd foldername Step 2: After creating your project folder i.e. foldername, move to it using the following command: cd foldername Step 3: After creating the ReactJS application, Install the required module using the following command:npm install antd Step 3: After creating the ReactJS application, Install the required module using the following command: npm install antd Project Structure: It will look like the following. Project Structure Example: Now write down the following code in the App.js file. Here, App is our default component where we have written our code. App.js import React, { useState } from 'react'import "antd/dist/antd.css";import { Switch } from 'antd'; export default function App() { const [currentValue, setCurrentValue] = useState(false) return ( <div style={{ display: 'block', width: 700, padding: 30 }}> <h4>ReactJS Ant-Design Switch Component</h4> <Switch onChange={(value) => { setCurrentValue(value) }} /> <br /> <p>Current Mode of Switch: {`${currentValue}`} </p> </div> );} Step to Run Application: Run the application using the following command from the root directory of the project: npm start Output: Now open your browser and go to http://localhost:3000/, you will see the following output: Reference: https://ant.design/components/switch/ ReactJS-Ant Design ReactJS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to fetch data from an API in ReactJS ? How to redirect to another page in ReactJS ? How to pass data from child component to its parent in ReactJS ? How to pass data from one component to other component in ReactJS ? Create a Responsive Navbar using ReactJS Remove elements from a JavaScript Array Installation of Node.js on Linux Convert a string to an integer in JavaScript How to fetch data from an API in ReactJS ? Top 10 Projects For Beginners To Practice HTML and CSS Skills
[ { "code": null, "e": 35483, "s": 35455, "text": "\n21 May, 2021" }, { "code": null, "e": 35737, "s": 35483, "text": "Ant Design Library has this component pre-built, and it is very easy to integrate as well. Switch components are used to toggle the state of a single setting on or off. We can use the following approach in ReactJS to use the Ant Design Switch Component." }, { "code": null, "e": 35753, "s": 35737, "text": "Switch Methods:" }, { "code": null, "e": 35819, "s": 35753, "text": "blur(): This method is used to remove the focus from the element." }, { "code": null, "e": 35881, "s": 35819, "text": "focus(): This method is used to get the focus on the element." }, { "code": null, "e": 35895, "s": 35881, "text": "Switch Props:" }, { "code": null, "e": 35961, "s": 35895, "text": "autoFocus: It is used to get focus when the component is mounted." }, { "code": null, "e": 36021, "s": 35961, "text": "checked: It indicates whether the switch is checked or not." }, { "code": null, "e": 36103, "s": 36021, "text": "checkedChildren: It is the content that is to be shown when the state is checked." }, { "code": null, "e": 36165, "s": 36103, "text": "className: It is used to pass the class name for this switch." }, { "code": null, "e": 36235, "s": 36165, "text": "defaultChecked: It indicates whether to set the initial state or not." }, { "code": null, "e": 36279, "s": 36235, "text": "disabled: It is used to disable the switch." }, { "code": null, "e": 36339, "s": 36279, "text": "loading: It is used to show to loading state of the switch." }, { "code": null, "e": 36390, "s": 36339, "text": "size: It is used to denote the size of the switch." }, { "code": null, "e": 36476, "s": 36390, "text": "unCheckedChildren: It is the content that is to be shown when the state is unchecked." }, { "code": null, "e": 36553, "s": 36476, "text": "onChange: It is the callback function which is triggered when state changes." }, { "code": null, "e": 36625, "s": 36553, "text": "onClick: It is the callback function which is triggered on click event." }, { "code": null, "e": 36675, "s": 36625, "text": "Creating React Application And Installing Module:" }, { "code": null, "e": 36770, "s": 36675, "text": "Step 1: Create a React application using the following command:npx create-react-app foldername" }, { "code": null, "e": 36834, "s": 36770, "text": "Step 1: Create a React application using the following command:" }, { "code": null, "e": 36866, "s": 36834, "text": "npx create-react-app foldername" }, { "code": null, "e": 36979, "s": 36866, "text": "Step 2: After creating your project folder i.e. foldername, move to it using the following command:cd foldername" }, { "code": null, "e": 37079, "s": 36979, "text": "Step 2: After creating your project folder i.e. foldername, move to it using the following command:" }, { "code": null, "e": 37093, "s": 37079, "text": "cd foldername" }, { "code": null, "e": 37214, "s": 37093, "text": "Step 3: After creating the ReactJS application, Install the required module using the following command:npm install antd" }, { "code": null, "e": 37319, "s": 37214, "text": "Step 3: After creating the ReactJS application, Install the required module using the following command:" }, { "code": null, "e": 37336, "s": 37319, "text": "npm install antd" }, { "code": null, "e": 37388, "s": 37336, "text": "Project Structure: It will look like the following." }, { "code": null, "e": 37406, "s": 37388, "text": "Project Structure" }, { "code": null, "e": 37536, "s": 37406, "text": "Example: Now write down the following code in the App.js file. Here, App is our default component where we have written our code." }, { "code": null, "e": 37543, "s": 37536, "text": "App.js" }, { "code": "import React, { useState } from 'react'import \"antd/dist/antd.css\";import { Switch } from 'antd'; export default function App() { const [currentValue, setCurrentValue] = useState(false) return ( <div style={{ display: 'block', width: 700, padding: 30 }}> <h4>ReactJS Ant-Design Switch Component</h4> <Switch onChange={(value) => { setCurrentValue(value) }} /> <br /> <p>Current Mode of Switch: {`${currentValue}`} </p> </div> );}", "e": 38016, "s": 37543, "text": null }, { "code": null, "e": 38129, "s": 38016, "text": "Step to Run Application: Run the application using the following command from the root directory of the project:" }, { "code": null, "e": 38139, "s": 38129, "text": "npm start" }, { "code": null, "e": 38238, "s": 38139, "text": "Output: Now open your browser and go to http://localhost:3000/, you will see the following output:" }, { "code": null, "e": 38287, "s": 38238, "text": "Reference: https://ant.design/components/switch/" }, { "code": null, "e": 38306, "s": 38287, "text": "ReactJS-Ant Design" }, { "code": null, "e": 38314, "s": 38306, "text": "ReactJS" }, { "code": null, "e": 38331, "s": 38314, "text": "Web Technologies" }, { "code": null, "e": 38429, "s": 38331, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 38472, "s": 38429, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 38517, "s": 38472, "text": "How to redirect to another page in ReactJS ?" }, { "code": null, "e": 38582, "s": 38517, "text": "How to pass data from child component to its parent in ReactJS ?" }, { "code": null, "e": 38650, "s": 38582, "text": "How to pass data from one component to other component in ReactJS ?" }, { "code": null, "e": 38691, "s": 38650, "text": "Create a Responsive Navbar using ReactJS" }, { "code": null, "e": 38731, "s": 38691, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 38764, "s": 38731, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 38809, "s": 38764, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 38852, "s": 38809, "text": "How to fetch data from an API in ReactJS ?" } ]
Python | Pandas Series.sample() - GeeksforGeeks
07 Feb, 2019 Pandas series is a One-dimensional ndarray with axis labels. The labels need not be unique but must be a hashable type. The object supports both integer- and label-based indexing and provides a host of methods for performing operations involving the index. Pandas Series.sample() function return a random sample of items from an axis of object. We can also use random_state for reproducibility. Syntax: Series.sample(n=None, frac=None, replace=False, weights=None, random_state=None, axis=None) Parameter :n : Number of items from axis to return.frac : Fraction of axis items to return.replace : Sample with or without replacement.weights : Default ‘None’ results in equal probability weighting.random_state : Seed for the random number generator (if int), or numpy RandomState object.axis : Axis to sample. Returns : Series or DataFrame Example #1: Use Series.sample() function to draw random sample of the values from the given Series object. # importing pandas as pdimport pandas as pd # Creating the Seriessr = pd.Series(['New York', 'Chicago', 'Toronto', 'Lisbon', 'Rio', 'Moscow']) # Create the Datetime Indexindex_ = ['City 1', 'City 2', 'City 3', 'City 4', 'City 5', 'City 6'] # set the indexsr.index = index_ # Print the seriesprint(sr) Output :Now we will use Series.sample() function to draw a random sample of values from the given Series object. # Draw random sample of 3 valuesselected_cities = sr.sample(n = 3) # Print the returned Series objectprint(selected_cities) Output :As we can see in the output, the Series.sample() function has successfully returned a random sample of 3 values from the given Series object. Example #2: Use Series.sample() function to draw random sample of the values from the given Series object. # importing pandas as pdimport pandas as pd # Creating the Seriessr = pd.Series([100, 25, 32, 118, 24, 65]) # Create the Indexindex_ = ['Coca Cola', 'Sprite', 'Coke', 'Fanta', 'Dew', 'ThumbsUp'] # set the indexsr.index = index_ # Print the seriesprint(sr) Output : Now we will use Series.sample() function to select a random sample of size equivalent to 25% of the size of the given Series object. # Draw random sample of size of 25 % of the original objectselected_items = sr.sample(frac = 0.25) # Print the returned Series objectprint(selected_items) Output : As we can see in the output, the Series.sample() function has successfully returned a random sample of 2 values from the given Series object, which is 25% of the size of the original series object. Python pandas-series Python pandas-series-methods Python-pandas Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Check if element exists in list in Python How To Convert Python Dictionary To JSON? How to drop one or multiple columns in Pandas Dataframe Python Classes and Objects Python | Get unique values from a list Python | os.path.join() method Create a directory in Python Defaultdict in Python Python | Pandas dataframe.groupby()
[ { "code": null, "e": 25537, "s": 25509, "text": "\n07 Feb, 2019" }, { "code": null, "e": 25794, "s": 25537, "text": "Pandas series is a One-dimensional ndarray with axis labels. The labels need not be unique but must be a hashable type. The object supports both integer- and label-based indexing and provides a host of methods for performing operations involving the index." }, { "code": null, "e": 25932, "s": 25794, "text": "Pandas Series.sample() function return a random sample of items from an axis of object. We can also use random_state for reproducibility." }, { "code": null, "e": 26032, "s": 25932, "text": "Syntax: Series.sample(n=None, frac=None, replace=False, weights=None, random_state=None, axis=None)" }, { "code": null, "e": 26345, "s": 26032, "text": "Parameter :n : Number of items from axis to return.frac : Fraction of axis items to return.replace : Sample with or without replacement.weights : Default ‘None’ results in equal probability weighting.random_state : Seed for the random number generator (if int), or numpy RandomState object.axis : Axis to sample." }, { "code": null, "e": 26375, "s": 26345, "text": "Returns : Series or DataFrame" }, { "code": null, "e": 26482, "s": 26375, "text": "Example #1: Use Series.sample() function to draw random sample of the values from the given Series object." }, { "code": "# importing pandas as pdimport pandas as pd # Creating the Seriessr = pd.Series(['New York', 'Chicago', 'Toronto', 'Lisbon', 'Rio', 'Moscow']) # Create the Datetime Indexindex_ = ['City 1', 'City 2', 'City 3', 'City 4', 'City 5', 'City 6'] # set the indexsr.index = index_ # Print the seriesprint(sr)", "e": 26787, "s": 26482, "text": null }, { "code": null, "e": 26900, "s": 26787, "text": "Output :Now we will use Series.sample() function to draw a random sample of values from the given Series object." }, { "code": "# Draw random sample of 3 valuesselected_cities = sr.sample(n = 3) # Print the returned Series objectprint(selected_cities)", "e": 27025, "s": 26900, "text": null }, { "code": null, "e": 27282, "s": 27025, "text": "Output :As we can see in the output, the Series.sample() function has successfully returned a random sample of 3 values from the given Series object. Example #2: Use Series.sample() function to draw random sample of the values from the given Series object." }, { "code": "# importing pandas as pdimport pandas as pd # Creating the Seriessr = pd.Series([100, 25, 32, 118, 24, 65]) # Create the Indexindex_ = ['Coca Cola', 'Sprite', 'Coke', 'Fanta', 'Dew', 'ThumbsUp'] # set the indexsr.index = index_ # Print the seriesprint(sr)", "e": 27542, "s": 27282, "text": null }, { "code": null, "e": 27551, "s": 27542, "text": "Output :" }, { "code": null, "e": 27684, "s": 27551, "text": "Now we will use Series.sample() function to select a random sample of size equivalent to 25% of the size of the given Series object." }, { "code": "# Draw random sample of size of 25 % of the original objectselected_items = sr.sample(frac = 0.25) # Print the returned Series objectprint(selected_items)", "e": 27840, "s": 27684, "text": null }, { "code": null, "e": 27849, "s": 27840, "text": "Output :" }, { "code": null, "e": 28047, "s": 27849, "text": "As we can see in the output, the Series.sample() function has successfully returned a random sample of 2 values from the given Series object, which is 25% of the size of the original series object." }, { "code": null, "e": 28068, "s": 28047, "text": "Python pandas-series" }, { "code": null, "e": 28097, "s": 28068, "text": "Python pandas-series-methods" }, { "code": null, "e": 28111, "s": 28097, "text": "Python-pandas" }, { "code": null, "e": 28118, "s": 28111, "text": "Python" }, { "code": null, "e": 28216, "s": 28118, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28248, "s": 28216, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 28290, "s": 28248, "text": "Check if element exists in list in Python" }, { "code": null, "e": 28332, "s": 28290, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 28388, "s": 28332, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 28415, "s": 28388, "text": "Python Classes and Objects" }, { "code": null, "e": 28454, "s": 28415, "text": "Python | Get unique values from a list" }, { "code": null, "e": 28485, "s": 28454, "text": "Python | os.path.join() method" }, { "code": null, "e": 28514, "s": 28485, "text": "Create a directory in Python" }, { "code": null, "e": 28536, "s": 28514, "text": "Defaultdict in Python" } ]
Python 3.6 Dictionary Implementation using Hash Tables - GeeksforGeeks
16 Aug, 2021 Dictionary in Python is a collection of data values, used to store data values like a map, which, unlike other Data Types that hold only a single value as an element, Dictionary holds key:value pair. Key-value is provided in the dictionary to make it more optimized. Each key-value pair in a Dictionary is separated by a colon :, whereas each key is separated by a ‘comma’. To know more about dictionaries click here. Based on a proposal by Raymond Hettinger the new dict() function has 20% to 25% less memory usage compared to python v.3.5 or less. It relies upon the order-preserving semantics proposed by Raymond Hettinger. This implementation makes the dictionaries more compact and provides a faster iteration over them. The memory layout of dictionaries in earlier versions was unnecessarily inefficient. It comprised of a sparse table of 24-byte entries that stored the hash value, the key pointer, and the value pointer. The memory layout of dictionaries in version 3.5 and less were implemented to store in a single sparse table. Example: for the below dictionary: d = {'banana':'yellow', 'grapes':'green', 'apple':'red'} used to store as: entries = [['--', '--', '--'], [-5850766811922200084, 'grapes', 'green'], ['--', '--', '--'], ['--', '--', '--'], ['--', '--', '--'], [2247849978273412954, 'banana', 'yellow'], ['--', '--', '--'], [-2069363430498323624, 'apple', 'red']] Instead, in the new dict() implementation the data is now being organized in a dense table referenced by a sparse table of indices as follows: indices = [None, 1, None, None, None, 0, None, 2] entries = [[2247849978273412954, 'banana', 'yellow'] [-5850766811922200084, 'grapes', 'green'], [-2069363430498323624, 'apple', 'red']] It is important to notice that in the new dict() implementation only the data layout has been changed and no changes are made in the hash table algorithms. Neither the collision statics nor the table search order has been changed. This new implementation of dict() is believed to significantly compress dictionaries for memory saving depending upon the size of the getdictionary. Small dictionaries gets the most benefit out of it. For a sparse table of size t with n entries, the sizes are: curr_size = 24 * t new_size = 24 * n + sizeof(index) * t In the above example banana/grapes/apple, the size of the former implementation is 192 bytes ( eight 24-byte entries) and the later implementation has a size of 90 bytes ( three 24-byte entries and eight 1-byte indices ). That shows around 58% compression in size of the dictionary. In addition to saving memory, the new memory layout makes iteration faster. Now functions like Keys(), items(), and values can loop over the dense table without having to skip empty slots, unlike the older implementation. Other benefits of this new implementation are better cache utilization, faster resizing and fewer touches to the memory. anikaseth98 ddeevviissaavviittaa Python-datatype Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Check if element exists in list in Python How To Convert Python Dictionary To JSON? Python Classes and Objects How to drop one or multiple columns in Pandas Dataframe Defaultdict in Python Python | Get unique values from a list Python | os.path.join() method Create a directory in Python Python | Pandas dataframe.groupby()
[ { "code": null, "e": 25537, "s": 25509, "text": "\n16 Aug, 2021" }, { "code": null, "e": 25956, "s": 25537, "text": "Dictionary in Python is a collection of data values, used to store data values like a map, which, unlike other Data Types that hold only a single value as an element, Dictionary holds key:value pair. Key-value is provided in the dictionary to make it more optimized. Each key-value pair in a Dictionary is separated by a colon :, whereas each key is separated by a ‘comma’. To know more about dictionaries click here. " }, { "code": null, "e": 26265, "s": 25956, "text": "Based on a proposal by Raymond Hettinger the new dict() function has 20% to 25% less memory usage compared to python v.3.5 or less. It relies upon the order-preserving semantics proposed by Raymond Hettinger. This implementation makes the dictionaries more compact and provides a faster iteration over them. " }, { "code": null, "e": 26579, "s": 26265, "text": "The memory layout of dictionaries in earlier versions was unnecessarily inefficient. It comprised of a sparse table of 24-byte entries that stored the hash value, the key pointer, and the value pointer. The memory layout of dictionaries in version 3.5 and less were implemented to store in a single sparse table. " }, { "code": null, "e": 26589, "s": 26579, "text": "Example: " }, { "code": null, "e": 27039, "s": 26589, "text": "for the below dictionary:\n\nd = {'banana':'yellow', 'grapes':'green', 'apple':'red'}\n\nused to store as:\n\n entries = [['--', '--', '--'],\n [-5850766811922200084, 'grapes', 'green'],\n ['--', '--', '--'],\n ['--', '--', '--'],\n ['--', '--', '--'],\n [2247849978273412954, 'banana', 'yellow'],\n ['--', '--', '--'],\n [-2069363430498323624, 'apple', 'red']]" }, { "code": null, "e": 27183, "s": 27039, "text": "Instead, in the new dict() implementation the data is now being organized in a dense table referenced by a sparse table of indices as follows: " }, { "code": null, "e": 27398, "s": 27183, "text": " indices = [None, 1, None, None, None, 0, None, 2]\n entries = [[2247849978273412954, 'banana', 'yellow']\n [-5850766811922200084, 'grapes', 'green'],\n [-2069363430498323624, 'apple', 'red']]" }, { "code": null, "e": 27630, "s": 27398, "text": "It is important to notice that in the new dict() implementation only the data layout has been changed and no changes are made in the hash table algorithms. Neither the collision statics nor the table search order has been changed. " }, { "code": null, "e": 27832, "s": 27630, "text": "This new implementation of dict() is believed to significantly compress dictionaries for memory saving depending upon the size of the getdictionary. Small dictionaries gets the most benefit out of it. " }, { "code": null, "e": 27893, "s": 27832, "text": "For a sparse table of size t with n entries, the sizes are: " }, { "code": null, "e": 27950, "s": 27893, "text": "curr_size = 24 * t\nnew_size = 24 * n + sizeof(index) * t" }, { "code": null, "e": 28234, "s": 27950, "text": "In the above example banana/grapes/apple, the size of the former implementation is 192 bytes ( eight 24-byte entries) and the later implementation has a size of 90 bytes ( three 24-byte entries and eight 1-byte indices ). That shows around 58% compression in size of the dictionary. " }, { "code": null, "e": 28578, "s": 28234, "text": "In addition to saving memory, the new memory layout makes iteration faster. Now functions like Keys(), items(), and values can loop over the dense table without having to skip empty slots, unlike the older implementation. Other benefits of this new implementation are better cache utilization, faster resizing and fewer touches to the memory. " }, { "code": null, "e": 28590, "s": 28578, "text": "anikaseth98" }, { "code": null, "e": 28611, "s": 28590, "text": "ddeevviissaavviittaa" }, { "code": null, "e": 28627, "s": 28611, "text": "Python-datatype" }, { "code": null, "e": 28634, "s": 28627, "text": "Python" }, { "code": null, "e": 28732, "s": 28634, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28764, "s": 28732, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 28806, "s": 28764, "text": "Check if element exists in list in Python" }, { "code": null, "e": 28848, "s": 28806, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 28875, "s": 28848, "text": "Python Classes and Objects" }, { "code": null, "e": 28931, "s": 28875, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 28953, "s": 28931, "text": "Defaultdict in Python" }, { "code": null, "e": 28992, "s": 28953, "text": "Python | Get unique values from a list" }, { "code": null, "e": 29023, "s": 28992, "text": "Python | os.path.join() method" }, { "code": null, "e": 29052, "s": 29023, "text": "Create a directory in Python" } ]
Search in a Row-wise and Column-wise Sorted 2D Array using Divide and Conquer algorithm - GeeksforGeeks
02 Jun, 2021 Given an n x n matrix, where every row and column is sorted in increasing order. Given a key, how to decide whether this key is in the matrix. A linear time complexity is discussed in the previous post. This problem can also be a very good example for divide and conquer algorithms. Following is divide and conquer algorithm.1) Find the middle element. 2) If middle element is same as key return. 3) If middle element is lesser than key then ....3a) search submatrix on lower side of middle element ....3b) Search submatrix on right hand side.of middle element 4) If middle element is greater than key then ....4a) search vertical submatrix on left side of middle element ....4b) search submatrix on right hand side. Following implementation of above algorithm. C++ Java Python3 C# Javascript // C++ program for implementation of// divide and conquer algorithm// to find a given key in a row-wise// and column-wise sorted 2D array#include<bits/stdc++.h>#define ROW 4#define COL 4using namespace std; // A divide and conquer method to// search a given key in mat[]// in rows from fromRow to toRow// and columns from fromCol to// toColvoid search(int mat[ROW][COL], int fromRow, int toRow, int fromCol, int toCol, int key) { // Find middle and compare with middle int i = fromRow + (toRow-fromRow )/2; int j = fromCol + (toCol-fromCol )/2; if (mat[i][j] == key) // If key is present at middle cout<<"Found "<< key << " at "<< i << " " << j<<endl; else { // right-up quarter of matrix is searched in all cases. // Provided it is different from current call if (i != toRow || j != fromCol) search(mat, fromRow, i, j, toCol, key); // Special case for iteration with 1*2 matrix // mat[i][j] and mat[i][j+1] are only two elements. // So just check second element if (fromRow == toRow && fromCol + 1 == toCol) if (mat[fromRow][toCol] == key) cout<<"Found "<< key<< " at "<< fromRow << " " << toCol<<endl; // If middle key is lesser then search lower horizontal // matrix and right hand side matrix if (mat[i][j] < key) { // search lower horizontal if such matrix exists if (i + 1 <= toRow) search(mat, i + 1, toRow, fromCol, toCol, key); } // If middle key is greater then search left vertical // matrix and right hand side matrix else { // search left vertical if such matrix exists if (j - 1 >= fromCol) search(mat, fromRow, toRow, fromCol, j - 1, key); } } } // Driver codeint main(){ int mat[ROW][COL] = { {10, 20, 30, 40}, {15, 25, 35, 45}, {27, 29, 37, 48}, {32, 33, 39, 50}}; int key = 50; for (int i = 0; i < ROW; i++) for (int j = 0; j < COL; j++) search(mat, 0, ROW - 1, 0, COL - 1, mat[i][j]); return 0;} // This code is contributed by Rajput-Ji // Java program for implementation of divide and conquer algorithm// to find a given key in a row-wise and column-wise sorted 2D arrayclass SearchInMatrix{ public static void main(String[] args) { int[][] mat = new int[][] { {10, 20, 30, 40}, {15, 25, 35, 45}, {27, 29, 37, 48}, {32, 33, 39, 50}}; int rowcount = 4,colCount=4,key=50; for (int i=0; i<rowcount; i++) for (int j=0; j<colCount; j++) search(mat, 0, rowcount-1, 0, colCount-1, mat[i][j]); } // A divide and conquer method to search a given key in mat[] // in rows from fromRow to toRow and columns from fromCol to // toCol public static void search(int[][] mat, int fromRow, int toRow, int fromCol, int toCol, int key) { // Find middle and compare with middle int i = fromRow + (toRow-fromRow )/2; int j = fromCol + (toCol-fromCol )/2; if (mat[i][j] == key) // If key is present at middle System.out.println("Found "+ key + " at "+ i + " " + j); else { // right-up quarter of matrix is searched in all cases. // Provided it is different from current call if (i!=toRow || j!=fromCol) search(mat,fromRow,i,j,toCol,key); // Special case for iteration with 1*2 matrix // mat[i][j] and mat[i][j+1] are only two elements. // So just check second element if (fromRow == toRow && fromCol + 1 == toCol) if (mat[fromRow][toCol] == key) System.out.println("Found "+ key+ " at "+ fromRow + " " + toCol); // If middle key is lesser then search lower horizontal // matrix and right hand side matrix if (mat[i][j] < key) { // search lower horizontal if such matrix exists if (i+1<=toRow) search(mat, i+1, toRow, fromCol, toCol, key); } // If middle key is greater then search left vertical // matrix and right hand side matrix else { // search left vertical if such matrix exists if (j-1>=fromCol) search(mat, fromRow, toRow, fromCol, j-1, key); } } }} # Python3 program for implementation of# divide and conquer algorithm to find# a given key in a row-wise and column-wise# sorted 2D array a divide and conquer method# to search a given key in mat in rows from# fromRow to toRow and columns from fromCol to# toColdef search(mat, fromRow, toRow, fromCol, toCol, key): # Find middle and compare with middle i = fromRow + (toRow - fromRow) // 2; j = fromCol + (toCol - fromCol) // 2; if (mat[i][j] == key): # If key is present at middle print("Found " , key , " at " , i , " " , j); else: # right-up quarter of matrix is searched in all cases. # Provided it is different from current call if (i != toRow or j != fromCol): search(mat, fromRow, i, j, toCol, key); # Special case for iteration with 1*2 matrix # mat[i][j] and mat[i][j+1] are only two elements. # So just check second element if (fromRow == toRow and fromCol + 1 == toCol): if (mat[fromRow][toCol] == key): print("Found " , key , " at " , fromRow , " " , toCol); # If middle key is lesser then search lower horizontal # matrix and right hand side matrix if (mat[i][j] < key): # search lower horizontal if such matrix exists if (i + 1 <= toRow): search(mat, i + 1, toRow, fromCol, toCol, key); # If middle key is greater then search left vertical # matrix and right hand side matrix else: # search left vertical if such matrix exists if (j - 1 >= fromCol): search(mat, fromRow, toRow, fromCol, j - 1, key); # Driver codeif __name__ == '__main__': mat = [[ 10, 20, 30, 40], [15, 25, 35, 45], [27, 29, 37, 48], [32, 33, 39, 50]]; rowcount = 4; colCount = 4; key = 50; for i in range(rowcount): for j in range(colCount): search(mat, 0, rowcount - 1, 0, colCount - 1, mat[i][j]); # This code is contributed by 29AjayKumar // C# program for implementation of// divide and conquer algorithm// to find a given key in a row-wise// and column-wise sorted 2D arrayusing System; public class SearchInMatrix{ public static void Main(String[] args) { int[,] mat = new int[,] { {10, 20, 30, 40}, {15, 25, 35, 45}, {27, 29, 37, 48}, {32, 33, 39, 50}}; int rowcount = 4, colCount = 4, key = 50; for (int i = 0; i < rowcount; i++) for (int j = 0; j < colCount; j++) search(mat, 0, rowcount - 1, 0, colCount - 1, mat[i, j]); } // A divide and conquer method to // search a given key in mat[] // in rows from fromRow to toRow // and columns from fromCol to // toCol public static void search(int[,] mat, int fromRow, int toRow, int fromCol, int toCol, int key) { // Find middle and compare with middle int i = fromRow + (toRow-fromRow )/2; int j = fromCol + (toCol-fromCol )/2; if (mat[i, j] == key) // If key is present at middle Console.WriteLine("Found "+ key + " at "+ i + " " + j); else { // right-up quarter of matrix is searched in all cases. // Provided it is different from current call if (i != toRow || j != fromCol) search(mat, fromRow, i, j, toCol, key); // Special case for iteration with 1*2 matrix // mat[i][j] and mat[i][j+1] are only two elements. // So just check second element if (fromRow == toRow && fromCol + 1 == toCol) if (mat[fromRow,toCol] == key) Console.WriteLine("Found "+ key + " at "+ fromRow + " " + toCol); // If middle key is lesser then search lower horizontal // matrix and right hand side matrix if (mat[i, j] < key) { // search lower horizontal if such matrix exists if (i + 1 <= toRow) search(mat, i + 1, toRow, fromCol, toCol, key); } // If middle key is greater then search left vertical // matrix and right hand side matrix else { // search left vertical if such matrix exists if (j - 1 >= fromCol) search(mat, fromRow, toRow, fromCol, j - 1, key); } } }} // This code has been contributed by 29AjayKumar <script> // JavaScript program for implementation// of divide and conquer algorithm// to find a given key in a row-wise// and column-wise sorted 2D array // A divide and conquer method to search a given key in mat // in rows from fromRow to toRow and columns from fromCol to // toCol function search(mat , fromRow , toRow, fromCol , toCol , key) { // Find middle and compare with middle var i = parseInt(fromRow + (toRow-fromRow )/2); var j = parseInt(fromCol + (toCol-fromCol )/2); if (mat[i][j] == key) // If key is present at middle document.write("Found "+ key + " at "+ i + " " + j+"<br/>"); else { // right-up quarter of matrix is searched in all cases. // Provided it is different from current call if (i!=toRow || j!=fromCol) search(mat,fromRow,i,j,toCol,key); // Special case for iteration with 1*2 matrix // mat[i][j] and mat[i][j+1] are only two elements. // So just check second element if (fromRow == toRow && fromCol + 1 == toCol) if (mat[fromRow][toCol] == key) document.write("Found "+ key+ " at "+ fromRow + " " + toCol+"<br/>"); // If middle key is lesser then search lower horizontal // matrix and right hand side matrix if (mat[i][j] < key) { // search lower horizontal if such matrix exists if (i+1<=toRow) search(mat, i+1, toRow, fromCol, toCol, key); } // If middle key is greater then search left vertical // matrix and right hand side matrix else { // search left vertical if such matrix exists if (j-1>=fromCol) search(mat, fromRow, toRow, fromCol, j-1, key); } } } var mat = [[10, 20, 30, 40], [15, 25, 35, 45], [27, 29, 37, 48], [32, 33, 39, 50]]; var rowcount = 4,colCount=4,key=50; for (var i=0; i<rowcount; i++) for (var j=0; j<colCount; j++) search(mat, 0, rowcount-1, 0, colCount-1, mat[i][j]); // This code contributed by umadevi9616 </script> Output: Found 10 at 0 0 Found 20 at 0 1 Found 30 at 0 2 Found 40 at 0 3 Found 15 at 1 0 Found 25 at 1 1 Found 35 at 1 2 Found 45 at 1 3 Found 27 at 2 0 Found 29 at 2 1 Found 37 at 2 2 Found 48 at 2 3 Found 32 at 3 0 Found 33 at 3 1 Found 39 at 3 2 Found 50 at 3 3 Time complexity: We are given a n*n matrix, the algorithm can be seen as recurring for 3 matrices of size n/2 x n/2. Following is recurrence for time complexity T(n) = 3T(n/2) + O(1) The solution of recurrence is O(n1.58) using Master Method. But the actual implementation calls for one submatrix of size n x n/2 or n/2 x n, and other submatrix of size n/2 x n/2.This article is contributed by Kaushik Lele. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above 29AjayKumar Rajput-Ji umadevi9616 Divide and Conquer Divide and Conquer Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Binary Search In JavaScript Find a Fixed Point (Value equal to index) in a given array Binary Search (bisect) in Python K-th Element of Two Sorted Arrays Convex Hull using Divide and Conquer Algorithm Multiply two polynomials Search element in a sorted matrix Median of an unsorted array using Quick Select Algorithm Decrease and Conquer Write you own Power without using multiplication(*) and division(/) operators
[ { "code": null, "e": 26159, "s": 26131, "text": "\n02 Jun, 2021" }, { "code": null, "e": 26877, "s": 26159, "text": "Given an n x n matrix, where every row and column is sorted in increasing order. Given a key, how to decide whether this key is in the matrix. A linear time complexity is discussed in the previous post. This problem can also be a very good example for divide and conquer algorithms. Following is divide and conquer algorithm.1) Find the middle element. 2) If middle element is same as key return. 3) If middle element is lesser than key then ....3a) search submatrix on lower side of middle element ....3b) Search submatrix on right hand side.of middle element 4) If middle element is greater than key then ....4a) search vertical submatrix on left side of middle element ....4b) search submatrix on right hand side. " }, { "code": null, "e": 26924, "s": 26877, "text": "Following implementation of above algorithm. " }, { "code": null, "e": 26928, "s": 26924, "text": "C++" }, { "code": null, "e": 26933, "s": 26928, "text": "Java" }, { "code": null, "e": 26941, "s": 26933, "text": "Python3" }, { "code": null, "e": 26944, "s": 26941, "text": "C#" }, { "code": null, "e": 26955, "s": 26944, "text": "Javascript" }, { "code": "// C++ program for implementation of// divide and conquer algorithm// to find a given key in a row-wise// and column-wise sorted 2D array#include<bits/stdc++.h>#define ROW 4#define COL 4using namespace std; // A divide and conquer method to// search a given key in mat[]// in rows from fromRow to toRow// and columns from fromCol to// toColvoid search(int mat[ROW][COL], int fromRow, int toRow, int fromCol, int toCol, int key) { // Find middle and compare with middle int i = fromRow + (toRow-fromRow )/2; int j = fromCol + (toCol-fromCol )/2; if (mat[i][j] == key) // If key is present at middle cout<<\"Found \"<< key << \" at \"<< i << \" \" << j<<endl; else { // right-up quarter of matrix is searched in all cases. // Provided it is different from current call if (i != toRow || j != fromCol) search(mat, fromRow, i, j, toCol, key); // Special case for iteration with 1*2 matrix // mat[i][j] and mat[i][j+1] are only two elements. // So just check second element if (fromRow == toRow && fromCol + 1 == toCol) if (mat[fromRow][toCol] == key) cout<<\"Found \"<< key<< \" at \"<< fromRow << \" \" << toCol<<endl; // If middle key is lesser then search lower horizontal // matrix and right hand side matrix if (mat[i][j] < key) { // search lower horizontal if such matrix exists if (i + 1 <= toRow) search(mat, i + 1, toRow, fromCol, toCol, key); } // If middle key is greater then search left vertical // matrix and right hand side matrix else { // search left vertical if such matrix exists if (j - 1 >= fromCol) search(mat, fromRow, toRow, fromCol, j - 1, key); } } } // Driver codeint main(){ int mat[ROW][COL] = { {10, 20, 30, 40}, {15, 25, 35, 45}, {27, 29, 37, 48}, {32, 33, 39, 50}}; int key = 50; for (int i = 0; i < ROW; i++) for (int j = 0; j < COL; j++) search(mat, 0, ROW - 1, 0, COL - 1, mat[i][j]); return 0;} // This code is contributed by Rajput-Ji", "e": 29366, "s": 26955, "text": null }, { "code": "// Java program for implementation of divide and conquer algorithm// to find a given key in a row-wise and column-wise sorted 2D arrayclass SearchInMatrix{ public static void main(String[] args) { int[][] mat = new int[][] { {10, 20, 30, 40}, {15, 25, 35, 45}, {27, 29, 37, 48}, {32, 33, 39, 50}}; int rowcount = 4,colCount=4,key=50; for (int i=0; i<rowcount; i++) for (int j=0; j<colCount; j++) search(mat, 0, rowcount-1, 0, colCount-1, mat[i][j]); } // A divide and conquer method to search a given key in mat[] // in rows from fromRow to toRow and columns from fromCol to // toCol public static void search(int[][] mat, int fromRow, int toRow, int fromCol, int toCol, int key) { // Find middle and compare with middle int i = fromRow + (toRow-fromRow )/2; int j = fromCol + (toCol-fromCol )/2; if (mat[i][j] == key) // If key is present at middle System.out.println(\"Found \"+ key + \" at \"+ i + \" \" + j); else { // right-up quarter of matrix is searched in all cases. // Provided it is different from current call if (i!=toRow || j!=fromCol) search(mat,fromRow,i,j,toCol,key); // Special case for iteration with 1*2 matrix // mat[i][j] and mat[i][j+1] are only two elements. // So just check second element if (fromRow == toRow && fromCol + 1 == toCol) if (mat[fromRow][toCol] == key) System.out.println(\"Found \"+ key+ \" at \"+ fromRow + \" \" + toCol); // If middle key is lesser then search lower horizontal // matrix and right hand side matrix if (mat[i][j] < key) { // search lower horizontal if such matrix exists if (i+1<=toRow) search(mat, i+1, toRow, fromCol, toCol, key); } // If middle key is greater then search left vertical // matrix and right hand side matrix else { // search left vertical if such matrix exists if (j-1>=fromCol) search(mat, fromRow, toRow, fromCol, j-1, key); } } }}", "e": 31815, "s": 29366, "text": null }, { "code": "# Python3 program for implementation of# divide and conquer algorithm to find# a given key in a row-wise and column-wise# sorted 2D array a divide and conquer method# to search a given key in mat in rows from# fromRow to toRow and columns from fromCol to# toColdef search(mat, fromRow, toRow, fromCol, toCol, key): # Find middle and compare with middle i = fromRow + (toRow - fromRow) // 2; j = fromCol + (toCol - fromCol) // 2; if (mat[i][j] == key): # If key is present at middle print(\"Found \" , key , \" at \" , i , \" \" , j); else: # right-up quarter of matrix is searched in all cases. # Provided it is different from current call if (i != toRow or j != fromCol): search(mat, fromRow, i, j, toCol, key); # Special case for iteration with 1*2 matrix # mat[i][j] and mat[i][j+1] are only two elements. # So just check second element if (fromRow == toRow and fromCol + 1 == toCol): if (mat[fromRow][toCol] == key): print(\"Found \" , key , \" at \" , fromRow , \" \" , toCol); # If middle key is lesser then search lower horizontal # matrix and right hand side matrix if (mat[i][j] < key): # search lower horizontal if such matrix exists if (i + 1 <= toRow): search(mat, i + 1, toRow, fromCol, toCol, key); # If middle key is greater then search left vertical # matrix and right hand side matrix else: # search left vertical if such matrix exists if (j - 1 >= fromCol): search(mat, fromRow, toRow, fromCol, j - 1, key); # Driver codeif __name__ == '__main__': mat = [[ 10, 20, 30, 40], [15, 25, 35, 45], [27, 29, 37, 48], [32, 33, 39, 50]]; rowcount = 4; colCount = 4; key = 50; for i in range(rowcount): for j in range(colCount): search(mat, 0, rowcount - 1, 0, colCount - 1, mat[i][j]); # This code is contributed by 29AjayKumar", "e": 33840, "s": 31815, "text": null }, { "code": "// C# program for implementation of// divide and conquer algorithm// to find a given key in a row-wise// and column-wise sorted 2D arrayusing System; public class SearchInMatrix{ public static void Main(String[] args) { int[,] mat = new int[,] { {10, 20, 30, 40}, {15, 25, 35, 45}, {27, 29, 37, 48}, {32, 33, 39, 50}}; int rowcount = 4, colCount = 4, key = 50; for (int i = 0; i < rowcount; i++) for (int j = 0; j < colCount; j++) search(mat, 0, rowcount - 1, 0, colCount - 1, mat[i, j]); } // A divide and conquer method to // search a given key in mat[] // in rows from fromRow to toRow // and columns from fromCol to // toCol public static void search(int[,] mat, int fromRow, int toRow, int fromCol, int toCol, int key) { // Find middle and compare with middle int i = fromRow + (toRow-fromRow )/2; int j = fromCol + (toCol-fromCol )/2; if (mat[i, j] == key) // If key is present at middle Console.WriteLine(\"Found \"+ key + \" at \"+ i + \" \" + j); else { // right-up quarter of matrix is searched in all cases. // Provided it is different from current call if (i != toRow || j != fromCol) search(mat, fromRow, i, j, toCol, key); // Special case for iteration with 1*2 matrix // mat[i][j] and mat[i][j+1] are only two elements. // So just check second element if (fromRow == toRow && fromCol + 1 == toCol) if (mat[fromRow,toCol] == key) Console.WriteLine(\"Found \"+ key + \" at \"+ fromRow + \" \" + toCol); // If middle key is lesser then search lower horizontal // matrix and right hand side matrix if (mat[i, j] < key) { // search lower horizontal if such matrix exists if (i + 1 <= toRow) search(mat, i + 1, toRow, fromCol, toCol, key); } // If middle key is greater then search left vertical // matrix and right hand side matrix else { // search left vertical if such matrix exists if (j - 1 >= fromCol) search(mat, fromRow, toRow, fromCol, j - 1, key); } } }} // This code has been contributed by 29AjayKumar", "e": 36391, "s": 33840, "text": null }, { "code": "<script> // JavaScript program for implementation// of divide and conquer algorithm// to find a given key in a row-wise// and column-wise sorted 2D array // A divide and conquer method to search a given key in mat // in rows from fromRow to toRow and columns from fromCol to // toCol function search(mat , fromRow , toRow, fromCol , toCol , key) { // Find middle and compare with middle var i = parseInt(fromRow + (toRow-fromRow )/2); var j = parseInt(fromCol + (toCol-fromCol )/2); if (mat[i][j] == key) // If key is present at middle document.write(\"Found \"+ key + \" at \"+ i + \" \" + j+\"<br/>\"); else { // right-up quarter of matrix is searched in all cases. // Provided it is different from current call if (i!=toRow || j!=fromCol) search(mat,fromRow,i,j,toCol,key); // Special case for iteration with 1*2 matrix // mat[i][j] and mat[i][j+1] are only two elements. // So just check second element if (fromRow == toRow && fromCol + 1 == toCol) if (mat[fromRow][toCol] == key) document.write(\"Found \"+ key+ \" at \"+ fromRow + \" \" + toCol+\"<br/>\"); // If middle key is lesser then search lower horizontal // matrix and right hand side matrix if (mat[i][j] < key) { // search lower horizontal if such matrix exists if (i+1<=toRow) search(mat, i+1, toRow, fromCol, toCol, key); } // If middle key is greater then search left vertical // matrix and right hand side matrix else { // search left vertical if such matrix exists if (j-1>=fromCol) search(mat, fromRow, toRow, fromCol, j-1, key); } } } var mat = [[10, 20, 30, 40], [15, 25, 35, 45], [27, 29, 37, 48], [32, 33, 39, 50]]; var rowcount = 4,colCount=4,key=50; for (var i=0; i<rowcount; i++) for (var j=0; j<colCount; j++) search(mat, 0, rowcount-1, 0, colCount-1, mat[i][j]); // This code contributed by umadevi9616 </script>", "e": 38782, "s": 36391, "text": null }, { "code": null, "e": 38792, "s": 38782, "text": "Output: " }, { "code": null, "e": 39048, "s": 38792, "text": "Found 10 at 0 0\nFound 20 at 0 1\nFound 30 at 0 2\nFound 40 at 0 3\nFound 15 at 1 0\nFound 25 at 1 1\nFound 35 at 1 2\nFound 45 at 1 3\nFound 27 at 2 0\nFound 29 at 2 1\nFound 37 at 2 2\nFound 48 at 2 3\nFound 32 at 3 0\nFound 33 at 3 1\nFound 39 at 3 2\nFound 50 at 3 3" }, { "code": null, "e": 39210, "s": 39048, "text": "Time complexity: We are given a n*n matrix, the algorithm can be seen as recurring for 3 matrices of size n/2 x n/2. Following is recurrence for time complexity " }, { "code": null, "e": 39234, "s": 39210, "text": " T(n) = 3T(n/2) + O(1) " }, { "code": null, "e": 39584, "s": 39234, "text": "The solution of recurrence is O(n1.58) using Master Method. But the actual implementation calls for one submatrix of size n x n/2 or n/2 x n, and other submatrix of size n/2 x n/2.This article is contributed by Kaushik Lele. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above " }, { "code": null, "e": 39596, "s": 39584, "text": "29AjayKumar" }, { "code": null, "e": 39606, "s": 39596, "text": "Rajput-Ji" }, { "code": null, "e": 39618, "s": 39606, "text": "umadevi9616" }, { "code": null, "e": 39637, "s": 39618, "text": "Divide and Conquer" }, { "code": null, "e": 39656, "s": 39637, "text": "Divide and Conquer" }, { "code": null, "e": 39754, "s": 39656, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 39782, "s": 39754, "text": "Binary Search In JavaScript" }, { "code": null, "e": 39841, "s": 39782, "text": "Find a Fixed Point (Value equal to index) in a given array" }, { "code": null, "e": 39874, "s": 39841, "text": "Binary Search (bisect) in Python" }, { "code": null, "e": 39908, "s": 39874, "text": "K-th Element of Two Sorted Arrays" }, { "code": null, "e": 39955, "s": 39908, "text": "Convex Hull using Divide and Conquer Algorithm" }, { "code": null, "e": 39980, "s": 39955, "text": "Multiply two polynomials" }, { "code": null, "e": 40014, "s": 39980, "text": "Search element in a sorted matrix" }, { "code": null, "e": 40071, "s": 40014, "text": "Median of an unsorted array using Quick Select Algorithm" }, { "code": null, "e": 40092, "s": 40071, "text": "Decrease and Conquer" } ]
AWT CheckboxMenuItem Class
The CheckboxMenuItem class represents a check box which can be included in a menu. Selecting the check box in the menu changes control's state from on to off or from off to on. Following is the declaration for java.awt.CheckboxMenuItem class: public class CheckboxMenuItem extends MenuItem implements ItemSelectable, Accessible CheckboxMenuItem() Create a check box menu item with an empty label. CheckboxMenuItem(label) Create a check box menu item with the specified label. CheckboxMenuItem(label, boolean state) Create a check box menu item with the specified label and state. void addItemListener(ItemListener l) Adds the specified item listener to receive item events from this check box menu item. void addNotify() Creates the peer of the checkbox item. AccessibleContext getAccessibleContext() Gets the AccessibleContext associated with this CheckboxMenuItem. ItemListener[] getItemListeners() Returns an array of all the item listeners registered on this checkbox menuitem. <T extends EventListener> T[] getListeners(Class<T> listenerType) Returns an array of all the objects currently registered as FooListeners upon this CheckboxMenuItem. Object[] getSelectedObjects() Returns the an array (length 1) containing the checkbox menu item label or null if the checkbox is not selected. boolean getState() Determines whether the state of this check box menu item is "on" or "off." param() Returns a representing the state of this CheckBoxMenuItem. protected void processEvent(AWTEvent e) Processes events on this check box menu item. protected void processItemEvent(ItemEvent e) Processes item events occurring on this check box menu item by dispatching them to any registered ItemListener objects. void removeItemListener(ItemListener l) Removes the specified item listener so that it no longer receives item events from this check box menu item. void setState(boolean b) Sets this check box menu item to the specifed state. This class inherits methods from the following classes: java.awt.MenuItem java.awt.MenuItem java.awt.MenuComponent java.awt.MenuComponent java.lang.Object java.lang.Object Create the following java program using any editor of your choice in say D:/ > AWT > com > tutorialspoint > gui > package com.tutorialspoint.gui; import java.awt.*; import java.awt.event.*; public class AWTMenuDemo { private Frame mainFrame; private Label headerLabel; private Label statusLabel; private Panel controlPanel; public AWTMenuDemo(){ prepareGUI(); } public static void main([] args){ AWTMenuDemo awtMenuDemo = new AWTMenuDemo(); awtMenuDemo.showMenuDemo(); } private void prepareGUI(){ mainFrame = new Frame("Java AWT Examples"); mainFrame.setSize(400,400); mainFrame.setLayout(new GridLayout(3, 1)); mainFrame.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent windowEvent){ System.exit(0); } }); headerLabel = new Label(); headerLabel.setAlignment(Label.CENTER); statusLabel = new Label(); statusLabel.setAlignment(Label.CENTER); statusLabel.setSize(350,100); controlPanel = new Panel(); controlPanel.setLayout(new FlowLayout()); mainFrame.add(headerLabel); mainFrame.add(controlPanel); mainFrame.add(statusLabel); mainFrame.setVisible(true); } private void showMenuDemo(){ //create a menu bar final MenuBar menuBar = new MenuBar(); //create menus Menu fileMenu = new Menu("File"); Menu editMenu = new Menu("Edit"); final Menu aboutMenu = new Menu("About"); //create menu items MenuItem newMenuItem = new MenuItem("New",new MenuShortcut(KeyEvent.VK_N)); newMenuItem.setActionCommand("New"); MenuItem openMenuItem = new MenuItem("Open"); openMenuItem.setActionCommand("Open"); MenuItem saveMenuItem = new MenuItem("Save"); saveMenuItem.setActionCommand("Save"); MenuItem exitMenuItem = new MenuItem("Exit"); exitMenuItem.setActionCommand("Exit"); MenuItem cutMenuItem = new MenuItem("Cut"); cutMenuItem.setActionCommand("Cut"); MenuItem copyMenuItem = new MenuItem("Copy"); copyMenuItem.setActionCommand("Copy"); MenuItem pasteMenuItem = new MenuItem("Paste"); pasteMenuItem.setActionCommand("Paste"); MenuItemListener menuItemListener = new MenuItemListener(); newMenuItem.addActionListener(menuItemListener); openMenuItem.addActionListener(menuItemListener); saveMenuItem.addActionListener(menuItemListener); exitMenuItem.addActionListener(menuItemListener); cutMenuItem.addActionListener(menuItemListener); copyMenuItem.addActionListener(menuItemListener); pasteMenuItem.addActionListener(menuItemListener); final CheckboxMenuItem showWindowMenu = new CheckboxMenuItem("Show About", true); showWindowMenu.addItemListener(new ItemListener() { public void itemStateChanged(ItemEvent e) { if(showWindowMenu.getState()){ menuBar.add(aboutMenu); }else{ menuBar.remove(aboutMenu); } } }); //add menu items to menus fileMenu.add(newMenuItem); fileMenu.add(openMenuItem); fileMenu.add(saveMenuItem); fileMenu.addSeparator(); fileMenu.add(showWindowMenu); fileMenu.addSeparator(); fileMenu.add(exitMenuItem); editMenu.add(cutMenuItem); editMenu.add(copyMenuItem); editMenu.add(pasteMenuItem); //add menu to menubar menuBar.add(fileMenu); menuBar.add(editMenu); menuBar.add(aboutMenu); //add menubar to the frame mainFrame.setMenuBar(menuBar); mainFrame.setVisible(true); } class MenuItemListener implements ActionListener { public void actionPerformed(ActionEvent e) { statusLabel.setText(e.getActionCommand() + " MenuItem clicked."); } } } [] args){ AWTMenuDemo awtMenuDemo = new AWTMenuDemo(); awtMenuDemo.showMenuDemo(); } private void prepareGUI(){ mainFrame = new Frame("Java AWT Examples"); mainFrame.setSize(400,400); mainFrame.setLayout(new GridLayout(3, 1)); mainFrame.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent windowEvent){ System.exit(0); } }); headerLabel = new Label(); headerLabel.setAlignment(Label.CENTER); statusLabel = new Label(); statusLabel.setAlignment(Label.CENTER); statusLabel.setSize(350,100); controlPanel = new Panel(); controlPanel.setLayout(new FlowLayout()); mainFrame.add(headerLabel); mainFrame.add(controlPanel); mainFrame.add(statusLabel); mainFrame.setVisible(true); } private void showMenuDemo(){ //create a menu bar final MenuBar menuBar = new MenuBar(); //create menus Menu fileMenu = new Menu("File"); Menu editMenu = new Menu("Edit"); final Menu aboutMenu = new Menu("About"); //create menu items MenuItem newMenuItem = new MenuItem("New",new MenuShortcut(KeyEvent.VK_N)); newMenuItem.setActionCommand("New"); MenuItem openMenuItem = new MenuItem("Open"); openMenuItem.setActionCommand("Open"); MenuItem saveMenuItem = new MenuItem("Save"); saveMenuItem.setActionCommand("Save"); MenuItem exitMenuItem = new MenuItem("Exit"); exitMenuItem.setActionCommand("Exit"); MenuItem cutMenuItem = new MenuItem("Cut"); cutMenuItem.setActionCommand("Cut"); MenuItem copyMenuItem = new MenuItem("Copy"); copyMenuItem.setActionCommand("Copy"); MenuItem pasteMenuItem = new MenuItem("Paste"); pasteMenuItem.setActionCommand("Paste"); MenuItemListener menuItemListener = new MenuItemListener(); newMenuItem.addActionListener(menuItemListener); openMenuItem.addActionListener(menuItemListener); saveMenuItem.addActionListener(menuItemListener); exitMenuItem.addActionListener(menuItemListener); cutMenuItem.addActionListener(menuItemListener); copyMenuItem.addActionListener(menuItemListener); pasteMenuItem.addActionListener(menuItemListener); final CheckboxMenuItem showWindowMenu = new CheckboxMenuItem("Show About", true); showWindowMenu.addItemListener(new ItemListener() { public void itemStateChanged(ItemEvent e) { if(showWindowMenu.getState()){ menuBar.add(aboutMenu); }else{ menuBar.remove(aboutMenu); } } }); //add menu items to menus fileMenu.add(newMenuItem); fileMenu.add(openMenuItem); fileMenu.add(saveMenuItem); fileMenu.addSeparator(); fileMenu.add(showWindowMenu); fileMenu.addSeparator(); fileMenu.add(exitMenuItem); editMenu.add(cutMenuItem); editMenu.add(copyMenuItem); editMenu.add(pasteMenuItem); //add menu to menubar menuBar.add(fileMenu); menuBar.add(editMenu); menuBar.add(aboutMenu); //add menubar to the frame mainFrame.setMenuBar(menuBar); mainFrame.setVisible(true); } class MenuItemListener implements ActionListener { public void actionPerformed(ActionEvent e) { statusLabel.setText(e.getActionCommand() + " MenuItem clicked."); } } } Compile the program using command prompt. Go to D:/ > AWT and type the following command. D:\AWT>javac com\tutorialspoint\gui\AWTMenuDemo.java If no error comes that means compilation is successful. Run the program using following command. D:\AWT>java com.tutorialspoint.gui.AWTMenuDemo Verify the following output. (Click on File Menu. Unselect "Show About" menu item.) 13 Lectures 2 hours EduOLC Print Add Notes Bookmark this page
[ { "code": null, "e": 1925, "s": 1747, "text": "The CheckboxMenuItem class represents a check box which can be included in a menu. Selecting the check box in the menu changes control's state from on to off or from off to on." }, { "code": null, "e": 1991, "s": 1925, "text": "Following is the declaration for java.awt.CheckboxMenuItem class:" }, { "code": null, "e": 2085, "s": 1991, "text": "public class CheckboxMenuItem\n extends MenuItem\n implements ItemSelectable, Accessible" }, { "code": null, "e": 2105, "s": 2085, "text": "CheckboxMenuItem() " }, { "code": null, "e": 2155, "s": 2105, "text": "Create a check box menu item with an empty label." }, { "code": null, "e": 2180, "s": 2155, "text": "CheckboxMenuItem(label) " }, { "code": null, "e": 2235, "s": 2180, "text": "Create a check box menu item with the specified label." }, { "code": null, "e": 2275, "s": 2235, "text": "CheckboxMenuItem(label, boolean state) " }, { "code": null, "e": 2340, "s": 2275, "text": "Create a check box menu item with the specified label and state." }, { "code": null, "e": 2379, "s": 2340, "text": "void addItemListener(ItemListener l) " }, { "code": null, "e": 2466, "s": 2379, "text": "Adds the specified item listener to receive item events from this check box menu item." }, { "code": null, "e": 2485, "s": 2466, "text": "void addNotify() " }, { "code": null, "e": 2524, "s": 2485, "text": "Creates the peer of the checkbox item." }, { "code": null, "e": 2567, "s": 2524, "text": "AccessibleContext getAccessibleContext() " }, { "code": null, "e": 2633, "s": 2567, "text": "Gets the AccessibleContext associated with this CheckboxMenuItem." }, { "code": null, "e": 2669, "s": 2633, "text": "ItemListener[] getItemListeners() " }, { "code": null, "e": 2750, "s": 2669, "text": "Returns an array of all the item listeners registered on this checkbox menuitem." }, { "code": null, "e": 2818, "s": 2750, "text": "<T extends EventListener> T[] getListeners(Class<T> listenerType) " }, { "code": null, "e": 2919, "s": 2818, "text": "Returns an array of all the objects currently registered as FooListeners upon this CheckboxMenuItem." }, { "code": null, "e": 2951, "s": 2919, "text": "Object[] getSelectedObjects() " }, { "code": null, "e": 3064, "s": 2951, "text": "Returns the an array (length 1) containing the checkbox menu item label or null if the checkbox is not selected." }, { "code": null, "e": 3085, "s": 3064, "text": "boolean getState() " }, { "code": null, "e": 3161, "s": 3085, "text": " Determines whether the state of this check box menu item is \"on\" or \"off.\"" }, { "code": null, "e": 3172, "s": 3161, "text": " param() " }, { "code": null, "e": 3231, "s": 3172, "text": "Returns a representing the state of this CheckBoxMenuItem." }, { "code": null, "e": 3273, "s": 3231, "text": "protected void\tprocessEvent(AWTEvent e) " }, { "code": null, "e": 3319, "s": 3273, "text": "Processes events on this check box menu item." }, { "code": null, "e": 3366, "s": 3319, "text": "protected void\tprocessItemEvent(ItemEvent e) " }, { "code": null, "e": 3486, "s": 3366, "text": "Processes item events occurring on this check box menu item by dispatching them to any registered ItemListener objects." }, { "code": null, "e": 3528, "s": 3486, "text": "void removeItemListener(ItemListener l) " }, { "code": null, "e": 3637, "s": 3528, "text": "Removes the specified item listener so that it no longer receives item events from this check box menu item." }, { "code": null, "e": 3664, "s": 3637, "text": "void setState(boolean b) " }, { "code": null, "e": 3717, "s": 3664, "text": "Sets this check box menu item to the specifed state." }, { "code": null, "e": 3773, "s": 3717, "text": "This class inherits methods from the following classes:" }, { "code": null, "e": 3791, "s": 3773, "text": "java.awt.MenuItem" }, { "code": null, "e": 3809, "s": 3791, "text": "java.awt.MenuItem" }, { "code": null, "e": 3832, "s": 3809, "text": "java.awt.MenuComponent" }, { "code": null, "e": 3855, "s": 3832, "text": "java.awt.MenuComponent" }, { "code": null, "e": 3872, "s": 3855, "text": "java.lang.Object" }, { "code": null, "e": 3889, "s": 3872, "text": "java.lang.Object" }, { "code": null, "e": 4003, "s": 3889, "text": "Create the following java program using any editor of your choice in say D:/ > AWT > com > tutorialspoint > gui >" }, { "code": null, "e": 7862, "s": 4003, "text": "package com.tutorialspoint.gui;\n\nimport java.awt.*;\nimport java.awt.event.*;\n\npublic class AWTMenuDemo {\n private Frame mainFrame;\n private Label headerLabel;\n private Label statusLabel;\n private Panel controlPanel;\n\n public AWTMenuDemo(){\n prepareGUI();\n }\n\n public static void main([] args){\n AWTMenuDemo awtMenuDemo = new AWTMenuDemo(); \n awtMenuDemo.showMenuDemo();\n }\n\n private void prepareGUI(){\n mainFrame = new Frame(\"Java AWT Examples\");\n mainFrame.setSize(400,400);\n mainFrame.setLayout(new GridLayout(3, 1));\n mainFrame.addWindowListener(new WindowAdapter() {\n public void windowClosing(WindowEvent windowEvent){\n System.exit(0);\n } \n }); \n headerLabel = new Label();\n headerLabel.setAlignment(Label.CENTER);\n statusLabel = new Label(); \n statusLabel.setAlignment(Label.CENTER);\n statusLabel.setSize(350,100);\n\n controlPanel = new Panel();\n controlPanel.setLayout(new FlowLayout());\n\n mainFrame.add(headerLabel);\n mainFrame.add(controlPanel);\n mainFrame.add(statusLabel);\n mainFrame.setVisible(true); \n }\n\n private void showMenuDemo(){\n //create a menu bar\n final MenuBar menuBar = new MenuBar();\n\n //create menus\n Menu fileMenu = new Menu(\"File\");\n Menu editMenu = new Menu(\"Edit\"); \n final Menu aboutMenu = new Menu(\"About\");\n\n //create menu items\n MenuItem newMenuItem = \n new MenuItem(\"New\",new MenuShortcut(KeyEvent.VK_N));\n newMenuItem.setActionCommand(\"New\");\n\n MenuItem openMenuItem = new MenuItem(\"Open\");\n openMenuItem.setActionCommand(\"Open\");\n\n MenuItem saveMenuItem = new MenuItem(\"Save\");\n saveMenuItem.setActionCommand(\"Save\");\n\n MenuItem exitMenuItem = new MenuItem(\"Exit\");\n exitMenuItem.setActionCommand(\"Exit\");\n\n MenuItem cutMenuItem = new MenuItem(\"Cut\");\n cutMenuItem.setActionCommand(\"Cut\");\n\n MenuItem copyMenuItem = new MenuItem(\"Copy\");\n copyMenuItem.setActionCommand(\"Copy\");\n\n MenuItem pasteMenuItem = new MenuItem(\"Paste\");\n pasteMenuItem.setActionCommand(\"Paste\");\n \n MenuItemListener menuItemListener = new MenuItemListener();\n\n newMenuItem.addActionListener(menuItemListener);\n openMenuItem.addActionListener(menuItemListener);\n saveMenuItem.addActionListener(menuItemListener);\n exitMenuItem.addActionListener(menuItemListener);\n cutMenuItem.addActionListener(menuItemListener);\n copyMenuItem.addActionListener(menuItemListener);\n pasteMenuItem.addActionListener(menuItemListener);\n\n final CheckboxMenuItem showWindowMenu = \n new CheckboxMenuItem(\"Show About\", true);\n showWindowMenu.addItemListener(new ItemListener() {\n public void itemStateChanged(ItemEvent e) {\n if(showWindowMenu.getState()){\n menuBar.add(aboutMenu);\n }else{\n menuBar.remove(aboutMenu);\n }\n }\n });\n\n //add menu items to menus\n fileMenu.add(newMenuItem);\n fileMenu.add(openMenuItem);\n fileMenu.add(saveMenuItem);\n fileMenu.addSeparator();\n fileMenu.add(showWindowMenu);\n fileMenu.addSeparator();\n fileMenu.add(exitMenuItem);\n\n editMenu.add(cutMenuItem);\n editMenu.add(copyMenuItem);\n editMenu.add(pasteMenuItem);\n\n //add menu to menubar\n menuBar.add(fileMenu);\n menuBar.add(editMenu);\n menuBar.add(aboutMenu);\n\n //add menubar to the frame\n mainFrame.setMenuBar(menuBar);\n mainFrame.setVisible(true); \n }\n\n class MenuItemListener implements ActionListener {\n public void actionPerformed(ActionEvent e) { \n statusLabel.setText(e.getActionCommand() \n + \" MenuItem clicked.\");\n } \n }\n}" }, { "code": null, "e": 11418, "s": 7862, "text": "[] args){\n AWTMenuDemo awtMenuDemo = new AWTMenuDemo(); \n awtMenuDemo.showMenuDemo();\n }\n\n private void prepareGUI(){\n mainFrame = new Frame(\"Java AWT Examples\");\n mainFrame.setSize(400,400);\n mainFrame.setLayout(new GridLayout(3, 1));\n mainFrame.addWindowListener(new WindowAdapter() {\n public void windowClosing(WindowEvent windowEvent){\n System.exit(0);\n } \n }); \n headerLabel = new Label();\n headerLabel.setAlignment(Label.CENTER);\n statusLabel = new Label(); \n statusLabel.setAlignment(Label.CENTER);\n statusLabel.setSize(350,100);\n\n controlPanel = new Panel();\n controlPanel.setLayout(new FlowLayout());\n\n mainFrame.add(headerLabel);\n mainFrame.add(controlPanel);\n mainFrame.add(statusLabel);\n mainFrame.setVisible(true); \n }\n\n private void showMenuDemo(){\n //create a menu bar\n final MenuBar menuBar = new MenuBar();\n\n //create menus\n Menu fileMenu = new Menu(\"File\");\n Menu editMenu = new Menu(\"Edit\"); \n final Menu aboutMenu = new Menu(\"About\");\n\n //create menu items\n MenuItem newMenuItem = \n new MenuItem(\"New\",new MenuShortcut(KeyEvent.VK_N));\n newMenuItem.setActionCommand(\"New\");\n\n MenuItem openMenuItem = new MenuItem(\"Open\");\n openMenuItem.setActionCommand(\"Open\");\n\n MenuItem saveMenuItem = new MenuItem(\"Save\");\n saveMenuItem.setActionCommand(\"Save\");\n\n MenuItem exitMenuItem = new MenuItem(\"Exit\");\n exitMenuItem.setActionCommand(\"Exit\");\n\n MenuItem cutMenuItem = new MenuItem(\"Cut\");\n cutMenuItem.setActionCommand(\"Cut\");\n\n MenuItem copyMenuItem = new MenuItem(\"Copy\");\n copyMenuItem.setActionCommand(\"Copy\");\n\n MenuItem pasteMenuItem = new MenuItem(\"Paste\");\n pasteMenuItem.setActionCommand(\"Paste\");\n \n MenuItemListener menuItemListener = new MenuItemListener();\n\n newMenuItem.addActionListener(menuItemListener);\n openMenuItem.addActionListener(menuItemListener);\n saveMenuItem.addActionListener(menuItemListener);\n exitMenuItem.addActionListener(menuItemListener);\n cutMenuItem.addActionListener(menuItemListener);\n copyMenuItem.addActionListener(menuItemListener);\n pasteMenuItem.addActionListener(menuItemListener);\n\n final CheckboxMenuItem showWindowMenu = \n new CheckboxMenuItem(\"Show About\", true);\n showWindowMenu.addItemListener(new ItemListener() {\n public void itemStateChanged(ItemEvent e) {\n if(showWindowMenu.getState()){\n menuBar.add(aboutMenu);\n }else{\n menuBar.remove(aboutMenu);\n }\n }\n });\n\n //add menu items to menus\n fileMenu.add(newMenuItem);\n fileMenu.add(openMenuItem);\n fileMenu.add(saveMenuItem);\n fileMenu.addSeparator();\n fileMenu.add(showWindowMenu);\n fileMenu.addSeparator();\n fileMenu.add(exitMenuItem);\n\n editMenu.add(cutMenuItem);\n editMenu.add(copyMenuItem);\n editMenu.add(pasteMenuItem);\n\n //add menu to menubar\n menuBar.add(fileMenu);\n menuBar.add(editMenu);\n menuBar.add(aboutMenu);\n\n //add menubar to the frame\n mainFrame.setMenuBar(menuBar);\n mainFrame.setVisible(true); \n }\n\n class MenuItemListener implements ActionListener {\n public void actionPerformed(ActionEvent e) { \n statusLabel.setText(e.getActionCommand() \n + \" MenuItem clicked.\");\n } \n }\n}" }, { "code": null, "e": 11509, "s": 11418, "text": "Compile the program using command prompt. Go to D:/ > AWT and type the following command." }, { "code": null, "e": 11562, "s": 11509, "text": "D:\\AWT>javac com\\tutorialspoint\\gui\\AWTMenuDemo.java" }, { "code": null, "e": 11659, "s": 11562, "text": "If no error comes that means compilation is successful. Run the program using following command." }, { "code": null, "e": 11706, "s": 11659, "text": "D:\\AWT>java com.tutorialspoint.gui.AWTMenuDemo" }, { "code": null, "e": 11790, "s": 11706, "text": "Verify the following output. (Click on File Menu. Unselect \"Show About\" menu item.)" }, { "code": null, "e": 11823, "s": 11790, "text": "\n 13 Lectures \n 2 hours \n" }, { "code": null, "e": 11831, "s": 11823, "text": " EduOLC" }, { "code": null, "e": 11838, "s": 11831, "text": " Print" }, { "code": null, "e": 11849, "s": 11838, "text": " Add Notes" } ]
How to convert string into float in JavaScript? - GeeksforGeeks
24 Jun, 2019 We can convert a string into a float in JavaScript by using some methods which are described below: By using Type Conversion of JavaScript By using parseFloat() Method Method 1: In this method we will use the Type Conversion feature of JavaScript which will convert the string value into float. Example: Below program demonstrates the above approach <script> // Javascript script // to convert string // to float value // Function to convert // string to float value function convert_to_float(a) { // Type conversion // of string to float var floatValue = +(a); // Return float value return floatValue; } //Driver code var n = "55.225"; // Call function n = convert_to_float(n); // Print result document.write("Converted value = " + n + "</br> Type of " + n + " = " +typeof n + "<br>"); var n = "-33.565"; // Call function n = convert_to_float(n); // Print result document.write("Converted value = " + n + "</br> Type of " + n + " = " +typeof n + "<br>");</script> Output: Converted value = 55.225 Type of 55.225 = number Converted value = -33.565 Type of -33.565 = number Method 2: In this method we will use the parseFloat() method which is an inbuilt function in JavaScript that is used to accept the string and convert it into a floating point number. If the string does not contain a numeral value or If the first character of the string is not a Number then it returns NaN i.e, not a number. Example: Below program demonstrates the above approach <script> // Javascript script // to convert string // to float value // Function to convert // string to float value function convert_to_float(a) { // Using parseFloat() method var floatValue = parseFloat(a); // Return float value return floatValue; } //Driver code var n = "245.165"; // Call function n = convert_to_float(n); // Print result document.write("Converted value = " + n + "</br> Type of " + n + " = " +typeof n + "<br>"); var n = "-915.55"; // Call function n = convert_to_float(n); // Print result document.write("Converted value = " + n + "</br> Type of " + n + " = " +typeof n + "<br>");</script> Output: Converted value = 245.165 Type of 245.165 = number Converted value = -915.55 Type of -915.55 = number Special Case: In French the float numbers are written by the use of comma (, ) as separator instead of dot(.) as separator.Example: The value 245.67 in French is written as 245, 67 To convert French string into float in JavaScript we will first use replace() method to replace every (, ) with (.) then follow any of above described method. Example: Below program demonstrates the above approach <script> // Javascript script // to convert string // to float value // Function to convert // string to float value function convert_to_float(a) { // Using parseFloat() method // and using replace() method // to replace ', ' with '.' var floatValue = parseFloat(a.replace(/, /, '.')); // Return float value return floatValue; } //Driver code var n = "245, 165"; // Call function n = convert_to_float(n); // Print result document.write("Converted value = " + n + "</br> Type of " + n + " = " +typeof n + "<br>"); var n = "-915, 55"; // Call function n = convert_to_float(n); // Print result document.write("Converted value = " + n + "</br> Type of " + n + " = " +typeof n + "<br>");</script> Output: Converted value = 245.165 Type of 245.165 = number Converted value = -915.55 Type of -915.55 = number JavaScript-Misc javascript-string Picked JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Remove elements from a JavaScript Array Convert a string to an integer in JavaScript Difference between var, let and const keywords in JavaScript Differences between Functional Components and Class Components in React How to append HTML code to a div using JavaScript ? Remove elements from a JavaScript Array Installation of Node.js on Linux Convert a string to an integer in JavaScript How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 25478, "s": 25450, "text": "\n24 Jun, 2019" }, { "code": null, "e": 25578, "s": 25478, "text": "We can convert a string into a float in JavaScript by using some methods which are described below:" }, { "code": null, "e": 25617, "s": 25578, "text": "By using Type Conversion of JavaScript" }, { "code": null, "e": 25646, "s": 25617, "text": "By using parseFloat() Method" }, { "code": null, "e": 25773, "s": 25646, "text": "Method 1: In this method we will use the Type Conversion feature of JavaScript which will convert the string value into float." }, { "code": null, "e": 25828, "s": 25773, "text": "Example: Below program demonstrates the above approach" }, { "code": "<script> // Javascript script // to convert string // to float value // Function to convert // string to float value function convert_to_float(a) { // Type conversion // of string to float var floatValue = +(a); // Return float value return floatValue; } //Driver code var n = \"55.225\"; // Call function n = convert_to_float(n); // Print result document.write(\"Converted value = \" + n + \"</br> Type of \" + n + \" = \" +typeof n + \"<br>\"); var n = \"-33.565\"; // Call function n = convert_to_float(n); // Print result document.write(\"Converted value = \" + n + \"</br> Type of \" + n + \" = \" +typeof n + \"<br>\");</script> ", "e": 26581, "s": 25828, "text": null }, { "code": null, "e": 26589, "s": 26581, "text": "Output:" }, { "code": null, "e": 26690, "s": 26589, "text": "Converted value = 55.225\nType of 55.225 = number\nConverted value = -33.565\nType of -33.565 = number\n" }, { "code": null, "e": 27015, "s": 26690, "text": "Method 2: In this method we will use the parseFloat() method which is an inbuilt function in JavaScript that is used to accept the string and convert it into a floating point number. If the string does not contain a numeral value or If the first character of the string is not a Number then it returns NaN i.e, not a number." }, { "code": null, "e": 27070, "s": 27015, "text": "Example: Below program demonstrates the above approach" }, { "code": "<script> // Javascript script // to convert string // to float value // Function to convert // string to float value function convert_to_float(a) { // Using parseFloat() method var floatValue = parseFloat(a); // Return float value return floatValue; } //Driver code var n = \"245.165\"; // Call function n = convert_to_float(n); // Print result document.write(\"Converted value = \" + n + \"</br> Type of \" + n + \" = \" +typeof n + \"<br>\"); var n = \"-915.55\"; // Call function n = convert_to_float(n); // Print result document.write(\"Converted value = \" + n + \"</br> Type of \" + n + \" = \" +typeof n + \"<br>\");</script> ", "e": 27814, "s": 27070, "text": null }, { "code": null, "e": 27822, "s": 27814, "text": "Output:" }, { "code": null, "e": 27925, "s": 27822, "text": "Converted value = 245.165\nType of 245.165 = number\nConverted value = -915.55\nType of -915.55 = number\n" }, { "code": null, "e": 28057, "s": 27925, "text": "Special Case: In French the float numbers are written by the use of comma (, ) as separator instead of dot(.) as separator.Example:" }, { "code": null, "e": 28107, "s": 28057, "text": "The value 245.67 in French is written as 245, 67\n" }, { "code": null, "e": 28266, "s": 28107, "text": "To convert French string into float in JavaScript we will first use replace() method to replace every (, ) with (.) then follow any of above described method." }, { "code": null, "e": 28321, "s": 28266, "text": "Example: Below program demonstrates the above approach" }, { "code": "<script> // Javascript script // to convert string // to float value // Function to convert // string to float value function convert_to_float(a) { // Using parseFloat() method // and using replace() method // to replace ', ' with '.' var floatValue = parseFloat(a.replace(/, /, '.')); // Return float value return floatValue; } //Driver code var n = \"245, 165\"; // Call function n = convert_to_float(n); // Print result document.write(\"Converted value = \" + n + \"</br> Type of \" + n + \" = \" +typeof n + \"<br>\"); var n = \"-915, 55\"; // Call function n = convert_to_float(n); // Print result document.write(\"Converted value = \" + n + \"</br> Type of \" + n + \" = \" +typeof n + \"<br>\");</script> ", "e": 29158, "s": 28321, "text": null }, { "code": null, "e": 29166, "s": 29158, "text": "Output:" }, { "code": null, "e": 29269, "s": 29166, "text": "Converted value = 245.165\nType of 245.165 = number\nConverted value = -915.55\nType of -915.55 = number\n" }, { "code": null, "e": 29285, "s": 29269, "text": "JavaScript-Misc" }, { "code": null, "e": 29303, "s": 29285, "text": "javascript-string" }, { "code": null, "e": 29310, "s": 29303, "text": "Picked" }, { "code": null, "e": 29321, "s": 29310, "text": "JavaScript" }, { "code": null, "e": 29338, "s": 29321, "text": "Web Technologies" }, { "code": null, "e": 29436, "s": 29338, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29476, "s": 29436, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 29521, "s": 29476, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 29582, "s": 29521, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 29654, "s": 29582, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 29706, "s": 29654, "text": "How to append HTML code to a div using JavaScript ?" }, { "code": null, "e": 29746, "s": 29706, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 29779, "s": 29746, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 29824, "s": 29779, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 29867, "s": 29824, "text": "How to fetch data from an API in ReactJS ?" } ]
High-Accuracy Covid 19 Prediction from Chest X-Ray Images using Pre-Trained Convolutional Neural Networks in PyTorch | by Bharat Sethuraman Sharman | Towards Data Science
Leveraging Efficientnet architecture to achieve 99%+ prediction accuracy on a Medical Imaging Dataset pertaining to Covid19 In this post, I will share my experience of developing a Convolutional Neural Network algorithm to predict Covid-19 from chest X-Ray images with high accuracy. I developed this algorithm while participating in an In-Class Kaggle competition for a Ph.D. level course on Deep Learning. I was happy to learn from the final competition Leaderboard that I stood 1st in the competition amongst 40 participating Ph.D. and Masters students of Statistics and Computer Science departments! Instead of moving straight to results, I will mention the challenges that I faced while I developed and trained the model and how I found ways to resolve them. While working on this problem, I experienced the truth first-hand in the saying “Enjoy the process, the result will take care of itself”! You can find my complete code on GitHub here. The Challenge in Brief Given an input chest X-ray image, the algorithm must detect whether the person has been infected with Covid-19 or not. We have a set of supervised X-ray images that have been carefully labeled by radiologists on which the model must be trained. Such a model can help health care professionals diagnose COVID-19 cases much more quickly than a radiologist having to go through each scan one by one especially in situations where a large number of people need to be tested in a short time window. Let’s take an example. The images shown below from the competition website are of people without (negative) and with (positive) Covid-19. Dataset Description The training dataset consists of 15264 (512x512 pixel) images that have been classified by an expert radiologist. The test dataset consists of 400 such images coming from the same distribution. You can find the dataset here. I found that the training dataset is significantly imbalanced with about 90% of the images being of the non-Covid class. The problem with significantly imbalanced sets is that even a naive learning algorithm that simply outputs the class of the majority class as the output will attain high accuracy. In other words, it will label everyone as being Covid-free and attain an ‘accuracy’ of 90% even though about 10% of the people actually have Covid. Initially, I started with the imbalanced training dataset as it is. From the benefit of hindsight, it turned out to be not the best starting point but one must start with what one has and in this case, it was the training dataset. I will describe it more in detail later in this article. Climbing the Performance Ladder — Steps and Missteps A deep learning algorithm has many moving parts and I found that training a high-performing model is as much an art as it is math. One does not know most of the answers when starting out and has to learn by experimentation. I will now describe how I went about selecting each of the hyperparameters and what I learned in the process. Learning Rate: A lower learning rate leads to better convergence but not necessarily the best test accuracy. The issue could be that the algorithm has not yet learned the set of weights that lead to the lowest error for the test set. A higher learning rate, on the other hand, can lead to the algorithm overshooting the optimal set of weights. I experimented with learning rates of 10e-3, 10e-4, and 10e-5 and found that 10e-4 led to the lowest error rates for the test dataset. Batch Size: On increasing the batch size to 256 or even down to 64, I ran into memory issues and therefore had to opt for a lower batch size. I experimented with 32 and 16. Out of these two batch sizes, the batch size of 32 led to the lowest error rates with a learning rate of 10e-4. The interplay of Learning Rate, Batch Size, and Accuracy has been explored well in this paper. The authors experimented with various learning rates and batch sizes for the VGG16 CNN. I started with a lower learning rate (lr=0.0001 as aginst 0.001) that turned out to the better choice later and went with the rule of thumb of setting the batch size as 32 which is quite common in deep learning practice. I thank the authors for the leads that I got from their study. A complex field like Deep Learning is never a lone wolf endeavor and we all stand on the shoulders of each other, not just the giants, to look ahead. Pre-Trained Model: Coming to the question of which pre-trained model to use; I came across an interesting article on the Google AI Blog that compared the accuracy on the Imagenet dataset vs the number of parameters in the model for several pre-trained models. Computer Vision is a quickly evolving field and new models keep getting developed at a fast pace. Initially, I had plans to use VGG16 or Resnet50 but when I saw this article on Efficientnet, I changed my mind in the favor of Efficientnet. I have an RTX 2070 GPU and that the limitations of my hardware placed a constraint on the model that I could use. I started with the b7 version of Efficientnet but my GPU quickly gave up as the model was not fitting in its memory. After numerous Kill -9 job_number on b7,b6,b5, and b4 models(the command to delete a model from computer memory in Linux :) ), I settled with Efficientnet b3. The sole reason to do so at that point in time was that it was the largest model in the Efficientnet family that finally fit within my GPU memory. Later on, this turned out to be an excellent choice! Epochs: With a model like Efficientnet b3 that has 12 Million parameters and the number of training dataset instances being in the order of tens of thousands, it is very easy to overtrain a model. In fact, I got a training accuracy of 1 while training the model with 20 Epochs! Don’t ask me the test accuracy for that case :) I used epochs ranging from 1 to 30 for various learning rate and batch size combinations. Sampling: I started with no sampling. Strangely, the model was classifying almost all the test cases as “1”, contrary to my expectation of “0”. I felt that the problem was that the test images were not being transformed as the training images were and the untransformed test images were somehow resembling the transformed training images of label “1” (more on this crucial topic later). I then used a weighted random sampler that led to an almost 50–50 representation of the 0 and 1 classes in the training dataset. However, it also led to the overall training dataset size reducing from ~15000 to just under ~3000. The accuracy improved but plateaued at around 0.86 with this sampling technique. Next, I oversampled from the minority class and brought the number of images from both the classes on par with each other. By doing so, my training dataset increased from 15000 to 26000. This certainly helped as I was now hitting the 90s in accuracy and I got an accuracy of about 0.94. Transformations- Appling the same transformations used on the training dataset to the test dataset: I was plateauing at 0.94 and others were getting accuracies of up to 0.975. This set me thinking hard about what I was missing in my model. I traced and re-traced the steps several times, while bathing, cooking, and walking. Suddenly, the Eureka moment came: Distribution! All machine learning rests on the assumption that the distribution of the test data is the same as that of the training data. Otherwise, what we are learning from the training dataset simply will not apply to the test dataset. By transforming the training images via rotations and translations, I was changing the distribution. However, by leaving the test images as it is, I was inadvertently applying the algorithm on a “different” distribution. I immediately applied identical transformations on the test images and lo and behold, I saw an accuracy of 0.975 for the first time! Tuning: Once this insight came, all that was left to be done was tuning the hyperparameters to achieve the best possible result. I tried various epochs and found that for this dataset with the pre-trained model, learning rate, and batch size that I used, I got the best test accuracy after 11 epochs of training. Could have I done better? Perhaps using Efficientnet-b7 coupled with a larger batch size could have led to even higher accuracy. If someone has a more powerful GPU/distributed computing system, please give it a shot and let me know. Practical Application: With this algorithm, a medical practitioner can identify Covid accurately in 99 out of 100 people rapidly (a matter of 40 minutes to train the algorithm on 15000 images and run it on 400 images) Taking into account only the classification time for the test images, it takes merely 1 minute for the algorithm to classify 400 images. So this can be very useful for field-staff to rapidly screen images and identify people who test positive. Having walked you through the algorithm discovery journey, I now move to the nuts-and-bolts aka development. Algorithm Development in PyTorch I developed my algorithm in PyTorch which is a Machine Learning Library that is well-suited for Computer Vision tasks. As the first step, I imported numpy, pandas, os, torch, etc, and set the base path where the data folder is located. Then I created pandas data frames to contain the training dataset image names and their labels and the test dataset image names respectively. As the first step, I imported numpy, pandas, os, torch, etc, and set the base path where the data folder is located. Then I created pandas data frames to contain the training dataset image names and their labels and the test dataset image names respectively. 2. To check whether the data frames were loaded properly, it is good to check the first few rows of train_dataset and the test_dataset. Here is the code and the resulting output from the Jupyter notebook: We see that the names of the images are in the File column and the Labels are in the Label column for the training images. For the test images, we have the names in the File column. 3. Here’s the code to view some of the images in the training dataset folder, This code will result in 15 X-Ray images of the type shown above. 4. The next step is to create the training dataset out of the images and the labels in a form that Pytorch can process. Dataloader is a function in Pytorch that enables us to conveniently pair images and their labels to create a matrix/tensor that can then be used by PyTorch as an input to a learning algorithm. 5. I then set the learning rate to be 10e-4 6. Next, I prepared the training set using the Dataset dataloader class that I created in step 4. I named it as training_set_untransformed as I have not yet applied the data transformations like rotation or translation to the images. 7. I then created a transforms.Compose method to resize the images, randomly apply rotation and horizontal translation and convert the resulting matrix to a tensor. Such a transform is useful for data augmentation. 8. The next step is to use the transforms method on the training dataset. For the images in the minority class (covid cases), I have upsampled them so that the number of images in both the classes are the same after the transformation is applied. 9. I then split these newly created images into training and validation sets in the 80:20 ratio. 10. Using the Dataloader function of Pytorch, I created batches of 32 each from the training dataset and shuffled them to ensure roughly equal representation of both classes in all the batches. 11. To enable GPU computation, I used the cuda.is_available() command. The Deep Learning code can also run on a CPU but would take much longer. 12. The following is the command to import Efficientnet-b3 from Pytorch and set the number of classes to 2. 13. After importing, the model has to be loaded to the memory of the GPU. If your model is too big for the GPU memory, you will get an error message and would need to select another model that will fit into the memory. Run the command on a Jupyter notebook and admire the complexity of Efficientnet! 14. It is good to save the weights generated by the training process periodically. In case if the model crashes due to some reason, we can call the saved weights and resume training instead of having to start from scratch again. 15. I used the cross-entropy loss as the criterion for loss calculation as we are dealing with a classification problem. I used the Adam optimizer, which is a well-known weight update method for deep learning, and set the number of epochs to 11 (this learning came after a lot of experimentation). Learning rate decay is a parameter used to update the learning rate after each epoch and I set a conservative decay rate of 0.99 as the learning rate is already low. I created two lists to track accuracy and loss histories. 16. Training the model: Here’s the training part of the code. I ran the model for 11 epochs and saved the 1st, 10th, and final (11th) versions of the model. It took about 40 minutes to train it. At the end of the 11th Epoch, I got an accuracy of 99% on the training dataset for both classes. Accuracy of 0: 99 %Accuracy of 1: 99 %[11 epoch] Accuracy of the network on the Training images: 99 17. Here is a plot of the training accuracy and cross-entropy loss over iterations. There are 7227 batch iterations and the plot shows how these values are changing over the batch iterations. 18. The next step is to apply the transforms. Compose to the test dataset as well to make it conform to the same distribution as the training dataset. 19. To predict the class of test images, we need to define a predict_image function: 20. The following code snippet checks how well the model is doing on the validation dataset. 21. With the following lines, one can predict the classes of the test set images and store them in a csv file. Conclusion Through this Kaggle Competition, I learned that conceiving and developing a Deep Learning Algorithm takes some patience and we must continuously keep looking for chinks in the model as well as the discoveries that others have made to make our models better. My article is a small way of paying it forward to the Machine Learning community so that we can share and learn together and improve our algorithms to solve problems in better ways! Hope you could learn something useful from my post. Please share your valuable feedback! Acknowledgement: I gratefully acknowledge Kartik Dutt who had developed code for a different Computer Vision challenge and whose parts of whose code I found appropriate for this deep learning task and incorporated in my work. (https://github.com/kartikdutt18/Kaggle-ATPOS-Efficient_Net/blob/master/Efficient_Net.ipynb)
[ { "code": null, "e": 296, "s": 172, "text": "Leveraging Efficientnet architecture to achieve 99%+ prediction accuracy on a Medical Imaging Dataset pertaining to Covid19" }, { "code": null, "e": 1074, "s": 296, "text": "In this post, I will share my experience of developing a Convolutional Neural Network algorithm to predict Covid-19 from chest X-Ray images with high accuracy. I developed this algorithm while participating in an In-Class Kaggle competition for a Ph.D. level course on Deep Learning. I was happy to learn from the final competition Leaderboard that I stood 1st in the competition amongst 40 participating Ph.D. and Masters students of Statistics and Computer Science departments! Instead of moving straight to results, I will mention the challenges that I faced while I developed and trained the model and how I found ways to resolve them. While working on this problem, I experienced the truth first-hand in the saying “Enjoy the process, the result will take care of itself”!" }, { "code": null, "e": 1120, "s": 1074, "text": "You can find my complete code on GitHub here." }, { "code": null, "e": 1143, "s": 1120, "text": "The Challenge in Brief" }, { "code": null, "e": 1637, "s": 1143, "text": "Given an input chest X-ray image, the algorithm must detect whether the person has been infected with Covid-19 or not. We have a set of supervised X-ray images that have been carefully labeled by radiologists on which the model must be trained. Such a model can help health care professionals diagnose COVID-19 cases much more quickly than a radiologist having to go through each scan one by one especially in situations where a large number of people need to be tested in a short time window." }, { "code": null, "e": 1775, "s": 1637, "text": "Let’s take an example. The images shown below from the competition website are of people without (negative) and with (positive) Covid-19." }, { "code": null, "e": 1795, "s": 1775, "text": "Dataset Description" }, { "code": null, "e": 2020, "s": 1795, "text": "The training dataset consists of 15264 (512x512 pixel) images that have been classified by an expert radiologist. The test dataset consists of 400 such images coming from the same distribution. You can find the dataset here." }, { "code": null, "e": 2757, "s": 2020, "text": "I found that the training dataset is significantly imbalanced with about 90% of the images being of the non-Covid class. The problem with significantly imbalanced sets is that even a naive learning algorithm that simply outputs the class of the majority class as the output will attain high accuracy. In other words, it will label everyone as being Covid-free and attain an ‘accuracy’ of 90% even though about 10% of the people actually have Covid. Initially, I started with the imbalanced training dataset as it is. From the benefit of hindsight, it turned out to be not the best starting point but one must start with what one has and in this case, it was the training dataset. I will describe it more in detail later in this article." }, { "code": null, "e": 2810, "s": 2757, "text": "Climbing the Performance Ladder — Steps and Missteps" }, { "code": null, "e": 3034, "s": 2810, "text": "A deep learning algorithm has many moving parts and I found that training a high-performing model is as much an art as it is math. One does not know most of the answers when starting out and has to learn by experimentation." }, { "code": null, "e": 3144, "s": 3034, "text": "I will now describe how I went about selecting each of the hyperparameters and what I learned in the process." }, { "code": null, "e": 3623, "s": 3144, "text": "Learning Rate: A lower learning rate leads to better convergence but not necessarily the best test accuracy. The issue could be that the algorithm has not yet learned the set of weights that lead to the lowest error for the test set. A higher learning rate, on the other hand, can lead to the algorithm overshooting the optimal set of weights. I experimented with learning rates of 10e-3, 10e-4, and 10e-5 and found that 10e-4 led to the lowest error rates for the test dataset." }, { "code": null, "e": 4375, "s": 3623, "text": "Batch Size: On increasing the batch size to 256 or even down to 64, I ran into memory issues and therefore had to opt for a lower batch size. I experimented with 32 and 16. Out of these two batch sizes, the batch size of 32 led to the lowest error rates with a learning rate of 10e-4. The interplay of Learning Rate, Batch Size, and Accuracy has been explored well in this paper. The authors experimented with various learning rates and batch sizes for the VGG16 CNN. I started with a lower learning rate (lr=0.0001 as aginst 0.001) that turned out to the better choice later and went with the rule of thumb of setting the batch size as 32 which is quite common in deep learning practice. I thank the authors for the leads that I got from their study." }, { "code": null, "e": 4525, "s": 4375, "text": "A complex field like Deep Learning is never a lone wolf endeavor and we all stand on the shoulders of each other, not just the giants, to look ahead." }, { "code": null, "e": 5614, "s": 4525, "text": "Pre-Trained Model: Coming to the question of which pre-trained model to use; I came across an interesting article on the Google AI Blog that compared the accuracy on the Imagenet dataset vs the number of parameters in the model for several pre-trained models. Computer Vision is a quickly evolving field and new models keep getting developed at a fast pace. Initially, I had plans to use VGG16 or Resnet50 but when I saw this article on Efficientnet, I changed my mind in the favor of Efficientnet. I have an RTX 2070 GPU and that the limitations of my hardware placed a constraint on the model that I could use. I started with the b7 version of Efficientnet but my GPU quickly gave up as the model was not fitting in its memory. After numerous Kill -9 job_number on b7,b6,b5, and b4 models(the command to delete a model from computer memory in Linux :) ), I settled with Efficientnet b3. The sole reason to do so at that point in time was that it was the largest model in the Efficientnet family that finally fit within my GPU memory. Later on, this turned out to be an excellent choice!" }, { "code": null, "e": 6030, "s": 5614, "text": "Epochs: With a model like Efficientnet b3 that has 12 Million parameters and the number of training dataset instances being in the order of tens of thousands, it is very easy to overtrain a model. In fact, I got a training accuracy of 1 while training the model with 20 Epochs! Don’t ask me the test accuracy for that case :) I used epochs ranging from 1 to 30 for various learning rate and batch size combinations." }, { "code": null, "e": 7014, "s": 6030, "text": "Sampling: I started with no sampling. Strangely, the model was classifying almost all the test cases as “1”, contrary to my expectation of “0”. I felt that the problem was that the test images were not being transformed as the training images were and the untransformed test images were somehow resembling the transformed training images of label “1” (more on this crucial topic later). I then used a weighted random sampler that led to an almost 50–50 representation of the 0 and 1 classes in the training dataset. However, it also led to the overall training dataset size reducing from ~15000 to just under ~3000. The accuracy improved but plateaued at around 0.86 with this sampling technique. Next, I oversampled from the minority class and brought the number of images from both the classes on par with each other. By doing so, my training dataset increased from 15000 to 26000. This certainly helped as I was now hitting the 90s in accuracy and I got an accuracy of about 0.94." }, { "code": null, "e": 7339, "s": 7014, "text": "Transformations- Appling the same transformations used on the training dataset to the test dataset: I was plateauing at 0.94 and others were getting accuracies of up to 0.975. This set me thinking hard about what I was missing in my model. I traced and re-traced the steps several times, while bathing, cooking, and walking." }, { "code": null, "e": 7968, "s": 7339, "text": "Suddenly, the Eureka moment came: Distribution! All machine learning rests on the assumption that the distribution of the test data is the same as that of the training data. Otherwise, what we are learning from the training dataset simply will not apply to the test dataset. By transforming the training images via rotations and translations, I was changing the distribution. However, by leaving the test images as it is, I was inadvertently applying the algorithm on a “different” distribution. I immediately applied identical transformations on the test images and lo and behold, I saw an accuracy of 0.975 for the first time!" }, { "code": null, "e": 8281, "s": 7968, "text": "Tuning: Once this insight came, all that was left to be done was tuning the hyperparameters to achieve the best possible result. I tried various epochs and found that for this dataset with the pre-trained model, learning rate, and batch size that I used, I got the best test accuracy after 11 epochs of training." }, { "code": null, "e": 8307, "s": 8281, "text": "Could have I done better?" }, { "code": null, "e": 8514, "s": 8307, "text": "Perhaps using Efficientnet-b7 coupled with a larger batch size could have led to even higher accuracy. If someone has a more powerful GPU/distributed computing system, please give it a shot and let me know." }, { "code": null, "e": 8976, "s": 8514, "text": "Practical Application: With this algorithm, a medical practitioner can identify Covid accurately in 99 out of 100 people rapidly (a matter of 40 minutes to train the algorithm on 15000 images and run it on 400 images) Taking into account only the classification time for the test images, it takes merely 1 minute for the algorithm to classify 400 images. So this can be very useful for field-staff to rapidly screen images and identify people who test positive." }, { "code": null, "e": 9085, "s": 8976, "text": "Having walked you through the algorithm discovery journey, I now move to the nuts-and-bolts aka development." }, { "code": null, "e": 9118, "s": 9085, "text": "Algorithm Development in PyTorch" }, { "code": null, "e": 9237, "s": 9118, "text": "I developed my algorithm in PyTorch which is a Machine Learning Library that is well-suited for Computer Vision tasks." }, { "code": null, "e": 9496, "s": 9237, "text": "As the first step, I imported numpy, pandas, os, torch, etc, and set the base path where the data folder is located. Then I created pandas data frames to contain the training dataset image names and their labels and the test dataset image names respectively." }, { "code": null, "e": 9755, "s": 9496, "text": "As the first step, I imported numpy, pandas, os, torch, etc, and set the base path where the data folder is located. Then I created pandas data frames to contain the training dataset image names and their labels and the test dataset image names respectively." }, { "code": null, "e": 9960, "s": 9755, "text": "2. To check whether the data frames were loaded properly, it is good to check the first few rows of train_dataset and the test_dataset. Here is the code and the resulting output from the Jupyter notebook:" }, { "code": null, "e": 10142, "s": 9960, "text": "We see that the names of the images are in the File column and the Labels are in the Label column for the training images. For the test images, we have the names in the File column." }, { "code": null, "e": 10220, "s": 10142, "text": "3. Here’s the code to view some of the images in the training dataset folder," }, { "code": null, "e": 10286, "s": 10220, "text": "This code will result in 15 X-Ray images of the type shown above." }, { "code": null, "e": 10599, "s": 10286, "text": "4. The next step is to create the training dataset out of the images and the labels in a form that Pytorch can process. Dataloader is a function in Pytorch that enables us to conveniently pair images and their labels to create a matrix/tensor that can then be used by PyTorch as an input to a learning algorithm." }, { "code": null, "e": 10643, "s": 10599, "text": "5. I then set the learning rate to be 10e-4" }, { "code": null, "e": 10877, "s": 10643, "text": "6. Next, I prepared the training set using the Dataset dataloader class that I created in step 4. I named it as training_set_untransformed as I have not yet applied the data transformations like rotation or translation to the images." }, { "code": null, "e": 11092, "s": 10877, "text": "7. I then created a transforms.Compose method to resize the images, randomly apply rotation and horizontal translation and convert the resulting matrix to a tensor. Such a transform is useful for data augmentation." }, { "code": null, "e": 11339, "s": 11092, "text": "8. The next step is to use the transforms method on the training dataset. For the images in the minority class (covid cases), I have upsampled them so that the number of images in both the classes are the same after the transformation is applied." }, { "code": null, "e": 11436, "s": 11339, "text": "9. I then split these newly created images into training and validation sets in the 80:20 ratio." }, { "code": null, "e": 11630, "s": 11436, "text": "10. Using the Dataloader function of Pytorch, I created batches of 32 each from the training dataset and shuffled them to ensure roughly equal representation of both classes in all the batches." }, { "code": null, "e": 11774, "s": 11630, "text": "11. To enable GPU computation, I used the cuda.is_available() command. The Deep Learning code can also run on a CPU but would take much longer." }, { "code": null, "e": 11882, "s": 11774, "text": "12. The following is the command to import Efficientnet-b3 from Pytorch and set the number of classes to 2." }, { "code": null, "e": 12182, "s": 11882, "text": "13. After importing, the model has to be loaded to the memory of the GPU. If your model is too big for the GPU memory, you will get an error message and would need to select another model that will fit into the memory. Run the command on a Jupyter notebook and admire the complexity of Efficientnet!" }, { "code": null, "e": 12411, "s": 12182, "text": "14. It is good to save the weights generated by the training process periodically. In case if the model crashes due to some reason, we can call the saved weights and resume training instead of having to start from scratch again." }, { "code": null, "e": 12933, "s": 12411, "text": "15. I used the cross-entropy loss as the criterion for loss calculation as we are dealing with a classification problem. I used the Adam optimizer, which is a well-known weight update method for deep learning, and set the number of epochs to 11 (this learning came after a lot of experimentation). Learning rate decay is a parameter used to update the learning rate after each epoch and I set a conservative decay rate of 0.99 as the learning rate is already low. I created two lists to track accuracy and loss histories." }, { "code": null, "e": 13128, "s": 12933, "text": "16. Training the model: Here’s the training part of the code. I ran the model for 11 epochs and saved the 1st, 10th, and final (11th) versions of the model. It took about 40 minutes to train it." }, { "code": null, "e": 13334, "s": 13128, "text": "At the end of the 11th Epoch, I got an accuracy of 99% on the training dataset for both classes. Accuracy of 0: 99 %Accuracy of 1: 99 %[11 epoch] Accuracy of the network on the Training images: 99 " }, { "code": null, "e": 13526, "s": 13334, "text": "17. Here is a plot of the training accuracy and cross-entropy loss over iterations. There are 7227 batch iterations and the plot shows how these values are changing over the batch iterations." }, { "code": null, "e": 13677, "s": 13526, "text": "18. The next step is to apply the transforms. Compose to the test dataset as well to make it conform to the same distribution as the training dataset." }, { "code": null, "e": 13762, "s": 13677, "text": "19. To predict the class of test images, we need to define a predict_image function:" }, { "code": null, "e": 13855, "s": 13762, "text": "20. The following code snippet checks how well the model is doing on the validation dataset." }, { "code": null, "e": 13966, "s": 13855, "text": "21. With the following lines, one can predict the classes of the test set images and store them in a csv file." }, { "code": null, "e": 13977, "s": 13966, "text": "Conclusion" }, { "code": null, "e": 14417, "s": 13977, "text": "Through this Kaggle Competition, I learned that conceiving and developing a Deep Learning Algorithm takes some patience and we must continuously keep looking for chinks in the model as well as the discoveries that others have made to make our models better. My article is a small way of paying it forward to the Machine Learning community so that we can share and learn together and improve our algorithms to solve problems in better ways!" }, { "code": null, "e": 14506, "s": 14417, "text": "Hope you could learn something useful from my post. Please share your valuable feedback!" } ]
Program to find the common ratio of three numbers - GeeksforGeeks
01 Apr, 2021 Given a:b and b:c. The task is to write a program to find ratio a:b:cExamples: Input: a:b = 2:3, b:c = 3:4 Output: 2:3:4 Input: a:b = 3:4, b:c = 8:9 Output: 6:8:9 Approach: The trick is to make the common term ‘b’ equal in both ratios. Therefore, multiply the first ratio by b2 (b term of second ratio) and the second ratio by b1. Given: a:b1 and b2:c Solution: a:b:c = (a*b2):(b1*b2):(c*b1)For example: If a : b = 5 : 9 and b : c = 7 : 4, then find a : b : c.Solution: Here, Make the common term ‘b’ equal in both ratios. Therefore, multiply the first ratio by 7 and the second ratio by 9. So, a : b = 35 : 63 and b : c = 63 : 36 Thus, a : b : c = 35 : 63 : 36 Below is the implementation of the above approach: C++ Java Python 3 C# PHP Javascript // C++ implementation of above approach#include <bits/stdc++.h>using namespace std; // Function to print a:b:cvoid solveProportion(int a, int b1, int b2, int c){ int A = a * b2; int B = b1 * b2; int C = b1 * c; // To print the given proportion // in simplest form. int gcd = __gcd(__gcd(A, B), C); cout << A / gcd << ":" << B / gcd << ":" << C / gcd;} // Driver codeint main(){ // Get the ratios int a, b1, b2, c; // Get ratio a:b1 a = 3; b1 = 4; // Get ratio b2:c b2 = 8; c = 9; // Find the ratio a:b:c solveProportion(a, b1, b2, c); return 0;} // Java implementation of above approach import java.util.*;import java.lang.*;import java.io.*;class GFG{ static int __gcd(int a,int b){ return b==0 ? a : __gcd(b, a%b);} // Function to print a:b:cstatic void solveProportion(int a, int b1, int b2, int c){ int A = a * b2; int B = b1 * b2; int C = b1 * c; // To print the given proportion // in simplest form. int gcd = __gcd(__gcd(A, B), C); System.out.print( A / gcd + ":" + B / gcd + ":" + C / gcd);} // Driver codepublic static void main(String args[]){ // Get the ratios int a, b1, b2, c; // Get ratio a:b1 a = 3; b1 = 4; // Get ratio b2:c b2 = 8; c = 9; // Find the ratio a:b:c solveProportion(a, b1, b2, c);}} # Python 3 implementation# of above approachimport math # Function to print a:b:cdef solveProportion(a, b1, b2, c): A = a * b2 B = b1 * b2 C = b1 * c # To print the given proportion # in simplest form. gcd1 = math.gcd(math.gcd(A, B), C) print( str(A // gcd1) + ":" + str(B // gcd1) + ":" + str(C // gcd1)) # Driver codeif __name__ == "__main__": # Get ratio a:b1 a = 3 b1 = 4 # Get ratio b2:c b2 = 8 c = 9 # Find the ratio a:b:c solveProportion(a, b1, b2, c) # This code is contributed# by ChitraNayal // C# implementation of above approachusing System; class GFG{static int __gcd(int a,int b){ return b == 0 ? a : __gcd(b, a % b);} // Function to print a:b:cstatic void solveProportion(int a, int b1, int b2, int c){ int A = a * b2; int B = b1 * b2; int C = b1 * c; // To print the given proportion // in simplest form. int gcd = __gcd(__gcd(A, B), C); Console.Write( A / gcd + ":" + B / gcd + ":" + C / gcd);} // Driver codepublic static void Main(){ // Get the ratios int a, b1, b2, c; // Get ratio a:b1 a = 3; b1 = 4; // Get ratio b2:c b2 = 8; c = 9; // Find the ratio a:b:c solveProportion(a, b1, b2, c);}} // This code is contributed// by Akanksha Rai(Abby_akku) <?php// PHP implementation of above approach function __gcd($a, $b){ return $b == 0 ? $a : __gcd($b, $a % $b);} // Function to print a:b:cfunction solveProportion($a, $b1, $b2, $c){ $A = $a * $b2; $B = $b1 * $b2; $C = $b1 * $c; // To print the given proportion // in simplest form. $gcd = __gcd(__gcd($A, $B), $C); echo ($A / $gcd) . ":" . ($B / $gcd) . ":" . ($C / $gcd);} // Driver code // Get the ratios// Get ratio a:b1$a = 3;$b1 = 4; // Get ratio b2:c$b2 = 8;$c = 9; // Find the ratio a:b:csolveProportion($a, $b1, $b2, $c); // This code is contributed by mits?> <script> // Javascript implementation of above approach function __gcd(a, b) { return b == 0 ? a : __gcd(b, a % b); } // Function to print a:b:c function solveProportion(a, b1, b2, c) { let A = a * b2; let B = b1 * b2; let C = b1 * c; // To print the given proportion // in simplest form. let gcd = __gcd(__gcd(A, B), C); document.write( A / gcd + ":" + B / gcd + ":" + C / gcd); } // Get the ratios let a, b1, b2, c; // Get ratio a:b1 a = 3; b1 = 4; // Get ratio b2:c b2 = 8; c = 9; // Find the ratio a:b:c solveProportion(a, b1, b2, c); // This code is contributed by divyeshrabadiya07.</script> 6:8:9 tufan_gupta2000 Akanksha_Rai ukasp Mithun Kumar divyeshrabadiya07 Ratio and Proportion Technical Scripter 2018 Mathematical School Programming Mathematical 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 Program for factorial of a number Python Dictionary Arrays in C/C++ Inheritance in C++ Reverse a string in Java Interfaces in Java
[ { "code": null, "e": 24738, "s": 24710, "text": "\n01 Apr, 2021" }, { "code": null, "e": 24819, "s": 24738, "text": "Given a:b and b:c. The task is to write a program to find ratio a:b:cExamples: " }, { "code": null, "e": 24905, "s": 24819, "text": "Input: a:b = 2:3, b:c = 3:4\nOutput: 2:3:4\n\nInput: a:b = 3:4, b:c = 8:9\nOutput: 6:8:9" }, { "code": null, "e": 25076, "s": 24907, "text": "Approach: The trick is to make the common term ‘b’ equal in both ratios. Therefore, multiply the first ratio by b2 (b term of second ratio) and the second ratio by b1. " }, { "code": null, "e": 25407, "s": 25076, "text": "Given: a:b1 and b2:c Solution: a:b:c = (a*b2):(b1*b2):(c*b1)For example: If a : b = 5 : 9 and b : c = 7 : 4, then find a : b : c.Solution: Here, Make the common term ‘b’ equal in both ratios. Therefore, multiply the first ratio by 7 and the second ratio by 9. So, a : b = 35 : 63 and b : c = 63 : 36 Thus, a : b : c = 35 : 63 : 36" }, { "code": null, "e": 25460, "s": 25407, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 25464, "s": 25460, "text": "C++" }, { "code": null, "e": 25469, "s": 25464, "text": "Java" }, { "code": null, "e": 25478, "s": 25469, "text": "Python 3" }, { "code": null, "e": 25481, "s": 25478, "text": "C#" }, { "code": null, "e": 25485, "s": 25481, "text": "PHP" }, { "code": null, "e": 25496, "s": 25485, "text": "Javascript" }, { "code": "// C++ implementation of above approach#include <bits/stdc++.h>using namespace std; // Function to print a:b:cvoid solveProportion(int a, int b1, int b2, int c){ int A = a * b2; int B = b1 * b2; int C = b1 * c; // To print the given proportion // in simplest form. int gcd = __gcd(__gcd(A, B), C); cout << A / gcd << \":\" << B / gcd << \":\" << C / gcd;} // Driver codeint main(){ // Get the ratios int a, b1, b2, c; // Get ratio a:b1 a = 3; b1 = 4; // Get ratio b2:c b2 = 8; c = 9; // Find the ratio a:b:c solveProportion(a, b1, b2, c); return 0;}", "e": 26119, "s": 25496, "text": null }, { "code": "// Java implementation of above approach import java.util.*;import java.lang.*;import java.io.*;class GFG{ static int __gcd(int a,int b){ return b==0 ? a : __gcd(b, a%b);} // Function to print a:b:cstatic void solveProportion(int a, int b1, int b2, int c){ int A = a * b2; int B = b1 * b2; int C = b1 * c; // To print the given proportion // in simplest form. int gcd = __gcd(__gcd(A, B), C); System.out.print( A / gcd + \":\" + B / gcd + \":\" + C / gcd);} // Driver codepublic static void main(String args[]){ // Get the ratios int a, b1, b2, c; // Get ratio a:b1 a = 3; b1 = 4; // Get ratio b2:c b2 = 8; c = 9; // Find the ratio a:b:c solveProportion(a, b1, b2, c);}}", "e": 26873, "s": 26119, "text": null }, { "code": "# Python 3 implementation# of above approachimport math # Function to print a:b:cdef solveProportion(a, b1, b2, c): A = a * b2 B = b1 * b2 C = b1 * c # To print the given proportion # in simplest form. gcd1 = math.gcd(math.gcd(A, B), C) print( str(A // gcd1) + \":\" + str(B // gcd1) + \":\" + str(C // gcd1)) # Driver codeif __name__ == \"__main__\": # Get ratio a:b1 a = 3 b1 = 4 # Get ratio b2:c b2 = 8 c = 9 # Find the ratio a:b:c solveProportion(a, b1, b2, c) # This code is contributed# by ChitraNayal", "e": 27446, "s": 26873, "text": null }, { "code": "// C# implementation of above approachusing System; class GFG{static int __gcd(int a,int b){ return b == 0 ? a : __gcd(b, a % b);} // Function to print a:b:cstatic void solveProportion(int a, int b1, int b2, int c){ int A = a * b2; int B = b1 * b2; int C = b1 * c; // To print the given proportion // in simplest form. int gcd = __gcd(__gcd(A, B), C); Console.Write( A / gcd + \":\" + B / gcd + \":\" + C / gcd);} // Driver codepublic static void Main(){ // Get the ratios int a, b1, b2, c; // Get ratio a:b1 a = 3; b1 = 4; // Get ratio b2:c b2 = 8; c = 9; // Find the ratio a:b:c solveProportion(a, b1, b2, c);}} // This code is contributed// by Akanksha Rai(Abby_akku)", "e": 28236, "s": 27446, "text": null }, { "code": "<?php// PHP implementation of above approach function __gcd($a, $b){ return $b == 0 ? $a : __gcd($b, $a % $b);} // Function to print a:b:cfunction solveProportion($a, $b1, $b2, $c){ $A = $a * $b2; $B = $b1 * $b2; $C = $b1 * $c; // To print the given proportion // in simplest form. $gcd = __gcd(__gcd($A, $B), $C); echo ($A / $gcd) . \":\" . ($B / $gcd) . \":\" . ($C / $gcd);} // Driver code // Get the ratios// Get ratio a:b1$a = 3;$b1 = 4; // Get ratio b2:c$b2 = 8;$c = 9; // Find the ratio a:b:csolveProportion($a, $b1, $b2, $c); // This code is contributed by mits?>", "e": 28838, "s": 28236, "text": null }, { "code": "<script> // Javascript implementation of above approach function __gcd(a, b) { return b == 0 ? a : __gcd(b, a % b); } // Function to print a:b:c function solveProportion(a, b1, b2, c) { let A = a * b2; let B = b1 * b2; let C = b1 * c; // To print the given proportion // in simplest form. let gcd = __gcd(__gcd(A, B), C); document.write( A / gcd + \":\" + B / gcd + \":\" + C / gcd); } // Get the ratios let a, b1, b2, c; // Get ratio a:b1 a = 3; b1 = 4; // Get ratio b2:c b2 = 8; c = 9; // Find the ratio a:b:c solveProportion(a, b1, b2, c); // This code is contributed by divyeshrabadiya07.</script>", "e": 29572, "s": 28838, "text": null }, { "code": null, "e": 29578, "s": 29572, "text": "6:8:9" }, { "code": null, "e": 29596, "s": 29580, "text": "tufan_gupta2000" }, { "code": null, "e": 29609, "s": 29596, "text": "Akanksha_Rai" }, { "code": null, "e": 29615, "s": 29609, "text": "ukasp" }, { "code": null, "e": 29628, "s": 29615, "text": "Mithun Kumar" }, { "code": null, "e": 29646, "s": 29628, "text": "divyeshrabadiya07" }, { "code": null, "e": 29667, "s": 29646, "text": "Ratio and Proportion" }, { "code": null, "e": 29691, "s": 29667, "text": "Technical Scripter 2018" }, { "code": null, "e": 29704, "s": 29691, "text": "Mathematical" }, { "code": null, "e": 29723, "s": 29704, "text": "School Programming" }, { "code": null, "e": 29736, "s": 29723, "text": "Mathematical" }, { "code": null, "e": 29834, "s": 29736, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29843, "s": 29834, "text": "Comments" }, { "code": null, "e": 29856, "s": 29843, "text": "Old Comments" }, { "code": null, "e": 29880, "s": 29856, "text": "Merge two sorted arrays" }, { "code": null, "e": 29923, "s": 29880, "text": "Modulo Operator (%) in C/C++ with Examples" }, { "code": null, "e": 29937, "s": 29923, "text": "Prime Numbers" }, { "code": null, "e": 29986, "s": 29937, "text": "Program to find sum of elements in a given array" }, { "code": null, "e": 30020, "s": 29986, "text": "Program for factorial of a number" }, { "code": null, "e": 30038, "s": 30020, "text": "Python Dictionary" }, { "code": null, "e": 30054, "s": 30038, "text": "Arrays in C/C++" }, { "code": null, "e": 30073, "s": 30054, "text": "Inheritance in C++" }, { "code": null, "e": 30098, "s": 30073, "text": "Reverse a string in Java" } ]
Integrate Angular 7 with ElectronJS - GeeksforGeeks
17 May, 2020 ElectronJS is an Open Source Framework used for building Cross-Platform native desktop applications using web technologies such as HTML, CSS, and JavaScript which are capable of running on Windows, macOS, and Linux operating systems. It combines the Chromium engine and NodeJS into a Single Runtime. Electron can be combined with several powerful frameworks such as Angular 4+, AngularJS 1.x, React, etc for building complex applications and providing enhanced functionality. Electron at its core is a NodeJS application which can interact with the native OS environment. With NodeJS integration we can access several low-level APIs which otherwise would not be accessible in a Sandbox Browser environment. With Angular integration, we gain access to several advantages and features such as MVC (Model-View-Controller) architecture, modules and custom directives. This tutorial will demonstrate how to integrate Angular 7 with ElectronJS and also access the Electron APIs from within Angular. We assume you are familiar with the prerequisites as covered in the above-mentioned link. For Electron and Angular to work, node and npm need to be pre-installed in the system. Note: This tutorial is applicable to work with Angular 5+ versions as well. Example: Follow the given steps to integrate Angular 7 with Electron. Step 1: Navigate to an Empty Directory to set up the project, and run the following command,npm install -g @angular/cliTo install the Angular CLI globally. The Angular CLI tool is used to create projects, perform tasks such as testing and deployment, and generate various components of the code. Create a new Angular project by running the following command and provide the project name of your choosing,ng new ang-electronThis command prompts you to provide information about features to include in the project. Choose the appropriate by pressing the Enter key.This will also install the required Angular dependencies and packages into node_modules. Once done, Install Electron using npm and save it as a dev-dependency.npm install electron --save-devAt this point, the Angular application is ready and can be served locally. To serve the application on localhost, run the following commands,cd ang-electron ng serve npm install -g @angular/cli To install the Angular CLI globally. The Angular CLI tool is used to create projects, perform tasks such as testing and deployment, and generate various components of the code. Create a new Angular project by running the following command and provide the project name of your choosing, ng new ang-electron This command prompts you to provide information about features to include in the project. Choose the appropriate by pressing the Enter key. This will also install the required Angular dependencies and packages into node_modules. Once done, Install Electron using npm and save it as a dev-dependency. npm install electron --save-dev At this point, the Angular application is ready and can be served locally. To serve the application on localhost, run the following commands, cd ang-electron ng serve Step 2: We will connect both the frameworks via code to launch the Electron application and make it use Angular. As with any Electron project, we need to create an entry point into the application. Create the main.js file in our base project folder. This file is going to be our entry point into the application.main.js:const { app, BrowserWindow } = require('electron') function createWindow () { // Create the browser window. const win = new BrowserWindow({ width: 800, height: 600, webPreferences: { nodeIntegration: true } }) // Load the index.html of the app // From the dist folder which is created // After running the build command win.loadFile('dist/ang-electron/index.html') // Open the DevTools. win.webContents.openDevTools()} // This method will be called when Electron has finished// initialization and is ready to create browser windows.// Some APIs can only be used after this event occurs.// This method is equivalent to 'app.on('ready', function())'app.whenReady().then(createWindow) // Quit when all windows are closed.app.on('window-all-closed', () => { // On macOS it is common for applications and their // menu bar to stay active until the user quits // explicitly with Cmd + Q if (process.platform !== 'darwin') { app.quit() }}) app.on('activate', () => { // On macOS it's common to re-create a window in the // app when the dock icon is clicked and there are // no other windows open. if (BrowserWindow.getAllWindows().length === 0) { createWindow() }}) // In this file, you can include the rest of your app's // specific main process code. You can also put them in // separate files and require them here.For the Boilerplate code of the main.js file, Refer this link. We have modified the code to suit our project needs. Once we run the build command, it is going to create a distribution of our angular project in the dist folder. We are going to refer the index.html file from this folder. main.js: const { app, BrowserWindow } = require('electron') function createWindow () { // Create the browser window. const win = new BrowserWindow({ width: 800, height: 600, webPreferences: { nodeIntegration: true } }) // Load the index.html of the app // From the dist folder which is created // After running the build command win.loadFile('dist/ang-electron/index.html') // Open the DevTools. win.webContents.openDevTools()} // This method will be called when Electron has finished// initialization and is ready to create browser windows.// Some APIs can only be used after this event occurs.// This method is equivalent to 'app.on('ready', function())'app.whenReady().then(createWindow) // Quit when all windows are closed.app.on('window-all-closed', () => { // On macOS it is common for applications and their // menu bar to stay active until the user quits // explicitly with Cmd + Q if (process.platform !== 'darwin') { app.quit() }}) app.on('activate', () => { // On macOS it's common to re-create a window in the // app when the dock icon is clicked and there are // no other windows open. if (BrowserWindow.getAllWindows().length === 0) { createWindow() }}) // In this file, you can include the rest of your app's // specific main process code. You can also put them in // separate files and require them here. For the Boilerplate code of the main.js file, Refer this link. We have modified the code to suit our project needs. Once we run the build command, it is going to create a distribution of our angular project in the dist folder. We are going to refer the index.html file from this folder. Step 3: A small change is required in the index.html file located in the src folder. Replace the following code.<base href="/">with<'base href="./">This change is important otherwise it won’t be able to find and refer the necessary files required to run the application from dist folder. We also need to make a few changes to the package.json file.package.json:{ "name": "ang-electron", "version": "0.0.0", "main": "main.js", "scripts": { "ng": "ng", "start": "ng serve", "build": "ng build", "test": "ng test", "lint": "ng lint", "e2e": "ng e2e", "electron": "ng build && electron ." }, // ... We have specified the main.js file as required by Electron. We have also introduced a new custom electron command in the scripts tag for building and launching the application. The ng build command is used for building the Angular application and deploying the build artifacts. It writes generated build artifacts to the output folder. By default, the output folder is dist/.Output: Once the respective changes are done, we are ready to launch the Electron application. To launch the application, run the command,npm run electron <base href="/"> with <'base href="./"> This change is important otherwise it won’t be able to find and refer the necessary files required to run the application from dist folder. We also need to make a few changes to the package.json file. package.json: { "name": "ang-electron", "version": "0.0.0", "main": "main.js", "scripts": { "ng": "ng", "start": "ng serve", "build": "ng build", "test": "ng test", "lint": "ng lint", "e2e": "ng e2e", "electron": "ng build && electron ." }, // ... We have specified the main.js file as required by Electron. We have also introduced a new custom electron command in the scripts tag for building and launching the application. The ng build command is used for building the Angular application and deploying the build artifacts. It writes generated build artifacts to the output folder. By default, the output folder is dist/. Output: Once the respective changes are done, we are ready to launch the Electron application. To launch the application, run the command, npm run electron Step 4: At this point, we have successfully integrated Angular with Electron. To use the Electron APIs within Angular, we can follow any of the two approaches:Approach 1: Using an external package to access the Electron APIs. We will use the ngx-electron npm package for this purpose. We can use this package as a simple Angular Service to access Electron APIs. For more detailed Information, Refer this link. To install this package, run the following command:npm install ngx-electron --saveOnce it is successfully installed, we will import it in our app.module.ts file for it to be used throughout the application.app.module.ts:import { BrowserModule } from '@angular/platform-browser';import { NgModule } from '@angular/core';import { AppRoutingModule } from './app-routing.module';import { AppComponent } from './app.component';import { NgxElectronModule } from 'ngx-electron'; @NgModule({ declarations: [ AppComponent ], imports: [ BrowserModule, AppRoutingModule, NgxElectronModule ], providers: [], bootstrap: [AppComponent]})export class AppModule { }For the list of Electron APIs supported by this package, Refer to this https://www.npmjs.com/package/ngx-electron#properties. We will use the Electron shell API from the ngx-electron package.app.component.html:<div style="text-align:center"> <h1> Welcome to {{ title }}! </h1></div> <button (click)="openWindow()"> Click here to Access GeeksForGeeks</button> <router-outlet></router-outlet>The Click here to Access GeeksForGeeks button does not have any functionality associated with it. To change this, make the following changes to the app.component.ts file.app.component.ts:import { Component } from '@angular/core';import { ElectronService } from 'ngx-electron'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css']})export class AppComponent { title = 'ang-electron'; constructor(private electronService: ElectronService) {} openWindow() { // Accessing the Shell API from ngx-electron this.electronService .shell.openExternal('https://www.geeksforgeeks.org/'); }}The ElectronService exposes all Electron APIs accessible from within the Renderer Process. We will create an Instance of the ElectronService in the constructor through Dependency Injection.Output:Approach 2: By creating an Electron Service component and sharing it across the application for using the Electron APIs. We will generate the Electron Service by running the following CLI command:ng generate service elec --skipTests=trueThe –skipTests=true does not create the spec.ts Test files for new services. This command will generate a new elec.service.ts file within the src/app folder. In this file, we will declare and add all Electron Imports which can then be used throughout the application. We will use the Electron shell API from the Main Process.elec.service.ts:import { Injectable } from '@angular/core';import { shell } from 'electron'; @Injectable({ providedIn: 'root'})export class ElecService { shell: typeof shell; constructor() { this.shell = (<any>window).require("electron").shell; }}The any keyword is for Type Assertion on the window object. Converting this Object using any indicates that you are no longer bound by the compiler to the default properties of the window object. This is used to prevent compile-time type errors when using Electron modules. If type-casting is ignored on the windows object, we will receive the following error:ERROR in ./node_modules/electron/index.js Module not found: Error: Can't resolve 'fs'The typeof operator returns the data type of its operand in the form of a string. In this case, the operand is the shell module of Electron. Using this approach gives us access to all Electron APIs throughout the Application. To use this service, add the following to the app.component.ts file.app.component.ts:import { Component } from '@angular/core';import { ElectronService } from 'ngx-electron';import { ElecService } from '../app/elec.service'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css']})export class AppComponent { title = 'ang-electron'; // Creating Instances through Dependency Injection constructor(private electronService: ElectronService, private elecService: ElecService) {} openWindow() { // Accessing the Shell API from ngx-electron // this.electronService // .shell.openExternal('https://www.geeksforgeeks.org/'); // Accessing the Shell API from ElecService this.elecService.shell .openExternal('https://www.geeksforgeeks.org/'); }}Output: Approach 1: Using an external package to access the Electron APIs. We will use the ngx-electron npm package for this purpose. We can use this package as a simple Angular Service to access Electron APIs. For more detailed Information, Refer this link. To install this package, run the following command:npm install ngx-electron --saveOnce it is successfully installed, we will import it in our app.module.ts file for it to be used throughout the application.app.module.ts:import { BrowserModule } from '@angular/platform-browser';import { NgModule } from '@angular/core';import { AppRoutingModule } from './app-routing.module';import { AppComponent } from './app.component';import { NgxElectronModule } from 'ngx-electron'; @NgModule({ declarations: [ AppComponent ], imports: [ BrowserModule, AppRoutingModule, NgxElectronModule ], providers: [], bootstrap: [AppComponent]})export class AppModule { }For the list of Electron APIs supported by this package, Refer to this https://www.npmjs.com/package/ngx-electron#properties. We will use the Electron shell API from the ngx-electron package.app.component.html:<div style="text-align:center"> <h1> Welcome to {{ title }}! </h1></div> <button (click)="openWindow()"> Click here to Access GeeksForGeeks</button> <router-outlet></router-outlet>The Click here to Access GeeksForGeeks button does not have any functionality associated with it. To change this, make the following changes to the app.component.ts file.app.component.ts:import { Component } from '@angular/core';import { ElectronService } from 'ngx-electron'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css']})export class AppComponent { title = 'ang-electron'; constructor(private electronService: ElectronService) {} openWindow() { // Accessing the Shell API from ngx-electron this.electronService .shell.openExternal('https://www.geeksforgeeks.org/'); }}The ElectronService exposes all Electron APIs accessible from within the Renderer Process. We will create an Instance of the ElectronService in the constructor through Dependency Injection.Output: npm install ngx-electron --save Once it is successfully installed, we will import it in our app.module.ts file for it to be used throughout the application. app.module.ts: import { BrowserModule } from '@angular/platform-browser';import { NgModule } from '@angular/core';import { AppRoutingModule } from './app-routing.module';import { AppComponent } from './app.component';import { NgxElectronModule } from 'ngx-electron'; @NgModule({ declarations: [ AppComponent ], imports: [ BrowserModule, AppRoutingModule, NgxElectronModule ], providers: [], bootstrap: [AppComponent]})export class AppModule { } For the list of Electron APIs supported by this package, Refer to this https://www.npmjs.com/package/ngx-electron#properties. We will use the Electron shell API from the ngx-electron package. app.component.html: <div style="text-align:center"> <h1> Welcome to {{ title }}! </h1></div> <button (click)="openWindow()"> Click here to Access GeeksForGeeks</button> <router-outlet></router-outlet> The Click here to Access GeeksForGeeks button does not have any functionality associated with it. To change this, make the following changes to the app.component.ts file. app.component.ts: import { Component } from '@angular/core';import { ElectronService } from 'ngx-electron'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css']})export class AppComponent { title = 'ang-electron'; constructor(private electronService: ElectronService) {} openWindow() { // Accessing the Shell API from ngx-electron this.electronService .shell.openExternal('https://www.geeksforgeeks.org/'); }} The ElectronService exposes all Electron APIs accessible from within the Renderer Process. We will create an Instance of the ElectronService in the constructor through Dependency Injection. Output: Approach 2: By creating an Electron Service component and sharing it across the application for using the Electron APIs. We will generate the Electron Service by running the following CLI command:ng generate service elec --skipTests=trueThe –skipTests=true does not create the spec.ts Test files for new services. This command will generate a new elec.service.ts file within the src/app folder. In this file, we will declare and add all Electron Imports which can then be used throughout the application. We will use the Electron shell API from the Main Process.elec.service.ts:import { Injectable } from '@angular/core';import { shell } from 'electron'; @Injectable({ providedIn: 'root'})export class ElecService { shell: typeof shell; constructor() { this.shell = (<any>window).require("electron").shell; }}The any keyword is for Type Assertion on the window object. Converting this Object using any indicates that you are no longer bound by the compiler to the default properties of the window object. This is used to prevent compile-time type errors when using Electron modules. If type-casting is ignored on the windows object, we will receive the following error:ERROR in ./node_modules/electron/index.js Module not found: Error: Can't resolve 'fs'The typeof operator returns the data type of its operand in the form of a string. In this case, the operand is the shell module of Electron. Using this approach gives us access to all Electron APIs throughout the Application. To use this service, add the following to the app.component.ts file.app.component.ts:import { Component } from '@angular/core';import { ElectronService } from 'ngx-electron';import { ElecService } from '../app/elec.service'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css']})export class AppComponent { title = 'ang-electron'; // Creating Instances through Dependency Injection constructor(private electronService: ElectronService, private elecService: ElecService) {} openWindow() { // Accessing the Shell API from ngx-electron // this.electronService // .shell.openExternal('https://www.geeksforgeeks.org/'); // Accessing the Shell API from ElecService this.elecService.shell .openExternal('https://www.geeksforgeeks.org/'); }}Output: ng generate service elec --skipTests=true The –skipTests=true does not create the spec.ts Test files for new services. This command will generate a new elec.service.ts file within the src/app folder. In this file, we will declare and add all Electron Imports which can then be used throughout the application. We will use the Electron shell API from the Main Process. elec.service.ts: import { Injectable } from '@angular/core';import { shell } from 'electron'; @Injectable({ providedIn: 'root'})export class ElecService { shell: typeof shell; constructor() { this.shell = (<any>window).require("electron").shell; }} The any keyword is for Type Assertion on the window object. Converting this Object using any indicates that you are no longer bound by the compiler to the default properties of the window object. This is used to prevent compile-time type errors when using Electron modules. If type-casting is ignored on the windows object, we will receive the following error: ERROR in ./node_modules/electron/index.js Module not found: Error: Can't resolve 'fs' The typeof operator returns the data type of its operand in the form of a string. In this case, the operand is the shell module of Electron. Using this approach gives us access to all Electron APIs throughout the Application. To use this service, add the following to the app.component.ts file. app.component.ts: import { Component } from '@angular/core';import { ElectronService } from 'ngx-electron';import { ElecService } from '../app/elec.service'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css']})export class AppComponent { title = 'ang-electron'; // Creating Instances through Dependency Injection constructor(private electronService: ElectronService, private elecService: ElecService) {} openWindow() { // Accessing the Shell API from ngx-electron // this.electronService // .shell.openExternal('https://www.geeksforgeeks.org/'); // Accessing the Shell API from ElecService this.elecService.shell .openExternal('https://www.geeksforgeeks.org/'); }} Output: AngularJS-Misc ElectronJS AngularJS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Angular PrimeNG Dropdown Component Auth Guards in Angular 9/10/11 Angular PrimeNG Calendar Component Angular PrimeNG Messages Component How to bundle an Angular app for production? Remove elements from a JavaScript Array Installation of Node.js on Linux Convert a string to an integer in JavaScript How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 25668, "s": 25640, "text": "\n17 May, 2020" }, { "code": null, "e": 25968, "s": 25668, "text": "ElectronJS is an Open Source Framework used for building Cross-Platform native desktop applications using web technologies such as HTML, CSS, and JavaScript which are capable of running on Windows, macOS, and Linux operating systems. It combines the Chromium engine and NodeJS into a Single Runtime." }, { "code": null, "e": 26661, "s": 25968, "text": "Electron can be combined with several powerful frameworks such as Angular 4+, AngularJS 1.x, React, etc for building complex applications and providing enhanced functionality. Electron at its core is a NodeJS application which can interact with the native OS environment. With NodeJS integration we can access several low-level APIs which otherwise would not be accessible in a Sandbox Browser environment. With Angular integration, we gain access to several advantages and features such as MVC (Model-View-Controller) architecture, modules and custom directives. This tutorial will demonstrate how to integrate Angular 7 with ElectronJS and also access the Electron APIs from within Angular." }, { "code": null, "e": 26838, "s": 26661, "text": "We assume you are familiar with the prerequisites as covered in the above-mentioned link. For Electron and Angular to work, node and npm need to be pre-installed in the system." }, { "code": null, "e": 26914, "s": 26838, "text": "Note: This tutorial is applicable to work with Angular 5+ versions as well." }, { "code": null, "e": 26984, "s": 26914, "text": "Example: Follow the given steps to integrate Angular 7 with Electron." }, { "code": null, "e": 27902, "s": 26984, "text": "Step 1: Navigate to an Empty Directory to set up the project, and run the following command,npm install -g @angular/cliTo install the Angular CLI globally. The Angular CLI tool is used to create projects, perform tasks such as testing and deployment, and generate various components of the code. Create a new Angular project by running the following command and provide the project name of your choosing,ng new ang-electronThis command prompts you to provide information about features to include in the project. Choose the appropriate by pressing the Enter key.This will also install the required Angular dependencies and packages into node_modules. Once done, Install Electron using npm and save it as a dev-dependency.npm install electron --save-devAt this point, the Angular application is ready and can be served locally. To serve the application on localhost, run the following commands,cd ang-electron\nng serve" }, { "code": null, "e": 27930, "s": 27902, "text": "npm install -g @angular/cli" }, { "code": null, "e": 28216, "s": 27930, "text": "To install the Angular CLI globally. The Angular CLI tool is used to create projects, perform tasks such as testing and deployment, and generate various components of the code. Create a new Angular project by running the following command and provide the project name of your choosing," }, { "code": null, "e": 28236, "s": 28216, "text": "ng new ang-electron" }, { "code": null, "e": 28376, "s": 28236, "text": "This command prompts you to provide information about features to include in the project. Choose the appropriate by pressing the Enter key." }, { "code": null, "e": 28536, "s": 28376, "text": "This will also install the required Angular dependencies and packages into node_modules. Once done, Install Electron using npm and save it as a dev-dependency." }, { "code": null, "e": 28568, "s": 28536, "text": "npm install electron --save-dev" }, { "code": null, "e": 28710, "s": 28568, "text": "At this point, the Angular application is ready and can be served locally. To serve the application on localhost, run the following commands," }, { "code": null, "e": 28735, "s": 28710, "text": "cd ang-electron\nng serve" }, { "code": null, "e": 30708, "s": 28735, "text": "Step 2: We will connect both the frameworks via code to launch the Electron application and make it use Angular. As with any Electron project, we need to create an entry point into the application. Create the main.js file in our base project folder. This file is going to be our entry point into the application.main.js:const { app, BrowserWindow } = require('electron') function createWindow () { // Create the browser window. const win = new BrowserWindow({ width: 800, height: 600, webPreferences: { nodeIntegration: true } }) // Load the index.html of the app // From the dist folder which is created // After running the build command win.loadFile('dist/ang-electron/index.html') // Open the DevTools. win.webContents.openDevTools()} // This method will be called when Electron has finished// initialization and is ready to create browser windows.// Some APIs can only be used after this event occurs.// This method is equivalent to 'app.on('ready', function())'app.whenReady().then(createWindow) // Quit when all windows are closed.app.on('window-all-closed', () => { // On macOS it is common for applications and their // menu bar to stay active until the user quits // explicitly with Cmd + Q if (process.platform !== 'darwin') { app.quit() }}) app.on('activate', () => { // On macOS it's common to re-create a window in the // app when the dock icon is clicked and there are // no other windows open. if (BrowserWindow.getAllWindows().length === 0) { createWindow() }}) // In this file, you can include the rest of your app's // specific main process code. You can also put them in // separate files and require them here.For the Boilerplate code of the main.js file, Refer this link. We have modified the code to suit our project needs. Once we run the build command, it is going to create a distribution of our angular project in the dist folder. We are going to refer the index.html file from this folder." }, { "code": null, "e": 30717, "s": 30708, "text": "main.js:" }, { "code": "const { app, BrowserWindow } = require('electron') function createWindow () { // Create the browser window. const win = new BrowserWindow({ width: 800, height: 600, webPreferences: { nodeIntegration: true } }) // Load the index.html of the app // From the dist folder which is created // After running the build command win.loadFile('dist/ang-electron/index.html') // Open the DevTools. win.webContents.openDevTools()} // This method will be called when Electron has finished// initialization and is ready to create browser windows.// Some APIs can only be used after this event occurs.// This method is equivalent to 'app.on('ready', function())'app.whenReady().then(createWindow) // Quit when all windows are closed.app.on('window-all-closed', () => { // On macOS it is common for applications and their // menu bar to stay active until the user quits // explicitly with Cmd + Q if (process.platform !== 'darwin') { app.quit() }}) app.on('activate', () => { // On macOS it's common to re-create a window in the // app when the dock icon is clicked and there are // no other windows open. if (BrowserWindow.getAllWindows().length === 0) { createWindow() }}) // In this file, you can include the rest of your app's // specific main process code. You can also put them in // separate files and require them here.", "e": 32084, "s": 30717, "text": null }, { "code": null, "e": 32371, "s": 32084, "text": "For the Boilerplate code of the main.js file, Refer this link. We have modified the code to suit our project needs. Once we run the build command, it is going to create a distribution of our angular project in the dist folder. We are going to refer the index.html file from this folder." }, { "code": null, "e": 33534, "s": 32371, "text": "Step 3: A small change is required in the index.html file located in the src folder. Replace the following code.<base href=\"/\">with<'base href=\"./\">This change is important otherwise it won’t be able to find and refer the necessary files required to run the application from dist folder. We also need to make a few changes to the package.json file.package.json:{\n \"name\": \"ang-electron\",\n \"version\": \"0.0.0\",\n \"main\": \"main.js\",\n \"scripts\": {\n \"ng\": \"ng\",\n \"start\": \"ng serve\",\n \"build\": \"ng build\",\n \"test\": \"ng test\",\n \"lint\": \"ng lint\",\n \"e2e\": \"ng e2e\",\n \"electron\": \"ng build && electron .\"\n },\n// ...\nWe have specified the main.js file as required by Electron. We have also introduced a new custom electron command in the scripts tag for building and launching the application. The ng build command is used for building the Angular application and deploying the build artifacts. It writes generated build artifacts to the output folder. By default, the output folder is dist/.Output: Once the respective changes are done, we are ready to launch the Electron application. To launch the application, run the command,npm run electron" }, { "code": null, "e": 33550, "s": 33534, "text": "<base href=\"/\">" }, { "code": null, "e": 33555, "s": 33550, "text": "with" }, { "code": null, "e": 33573, "s": 33555, "text": "<'base href=\"./\">" }, { "code": null, "e": 33774, "s": 33573, "text": "This change is important otherwise it won’t be able to find and refer the necessary files required to run the application from dist folder. We also need to make a few changes to the package.json file." }, { "code": null, "e": 33788, "s": 33774, "text": "package.json:" }, { "code": null, "e": 34061, "s": 33788, "text": "{\n \"name\": \"ang-electron\",\n \"version\": \"0.0.0\",\n \"main\": \"main.js\",\n \"scripts\": {\n \"ng\": \"ng\",\n \"start\": \"ng serve\",\n \"build\": \"ng build\",\n \"test\": \"ng test\",\n \"lint\": \"ng lint\",\n \"e2e\": \"ng e2e\",\n \"electron\": \"ng build && electron .\"\n },\n// ...\n" }, { "code": null, "e": 34437, "s": 34061, "text": "We have specified the main.js file as required by Electron. We have also introduced a new custom electron command in the scripts tag for building and launching the application. The ng build command is used for building the Angular application and deploying the build artifacts. It writes generated build artifacts to the output folder. By default, the output folder is dist/." }, { "code": null, "e": 34576, "s": 34437, "text": "Output: Once the respective changes are done, we are ready to launch the Electron application. To launch the application, run the command," }, { "code": null, "e": 34593, "s": 34576, "text": "npm run electron" }, { "code": null, "e": 39276, "s": 34593, "text": "Step 4: At this point, we have successfully integrated Angular with Electron. To use the Electron APIs within Angular, we can follow any of the two approaches:Approach 1: Using an external package to access the Electron APIs. We will use the ngx-electron npm package for this purpose. We can use this package as a simple Angular Service to access Electron APIs. For more detailed Information, Refer this link. To install this package, run the following command:npm install ngx-electron --saveOnce it is successfully installed, we will import it in our app.module.ts file for it to be used throughout the application.app.module.ts:import { BrowserModule } from '@angular/platform-browser';import { NgModule } from '@angular/core';import { AppRoutingModule } from './app-routing.module';import { AppComponent } from './app.component';import { NgxElectronModule } from 'ngx-electron'; @NgModule({ declarations: [ AppComponent ], imports: [ BrowserModule, AppRoutingModule, NgxElectronModule ], providers: [], bootstrap: [AppComponent]})export class AppModule { }For the list of Electron APIs supported by this package, Refer to this https://www.npmjs.com/package/ngx-electron#properties. We will use the Electron shell API from the ngx-electron package.app.component.html:<div style=\"text-align:center\"> <h1> Welcome to {{ title }}! </h1></div> <button (click)=\"openWindow()\"> Click here to Access GeeksForGeeks</button> <router-outlet></router-outlet>The Click here to Access GeeksForGeeks button does not have any functionality associated with it. To change this, make the following changes to the app.component.ts file.app.component.ts:import { Component } from '@angular/core';import { ElectronService } from 'ngx-electron'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css']})export class AppComponent { title = 'ang-electron'; constructor(private electronService: ElectronService) {} openWindow() { // Accessing the Shell API from ngx-electron this.electronService .shell.openExternal('https://www.geeksforgeeks.org/'); }}The ElectronService exposes all Electron APIs accessible from within the Renderer Process. We will create an Instance of the ElectronService in the constructor through Dependency Injection.Output:Approach 2: By creating an Electron Service component and sharing it across the application for using the Electron APIs. We will generate the Electron Service by running the following CLI command:ng generate service elec --skipTests=trueThe –skipTests=true does not create the spec.ts Test files for new services. This command will generate a new elec.service.ts file within the src/app folder. In this file, we will declare and add all Electron Imports which can then be used throughout the application. We will use the Electron shell API from the Main Process.elec.service.ts:import { Injectable } from '@angular/core';import { shell } from 'electron'; @Injectable({ providedIn: 'root'})export class ElecService { shell: typeof shell; constructor() { this.shell = (<any>window).require(\"electron\").shell; }}The any keyword is for Type Assertion on the window object. Converting this Object using any indicates that you are no longer bound by the compiler to the default properties of the window object. This is used to prevent compile-time type errors when using Electron modules. If type-casting is ignored on the windows object, we will receive the following error:ERROR in ./node_modules/electron/index.js\nModule not found: Error: Can't resolve 'fs'The typeof operator returns the data type of its operand in the form of a string. In this case, the operand is the shell module of Electron. Using this approach gives us access to all Electron APIs throughout the Application. To use this service, add the following to the app.component.ts file.app.component.ts:import { Component } from '@angular/core';import { ElectronService } from 'ngx-electron';import { ElecService } from '../app/elec.service'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css']})export class AppComponent { title = 'ang-electron'; // Creating Instances through Dependency Injection constructor(private electronService: ElectronService, private elecService: ElecService) {} openWindow() { // Accessing the Shell API from ngx-electron // this.electronService // .shell.openExternal('https://www.geeksforgeeks.org/'); // Accessing the Shell API from ElecService this.elecService.shell .openExternal('https://www.geeksforgeeks.org/'); }}Output:" }, { "code": null, "e": 41451, "s": 39276, "text": "Approach 1: Using an external package to access the Electron APIs. We will use the ngx-electron npm package for this purpose. We can use this package as a simple Angular Service to access Electron APIs. For more detailed Information, Refer this link. To install this package, run the following command:npm install ngx-electron --saveOnce it is successfully installed, we will import it in our app.module.ts file for it to be used throughout the application.app.module.ts:import { BrowserModule } from '@angular/platform-browser';import { NgModule } from '@angular/core';import { AppRoutingModule } from './app-routing.module';import { AppComponent } from './app.component';import { NgxElectronModule } from 'ngx-electron'; @NgModule({ declarations: [ AppComponent ], imports: [ BrowserModule, AppRoutingModule, NgxElectronModule ], providers: [], bootstrap: [AppComponent]})export class AppModule { }For the list of Electron APIs supported by this package, Refer to this https://www.npmjs.com/package/ngx-electron#properties. We will use the Electron shell API from the ngx-electron package.app.component.html:<div style=\"text-align:center\"> <h1> Welcome to {{ title }}! </h1></div> <button (click)=\"openWindow()\"> Click here to Access GeeksForGeeks</button> <router-outlet></router-outlet>The Click here to Access GeeksForGeeks button does not have any functionality associated with it. To change this, make the following changes to the app.component.ts file.app.component.ts:import { Component } from '@angular/core';import { ElectronService } from 'ngx-electron'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css']})export class AppComponent { title = 'ang-electron'; constructor(private electronService: ElectronService) {} openWindow() { // Accessing the Shell API from ngx-electron this.electronService .shell.openExternal('https://www.geeksforgeeks.org/'); }}The ElectronService exposes all Electron APIs accessible from within the Renderer Process. We will create an Instance of the ElectronService in the constructor through Dependency Injection.Output:" }, { "code": null, "e": 41483, "s": 41451, "text": "npm install ngx-electron --save" }, { "code": null, "e": 41608, "s": 41483, "text": "Once it is successfully installed, we will import it in our app.module.ts file for it to be used throughout the application." }, { "code": null, "e": 41623, "s": 41608, "text": "app.module.ts:" }, { "code": "import { BrowserModule } from '@angular/platform-browser';import { NgModule } from '@angular/core';import { AppRoutingModule } from './app-routing.module';import { AppComponent } from './app.component';import { NgxElectronModule } from 'ngx-electron'; @NgModule({ declarations: [ AppComponent ], imports: [ BrowserModule, AppRoutingModule, NgxElectronModule ], providers: [], bootstrap: [AppComponent]})export class AppModule { }", "e": 42072, "s": 41623, "text": null }, { "code": null, "e": 42264, "s": 42072, "text": "For the list of Electron APIs supported by this package, Refer to this https://www.npmjs.com/package/ngx-electron#properties. We will use the Electron shell API from the ngx-electron package." }, { "code": null, "e": 42284, "s": 42264, "text": "app.component.html:" }, { "code": "<div style=\"text-align:center\"> <h1> Welcome to {{ title }}! </h1></div> <button (click)=\"openWindow()\"> Click here to Access GeeksForGeeks</button> <router-outlet></router-outlet>", "e": 42474, "s": 42284, "text": null }, { "code": null, "e": 42645, "s": 42474, "text": "The Click here to Access GeeksForGeeks button does not have any functionality associated with it. To change this, make the following changes to the app.component.ts file." }, { "code": null, "e": 42663, "s": 42645, "text": "app.component.ts:" }, { "code": "import { Component } from '@angular/core';import { ElectronService } from 'ngx-electron'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css']})export class AppComponent { title = 'ang-electron'; constructor(private electronService: ElectronService) {} openWindow() { // Accessing the Shell API from ngx-electron this.electronService .shell.openExternal('https://www.geeksforgeeks.org/'); }}", "e": 43137, "s": 42663, "text": null }, { "code": null, "e": 43327, "s": 43137, "text": "The ElectronService exposes all Electron APIs accessible from within the Renderer Process. We will create an Instance of the ElectronService in the constructor through Dependency Injection." }, { "code": null, "e": 43335, "s": 43327, "text": "Output:" }, { "code": null, "e": 45685, "s": 43335, "text": "Approach 2: By creating an Electron Service component and sharing it across the application for using the Electron APIs. We will generate the Electron Service by running the following CLI command:ng generate service elec --skipTests=trueThe –skipTests=true does not create the spec.ts Test files for new services. This command will generate a new elec.service.ts file within the src/app folder. In this file, we will declare and add all Electron Imports which can then be used throughout the application. We will use the Electron shell API from the Main Process.elec.service.ts:import { Injectable } from '@angular/core';import { shell } from 'electron'; @Injectable({ providedIn: 'root'})export class ElecService { shell: typeof shell; constructor() { this.shell = (<any>window).require(\"electron\").shell; }}The any keyword is for Type Assertion on the window object. Converting this Object using any indicates that you are no longer bound by the compiler to the default properties of the window object. This is used to prevent compile-time type errors when using Electron modules. If type-casting is ignored on the windows object, we will receive the following error:ERROR in ./node_modules/electron/index.js\nModule not found: Error: Can't resolve 'fs'The typeof operator returns the data type of its operand in the form of a string. In this case, the operand is the shell module of Electron. Using this approach gives us access to all Electron APIs throughout the Application. To use this service, add the following to the app.component.ts file.app.component.ts:import { Component } from '@angular/core';import { ElectronService } from 'ngx-electron';import { ElecService } from '../app/elec.service'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css']})export class AppComponent { title = 'ang-electron'; // Creating Instances through Dependency Injection constructor(private electronService: ElectronService, private elecService: ElecService) {} openWindow() { // Accessing the Shell API from ngx-electron // this.electronService // .shell.openExternal('https://www.geeksforgeeks.org/'); // Accessing the Shell API from ElecService this.elecService.shell .openExternal('https://www.geeksforgeeks.org/'); }}Output:" }, { "code": null, "e": 45727, "s": 45685, "text": "ng generate service elec --skipTests=true" }, { "code": null, "e": 46053, "s": 45727, "text": "The –skipTests=true does not create the spec.ts Test files for new services. This command will generate a new elec.service.ts file within the src/app folder. In this file, we will declare and add all Electron Imports which can then be used throughout the application. We will use the Electron shell API from the Main Process." }, { "code": null, "e": 46070, "s": 46053, "text": "elec.service.ts:" }, { "code": "import { Injectable } from '@angular/core';import { shell } from 'electron'; @Injectable({ providedIn: 'root'})export class ElecService { shell: typeof shell; constructor() { this.shell = (<any>window).require(\"electron\").shell; }}", "e": 46313, "s": 46070, "text": null }, { "code": null, "e": 46674, "s": 46313, "text": "The any keyword is for Type Assertion on the window object. Converting this Object using any indicates that you are no longer bound by the compiler to the default properties of the window object. This is used to prevent compile-time type errors when using Electron modules. If type-casting is ignored on the windows object, we will receive the following error:" }, { "code": null, "e": 46760, "s": 46674, "text": "ERROR in ./node_modules/electron/index.js\nModule not found: Error: Can't resolve 'fs'" }, { "code": null, "e": 47055, "s": 46760, "text": "The typeof operator returns the data type of its operand in the form of a string. In this case, the operand is the shell module of Electron. Using this approach gives us access to all Electron APIs throughout the Application. To use this service, add the following to the app.component.ts file." }, { "code": null, "e": 47073, "s": 47055, "text": "app.component.ts:" }, { "code": "import { Component } from '@angular/core';import { ElectronService } from 'ngx-electron';import { ElecService } from '../app/elec.service'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css']})export class AppComponent { title = 'ang-electron'; // Creating Instances through Dependency Injection constructor(private electronService: ElectronService, private elecService: ElecService) {} openWindow() { // Accessing the Shell API from ngx-electron // this.electronService // .shell.openExternal('https://www.geeksforgeeks.org/'); // Accessing the Shell API from ElecService this.elecService.shell .openExternal('https://www.geeksforgeeks.org/'); }}", "e": 47840, "s": 47073, "text": null }, { "code": null, "e": 47848, "s": 47840, "text": "Output:" }, { "code": null, "e": 47863, "s": 47848, "text": "AngularJS-Misc" }, { "code": null, "e": 47874, "s": 47863, "text": "ElectronJS" }, { "code": null, "e": 47884, "s": 47874, "text": "AngularJS" }, { "code": null, "e": 47901, "s": 47884, "text": "Web Technologies" }, { "code": null, "e": 47999, "s": 47901, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 48034, "s": 47999, "text": "Angular PrimeNG Dropdown Component" }, { "code": null, "e": 48065, "s": 48034, "text": "Auth Guards in Angular 9/10/11" }, { "code": null, "e": 48100, "s": 48065, "text": "Angular PrimeNG Calendar Component" }, { "code": null, "e": 48135, "s": 48100, "text": "Angular PrimeNG Messages Component" }, { "code": null, "e": 48180, "s": 48135, "text": "How to bundle an Angular app for production?" }, { "code": null, "e": 48220, "s": 48180, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 48253, "s": 48220, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 48298, "s": 48253, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 48341, "s": 48298, "text": "How to fetch data from an API in ReactJS ?" } ]
How to plot half or quarter polar plots in Matplotlib?
To plot half or quarter polar plots 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. Create a new figure or activate an existing figure using figure() method. Create a new figure or activate an existing figure using figure() method. Add an axes to the figure as part of a subplot arrangement. Add an axes to the figure as part of a subplot arrangement. For half or quarter polar plots, use set_thetamax() method. For half or quarter polar plots, use set_thetamax() method. To display the figure, use show() method. To display the figure, use show() method. from matplotlib import pyplot as plt plt.rcParams["figure.figsize"] = [7.50, 3.50] plt.rcParams["figure.autolayout"] = True fig = plt.figure() ax = fig.add_subplot(111, projection="polar") max_theta = 90 ax.set_thetamax(max_theta) plt.show()
[ { "code": null, "e": 1147, "s": 1062, "text": "To plot half or quarter polar plots in Matplotlib, we can take the following steps −" }, { "code": null, "e": 1223, "s": 1147, "text": "Set the figure size and adjust the padding between and around the subplots." }, { "code": null, "e": 1299, "s": 1223, "text": "Set the figure size and adjust the padding between and around the subplots." }, { "code": null, "e": 1373, "s": 1299, "text": "Create a new figure or activate an existing figure using figure() method." }, { "code": null, "e": 1447, "s": 1373, "text": "Create a new figure or activate an existing figure using figure() method." }, { "code": null, "e": 1507, "s": 1447, "text": "Add an axes to the figure as part of a subplot arrangement." }, { "code": null, "e": 1567, "s": 1507, "text": "Add an axes to the figure as part of a subplot arrangement." }, { "code": null, "e": 1627, "s": 1567, "text": "For half or quarter polar plots, use set_thetamax() method." }, { "code": null, "e": 1687, "s": 1627, "text": "For half or quarter polar plots, use set_thetamax() method." }, { "code": null, "e": 1729, "s": 1687, "text": "To display the figure, use show() method." }, { "code": null, "e": 1771, "s": 1729, "text": "To display the figure, use show() method." }, { "code": null, "e": 2015, "s": 1771, "text": "from matplotlib import pyplot as plt\n\nplt.rcParams[\"figure.figsize\"] = [7.50, 3.50]\nplt.rcParams[\"figure.autolayout\"] = True\n\nfig = plt.figure()\nax = fig.add_subplot(111, projection=\"polar\")\nmax_theta = 90\nax.set_thetamax(max_theta)\nplt.show()" } ]
Reference to a constructor using method references in Java8
Lambda expressions In Java allows you to pass functionality as an argument to a method. You can also call an existing method using lambda expressions. list.forEach(n -> System.out.println(n)); Method references are simple, easy-to-read lambda expressions to call/refer and the existing method by name in a lambda expression. In addition to the instance and static methods, you can also refer a constructor by using the new keyword. Following is the syntax to reference a constructor in Java. ClassName::new interface myInterface{ Test greet(String data); } class Test{ Test(String data){ System.out.println(data); } } public class MethodReferences { public static void main(String args[]) { myInterface in = Test::new; in.greet("Welcome to Tutorilspoint"); } } Welcome to Tutorilspoint
[ { "code": null, "e": 1213, "s": 1062, "text": "Lambda expressions In Java allows you to pass functionality as an argument to a\nmethod. You can also call an existing method using lambda expressions." }, { "code": null, "e": 1255, "s": 1213, "text": "list.forEach(n -> System.out.println(n));" }, { "code": null, "e": 1494, "s": 1255, "text": "Method references are simple, easy-to-read lambda expressions to call/refer and the existing method by name in a lambda expression. In addition to the instance and static methods, you can also refer a constructor by using the new keyword." }, { "code": null, "e": 1554, "s": 1494, "text": "Following is the syntax to reference a constructor in Java." }, { "code": null, "e": 1569, "s": 1554, "text": "ClassName::new" }, { "code": null, "e": 1859, "s": 1569, "text": "interface myInterface{\n Test greet(String data);\n}\nclass Test{\n Test(String data){\n System.out.println(data);\n }\n}\npublic class MethodReferences {\n public static void main(String args[]) {\n myInterface in = Test::new;\n in.greet(\"Welcome to Tutorilspoint\");\n }\n}" }, { "code": null, "e": 1884, "s": 1859, "text": "Welcome to Tutorilspoint" } ]
Which MySQL Data Type can be used to store Negative Number?
You can use TINYINT data type in MySQL to store negative number. Following is the syntax − CREATE TABLE yourTableName ( yourColumnName TINYINT . . . . N ); Let us first create a table with a column set as type TINYINT − mysql> create table DemoTable ( Number tinyint ); Query OK, 0 rows affected (0.69 sec) Insert some records in the table using insert command − mysql> insert into DemoTable values(-10); Query OK, 1 row affected (0.17 sec) mysql> insert into DemoTable values(-128); Query OK, 1 row affected (0.14 sec) mysql> insert into DemoTable values(128); ERROR 1264 (22003): Out of range value for column 'Number' at row 1 mysql> insert into DemoTable values(127); Query OK, 1 row affected (0.23 sec) mysql> insert into DemoTable values(-1); Query OK, 1 row affected (0.14 sec) mysql> insert into DemoTable values(14); Query OK, 1 row affected (0.19 sec) Display all records from the table using select statement − mysql> select *from DemoTable; This will produce the following output − +--------+ | Number | +--------+ | -10 | | -128 | | 127 | | -1 | | 14 | +--------+ 5 rows in set (0.00 sec)
[ { "code": null, "e": 1153, "s": 1062, "text": "You can use TINYINT data type in MySQL to store negative number. Following is the syntax −" }, { "code": null, "e": 1243, "s": 1153, "text": "CREATE TABLE yourTableName\n (\n\n yourColumnName TINYINT\n .\n .\n .\n .\n N\n );" }, { "code": null, "e": 1307, "s": 1243, "text": "Let us first create a table with a column set as type TINYINT −" }, { "code": null, "e": 1404, "s": 1307, "text": "mysql> create table DemoTable\n (\n\n Number tinyint\n );\nQuery OK, 0 rows affected (0.69 sec)" }, { "code": null, "e": 1460, "s": 1404, "text": "Insert some records in the table using insert command −" }, { "code": null, "e": 1964, "s": 1460, "text": "mysql> insert into DemoTable values(-10);\nQuery OK, 1 row affected (0.17 sec)\n\nmysql> insert into DemoTable values(-128);\nQuery OK, 1 row affected (0.14 sec)\n\nmysql> insert into DemoTable values(128);\nERROR 1264 (22003): Out of range value for column 'Number' at row 1\n\nmysql> insert into DemoTable values(127);\nQuery OK, 1 row affected (0.23 sec)\n\nmysql> insert into DemoTable values(-1);\nQuery OK, 1 row affected (0.14 sec)\n\nmysql> insert into DemoTable values(14);\nQuery OK, 1 row affected (0.19 sec)" }, { "code": null, "e": 2024, "s": 1964, "text": "Display all records from the table using select statement −" }, { "code": null, "e": 2055, "s": 2024, "text": "mysql> select *from DemoTable;" }, { "code": null, "e": 2096, "s": 2055, "text": "This will produce the following output −" }, { "code": null, "e": 2220, "s": 2096, "text": "+--------+\n| Number |\n+--------+\n| -10 |\n| -128 |\n| 127 |\n| -1 |\n| 14 |\n+--------+\n5 rows in set (0.00 sec)" } ]
RAPTOR Tool - A Flowchart Interpreter - GeeksforGeeks
09 Feb, 2018 RAPTOR(Rapid Algorithmic Prototyping Tool for Ordered Reasoning) is a free graphical authoring tool created by Martin C. Carlisle, Terry Wilson, Jeff Humphries and Jason Moore, designed specifically to help students visualize their algorithms and avoid syntactic baggage.Students can create flow-chart for a particular program and raptor tool will generate code for it in various programming languages, such as C, C++, Java and so on. Symbols in RAPTOR Raptor has 6 types of symbols, each of which represents a unique kind of instruction. They are – Assignment, Call, Input, Output, Selection and Loop symbols. The following image shows these symbols- RAPTOR Program Structure A RAPTOR program consists of connected symbols that represent actions to be executed. The arrows that connect the symbols determine the order in which the actions are performed.The execution of a RAPTOR program begins at the Start symbol and goes along the arrows to execute the program.The program stops executing when the End symbol is reached. The arrows that connect the symbols determine the order in which the actions are performed. The execution of a RAPTOR program begins at the Start symbol and goes along the arrows to execute the program. The program stops executing when the End symbol is reached. With the help of Generate option, the generated C++ code for the above flow chart is: // CPP program for illustrating RAPTOR#include <iostream>#include <string> using namespace std;int main(){ string raptor_prompt_variable_zzyz; float m; raptor_prompt_variable_zzyz ="enter the marks"; cout << raptor_prompt_variable_zzyz << endl; cin >> m; if (m>=90) { cout << "The grade is A" << endl; } else { if (m>=80) { cout << "The grade is B" << endl; } else { if (m>=60) { cout << "The grade is C" << endl; } else { cout << "The grade is D" << endl; } } } return 0;} In this way, any algorithm can be visualised by the students, and it can be converted into a code using the raptor tool. This article is contributed by Mrigendra Singh. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.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. GBlog Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Top 10 Front End Developer Skills That You Need in 2022 DSA Sheet by Love Babbar 6 Best IDE's For Python in 2022 A Freshers Guide To Programming ML | Underfitting and Overfitting Virtualization In Cloud Computing and Types Top 10 Programming Languages to Learn in 2022 What is web socket and how it is different from the HTTP? Top Selenium Frameworks You Should Know Introduction to Hill Climbing | Artificial Intelligence
[ { "code": null, "e": 24619, "s": 24591, "text": "\n09 Feb, 2018" }, { "code": null, "e": 25054, "s": 24619, "text": "RAPTOR(Rapid Algorithmic Prototyping Tool for Ordered Reasoning) is a free graphical authoring tool created by Martin C. Carlisle, Terry Wilson, Jeff Humphries and Jason Moore, designed specifically to help students visualize their algorithms and avoid syntactic baggage.Students can create flow-chart for a particular program and raptor tool will generate code for it in various programming languages, such as C, C++, Java and so on." }, { "code": null, "e": 25072, "s": 25054, "text": "Symbols in RAPTOR" }, { "code": null, "e": 25271, "s": 25072, "text": "Raptor has 6 types of symbols, each of which represents a unique kind of instruction. They are – Assignment, Call, Input, Output, Selection and Loop symbols. The following image shows these symbols-" }, { "code": null, "e": 25296, "s": 25271, "text": "RAPTOR Program Structure" }, { "code": null, "e": 25382, "s": 25296, "text": "A RAPTOR program consists of connected symbols that represent actions to be executed." }, { "code": null, "e": 25643, "s": 25382, "text": "The arrows that connect the symbols determine the order in which the actions are performed.The execution of a RAPTOR program begins at the Start symbol and goes along the arrows to execute the program.The program stops executing when the End symbol is reached." }, { "code": null, "e": 25735, "s": 25643, "text": "The arrows that connect the symbols determine the order in which the actions are performed." }, { "code": null, "e": 25846, "s": 25735, "text": "The execution of a RAPTOR program begins at the Start symbol and goes along the arrows to execute the program." }, { "code": null, "e": 25906, "s": 25846, "text": "The program stops executing when the End symbol is reached." }, { "code": null, "e": 25992, "s": 25906, "text": "With the help of Generate option, the generated C++ code for the above flow chart is:" }, { "code": "// CPP program for illustrating RAPTOR#include <iostream>#include <string> using namespace std;int main(){ string raptor_prompt_variable_zzyz; float m; raptor_prompt_variable_zzyz =\"enter the marks\"; cout << raptor_prompt_variable_zzyz << endl; cin >> m; if (m>=90) { cout << \"The grade is A\" << endl; } else { if (m>=80) { cout << \"The grade is B\" << endl; } else { if (m>=60) { cout << \"The grade is C\" << endl; } else { cout << \"The grade is D\" << endl; } } } return 0;}", "e": 26608, "s": 25992, "text": null }, { "code": null, "e": 26729, "s": 26608, "text": "In this way, any algorithm can be visualised by the students, and it can be converted into a code using the raptor tool." }, { "code": null, "e": 27032, "s": 26729, "text": "This article is contributed by Mrigendra Singh. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.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": 27157, "s": 27032, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 27163, "s": 27157, "text": "GBlog" }, { "code": null, "e": 27261, "s": 27163, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27270, "s": 27261, "text": "Comments" }, { "code": null, "e": 27283, "s": 27270, "text": "Old Comments" }, { "code": null, "e": 27339, "s": 27283, "text": "Top 10 Front End Developer Skills That You Need in 2022" }, { "code": null, "e": 27364, "s": 27339, "text": "DSA Sheet by Love Babbar" }, { "code": null, "e": 27396, "s": 27364, "text": "6 Best IDE's For Python in 2022" }, { "code": null, "e": 27428, "s": 27396, "text": "A Freshers Guide To Programming" }, { "code": null, "e": 27462, "s": 27428, "text": "ML | Underfitting and Overfitting" }, { "code": null, "e": 27506, "s": 27462, "text": "Virtualization In Cloud Computing and Types" }, { "code": null, "e": 27552, "s": 27506, "text": "Top 10 Programming Languages to Learn in 2022" }, { "code": null, "e": 27610, "s": 27552, "text": "What is web socket and how it is different from the HTTP?" }, { "code": null, "e": 27650, "s": 27610, "text": "Top Selenium Frameworks You Should Know" } ]
Practical Introduction to PySpark | by Soner Yıldırım | Towards Data Science
Spark is an analytics engine used for large-scale data processing. It lets you spread both data and computations over clusters to achieve a substantial performance increase. Since it is getting easier and less expensive to collect and store data, we are likely to have huge amounts of data when working on a real life problem. Thus, distributed engines like Spark are becoming the predominant tools in the data science ecosystem. PySpark is a Python API for Spark. It combines the simplicity of Python with the efficiency of Spark which results in a cooperation that is highly appreciated by both data scientists and engineers. In this article, we will go over several examples to introduce SQL module of PySpark which is used for working with structured data. We first need to create a SparkSession which serves as an entry point to Spark SQL. from pyspark.sql import SparkSessionsc = SparkSession.builder.getOrCreate()sc.sparkContext.setLogLevel("WARN")print(sc)<pyspark.sql.session.SparkSession object at 0x7fecd819e630> We will use this SparkSession object to interact with functions and methods of Spark SQL. Let’s create a spark data frame by reading a csv file. We will be using the Melbourne housing dataset available on Kaggle. df = sc.read.option("header", "true").csv( "/home/sparkuser/Desktop/melb_housing.csv") We will make the data frame smaller by selecting only 5 columns. The list of columns can be viewed using the “df.columns” method. df = df.select("Type", "Landsize", "Distance", "Regionname", "Price")df.show(5) As we will see in the examples, PySpark syntax seems like a mixture of Pandas and SQL. Thus, if you are already working with these tool, it will be relatively easy for you to learn PySpark. We can sort the rows in data frame using the orderBy function. Let’s check the 5 most expensive houses in the dataset. df.orderBy("Price", ascending=False).show(5) The SQL module of PySpark has numerous functions available for data analysis and manipulation. We can either import all of them at once or separately. # import all functionsfrom pyspark.sql import functions as F There are 3 different types of houses in the dataset. We can calculate the average price of each type using the groupby function. df.groupby("Type").agg(F.round(F.mean("Price")).alias("Avg_price")).show() Let’s elaborate on the syntax. We group the observations (i.e. rows) by the type column. Then we calculate the average price for each group. The round function is used for rounding up the decimal points. The alias method changes the name of the aggregated column. It is similar to the “as” keyword in SQL. The distance column shows the distance to the central business district. The house prices usually decrease as we move away from the city centre. We can confirm our anticipation by calculating the average house price for houses with a distance higher than 3 miles. df.filter(F.col("Distance") > 3).groupby("Type").agg( F.round(F.mean("Price")).alias("Avg_price")).show() We use the filter function to apply a condition on the distance column. Results confirm our anticipation. The average price has decreased for each type. Two other useful functions are count and countDistinct which count the number of total and distinct observations (i.e. rows) in a group, respectively. For instance, the following code returns the number of houses for each type along with the number of distinct prices. df.groupby("Type").agg( F.count("Price").alias("n_houses"), F.countDistinct("Price").alias("n_distinct_price")).show() A typical task in data analysis is to derive new columns based on the existing ones. It may be a part of your feature engineering process. Regarding the housing dataset, we can create a new feature that represents the price per unit land size. To accomplish this task, the withColumn function can be used as follows: df = df.withColumn( "Price_per_size", F.round(F.col("Landsize")*1000 / F.col("Price"), 2)) The name of the new column is “Price_per_size”. The next line specifies the steps in deriving the values. We multiply the land size with 1000 and divide it by the house price. The result is rounded up to two decimal points. We have covered an introduction to data analysis and manipulation with PySpark. The SQL module of PySpark offers many more functions and methods to perform efficient data analysis. It is important to note that Spark is optimized for large-scale data. Thus, you may not see any performance increase when working with small-scale data. In fact, Pandas might outperform PySpark when working with small datasets. Thank you for reading. Please let me know if you have any feedback.
[ { "code": null, "e": 345, "s": 171, "text": "Spark is an analytics engine used for large-scale data processing. It lets you spread both data and computations over clusters to achieve a substantial performance increase." }, { "code": null, "e": 601, "s": 345, "text": "Since it is getting easier and less expensive to collect and store data, we are likely to have huge amounts of data when working on a real life problem. Thus, distributed engines like Spark are becoming the predominant tools in the data science ecosystem." }, { "code": null, "e": 799, "s": 601, "text": "PySpark is a Python API for Spark. It combines the simplicity of Python with the efficiency of Spark which results in a cooperation that is highly appreciated by both data scientists and engineers." }, { "code": null, "e": 932, "s": 799, "text": "In this article, we will go over several examples to introduce SQL module of PySpark which is used for working with structured data." }, { "code": null, "e": 1016, "s": 932, "text": "We first need to create a SparkSession which serves as an entry point to Spark SQL." }, { "code": null, "e": 1195, "s": 1016, "text": "from pyspark.sql import SparkSessionsc = SparkSession.builder.getOrCreate()sc.sparkContext.setLogLevel(\"WARN\")print(sc)<pyspark.sql.session.SparkSession object at 0x7fecd819e630>" }, { "code": null, "e": 1408, "s": 1195, "text": "We will use this SparkSession object to interact with functions and methods of Spark SQL. Let’s create a spark data frame by reading a csv file. We will be using the Melbourne housing dataset available on Kaggle." }, { "code": null, "e": 1498, "s": 1408, "text": "df = sc.read.option(\"header\", \"true\").csv( \"/home/sparkuser/Desktop/melb_housing.csv\")" }, { "code": null, "e": 1628, "s": 1498, "text": "We will make the data frame smaller by selecting only 5 columns. The list of columns can be viewed using the “df.columns” method." }, { "code": null, "e": 1708, "s": 1628, "text": "df = df.select(\"Type\", \"Landsize\", \"Distance\", \"Regionname\", \"Price\")df.show(5)" }, { "code": null, "e": 1898, "s": 1708, "text": "As we will see in the examples, PySpark syntax seems like a mixture of Pandas and SQL. Thus, if you are already working with these tool, it will be relatively easy for you to learn PySpark." }, { "code": null, "e": 2017, "s": 1898, "text": "We can sort the rows in data frame using the orderBy function. Let’s check the 5 most expensive houses in the dataset." }, { "code": null, "e": 2062, "s": 2017, "text": "df.orderBy(\"Price\", ascending=False).show(5)" }, { "code": null, "e": 2213, "s": 2062, "text": "The SQL module of PySpark has numerous functions available for data analysis and manipulation. We can either import all of them at once or separately." }, { "code": null, "e": 2274, "s": 2213, "text": "# import all functionsfrom pyspark.sql import functions as F" }, { "code": null, "e": 2404, "s": 2274, "text": "There are 3 different types of houses in the dataset. We can calculate the average price of each type using the groupby function." }, { "code": null, "e": 2479, "s": 2404, "text": "df.groupby(\"Type\").agg(F.round(F.mean(\"Price\")).alias(\"Avg_price\")).show()" }, { "code": null, "e": 2785, "s": 2479, "text": "Let’s elaborate on the syntax. We group the observations (i.e. rows) by the type column. Then we calculate the average price for each group. The round function is used for rounding up the decimal points. The alias method changes the name of the aggregated column. It is similar to the “as” keyword in SQL." }, { "code": null, "e": 3049, "s": 2785, "text": "The distance column shows the distance to the central business district. The house prices usually decrease as we move away from the city centre. We can confirm our anticipation by calculating the average house price for houses with a distance higher than 3 miles." }, { "code": null, "e": 3158, "s": 3049, "text": "df.filter(F.col(\"Distance\") > 3).groupby(\"Type\").agg( F.round(F.mean(\"Price\")).alias(\"Avg_price\")).show()" }, { "code": null, "e": 3311, "s": 3158, "text": "We use the filter function to apply a condition on the distance column. Results confirm our anticipation. The average price has decreased for each type." }, { "code": null, "e": 3580, "s": 3311, "text": "Two other useful functions are count and countDistinct which count the number of total and distinct observations (i.e. rows) in a group, respectively. For instance, the following code returns the number of houses for each type along with the number of distinct prices." }, { "code": null, "e": 3705, "s": 3580, "text": "df.groupby(\"Type\").agg( F.count(\"Price\").alias(\"n_houses\"), F.countDistinct(\"Price\").alias(\"n_distinct_price\")).show()" }, { "code": null, "e": 3949, "s": 3705, "text": "A typical task in data analysis is to derive new columns based on the existing ones. It may be a part of your feature engineering process. Regarding the housing dataset, we can create a new feature that represents the price per unit land size." }, { "code": null, "e": 4022, "s": 3949, "text": "To accomplish this task, the withColumn function can be used as follows:" }, { "code": null, "e": 4120, "s": 4022, "text": "df = df.withColumn( \"Price_per_size\", F.round(F.col(\"Landsize\")*1000 / F.col(\"Price\"), 2))" }, { "code": null, "e": 4344, "s": 4120, "text": "The name of the new column is “Price_per_size”. The next line specifies the steps in deriving the values. We multiply the land size with 1000 and divide it by the house price. The result is rounded up to two decimal points." }, { "code": null, "e": 4525, "s": 4344, "text": "We have covered an introduction to data analysis and manipulation with PySpark. The SQL module of PySpark offers many more functions and methods to perform efficient data analysis." }, { "code": null, "e": 4753, "s": 4525, "text": "It is important to note that Spark is optimized for large-scale data. Thus, you may not see any performance increase when working with small-scale data. In fact, Pandas might outperform PySpark when working with small datasets." } ]
C# program to find all duplicate elements in an integer array
Firstly, set the array with duplicate elements. int[] arr = { 24, 10, 56, 32, 10, 43, 88, 32 }; Now declare a Dictionary and loop through the array to get the repeated elements. var d = new Dictionary < int, int > (); foreach(var res in arr) { if (d.ContainsKey(res)) d[res]++; else d[res] = 1; } Live Demo using System; using System.Collections.Generic; namespace Demo { public class Program { public static void Main(string[] args) { int[] arr = { 24, 10, 56, 32, 10, 43, 88, 32 }; var d = new Dictionary < int, int > (); foreach(var res in arr) { if (d.ContainsKey(res)) d[res]++; else d[res] = 1; } foreach(var val in d) Console.WriteLine("{0} occurred {1} times", val.Key, val.Value); } } } 24 occurred 1 times 10 occurred 2 times 56 occurred 1 times 32 occurred 2 times 43 occurred 1 times 88 occurred 1 times
[ { "code": null, "e": 1110, "s": 1062, "text": "Firstly, set the array with duplicate elements." }, { "code": null, "e": 1182, "s": 1110, "text": "int[] arr = {\n 24,\n 10,\n 56,\n 32,\n 10,\n 43,\n 88,\n 32\n};" }, { "code": null, "e": 1264, "s": 1182, "text": "Now declare a Dictionary and loop through the array to get the repeated elements." }, { "code": null, "e": 1401, "s": 1264, "text": "var d = new Dictionary < int, int > ();\nforeach(var res in arr) {\n if (d.ContainsKey(res))\n d[res]++;\n else\n d[res] = 1;\n}" }, { "code": null, "e": 1412, "s": 1401, "text": " Live Demo" }, { "code": null, "e": 2027, "s": 1412, "text": "using System;\nusing System.Collections.Generic;\n\nnamespace Demo {\n public class Program {\n public static void Main(string[] args) {\n int[] arr = {\n 24,\n 10,\n 56,\n 32,\n 10,\n 43,\n 88,\n 32\n };\n var d = new Dictionary < int, int > ();\n foreach(var res in arr) {\n if (d.ContainsKey(res))\n d[res]++;\n else\n d[res] = 1;\n }\n foreach(var val in d)\n Console.WriteLine(\"{0} occurred {1} times\", val.Key, val.Value);\n }\n }\n}" }, { "code": null, "e": 2147, "s": 2027, "text": "24 occurred 1 times\n10 occurred 2 times\n56 occurred 1 times\n32 occurred 2 times\n43 occurred 1 times\n88 occurred 1 times" } ]
Display Customizations for pandas Power Users | by Roman Orac | Towards Data Science
pandas has an options system that lets you customize some aspects of its behavior, display-related options being those the user is most likely to adjust. pandas display customizations are often overlooked part of pandas. For most users, defaults are good enough, but many users don’t know about display customizations and they find some alternative cumbersome method to overcome them. To become a pandas expert you should at least know about the display customization options. Here are a few links that might interest you: - Labeling and Data Engineering for Conversational AI and Analytics- Data Science for Business Leaders [Course]- Intro to Machine Learning with PyTorch [Course]- Become a Growth Product Manager [Course]- Deep Learning (Adaptive Computation and ML series) [Ebook]- Free skill tests for Data Scientists & Machine Learning Engineers Some of the links above are affiliate links and if you go through them to make a purchase I’ll earn a commission. Keep in mind that I link courses because of their quality and not because of the commission I receive from your purchases. To Step Up Your Pandas Game, read: medium.com import osimport platformfrom platform import python_versionimport jupyterlabimport pandas as pdimport randomprint("System")print("os name: %s" % os.name)print("system: %s" % platform.system())print("release: %s" % platform.release())print()print("Python")print("version: %s" % python_version())print()print("Python Packages")print("jupterlab==%s" % jupyterlab.__version__)print("pandas==%s" % pd.__version__)seed = 42random.seed(seed)pd.np.random.seed(seed) Let’s define the dataset. It has 100 rows and 2 columns: col1 has random numbers between 0 and 1, col2 has random sentences composed of 200 characters. def generate_sentence(n_chars=200): return ''.join(random.choice('abcdefg ') for _ in range(n_chars))n = 100df = pd.DataFrame( { "col1": pd.np.random.random_sample(n), "text": [generate_sentence() for _ in range(n)] })df.shape(100, 2) By default, pandas displays small and large numbers in scientific (exponential) notation. If the scientific notation is not your preferred format, you can disable it with a single command. Let’s replace the first value in col1 with a small number. pandas is forced to display col1 in scientific notation because of a small number. df.iloc[0, 0] = 1e-10df.head() With float_format we can set the number of decimal places we would like to display (10 in the example below). pd.options.display.float_format = '{:,.10f}'.formatdf.head() With reset_option command, we reset it back to scientific notation. pd.reset_option('display.float_format') When working with bigger datasets we notice that pandas doesn’t display all columns or rows. Obviously, this is for performance reasons. While I don’t mind hiding rows, it can get frustrating by not seeing all the columns (20 is the default limit). Let’s transform rows to columns to visualize the problem first hand. df.T Now, let’s set max columns to 100. pd.set_option("display.max_columns", 100)df.T To reset the max columns display, we can set it back to 20. pd.set_option("display.max_columns", 20) Pandas also has a get option to see, which value is currently set. pd.get_option('display.max_columns')20 We can do the same with display.max_rows for rows. Usually, when working with textual data, strings are only partially visible because of its length. Pandas enables us to increase the column width with max_colwidth option. pd.set_option('max_colwidth', 500) I am sure you are familiar with describe function with outputs summary statistics for each column in the DataFrame. The info option is like meta describe function, because it outputs metadata for the DataFrame, like data types, non-null objects, and memory usage. This is useful when working with large datasets. pd.set_option('large_repr', 'info')df pd.reset_option('large_repr') # reset it These were the most frequently used pandas display customizations. If you would like to learn more about display customizations read Options and settings section of pandas documentation. Follow me on Twitter, where I regularly tweet about Data Science and Machine Learning.
[ { "code": null, "e": 326, "s": 172, "text": "pandas has an options system that lets you customize some aspects of its behavior, display-related options being those the user is most likely to adjust." }, { "code": null, "e": 649, "s": 326, "text": "pandas display customizations are often overlooked part of pandas. For most users, defaults are good enough, but many users don’t know about display customizations and they find some alternative cumbersome method to overcome them. To become a pandas expert you should at least know about the display customization options." }, { "code": null, "e": 695, "s": 649, "text": "Here are a few links that might interest you:" }, { "code": null, "e": 1025, "s": 695, "text": "- Labeling and Data Engineering for Conversational AI and Analytics- Data Science for Business Leaders [Course]- Intro to Machine Learning with PyTorch [Course]- Become a Growth Product Manager [Course]- Deep Learning (Adaptive Computation and ML series) [Ebook]- Free skill tests for Data Scientists & Machine Learning Engineers" }, { "code": null, "e": 1262, "s": 1025, "text": "Some of the links above are affiliate links and if you go through them to make a purchase I’ll earn a commission. Keep in mind that I link courses because of their quality and not because of the commission I receive from your purchases." }, { "code": null, "e": 1297, "s": 1262, "text": "To Step Up Your Pandas Game, read:" }, { "code": null, "e": 1308, "s": 1297, "text": "medium.com" }, { "code": null, "e": 1766, "s": 1308, "text": "import osimport platformfrom platform import python_versionimport jupyterlabimport pandas as pdimport randomprint(\"System\")print(\"os name: %s\" % os.name)print(\"system: %s\" % platform.system())print(\"release: %s\" % platform.release())print()print(\"Python\")print(\"version: %s\" % python_version())print()print(\"Python Packages\")print(\"jupterlab==%s\" % jupyterlab.__version__)print(\"pandas==%s\" % pd.__version__)seed = 42random.seed(seed)pd.np.random.seed(seed)" }, { "code": null, "e": 1823, "s": 1766, "text": "Let’s define the dataset. It has 100 rows and 2 columns:" }, { "code": null, "e": 1864, "s": 1823, "text": "col1 has random numbers between 0 and 1," }, { "code": null, "e": 1918, "s": 1864, "text": "col2 has random sentences composed of 200 characters." }, { "code": null, "e": 2176, "s": 1918, "text": "def generate_sentence(n_chars=200): return ''.join(random.choice('abcdefg ') for _ in range(n_chars))n = 100df = pd.DataFrame( { \"col1\": pd.np.random.random_sample(n), \"text\": [generate_sentence() for _ in range(n)] })df.shape(100, 2)" }, { "code": null, "e": 2365, "s": 2176, "text": "By default, pandas displays small and large numbers in scientific (exponential) notation. If the scientific notation is not your preferred format, you can disable it with a single command." }, { "code": null, "e": 2507, "s": 2365, "text": "Let’s replace the first value in col1 with a small number. pandas is forced to display col1 in scientific notation because of a small number." }, { "code": null, "e": 2538, "s": 2507, "text": "df.iloc[0, 0] = 1e-10df.head()" }, { "code": null, "e": 2648, "s": 2538, "text": "With float_format we can set the number of decimal places we would like to display (10 in the example below)." }, { "code": null, "e": 2709, "s": 2648, "text": "pd.options.display.float_format = '{:,.10f}'.formatdf.head()" }, { "code": null, "e": 2777, "s": 2709, "text": "With reset_option command, we reset it back to scientific notation." }, { "code": null, "e": 2817, "s": 2777, "text": "pd.reset_option('display.float_format')" }, { "code": null, "e": 3066, "s": 2817, "text": "When working with bigger datasets we notice that pandas doesn’t display all columns or rows. Obviously, this is for performance reasons. While I don’t mind hiding rows, it can get frustrating by not seeing all the columns (20 is the default limit)." }, { "code": null, "e": 3135, "s": 3066, "text": "Let’s transform rows to columns to visualize the problem first hand." }, { "code": null, "e": 3140, "s": 3135, "text": "df.T" }, { "code": null, "e": 3175, "s": 3140, "text": "Now, let’s set max columns to 100." }, { "code": null, "e": 3221, "s": 3175, "text": "pd.set_option(\"display.max_columns\", 100)df.T" }, { "code": null, "e": 3281, "s": 3221, "text": "To reset the max columns display, we can set it back to 20." }, { "code": null, "e": 3322, "s": 3281, "text": "pd.set_option(\"display.max_columns\", 20)" }, { "code": null, "e": 3389, "s": 3322, "text": "Pandas also has a get option to see, which value is currently set." }, { "code": null, "e": 3428, "s": 3389, "text": "pd.get_option('display.max_columns')20" }, { "code": null, "e": 3479, "s": 3428, "text": "We can do the same with display.max_rows for rows." }, { "code": null, "e": 3651, "s": 3479, "text": "Usually, when working with textual data, strings are only partially visible because of its length. Pandas enables us to increase the column width with max_colwidth option." }, { "code": null, "e": 3686, "s": 3651, "text": "pd.set_option('max_colwidth', 500)" }, { "code": null, "e": 3950, "s": 3686, "text": "I am sure you are familiar with describe function with outputs summary statistics for each column in the DataFrame. The info option is like meta describe function, because it outputs metadata for the DataFrame, like data types, non-null objects, and memory usage." }, { "code": null, "e": 3999, "s": 3950, "text": "This is useful when working with large datasets." }, { "code": null, "e": 4037, "s": 3999, "text": "pd.set_option('large_repr', 'info')df" }, { "code": null, "e": 4078, "s": 4037, "text": "pd.reset_option('large_repr') # reset it" }, { "code": null, "e": 4265, "s": 4078, "text": "These were the most frequently used pandas display customizations. If you would like to learn more about display customizations read Options and settings section of pandas documentation." } ]
ASP.NET - Multi Views
MultiView and View controls allow you to divide the content of a page into different groups, displaying only one group at a time. Each View control manages one group of content and all the View controls are held together in a MultiView control. The MultiView control is responsible for displaying one View control at a time. The View displayed is called the active view. The syntax of MultiView control is: <asp:MultView ID= "MultiView1" runat= "server"> </asp:MultiView> The syntax of View control is: <asp:View ID= "View1" runat= "server"> </asp:View> However, the View control cannot exist on its own. It would render error if you try to use it stand-alone. It is always used with a Multiview control as: <asp:MultView ID= "MultiView1" runat= "server"> <asp:View ID= "View1" runat= "server"> </asp:View> </asp:MultiView> Both View and MultiView controls are derived from Control class and inherit all its properties, methods, and events. The most important property of the View control is Visible property of type Boolean, which sets the visibility of a view. The MultiView control has the following important properties: The CommandName attribute of the button control associated with the navigation of the MultiView control are associated with some related field of the MultiView control. For example, if a button control with CommandName value as NextView is associated with the navigation of the multiview, it automatically navigates to the next view when the button is clicked. The following table shows the default command names of the above properties: The important methods of the multiview control are: Every time a view is changed, the page is posted back to the server and a number of events are raised. Some important events are: Apart from the above mentioned properties, methods and events, multiview control inherits the members of the control and object class. The example page has three views. Each view has two button for navigating through the views. The content file code is as follows: <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="multiviewdemo._Default" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" > <head runat="server"> <title> Untitled Page </title> </head> <body> <form id="form1" runat="server"> <div> <h2>MultiView and View Controls</h2> <asp:DropDownList ID="DropDownList1" runat="server" onselectedindexchanged="DropDownList1_SelectedIndexChanged"> </asp:DropDownList> <hr /> <asp:MultiView ID="MultiView1" runat="server" ActiveViewIndex="2" onactiveviewchanged="MultiView1_ActiveViewChanged" > <asp:View ID="View1" runat="server"> <h3>This is view 1</h3> <br /> <asp:Button CommandName="NextView" ID="btnnext1" runat="server" Text = "Go To Next" /> <asp:Button CommandArgument="View3" CommandName="SwitchViewByID" ID="btnlast" runat="server" Text ="Go To Last" /> </asp:View> <asp:View ID="View2" runat="server"> <h3>This is view 2</h3> <asp:Button CommandName="NextView" ID="btnnext2" runat="server" Text = "Go To Next" /> <asp:Button CommandName="PrevView" ID="btnprevious2" runat="server" Text = "Go To Previous View" /> </asp:View> <asp:View ID="View3" runat="server"> <h3> This is view 3</h3> <br /> <asp:Calendar ID="Calender1" runat="server"></asp:Calendar> <br /> <asp:Button CommandArgument="0" CommandName="SwitchViewByIndex" ID="btnfirst" runat="server" Text = "Go To Next" /> <asp:Button CommandName="PrevView" ID="btnprevious" runat="server" Text = "Go To Previous View" /> </asp:View> </asp:MultiView> </div> </form> </body> </html> Observe the following: The MultiView.ActiveViewIndex determines which view will be shown. This is the only view rendered on the page. The default value for the ActiveViewIndex is -1, when no view is shown. Since the ActiveViewIndex is defined as 2 in the example, it shows the third view, when executed. 51 Lectures 5.5 hours Anadi Sharma 44 Lectures 4.5 hours Kaushik Roy Chowdhury 42 Lectures 18 hours SHIVPRASAD KOIRALA 57 Lectures 3.5 hours University Code 40 Lectures 2.5 hours University Code 138 Lectures 9 hours Bhrugen Patel Print Add Notes Bookmark this page
[ { "code": null, "e": 2592, "s": 2347, "text": "MultiView and View controls allow you to divide the content of a page into different groups, displaying only one group at a time. Each View control manages one group of content and all the View controls are held together in a MultiView control." }, { "code": null, "e": 2718, "s": 2592, "text": "The MultiView control is responsible for displaying one View control at a time. The View displayed is called the active view." }, { "code": null, "e": 2754, "s": 2718, "text": "The syntax of MultiView control is:" }, { "code": null, "e": 2819, "s": 2754, "text": "<asp:MultView ID= \"MultiView1\" runat= \"server\">\n</asp:MultiView>" }, { "code": null, "e": 2850, "s": 2819, "text": "The syntax of View control is:" }, { "code": null, "e": 2901, "s": 2850, "text": "<asp:View ID= \"View1\" runat= \"server\">\n</asp:View>" }, { "code": null, "e": 3055, "s": 2901, "text": "However, the View control cannot exist on its own. It would render error if you try to use it stand-alone. It is always used with a Multiview control as:" }, { "code": null, "e": 3174, "s": 3055, "text": "<asp:MultView ID= \"MultiView1\" runat= \"server\">\n <asp:View ID= \"View1\" runat= \"server\"> </asp:View>\n</asp:MultiView>" }, { "code": null, "e": 3413, "s": 3174, "text": "Both View and MultiView controls are derived from Control class and inherit all its properties, methods, and events. The most important property of the View control is Visible property of type Boolean, which sets the visibility of a view." }, { "code": null, "e": 3475, "s": 3413, "text": "The MultiView control has the following important properties:" }, { "code": null, "e": 3644, "s": 3475, "text": "The CommandName attribute of the button control associated with the navigation of the MultiView control are associated with some related field of the MultiView control." }, { "code": null, "e": 3836, "s": 3644, "text": "For example, if a button control with CommandName value as NextView is associated with the navigation of the multiview, it automatically navigates to the next view when the button is clicked." }, { "code": null, "e": 3913, "s": 3836, "text": "The following table shows the default command names of the above properties:" }, { "code": null, "e": 3965, "s": 3913, "text": "The important methods of the multiview control are:" }, { "code": null, "e": 4095, "s": 3965, "text": "Every time a view is changed, the page is posted back to the server and a number of events are raised. Some important events are:" }, { "code": null, "e": 4230, "s": 4095, "text": "Apart from the above mentioned properties, methods and events, multiview control inherits the members of the control and object class." }, { "code": null, "e": 4323, "s": 4230, "text": "The example page has three views. Each view has two button for navigating through the views." }, { "code": null, "e": 4360, "s": 4323, "text": "The content file code is as follows:" }, { "code": null, "e": 6548, "s": 4360, "text": "<%@ Page Language=\"C#\" AutoEventWireup=\"true\" CodeBehind=\"Default.aspx.cs\" Inherits=\"multiviewdemo._Default\" %>\n\n<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n\n<html xmlns=\"http://www.w3.org/1999/xhtml\" >\n\n <head runat=\"server\">\n <title>\n Untitled Page\n </title>\n </head>\n \n <body>\n <form id=\"form1\" runat=\"server\">\n \n <div>\n <h2>MultiView and View Controls</h2>\n \n <asp:DropDownList ID=\"DropDownList1\" runat=\"server\" onselectedindexchanged=\"DropDownList1_SelectedIndexChanged\">\n </asp:DropDownList>\n \n <hr />\n \n <asp:MultiView ID=\"MultiView1\" runat=\"server\" ActiveViewIndex=\"2\" onactiveviewchanged=\"MultiView1_ActiveViewChanged\" >\n <asp:View ID=\"View1\" runat=\"server\">\n <h3>This is view 1</h3>\n <br />\n <asp:Button CommandName=\"NextView\" ID=\"btnnext1\" runat=\"server\" Text = \"Go To Next\" />\n <asp:Button CommandArgument=\"View3\" CommandName=\"SwitchViewByID\" ID=\"btnlast\" runat=\"server\" Text =\"Go To Last\" />\n </asp:View> \n\t\t\t\t\t\n <asp:View ID=\"View2\" runat=\"server\">\n <h3>This is view 2</h3>\n <asp:Button CommandName=\"NextView\" ID=\"btnnext2\" runat=\"server\" Text = \"Go To Next\" />\n <asp:Button CommandName=\"PrevView\" ID=\"btnprevious2\" runat=\"server\" Text = \"Go To Previous View\" />\n </asp:View> \n\n <asp:View ID=\"View3\" runat=\"server\">\n <h3> This is view 3</h3>\n <br />\n <asp:Calendar ID=\"Calender1\" runat=\"server\"></asp:Calendar>\n <br />\n <asp:Button CommandArgument=\"0\" CommandName=\"SwitchViewByIndex\" ID=\"btnfirst\" runat=\"server\" Text = \"Go To Next\" />\n <asp:Button CommandName=\"PrevView\" ID=\"btnprevious\" runat=\"server\" Text = \"Go To Previous View\" />\n </asp:View> \n \n </asp:MultiView>\n </div>\n \n </form>\n </body>\n</html>" }, { "code": null, "e": 6571, "s": 6548, "text": "Observe the following:" }, { "code": null, "e": 6852, "s": 6571, "text": "The MultiView.ActiveViewIndex determines which view will be shown. This is the only view rendered on the page. The default value for the ActiveViewIndex is -1, when no view is shown. Since the ActiveViewIndex is defined as 2 in the example, it shows the third view, when executed." }, { "code": null, "e": 6887, "s": 6852, "text": "\n 51 Lectures \n 5.5 hours \n" }, { "code": null, "e": 6901, "s": 6887, "text": " Anadi Sharma" }, { "code": null, "e": 6936, "s": 6901, "text": "\n 44 Lectures \n 4.5 hours \n" }, { "code": null, "e": 6959, "s": 6936, "text": " Kaushik Roy Chowdhury" }, { "code": null, "e": 6993, "s": 6959, "text": "\n 42 Lectures \n 18 hours \n" }, { "code": null, "e": 7013, "s": 6993, "text": " SHIVPRASAD KOIRALA" }, { "code": null, "e": 7048, "s": 7013, "text": "\n 57 Lectures \n 3.5 hours \n" }, { "code": null, "e": 7065, "s": 7048, "text": " University Code" }, { "code": null, "e": 7100, "s": 7065, "text": "\n 40 Lectures \n 2.5 hours \n" }, { "code": null, "e": 7117, "s": 7100, "text": " University Code" }, { "code": null, "e": 7151, "s": 7117, "text": "\n 138 Lectures \n 9 hours \n" }, { "code": null, "e": 7166, "s": 7151, "text": " Bhrugen Patel" }, { "code": null, "e": 7173, "s": 7166, "text": " Print" }, { "code": null, "e": 7184, "s": 7173, "text": " Add Notes" } ]
Drools - Introduction
Any Java enterprise level application can be split into three parts − UI − User Interface (Frontend) Service layer which is in turn connected to a database Business layer We have a number of frameworks that handle the UI and service layer together, for example, Spring and Struts. Yet, we did not have a standard way to handle the business logic until Drools came into existence. Drools is a Business Logic integration Platform (BLiP). It is written in Java. It is an open source project that is backed by JBoss and Red Hat, Inc. It extends and implements the Rete Pattern matching algorithm. In layman’s terms, Drools is a collection of tools that allow us to separate and reason over logic and data found within business processes. The two important keywords we need to notice are Logic and Data. Drools is split into two main parts: Authoring and Runtime. Authoring − Authoring process involves the creation of Rules files (.DRL files). Authoring − Authoring process involves the creation of Rules files (.DRL files). Runtime − It involves the creation of working memory and handling the activation. Runtime − It involves the creation of working memory and handling the activation. Drools is Rule Engine or a Production Rule System that uses the rule-based approach to implement and Expert System. Expert Systems are knowledge-based systems that use knowledge representation to process acquired knowledge into a knowledge base that can be used for reasoning. A Production Rule System is Turing complete with a focus on knowledge representation to express propositional and first-order logic in a concise, non-ambiguous and declarative manner. The brain of a Production Rules System is an Inference Engine that can scale to a large number of rules and facts. The Inference Engine matches facts and data against Production Rules – also called Productions or just Rules – to infer conclusions which result in actions. A Production Rule is a two-part structure that uses first-order logic for reasoning over knowledge representation. A business rule engine is a software system that executes one or more business rules in a runtime production environment. A Rule Engine allows you to define “What to Do” and not “How to do it.” Rules are pieces of knowledge often expressed as, "When some conditions occur, then do some tasks." When <Condition is true> Then <Take desired Action> The most important part of a Rule is its when part. If the when part is satisfied, the then part is triggered. rule <rule_name> <attribute> <value> when <conditions> then <actions> end The process of matching the new or existing facts against Production Rules is called Pattern Matching, which is performed by the Inference Engine. There are a number of algorithms used for Pattern Matching including − Linear Rete Treat Leaps Drools Implements and extends the Rete Algorithm. The Drools Rete implementation is called ReteOO, signifying that Drools has an enhanced and optimized implementation of the Rete algorithm for object-oriented systems. Rules make it easy to express solutions to difficult problems and get the solutions verified as well. Unlike codes, Rules are written in less complex language; Business Analysts can easily read and verify a set of rules. The data resides in the Domain Objects and the business logic resides in the Rules. Depending upon the kind of project, this kind of separation can be very advantageous. The Rete OO algorithm on which Drools is written is already a proven algorithm. With the help of Drools, your application becomes very scalable. If there are frequent change requests, one can add new rules without having to modify the existing rules. By using Rules, you create a repository of knowledge (a knowledge base) which is executable. It is a single point of truth for business policy. Ideally, Rules are so readable that they can also serve as documentation. Tools such as Eclipse provide ways to edit and manage rules and get immediate feedback, validation, and content assistance. Auditing and debugging tools are also available. Print Add Notes Bookmark this page
[ { "code": null, "e": 1867, "s": 1797, "text": "Any Java enterprise level application can be split into three parts −" }, { "code": null, "e": 1898, "s": 1867, "text": "UI − User Interface (Frontend)" }, { "code": null, "e": 1953, "s": 1898, "text": "Service layer which is in turn connected to a database" }, { "code": null, "e": 1968, "s": 1953, "text": "Business layer" }, { "code": null, "e": 2177, "s": 1968, "text": "We have a number of frameworks that handle the UI and service layer together, for example, Spring and Struts. Yet, we did not have a standard way to handle the business logic until Drools came into existence." }, { "code": null, "e": 2390, "s": 2177, "text": "Drools is a Business Logic integration Platform (BLiP). It is written in Java. It is an open source project that is backed by JBoss and Red Hat, Inc. It extends and implements the Rete Pattern matching algorithm." }, { "code": null, "e": 2596, "s": 2390, "text": "In layman’s terms, Drools is a collection of tools that allow us to separate and reason over logic and data found within business processes. The two important keywords we need to notice are Logic and Data." }, { "code": null, "e": 2656, "s": 2596, "text": "Drools is split into two main parts: Authoring and Runtime." }, { "code": null, "e": 2737, "s": 2656, "text": "Authoring − Authoring process involves the creation of Rules files (.DRL files)." }, { "code": null, "e": 2818, "s": 2737, "text": "Authoring − Authoring process involves the creation of Rules files (.DRL files)." }, { "code": null, "e": 2900, "s": 2818, "text": "Runtime − It involves the creation of working memory and handling the activation." }, { "code": null, "e": 2982, "s": 2900, "text": "Runtime − It involves the creation of working memory and handling the activation." }, { "code": null, "e": 3259, "s": 2982, "text": "Drools is Rule Engine or a Production Rule System that uses the rule-based approach to implement and Expert System. Expert Systems are knowledge-based systems that use knowledge representation to process acquired knowledge into a knowledge base that can be used for reasoning." }, { "code": null, "e": 3443, "s": 3259, "text": "A Production Rule System is Turing complete with a focus on knowledge representation to express propositional and first-order logic in a concise, non-ambiguous and declarative manner." }, { "code": null, "e": 3715, "s": 3443, "text": "The brain of a Production Rules System is an Inference Engine that can scale to a large number of rules and facts. The Inference Engine matches facts and data against Production Rules – also called Productions or just Rules – to infer conclusions which result in actions." }, { "code": null, "e": 3952, "s": 3715, "text": "A Production Rule is a two-part structure that uses first-order logic for reasoning over knowledge representation. A business rule engine is a software system that executes one or more business rules in a runtime production environment." }, { "code": null, "e": 4024, "s": 3952, "text": "A Rule Engine allows you to define “What to Do” and not “How to do it.”" }, { "code": null, "e": 4124, "s": 4024, "text": "Rules are pieces of knowledge often expressed as, \"When some conditions occur, then do some tasks.\"" }, { "code": null, "e": 4182, "s": 4124, "text": "When\n <Condition is true>\nThen\n <Take desired Action>" }, { "code": null, "e": 4293, "s": 4182, "text": "The most important part of a Rule is its when part. If the when part is satisfied, the then part is triggered." }, { "code": null, "e": 4403, "s": 4293, "text": "rule <rule_name>\n <attribute> <value>\n \n when\n <conditions>\n \n then\n <actions>\nend" }, { "code": null, "e": 4621, "s": 4403, "text": "The process of matching the new or existing facts against Production Rules is called Pattern Matching, which is performed by the Inference Engine. There are a number of algorithms used for Pattern Matching including −" }, { "code": null, "e": 4628, "s": 4621, "text": "Linear" }, { "code": null, "e": 4633, "s": 4628, "text": "Rete" }, { "code": null, "e": 4639, "s": 4633, "text": "Treat" }, { "code": null, "e": 4645, "s": 4639, "text": "Leaps" }, { "code": null, "e": 4863, "s": 4645, "text": "Drools Implements and extends the Rete Algorithm. The Drools Rete implementation is called ReteOO, signifying that Drools has an enhanced and optimized implementation of the Rete algorithm for object-oriented systems." }, { "code": null, "e": 5084, "s": 4863, "text": "Rules make it easy to express solutions to difficult problems and get the solutions verified as well. Unlike codes, Rules are written in less complex language; Business Analysts can easily read and verify a set of rules." }, { "code": null, "e": 5254, "s": 5084, "text": "The data resides in the Domain Objects and the business logic resides in the Rules. Depending upon the kind of project, this kind of separation can be very advantageous." }, { "code": null, "e": 5505, "s": 5254, "text": "The Rete OO algorithm on which Drools is written is already a proven algorithm. With the help of Drools, your application becomes very scalable. If there are frequent change requests, one can add new rules without having to modify the existing rules." }, { "code": null, "e": 5723, "s": 5505, "text": "By using Rules, you create a repository of knowledge (a knowledge base) which is executable. It is a single point of truth for business policy. Ideally, Rules are so readable that they can also serve as documentation." }, { "code": null, "e": 5896, "s": 5723, "text": "Tools such as Eclipse provide ways to edit and manage rules and get immediate feedback, validation, and content assistance. Auditing and debugging tools are also available." }, { "code": null, "e": 5903, "s": 5896, "text": " Print" }, { "code": null, "e": 5914, "s": 5903, "text": " Add Notes" } ]
How to create a zip file using Python?
Use the zipfile module to create a zip archive of a directory. Walk the directory tree using os.walk and add all the files in it recursively. import os import zipfile def zipdir(path, ziph): # ziph is zipfile handle for root, dirs, files in os.walk(path): for file in files: ziph.write(os.path.join(root, file)) zipf = zipfile.ZipFile('Zipped_file.zip', 'w', zipfile.ZIP_DEFLATED) zipdir('./my_folder', zipf) zipf.close() The above code will zip the contents of my_folder in a file 'Zipped_file.zip'. and store it in the current directory.
[ { "code": null, "e": 1204, "s": 1062, "text": "Use the zipfile module to create a zip archive of a directory. Walk the directory tree using os.walk and add all the files in it recursively." }, { "code": null, "e": 1512, "s": 1204, "text": "import os\nimport zipfile\ndef zipdir(path, ziph):\n # ziph is zipfile handle\n for root, dirs, files in os.walk(path):\n for file in files:\n ziph.write(os.path.join(root, file))\nzipf = zipfile.ZipFile('Zipped_file.zip', 'w', zipfile.ZIP_DEFLATED)\nzipdir('./my_folder', zipf)\nzipf.close()" }, { "code": null, "e": 1630, "s": 1512, "text": "The above code will zip the contents of my_folder in a file 'Zipped_file.zip'. and store it in the current directory." } ]
Redis - Keys Ttl Command
Redis TTL command is used to get the remaining time of the key expiry in seconds. Integer value TTL in milliseconds, or a negative value. TTL in milliseconds. -1, if key does not have expiry timeout. -2, if key does not exist. Following is the basic syntax of Redis TTL command. redis 127.0.0.1:6379> TTL KEY_NAME First, create a key in Redis and set some value in it. redis 127.0.0.1:6379> SET tutorialname redis OK Now, set the expiry of the key, and later check the remaining expiry time. redis 127.0.0.1:6379> EXPIRE tutorialname 60 1) (integer) 1 redis 127.0.0.1:6379> TTL tutorialname 1) (integer) 59 22 Lectures 40 mins Skillbakerystudios Print Add Notes Bookmark this page
[ { "code": null, "e": 2127, "s": 2045, "text": "Redis TTL command is used to get the remaining time of the key expiry in seconds." }, { "code": null, "e": 2183, "s": 2127, "text": "Integer value TTL in milliseconds, or a negative value." }, { "code": null, "e": 2204, "s": 2183, "text": "TTL in milliseconds." }, { "code": null, "e": 2245, "s": 2204, "text": "-1, if key does not have expiry timeout." }, { "code": null, "e": 2272, "s": 2245, "text": "-2, if key does not exist." }, { "code": null, "e": 2324, "s": 2272, "text": "Following is the basic syntax of Redis TTL command." }, { "code": null, "e": 2361, "s": 2324, "text": "redis 127.0.0.1:6379> TTL KEY_NAME \n" }, { "code": null, "e": 2416, "s": 2361, "text": "First, create a key in Redis and set some value in it." }, { "code": null, "e": 2467, "s": 2416, "text": "redis 127.0.0.1:6379> SET tutorialname redis \nOK \n" }, { "code": null, "e": 2542, "s": 2467, "text": "Now, set the expiry of the key, and later check the remaining expiry time." }, { "code": null, "e": 2661, "s": 2542, "text": "redis 127.0.0.1:6379> EXPIRE tutorialname 60 \n1) (integer) 1 \nredis 127.0.0.1:6379> TTL tutorialname \n1) (integer) 59\n" }, { "code": null, "e": 2693, "s": 2661, "text": "\n 22 Lectures \n 40 mins\n" }, { "code": null, "e": 2713, "s": 2693, "text": " Skillbakerystudios" }, { "code": null, "e": 2720, "s": 2713, "text": " Print" }, { "code": null, "e": 2731, "s": 2720, "text": " Add Notes" } ]
How to parse JSON in Java - GeeksforGeeks
07 Aug, 2019 JSON (JavaScript Object Notation) is a lightweight, text-based, language-independent data exchange format that is easy for humans and machines to read and write. JSON can represent two structured types: objects and arrays. An object is an unordered collection of zero or more name/value pairs. An array is an ordered sequence of zero or more values. The values can be strings, numbers, booleans, null, and these two structured types. Below is a simple example from Wikipedia that shows JSON representation of an object that describes a person. The object has string values for first name and last name, a number value for age, an object value representing the person’s address, and an array value of phone number objects. { "firstName": "John", "lastName": "Smith", "age": 25, "address": { "streetAddress": "21 2nd Street", "city": "New York", "state": "NY", "postalCode": 10021 }, "phoneNumbers": [ { "type": "home", "number": "212 555-1234" }, { "type": "fax", "number": "646 555-4567" } ] } JSON Processing in Java : The Java API for JSON Processing JSON.simple is a simple Java library that allow parse, generate, transform, and query JSON. Getting Started : You need to download the json-simple-1.1 jar and put it in your CLASSPATH before compiling and running the below example codes. For importing jar in IDE like eclipse, refer here. If you are using maven you may use the following maven link https://mvnrepository.com/artifact/com.googlecode.json-simple/json-simple/1.1.1 Json-Simple API : It provides object models for JSON object and array structures. These JSON structures are represented as object models using types JSONObject and JSONArray. JSONObject provides a Map view to access the unordered collection of zero or more name/value pairs from the model. Similarly, JSONArray provides a List view to access the ordered sequence of zero or more values from the model. Write JSON to a file Let us see an example that writes above JSON data into a file “JSONExample.json”, with help of JSONObject and JSONArray. // Java program for write JSON to a file import java.io.FileNotFoundException;import java.io.PrintWriter;import java.util.LinkedHashMap;import java.util.Map;import org.json.simple.JSONArray;import org.json.simple.JSONObject; public class JSONWriteExample{ public static void main(String[] args) throws FileNotFoundException { // creating JSONObject JSONObject jo = new JSONObject(); // putting data to JSONObject jo.put("firstName", "John"); jo.put("lastName", "Smith"); jo.put("age", 25); // for address data, first create LinkedHashMap Map m = new LinkedHashMap(4); m.put("streetAddress", "21 2nd Street"); m.put("city", "New York"); m.put("state", "NY"); m.put("postalCode", 10021); // putting address to JSONObject jo.put("address", m); // for phone numbers, first create JSONArray JSONArray ja = new JSONArray(); m = new LinkedHashMap(2); m.put("type", "home"); m.put("number", "212 555-1234"); // adding map to list ja.add(m); m = new LinkedHashMap(2); m.put("type", "fax"); m.put("number", "212 555-1234"); // adding map to list ja.add(m); // putting phoneNumbers to JSONObject jo.put("phoneNumbers", ja); // writing JSON to file:"JSONExample.json" in cwd PrintWriter pw = new PrintWriter("JSONExample.json"); pw.write(jo.toJSONString()); pw.flush(); pw.close(); }} Output from file “JSONExample.json” : { "lastName":"Smith", "address":{ "streetAddress":"21 2nd Street", "city":"New York", "state":"NY", "postalCode":10021 }, "age":25, "phoneNumbers":[ { "type":"home", "number":"212 555-1234" }, { "type":"fax", "number":"212 555-1234" } ], "firstName":"John" } Note : In JSON, An object is an unordered set of name/value pairs, so JSONObject doesn’t preserve the order of an object’s name/value pairs, since it is (by definition) not significant. Hence in our output file, order is not preserved. Read JSON from a file Let us see an example that read JSON data from above created file “JSONExample.json” with help of JSONParser, JSONObject and JSONArray. // Java program to read JSON from a file import java.io.FileReader;import java.util.Iterator;import java.util.Map; import org.json.simple.JSONArray;import org.json.simple.JSONObject;import org.json.simple.parser.*; public class JSONReadExample { public static void main(String[] args) throws Exception { // parsing file "JSONExample.json" Object obj = new JSONParser().parse(new FileReader("JSONExample.json")); // typecasting obj to JSONObject JSONObject jo = (JSONObject) obj; // getting firstName and lastName String firstName = (String) jo.get("firstName"); String lastName = (String) jo.get("lastName"); System.out.println(firstName); System.out.println(lastName); // getting age long age = (long) jo.get("age"); System.out.println(age); // getting address Map address = ((Map)jo.get("address")); // iterating address Map Iterator<Map.Entry> itr1 = address.entrySet().iterator(); while (itr1.hasNext()) { Map.Entry pair = itr1.next(); System.out.println(pair.getKey() + " : " + pair.getValue()); } // getting phoneNumbers JSONArray ja = (JSONArray) jo.get("phoneNumbers"); // iterating phoneNumbers Iterator itr2 = ja.iterator(); while (itr2.hasNext()) { itr1 = ((Map) itr2.next()).entrySet().iterator(); while (itr1.hasNext()) { Map.Entry pair = itr1.next(); System.out.println(pair.getKey() + " : " + pair.getValue()); } } }} Output: John Smith 25 streetAddress : 21 2nd Street postalCode : 10021 state : NY city : New York number : 212 555-1234 type : home number : 212 555-1234 type : fax This article is contributed by Gaurav Miglani. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.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. ankitjainst JSON Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Interfaces in Java ArrayList in Java Overriding in Java Stack Class in Java Collections in Java Set in Java Singleton Class in Java LinkedList in Java Multithreading in Java Inheritance in Java
[ { "code": null, "e": 24716, "s": 24688, "text": "\n07 Aug, 2019" }, { "code": null, "e": 25150, "s": 24716, "text": "JSON (JavaScript Object Notation) is a lightweight, text-based, language-independent data exchange format that is easy for humans and machines to read and write. JSON can represent two structured types: objects and arrays. An object is an unordered collection of zero or more name/value pairs. An array is an ordered sequence of zero or more values. The values can be strings, numbers, booleans, null, and these two structured types." }, { "code": null, "e": 25438, "s": 25150, "text": "Below is a simple example from Wikipedia that shows JSON representation of an object that describes a person. The object has string values for first name and last name, a number value for age, an object value representing the person’s address, and an array value of phone number objects." }, { "code": null, "e": 25853, "s": 25438, "text": "{\n \"firstName\": \"John\",\n \"lastName\": \"Smith\",\n \"age\": 25,\n \"address\": {\n \"streetAddress\": \"21 2nd Street\",\n \"city\": \"New York\",\n \"state\": \"NY\",\n \"postalCode\": 10021\n },\n \"phoneNumbers\": [\n {\n \"type\": \"home\",\n \"number\": \"212 555-1234\"\n },\n {\n \"type\": \"fax\",\n \"number\": \"646 555-4567\" \n }\n ] \n}\n" }, { "code": null, "e": 26004, "s": 25853, "text": "JSON Processing in Java : The Java API for JSON Processing JSON.simple is a simple Java library that allow parse, generate, transform, and query JSON." }, { "code": null, "e": 26150, "s": 26004, "text": "Getting Started : You need to download the json-simple-1.1 jar and put it in your CLASSPATH before compiling and running the below example codes." }, { "code": null, "e": 26201, "s": 26150, "text": "For importing jar in IDE like eclipse, refer here." }, { "code": null, "e": 26341, "s": 26201, "text": "If you are using maven you may use the following maven link https://mvnrepository.com/artifact/com.googlecode.json-simple/json-simple/1.1.1" }, { "code": null, "e": 26743, "s": 26341, "text": "Json-Simple API : It provides object models for JSON object and array structures. These JSON structures are represented as object models using types JSONObject and JSONArray. JSONObject provides a Map view to access the unordered collection of zero or more name/value pairs from the model. Similarly, JSONArray provides a List view to access the ordered sequence of zero or more values from the model." }, { "code": null, "e": 26764, "s": 26743, "text": "Write JSON to a file" }, { "code": null, "e": 26885, "s": 26764, "text": "Let us see an example that writes above JSON data into a file “JSONExample.json”, with help of JSONObject and JSONArray." }, { "code": "// Java program for write JSON to a file import java.io.FileNotFoundException;import java.io.PrintWriter;import java.util.LinkedHashMap;import java.util.Map;import org.json.simple.JSONArray;import org.json.simple.JSONObject; public class JSONWriteExample{ public static void main(String[] args) throws FileNotFoundException { // creating JSONObject JSONObject jo = new JSONObject(); // putting data to JSONObject jo.put(\"firstName\", \"John\"); jo.put(\"lastName\", \"Smith\"); jo.put(\"age\", 25); // for address data, first create LinkedHashMap Map m = new LinkedHashMap(4); m.put(\"streetAddress\", \"21 2nd Street\"); m.put(\"city\", \"New York\"); m.put(\"state\", \"NY\"); m.put(\"postalCode\", 10021); // putting address to JSONObject jo.put(\"address\", m); // for phone numbers, first create JSONArray JSONArray ja = new JSONArray(); m = new LinkedHashMap(2); m.put(\"type\", \"home\"); m.put(\"number\", \"212 555-1234\"); // adding map to list ja.add(m); m = new LinkedHashMap(2); m.put(\"type\", \"fax\"); m.put(\"number\", \"212 555-1234\"); // adding map to list ja.add(m); // putting phoneNumbers to JSONObject jo.put(\"phoneNumbers\", ja); // writing JSON to file:\"JSONExample.json\" in cwd PrintWriter pw = new PrintWriter(\"JSONExample.json\"); pw.write(jo.toJSONString()); pw.flush(); pw.close(); }}", "e": 28512, "s": 26885, "text": null }, { "code": null, "e": 28550, "s": 28512, "text": "Output from file “JSONExample.json” :" }, { "code": null, "e": 28944, "s": 28550, "text": "{\n \"lastName\":\"Smith\",\n \"address\":{\n \"streetAddress\":\"21 2nd Street\",\n \"city\":\"New York\",\n \"state\":\"NY\",\n \"postalCode\":10021\n },\n \"age\":25,\n \"phoneNumbers\":[\n {\n \"type\":\"home\", \"number\":\"212 555-1234\"\n },\n {\n \"type\":\"fax\", \"number\":\"212 555-1234\"\n }\n ],\n \"firstName\":\"John\"\n}\n" }, { "code": null, "e": 29180, "s": 28944, "text": "Note : In JSON, An object is an unordered set of name/value pairs, so JSONObject doesn’t preserve the order of an object’s name/value pairs, since it is (by definition) not significant. Hence in our output file, order is not preserved." }, { "code": null, "e": 29202, "s": 29180, "text": "Read JSON from a file" }, { "code": null, "e": 29338, "s": 29202, "text": "Let us see an example that read JSON data from above created file “JSONExample.json” with help of JSONParser, JSONObject and JSONArray." }, { "code": "// Java program to read JSON from a file import java.io.FileReader;import java.util.Iterator;import java.util.Map; import org.json.simple.JSONArray;import org.json.simple.JSONObject;import org.json.simple.parser.*; public class JSONReadExample { public static void main(String[] args) throws Exception { // parsing file \"JSONExample.json\" Object obj = new JSONParser().parse(new FileReader(\"JSONExample.json\")); // typecasting obj to JSONObject JSONObject jo = (JSONObject) obj; // getting firstName and lastName String firstName = (String) jo.get(\"firstName\"); String lastName = (String) jo.get(\"lastName\"); System.out.println(firstName); System.out.println(lastName); // getting age long age = (long) jo.get(\"age\"); System.out.println(age); // getting address Map address = ((Map)jo.get(\"address\")); // iterating address Map Iterator<Map.Entry> itr1 = address.entrySet().iterator(); while (itr1.hasNext()) { Map.Entry pair = itr1.next(); System.out.println(pair.getKey() + \" : \" + pair.getValue()); } // getting phoneNumbers JSONArray ja = (JSONArray) jo.get(\"phoneNumbers\"); // iterating phoneNumbers Iterator itr2 = ja.iterator(); while (itr2.hasNext()) { itr1 = ((Map) itr2.next()).entrySet().iterator(); while (itr1.hasNext()) { Map.Entry pair = itr1.next(); System.out.println(pair.getKey() + \" : \" + pair.getValue()); } } }}", "e": 31035, "s": 29338, "text": null }, { "code": null, "e": 31043, "s": 31035, "text": "Output:" }, { "code": null, "e": 31201, "s": 31043, "text": "John\nSmith\n25\nstreetAddress : 21 2nd Street\npostalCode : 10021\nstate : NY\ncity : New York\nnumber : 212 555-1234\ntype : home\nnumber : 212 555-1234\ntype : fax\n" }, { "code": null, "e": 31503, "s": 31201, "text": "This article is contributed by Gaurav Miglani. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.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": 31628, "s": 31503, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 31640, "s": 31628, "text": "ankitjainst" }, { "code": null, "e": 31645, "s": 31640, "text": "JSON" }, { "code": null, "e": 31650, "s": 31645, "text": "Java" }, { "code": null, "e": 31655, "s": 31650, "text": "Java" }, { "code": null, "e": 31753, "s": 31655, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31762, "s": 31753, "text": "Comments" }, { "code": null, "e": 31775, "s": 31762, "text": "Old Comments" }, { "code": null, "e": 31794, "s": 31775, "text": "Interfaces in Java" }, { "code": null, "e": 31812, "s": 31794, "text": "ArrayList in Java" }, { "code": null, "e": 31831, "s": 31812, "text": "Overriding in Java" }, { "code": null, "e": 31851, "s": 31831, "text": "Stack Class in Java" }, { "code": null, "e": 31871, "s": 31851, "text": "Collections in Java" }, { "code": null, "e": 31883, "s": 31871, "text": "Set in Java" }, { "code": null, "e": 31907, "s": 31883, "text": "Singleton Class in Java" }, { "code": null, "e": 31926, "s": 31907, "text": "LinkedList in Java" }, { "code": null, "e": 31949, "s": 31926, "text": "Multithreading in Java" } ]
VueJS - Template
We have learnt in the earlier chapters, how to get an output in the form of text content on the screen. In this chapter, we will learn how to get an output in the form of HTML template on the screen. To understand this, let us consider an example and see the output in the browser. <html> <head> <title>VueJs Instance</title> <script type = "text/javascript" src = "js/vue.js"></script> </head> <body> <div id = "vue_det"> <h1>Firstname : {{firstname}}</h1> <h1>Lastname : {{lastname}}</h1> <div>{{htmlcontent}}</div> </div> <script type = "text/javascript" src = "js/vue_template.js"></script> </body> </html> var vm = new Vue({ el: '#vue_det', data: { firstname : "Ria", lastname : "Singh", htmlcontent : "<div><h1>Vue Js Template</h1></div>" } }) Now, suppose we want to show the html content on the page. If we happen to use it with interpolation, i.e. with double curly brackets, this is what we will get in the browser. If we see the html content is displayed the same way we have given in the variable htmlcontent, this is not what we want, we want it to be displayed in a proper HTML content on the browser. For this, we will have to use v-html directive. The moment we assign v-html directive to the html element, VueJS knows that it has to output it as HTML content. Let’s add v-html directive in the .html file and see the difference. <html> <head> <title>VueJs Instance</title> <script type = "text/javascript" src = "js/vue.js"></script> </head> <body> <div id = "vue_det"> <h1>Firstname : {{firstname}}</h1> <h1>Lastname : {{lastname}}</h1> <div v-html = "htmlcontent"></div> </div> <script type = "text/javascript" src = "js/vue_template.js"></script> </body> </html> Now, we don’t need the double curly brackets to show the HTML content, instead we have used v-html = ”htmlcontent” where htmlcontent is defined inside the js file as follows − var vm = new Vue({ el: '#vue_det', data: { firstname : "Ria", lastname : "Singh", htmlcontent : "<div><h1>Vue Js Template</h1></div>" } }) The output in the browser is as follows − If we inspect the browser, we will see the content is added in the same way as it is defined in the .js file to the variable htmlcontent : "<div><h1>Vue Js Template</h1></div>". Let’s take a look at the inspect element in the browser. We have seen how to add HTML template to the DOM. Now, we will see how to add attributes to the exiting HTML elements. Consider, we have an image tag in the HTML file and we want to assign src, which is a part of Vue. <html> <head> <title>VueJs Instance</title> <script type = "text/javascript" src = "js/vue.js"></script> </head> <body> <div id = "vue_det"> <h1>Firstname : {{firstname}}</h1> <h1>Lastname : {{lastname}}</h1> <div v-html = "htmlcontent"></div> <img src = "" width = "300" height = "250" /> </div> <script type = "text/javascript" src = "js/vue_template1.js"></script> </body> </html> Look at the img tag above, the src is blank. We need to add the src to it from vue js. Let us take a look at how to do it. We will store the img src in the data object in the .js file as follows − var vm = new Vue({ el: '#vue_det', data: { firstname : "Ria", lastname : "Singh", htmlcontent : "<div><h1>Vue Js Template</h1></div>", imgsrc : "images/img.jpg" } }) If we assign the src as follows, the output in the browser will be as shown in the following screenshot. <img src = "{{imgsrc}}" width = "300" height = "250" /> We get a broken image. To assign any attribute to HMTL tag, we need to use v-bind directive. Let’s add the src to the image with v-bind directive. This is how it is assigned in .html file. <html> <head> <title>VueJs Instance</title> <script type = "text/javascript" src = "js/vue.js"></script> </head> <body> <div id = "vue_det"> <h1>Firstname : {{firstname}}</h1> <h1>Lastname : {{lastname}}</h1> <div v-html = "htmlcontent"></div> <img v-bind:src = "imgsrc" width = "300" height = "250" /> </div> <script type = "text/javascript" src = "js/vue_template1.js"></script> </body> </html> We need to prefix the src with v-bind:src = ”imgsrc” and the name of the variable with src. Following is the output in the browser. Let us inspect and check how the src looks like with v-bind. As seen in the above screenshot, the src is assigned without any vuejs properties to it. Print Add Notes Bookmark this page
[ { "code": null, "e": 2136, "s": 1936, "text": "We have learnt in the earlier chapters, how to get an output in the form of text content on the screen. In this chapter, we will learn how to get an output in the form of HTML template on the screen." }, { "code": null, "e": 2218, "s": 2136, "text": "To understand this, let us consider an example and see the output in the browser." }, { "code": null, "e": 2616, "s": 2218, "text": "<html>\n <head>\n <title>VueJs Instance</title>\n <script type = \"text/javascript\" src = \"js/vue.js\"></script>\n </head>\n <body>\n <div id = \"vue_det\">\n <h1>Firstname : {{firstname}}</h1>\n <h1>Lastname : {{lastname}}</h1>\n <div>{{htmlcontent}}</div>\n </div>\n <script type = \"text/javascript\" src = \"js/vue_template.js\"></script>\n </body>\n</html>" }, { "code": null, "e": 2783, "s": 2616, "text": "var vm = new Vue({\n el: '#vue_det',\n data: {\n firstname : \"Ria\",\n lastname : \"Singh\",\n htmlcontent : \"<div><h1>Vue Js Template</h1></div>\"\n }\n})" }, { "code": null, "e": 2959, "s": 2783, "text": "Now, suppose we want to show the html content on the page. If we happen to use it with interpolation, i.e. with double curly brackets, this is what we will get in the browser." }, { "code": null, "e": 3149, "s": 2959, "text": "If we see the html content is displayed the same way we have given in the variable htmlcontent, this is not what we want, we want it to be displayed in a proper HTML content on the browser." }, { "code": null, "e": 3379, "s": 3149, "text": "For this, we will have to use v-html directive. The moment we assign v-html directive to the html element, VueJS knows that it has to output it as HTML content. Let’s add v-html directive in the .html file and see the difference." }, { "code": null, "e": 3785, "s": 3379, "text": "<html>\n <head>\n <title>VueJs Instance</title>\n <script type = \"text/javascript\" src = \"js/vue.js\"></script>\n </head>\n <body>\n <div id = \"vue_det\">\n <h1>Firstname : {{firstname}}</h1>\n <h1>Lastname : {{lastname}}</h1>\n <div v-html = \"htmlcontent\"></div>\n </div>\n <script type = \"text/javascript\" src = \"js/vue_template.js\"></script>\n </body>\n</html>" }, { "code": null, "e": 3961, "s": 3785, "text": "Now, we don’t need the double curly brackets to show the HTML content, instead we have used v-html = ”htmlcontent” where htmlcontent is defined inside the js file as follows −" }, { "code": null, "e": 4128, "s": 3961, "text": "var vm = new Vue({\n el: '#vue_det',\n data: {\n firstname : \"Ria\",\n lastname : \"Singh\",\n htmlcontent : \"<div><h1>Vue Js Template</h1></div>\"\n }\n})" }, { "code": null, "e": 4170, "s": 4128, "text": "The output in the browser is as follows −" }, { "code": null, "e": 4348, "s": 4170, "text": "If we inspect the browser, we will see the content is added in the same way as it is defined in the .js file to the variable htmlcontent : \"<div><h1>Vue Js Template</h1></div>\"." }, { "code": null, "e": 4405, "s": 4348, "text": "Let’s take a look at the inspect element in the browser." }, { "code": null, "e": 4524, "s": 4405, "text": "We have seen how to add HTML template to the DOM. Now, we will see how to add attributes to the exiting HTML elements." }, { "code": null, "e": 4623, "s": 4524, "text": "Consider, we have an image tag in the HTML file and we want to assign src, which is a part of Vue." }, { "code": null, "e": 5085, "s": 4623, "text": "<html>\n <head>\n <title>VueJs Instance</title>\n <script type = \"text/javascript\" src = \"js/vue.js\"></script>\n </head>\n <body>\n <div id = \"vue_det\">\n <h1>Firstname : {{firstname}}</h1>\n <h1>Lastname : {{lastname}}</h1>\n <div v-html = \"htmlcontent\"></div>\n <img src = \"\" width = \"300\" height = \"250\" />\n </div>\n <script type = \"text/javascript\" src = \"js/vue_template1.js\"></script>\n </body>\n</html>" }, { "code": null, "e": 5282, "s": 5085, "text": "Look at the img tag above, the src is blank. We need to add the src to it from vue js. Let us take a look at how to do it. We will store the img src in the data object in the .js file as follows −" }, { "code": null, "e": 5482, "s": 5282, "text": "var vm = new Vue({\n el: '#vue_det',\n data: {\n firstname : \"Ria\",\n lastname : \"Singh\",\n htmlcontent : \"<div><h1>Vue Js Template</h1></div>\",\n imgsrc : \"images/img.jpg\"\n }\n})" }, { "code": null, "e": 5587, "s": 5482, "text": "If we assign the src as follows, the output in the browser will be as shown in the following screenshot." }, { "code": null, "e": 5643, "s": 5587, "text": "<img src = \"{{imgsrc}}\" width = \"300\" height = \"250\" />" }, { "code": null, "e": 5790, "s": 5643, "text": "We get a broken image. To assign any attribute to HMTL tag, we need to use v-bind directive. Let’s add the src to the image with v-bind directive." }, { "code": null, "e": 5832, "s": 5790, "text": "This is how it is assigned in .html file." }, { "code": null, "e": 6307, "s": 5832, "text": "<html>\n <head>\n <title>VueJs Instance</title>\n <script type = \"text/javascript\" src = \"js/vue.js\"></script>\n </head>\n <body>\n <div id = \"vue_det\">\n <h1>Firstname : {{firstname}}</h1>\n <h1>Lastname : {{lastname}}</h1>\n <div v-html = \"htmlcontent\"></div>\n <img v-bind:src = \"imgsrc\" width = \"300\" height = \"250\" />\n </div>\n <script type = \"text/javascript\" src = \"js/vue_template1.js\"></script>\n </body>\n</html>" }, { "code": null, "e": 6399, "s": 6307, "text": "We need to prefix the src with v-bind:src = ”imgsrc” and the name of the variable with src." }, { "code": null, "e": 6439, "s": 6399, "text": "Following is the output in the browser." }, { "code": null, "e": 6500, "s": 6439, "text": "Let us inspect and check how the src looks like with v-bind." }, { "code": null, "e": 6589, "s": 6500, "text": "As seen in the above screenshot, the src is assigned without any vuejs properties to it." }, { "code": null, "e": 6596, "s": 6589, "text": " Print" }, { "code": null, "e": 6607, "s": 6596, "text": " Add Notes" } ]
Collect Stock and Options Data Easily using Python and Ally Financial API — 3 Example Queries | by Eric Kleppen | Towards Data Science
For a period of my life, I was obsessed with financial markets and wanted to be a day trader. I worked nights, so it was easy to spend my mornings surrounded by computer monitors displaying everything from stocks, options, news and trade chat-rooms. Spoiler alert... I gave up on day trading, but not on investing. Ultimately, I learned that I loved analyzing data more than trading, and then I put my self on a path to learn data analysis and get into Data Science. When I was exploring ways to collect stock and options data, I checked out the API offered by one of my brokers, Ally Financial. It was free to use and easy to code. This is the cheat-sheet I put together for using the Ally Financial API to collect the following: Time and Sales for Stocks Options Market Depth Options Extended Quote If you’re not familiar with an API, check out some of these resources. It is possible to automate trades through their API, but I never got that far into it. Explore all the functionality in their documentation. www.ally.com You can find the complete cheat sheet at the bottom of the article or on my GitHub! github.com On to the code! Connecting to the API uses OAuth1. You can find a list of OAuth clients on the OAuth site here. I use the OAuth library requests_oauthlib. Use pip install requests-oauthlib as needed. import requestsfrom requests_oauthlib import OAuth1from config import (api_key, secret, oath_token, oath_secret)import pandas as pdimport sqlalchemyimport numpy as npimport sqlite3from sqlite3 import Errorimport matplotlib.pyplot as pltimport datetime as dt Notice I use a config file to import api_key, secret, oath_token, oath_secret. That way I don’t need to include those personal tokens in the code. #authentication auth = OAuth1(api_key, secret, oath_token, oath_secret) I pass the imported tokens to OAuth1. This will be used when we make the request to the API. This API call will return time and sales quote data based on a symbol passed as a query parameter. For a list of all the query parameters, check out the documentation. The example URL consists of the base url, api route, and query. Base url: https://api.tradeking.com/Route: v1/market/timesales.jsonQuery: ?symbols=MSFT&startdate=2019–05–03&interval=1min Documentation: https://www.ally.com/api/invest/documentation/market-timesales-get/ #url call to the apiurl = 'https://api.tradeking.com/v1/market/timesales.json?symbols=MSFT&startdate=2019-05-03&interval=1min'#api requestresponse = requests.get(url, auth = auth).json() Notice I pass the URL and oAuth values into requests and return the response as json. This is an example of the response: I put the quote data into a Panda’s DataFrame and format the data types. #send to data frame and format data typesdf = pd.DataFrame(response["response"]["quotes"]["quote"])df = df.sort_values(['datetime'], ascending = False)df['date'] = pd.to_datetime(df['date'])df['datetime'] = pd.to_datetime(df['datetime'], utc=False).dt.tz_convert('US/Central')df['hi'] = df["hi"].astype(float)df['incr_vol'] = df["incr_vl"].astype(float)df['last'] = df["last"].astype(float)df['lo'] = df["lo"].astype(float)df['opn'] = df["opn"].astype(float)df['vl'] = df['vl'].astype(float)df.head() The date time values need to be converted so they can be resampled. Resampling allows you to manipulate the frequency of a time series. According to the documentation, the Object must have a datetime-like index (DatetimeIndex, PeriodIndex, or TimedeltaIndex), or pass datetime-like values to the on or level keyword. #resample the time value to be greater than 1 min as needed. Example: 30 min resample for last pricedf.set_index(df['datetime'], inplace = True)df.head()df_resample30 = df.resample(rule = '30min', label = 'right').last()df_resample30.head() Notice the datetime increments by 30 minutes instead of 1 minute after the resampling. This api call provides market depth for options. This call will return the full list of available option strikes for a given symbol. While this request type is GET, POST can also be used and is recommended for longer queries. Documentation: https://www.ally.com/api/invest/documentation/market-options-search-get-post/ Base url: https://api.tradeking.com/Route: v1/market/timesales.jsonQuery: ?symbol=MSFT&query=xyear-eq%3A2019%20AND%20xmonth-eq%3A06%20AND%20strikeprice-eq%3A140 expiration year equals 2019:xyear-eq%3A 2019 and:%20AND%20 expiration month equals 06:xmonth-eq%3A 06 and strike price equals 140:%20AND%20 strikeprice -eq%3A 140 lt : less thangt : greater thangte : greater than or equal tolte : less than or equal toeq : equal to url = 'https://api.tradeking.com/v1/market/options/search.json?symbol=MSFT&query=xyear-eq%3A2019%20AND%20xmonth-eq%3A06%20AND%20strikeprice-eq%3A140'#api callresponse = requests.get(url, auth = auth).json()#load the response into the dataframedf = pd.DataFrame(response["response"]["quotes"]["quote"])df This route works for stocks, but this is an example of an option call since they are a bit more complex. This call will return quotes for a symbol or list of symbols passed as a query parameter. Documentation: https://www.ally.com/api/invest/documentation/market-ext-quotes-get-post/Base url: https://api.tradeking.com/Route: v1/market/ext/quotes.jsonQuery: ?symbols=MSFT190607C00140000 Underlying symbol — MSFT2 digit expiration year — 192 digit expiration month — 062 digit expiration day — 07“C” for Call or “P” for Put — C8 digit strike price — 00140000Specify desired fields in the query as needed using fids:i.e. fids=ask,bid,vol Although the naming convention has several components, it is fairly straight forward after a few examples. In the mean time, use the example image provided in the documentation or this cheat-sheet! url = 'https://api.tradeking.com/v1/market/ext/quotes.json?symbols=MSFT190607C00140000'#api callresponse = requests.get(url, auth = auth).json()#load the response into the dataframedf = pd.DataFrame(response["response"]["quotes"]["quote"], index = [0])df Using Pandas, it is easy to save the data to CSV or an SQL database. If you’re not familiar with SQLite, it is extremely easy to use. To quote the documentation: SQLite is a C library that provides a lightweight disk-based database that doesn’t require a separate server process and allows accessing the database using a nonstandard variant of the SQL query language. conn = sqlite3.connect('stockdata.sqlite')df.to_sql(table_name, conn) Using these three queries, it is easy to start collecting stock and options data using the Ally Financial API. Putting the data into a Panda’s dataframe makes it easy to understand the JSON information and store the data as a CSV or SQLite file. If you want to explore other APIs for stock data, check out Alphavantage too. Find the cheat sheet with documentation on my github! import requestsfrom requests_oauthlib import OAuth1from config import (api_key, secret, oath_token, oath_secret)import pandas as pdimport sqlalchemyimport numpy as npimport sqlite3from sqlite3 import Errorimport matplotlib.pyplot as pltimport datetime as dt#authentication auth = OAuth1(api_key, secret, oath_token, oath_secret)#url url = 'https://api.tradeking.com/v1/market/timesales.json?symbols=MSFT&startdate=2019-05-03&interval=1min'#api requestresponse = requests.get(url, auth = auth).json()#send to data frame and format data typesdf = pd.DataFrame(response["response"]["quotes"]["quote"])df = df.sort_values(['datetime'], ascending = False)df['date'] = pd.to_datetime(df['date'])df['datetime'] = pd.to_datetime(df['datetime'], utc=False).dt.tz_convert('US/Central')df['hi'] = df["hi"].astype(float)df['incr_vol'] = df["incr_vl"].astype(float)df['last'] = df["last"].astype(float)df['lo'] = df["lo"].astype(float)df['opn'] = df["opn"].astype(float)df['vl'] = df['vl'].astype(float)df.head()#resample the time value to be greater than 1 min as needed. Example: 30 min resample for last pricedf.set_index(df['datetime'], inplace = True)df.head()df_resample30 = df.resample(rule = '30min', label = 'right').last()df_resample30.head()#Options Search Exampleurl = 'https://api.tradeking.com/v1/market/options/search.json?symbol=MSFT&query=xyear-eq%3A2019%20AND%20xmonth-eq%3A06%20AND%20strikeprice-eq%3A140' response = requests.get(url, auth = auth).json() df = pd.DataFrame(response["response"]["quotes"]["quote"]) df.head()#Extended Quote Exampleurl = 'https://api.tradeking.com/v1/market/ext/quotes.json?symbols=MSFT190607C00140000'response = requests.get(url, auth = auth).json()df = pd.DataFrame(response["response"]["quotes"]["quote"], index = [0])df.head() If you enjoyed this, follow me on Medium for more Get FULL ACCESS and help support my content by subscribing Let’s connect on LinkedIn Analyze Data using Python? Check out my website — Eric Kleppen Check out my other tutorials for more python and sql!
[ { "code": null, "e": 638, "s": 171, "text": "For a period of my life, I was obsessed with financial markets and wanted to be a day trader. I worked nights, so it was easy to spend my mornings surrounded by computer monitors displaying everything from stocks, options, news and trade chat-rooms. Spoiler alert... I gave up on day trading, but not on investing. Ultimately, I learned that I loved analyzing data more than trading, and then I put my self on a path to learn data analysis and get into Data Science." }, { "code": null, "e": 902, "s": 638, "text": "When I was exploring ways to collect stock and options data, I checked out the API offered by one of my brokers, Ally Financial. It was free to use and easy to code. This is the cheat-sheet I put together for using the Ally Financial API to collect the following:" }, { "code": null, "e": 928, "s": 902, "text": "Time and Sales for Stocks" }, { "code": null, "e": 949, "s": 928, "text": "Options Market Depth" }, { "code": null, "e": 972, "s": 949, "text": "Options Extended Quote" }, { "code": null, "e": 1184, "s": 972, "text": "If you’re not familiar with an API, check out some of these resources. It is possible to automate trades through their API, but I never got that far into it. Explore all the functionality in their documentation." }, { "code": null, "e": 1197, "s": 1184, "text": "www.ally.com" }, { "code": null, "e": 1281, "s": 1197, "text": "You can find the complete cheat sheet at the bottom of the article or on my GitHub!" }, { "code": null, "e": 1292, "s": 1281, "text": "github.com" }, { "code": null, "e": 1308, "s": 1292, "text": "On to the code!" }, { "code": null, "e": 1492, "s": 1308, "text": "Connecting to the API uses OAuth1. You can find a list of OAuth clients on the OAuth site here. I use the OAuth library requests_oauthlib. Use pip install requests-oauthlib as needed." }, { "code": null, "e": 1750, "s": 1492, "text": "import requestsfrom requests_oauthlib import OAuth1from config import (api_key, secret, oath_token, oath_secret)import pandas as pdimport sqlalchemyimport numpy as npimport sqlite3from sqlite3 import Errorimport matplotlib.pyplot as pltimport datetime as dt" }, { "code": null, "e": 1897, "s": 1750, "text": "Notice I use a config file to import api_key, secret, oath_token, oath_secret. That way I don’t need to include those personal tokens in the code." }, { "code": null, "e": 1969, "s": 1897, "text": "#authentication auth = OAuth1(api_key, secret, oath_token, oath_secret)" }, { "code": null, "e": 2062, "s": 1969, "text": "I pass the imported tokens to OAuth1. This will be used when we make the request to the API." }, { "code": null, "e": 2294, "s": 2062, "text": "This API call will return time and sales quote data based on a symbol passed as a query parameter. For a list of all the query parameters, check out the documentation. The example URL consists of the base url, api route, and query." }, { "code": null, "e": 2417, "s": 2294, "text": "Base url: https://api.tradeking.com/Route: v1/market/timesales.jsonQuery: ?symbols=MSFT&startdate=2019–05–03&interval=1min" }, { "code": null, "e": 2500, "s": 2417, "text": "Documentation: https://www.ally.com/api/invest/documentation/market-timesales-get/" }, { "code": null, "e": 2687, "s": 2500, "text": "#url call to the apiurl = 'https://api.tradeking.com/v1/market/timesales.json?symbols=MSFT&startdate=2019-05-03&interval=1min'#api requestresponse = requests.get(url, auth = auth).json()" }, { "code": null, "e": 2809, "s": 2687, "text": "Notice I pass the URL and oAuth values into requests and return the response as json. This is an example of the response:" }, { "code": null, "e": 2882, "s": 2809, "text": "I put the quote data into a Panda’s DataFrame and format the data types." }, { "code": null, "e": 3384, "s": 2882, "text": "#send to data frame and format data typesdf = pd.DataFrame(response[\"response\"][\"quotes\"][\"quote\"])df = df.sort_values(['datetime'], ascending = False)df['date'] = pd.to_datetime(df['date'])df['datetime'] = pd.to_datetime(df['datetime'], utc=False).dt.tz_convert('US/Central')df['hi'] = df[\"hi\"].astype(float)df['incr_vol'] = df[\"incr_vl\"].astype(float)df['last'] = df[\"last\"].astype(float)df['lo'] = df[\"lo\"].astype(float)df['opn'] = df[\"opn\"].astype(float)df['vl'] = df['vl'].astype(float)df.head()" }, { "code": null, "e": 3701, "s": 3384, "text": "The date time values need to be converted so they can be resampled. Resampling allows you to manipulate the frequency of a time series. According to the documentation, the Object must have a datetime-like index (DatetimeIndex, PeriodIndex, or TimedeltaIndex), or pass datetime-like values to the on or level keyword." }, { "code": null, "e": 3942, "s": 3701, "text": "#resample the time value to be greater than 1 min as needed. Example: 30 min resample for last pricedf.set_index(df['datetime'], inplace = True)df.head()df_resample30 = df.resample(rule = '30min', label = 'right').last()df_resample30.head()" }, { "code": null, "e": 4029, "s": 3942, "text": "Notice the datetime increments by 30 minutes instead of 1 minute after the resampling." }, { "code": null, "e": 4255, "s": 4029, "text": "This api call provides market depth for options. This call will return the full list of available option strikes for a given symbol. While this request type is GET, POST can also be used and is recommended for longer queries." }, { "code": null, "e": 4348, "s": 4255, "text": "Documentation: https://www.ally.com/api/invest/documentation/market-options-search-get-post/" }, { "code": null, "e": 4509, "s": 4348, "text": "Base url: https://api.tradeking.com/Route: v1/market/timesales.jsonQuery: ?symbol=MSFT&query=xyear-eq%3A2019%20AND%20xmonth-eq%3A06%20AND%20strikeprice-eq%3A140" }, { "code": null, "e": 4554, "s": 4509, "text": "expiration year equals 2019:xyear-eq%3A 2019" }, { "code": null, "e": 4568, "s": 4554, "text": "and:%20AND%20" }, { "code": null, "e": 4611, "s": 4568, "text": "expiration month equals 06:xmonth-eq%3A 06" }, { "code": null, "e": 4672, "s": 4611, "text": "and strike price equals 140:%20AND%20 strikeprice -eq%3A 140" }, { "code": null, "e": 4774, "s": 4672, "text": "lt : less thangt : greater thangte : greater than or equal tolte : less than or equal toeq : equal to" }, { "code": null, "e": 5078, "s": 4774, "text": "url = 'https://api.tradeking.com/v1/market/options/search.json?symbol=MSFT&query=xyear-eq%3A2019%20AND%20xmonth-eq%3A06%20AND%20strikeprice-eq%3A140'#api callresponse = requests.get(url, auth = auth).json()#load the response into the dataframedf = pd.DataFrame(response[\"response\"][\"quotes\"][\"quote\"])df" }, { "code": null, "e": 5273, "s": 5078, "text": "This route works for stocks, but this is an example of an option call since they are a bit more complex. This call will return quotes for a symbol or list of symbols passed as a query parameter." }, { "code": null, "e": 5465, "s": 5273, "text": "Documentation: https://www.ally.com/api/invest/documentation/market-ext-quotes-get-post/Base url: https://api.tradeking.com/Route: v1/market/ext/quotes.jsonQuery: ?symbols=MSFT190607C00140000" }, { "code": null, "e": 5714, "s": 5465, "text": "Underlying symbol — MSFT2 digit expiration year — 192 digit expiration month — 062 digit expiration day — 07“C” for Call or “P” for Put — C8 digit strike price — 00140000Specify desired fields in the query as needed using fids:i.e. fids=ask,bid,vol" }, { "code": null, "e": 5912, "s": 5714, "text": "Although the naming convention has several components, it is fairly straight forward after a few examples. In the mean time, use the example image provided in the documentation or this cheat-sheet!" }, { "code": null, "e": 6167, "s": 5912, "text": "url = 'https://api.tradeking.com/v1/market/ext/quotes.json?symbols=MSFT190607C00140000'#api callresponse = requests.get(url, auth = auth).json()#load the response into the dataframedf = pd.DataFrame(response[\"response\"][\"quotes\"][\"quote\"], index = [0])df" }, { "code": null, "e": 6329, "s": 6167, "text": "Using Pandas, it is easy to save the data to CSV or an SQL database. If you’re not familiar with SQLite, it is extremely easy to use. To quote the documentation:" }, { "code": null, "e": 6535, "s": 6329, "text": "SQLite is a C library that provides a lightweight disk-based database that doesn’t require a separate server process and allows accessing the database using a nonstandard variant of the SQL query language." }, { "code": null, "e": 6605, "s": 6535, "text": "conn = sqlite3.connect('stockdata.sqlite')df.to_sql(table_name, conn)" }, { "code": null, "e": 6929, "s": 6605, "text": "Using these three queries, it is easy to start collecting stock and options data using the Ally Financial API. Putting the data into a Panda’s dataframe makes it easy to understand the JSON information and store the data as a CSV or SQLite file. If you want to explore other APIs for stock data, check out Alphavantage too." }, { "code": null, "e": 6983, "s": 6929, "text": "Find the cheat sheet with documentation on my github!" }, { "code": null, "e": 8753, "s": 6983, "text": "import requestsfrom requests_oauthlib import OAuth1from config import (api_key, secret, oath_token, oath_secret)import pandas as pdimport sqlalchemyimport numpy as npimport sqlite3from sqlite3 import Errorimport matplotlib.pyplot as pltimport datetime as dt#authentication auth = OAuth1(api_key, secret, oath_token, oath_secret)#url url = 'https://api.tradeking.com/v1/market/timesales.json?symbols=MSFT&startdate=2019-05-03&interval=1min'#api requestresponse = requests.get(url, auth = auth).json()#send to data frame and format data typesdf = pd.DataFrame(response[\"response\"][\"quotes\"][\"quote\"])df = df.sort_values(['datetime'], ascending = False)df['date'] = pd.to_datetime(df['date'])df['datetime'] = pd.to_datetime(df['datetime'], utc=False).dt.tz_convert('US/Central')df['hi'] = df[\"hi\"].astype(float)df['incr_vol'] = df[\"incr_vl\"].astype(float)df['last'] = df[\"last\"].astype(float)df['lo'] = df[\"lo\"].astype(float)df['opn'] = df[\"opn\"].astype(float)df['vl'] = df['vl'].astype(float)df.head()#resample the time value to be greater than 1 min as needed. Example: 30 min resample for last pricedf.set_index(df['datetime'], inplace = True)df.head()df_resample30 = df.resample(rule = '30min', label = 'right').last()df_resample30.head()#Options Search Exampleurl = 'https://api.tradeking.com/v1/market/options/search.json?symbol=MSFT&query=xyear-eq%3A2019%20AND%20xmonth-eq%3A06%20AND%20strikeprice-eq%3A140' response = requests.get(url, auth = auth).json() df = pd.DataFrame(response[\"response\"][\"quotes\"][\"quote\"]) df.head()#Extended Quote Exampleurl = 'https://api.tradeking.com/v1/market/ext/quotes.json?symbols=MSFT190607C00140000'response = requests.get(url, auth = auth).json()df = pd.DataFrame(response[\"response\"][\"quotes\"][\"quote\"], index = [0])df.head()" }, { "code": null, "e": 8803, "s": 8753, "text": "If you enjoyed this, follow me on Medium for more" }, { "code": null, "e": 8862, "s": 8803, "text": "Get FULL ACCESS and help support my content by subscribing" }, { "code": null, "e": 8888, "s": 8862, "text": "Let’s connect on LinkedIn" }, { "code": null, "e": 8936, "s": 8888, "text": "Analyze Data using Python? Check out my website" }, { "code": null, "e": 8951, "s": 8936, "text": "— Eric Kleppen" } ]
jsoup - Extract HTML
Following example will showcase use of methods to get inner html and outer html after parsing an HTML String into a Document object. Document document = Jsoup.parse(html); Element link = document.select("a").first(); System.out.println("Outer HTML: " + link.outerHtml()); System.out.println("Inner HTML: " + link.html()); Where document − document object represents the HTML DOM. document − document object represents the HTML DOM. Jsoup − main class to parse the given HTML String. Jsoup − main class to parse the given HTML String. html − HTML String. html − HTML String. link − Element object represent the html node element representing anchor tag. link − Element object represent the html node element representing anchor tag. link.outerHtml() − outerHtml() method retrives the element complete html. link.outerHtml() − outerHtml() method retrives the element complete html. link.html() − html() method retrives the element inner html. link.html() − html() method retrives the element inner html. Element object represent a dom elment and provides various method to get the html of a dom element. Create the following java program using any editor of your choice in say C:/> jsoup. JsoupTester.java import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; public class JsoupTester { public static void main(String[] args) { String html = "<html><head><title>Sample Title</title></head>" + "<body>" + "<p>Sample Content</p>" + "<div id='sampleDiv'><a href='www.google.com'>Google</a>" + "<h3><a>Sample</a><h3>" +"</div>" +"</body></html>"; Document document = Jsoup.parse(html); //a with href Element link = document.select("a").first(); System.out.println("Outer HTML: " + link.outerHtml()); System.out.println("Inner HTML: " + link.html()); } } Compile the class using javac compiler as follows: C:\jsoup>javac JsoupTester.java Now run the JsoupTester to see the result. C:\jsoup>java JsoupTester See the result. Outer HTML: <a href="www.google.com">Google</a> Inner HTML: Google Print Add Notes Bookmark this page
[ { "code": null, "e": 2163, "s": 2030, "text": "Following example will showcase use of methods to get inner html and outer html after parsing an HTML String into a Document object." }, { "code": null, "e": 2363, "s": 2163, "text": "Document document = Jsoup.parse(html);\nElement link = document.select(\"a\").first(); \n\nSystem.out.println(\"Outer HTML: \" + link.outerHtml());\nSystem.out.println(\"Inner HTML: \" + link.html());\n" }, { "code": null, "e": 2369, "s": 2363, "text": "Where" }, { "code": null, "e": 2421, "s": 2369, "text": "document − document object represents the HTML DOM." }, { "code": null, "e": 2473, "s": 2421, "text": "document − document object represents the HTML DOM." }, { "code": null, "e": 2524, "s": 2473, "text": "Jsoup − main class to parse the given HTML String." }, { "code": null, "e": 2575, "s": 2524, "text": "Jsoup − main class to parse the given HTML String." }, { "code": null, "e": 2595, "s": 2575, "text": "html − HTML String." }, { "code": null, "e": 2615, "s": 2595, "text": "html − HTML String." }, { "code": null, "e": 2694, "s": 2615, "text": "link − Element object represent the html node element representing anchor tag." }, { "code": null, "e": 2773, "s": 2694, "text": "link − Element object represent the html node element representing anchor tag." }, { "code": null, "e": 2847, "s": 2773, "text": "link.outerHtml() − outerHtml() method retrives the element complete html." }, { "code": null, "e": 2921, "s": 2847, "text": "link.outerHtml() − outerHtml() method retrives the element complete html." }, { "code": null, "e": 2982, "s": 2921, "text": "link.html() − html() method retrives the element inner html." }, { "code": null, "e": 3043, "s": 2982, "text": "link.html() − html() method retrives the element inner html." }, { "code": null, "e": 3143, "s": 3043, "text": "Element object represent a dom elment and provides various method to get the html of a dom element." }, { "code": null, "e": 3228, "s": 3143, "text": "Create the following java program using any editor of your choice in say C:/> jsoup." }, { "code": null, "e": 3245, "s": 3228, "text": "JsoupTester.java" }, { "code": null, "e": 3936, "s": 3245, "text": "import org.jsoup.Jsoup;\nimport org.jsoup.nodes.Document;\nimport org.jsoup.nodes.Element;\n\npublic class JsoupTester {\n public static void main(String[] args) {\n \n String html = \"<html><head><title>Sample Title</title></head>\"\n + \"<body>\"\n + \"<p>Sample Content</p>\"\n + \"<div id='sampleDiv'><a href='www.google.com'>Google</a>\"\n + \"<h3><a>Sample</a><h3>\"\n +\"</div>\"\n +\"</body></html>\";\n Document document = Jsoup.parse(html);\n\n //a with href\n Element link = document.select(\"a\").first(); \n\n System.out.println(\"Outer HTML: \" + link.outerHtml());\n System.out.println(\"Inner HTML: \" + link.html());\n }\n}" }, { "code": null, "e": 3987, "s": 3936, "text": "Compile the class using javac compiler as follows:" }, { "code": null, "e": 4020, "s": 3987, "text": "C:\\jsoup>javac JsoupTester.java\n" }, { "code": null, "e": 4063, "s": 4020, "text": "Now run the JsoupTester to see the result." }, { "code": null, "e": 4090, "s": 4063, "text": "C:\\jsoup>java JsoupTester\n" }, { "code": null, "e": 4106, "s": 4090, "text": "See the result." }, { "code": null, "e": 4174, "s": 4106, "text": "Outer HTML: <a href=\"www.google.com\">Google</a>\nInner HTML: Google\n" }, { "code": null, "e": 4181, "s": 4174, "text": " Print" }, { "code": null, "e": 4192, "s": 4181, "text": " Add Notes" } ]
How to create full-page tabs with CSS and JavaScript?
To create full-page tabs with CSS and JavaScript, the code is as follows − Live Demo <!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width, initial-scale=1"> <style> * {box-sizing: border-box} body, html { height: 100%; margin: 0; } .tablink { background-color: #555; color: white; float: left; border: none; outline: none; cursor: pointer; padding: 10px 14px; font-size: 15px; width:33.33%; } .tablink:hover { background-color: black; } .tabcontent { color: white; display: none; padding: 100px 20px; height: 100%; } #Home {background-color: blue;} #About {background-color: gray;} #Contact {background-color: orange;} </style> </head> <body> <button class="tablink" onclick="demo('Home', this, 'blue')">Home</button> <button class="tablink" onclick="demo('About', this, 'gray')" id="clickme">About</button> <button class="tablink" onclick="demo('Contact', this, 'orange')">ContactUs</button> <div id="Home" class="tabcontent"> <h3>Home</h3> <p>This is the Home page.</p> </div> <div id="About" class="tabcontent"> <h3>About</h3> <p>This is information about the company.</p> </div> <div id="Contact" class="tabcontent"> <h3>ContactUs</h3> <p>Contact us for any feedback, query and complaints.</p> </div> <script> function demo(pageName,elmnt,color) { var i, tabcontent, tablinks; tabcontent = document.getElementsByClassName("tabcontent"); for (i = 0; i < tabcontent.length; i++) { tabcontent[i].style.display = "none"; } tablinks = document.getElementsByClassName("tablink"); for (i = 0; i < tablinks.length; i++) { tablinks[i].style.backgroundColor = ""; } document.getElementById(pageName).style.display = "block"; elmnt.style.backgroundColor = color; } document.getElementById("clickme").click(); </script> </body> </html> This will produce the following output − Let’s now click the “ContactUs” tab −
[ { "code": null, "e": 1137, "s": 1062, "text": "To create full-page tabs with CSS and JavaScript, the code is as follows −" }, { "code": null, "e": 1148, "s": 1137, "text": " Live Demo" }, { "code": null, "e": 2923, "s": 1148, "text": "<!DOCTYPE html>\n<html>\n<head>\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n<style>\n* {box-sizing: border-box}\nbody, html {\n height: 100%;\n margin: 0;\n}\n.tablink {\n background-color: #555;\n color: white;\n float: left;\n border: none;\n outline: none;\n cursor: pointer;\n padding: 10px 14px;\n font-size: 15px;\n width:33.33%;\n}\n.tablink:hover {\n background-color: black;\n}\n.tabcontent {\n color: white;\n display: none;\n padding: 100px 20px;\n height: 100%;\n}\n#Home {background-color: blue;}\n#About {background-color: gray;}\n#Contact {background-color: orange;}\n</style>\n</head>\n<body>\n<button class=\"tablink\" onclick=\"demo('Home', this, 'blue')\">Home</button>\n<button class=\"tablink\" onclick=\"demo('About', this, 'gray')\" id=\"clickme\">About</button>\n<button class=\"tablink\" onclick=\"demo('Contact', this, 'orange')\">ContactUs</button>\n<div id=\"Home\" class=\"tabcontent\">\n <h3>Home</h3>\n <p>This is the Home page.</p>\n</div>\n<div id=\"About\" class=\"tabcontent\">\n <h3>About</h3>\n <p>This is information about the company.</p>\n</div>\n<div id=\"Contact\" class=\"tabcontent\">\n <h3>ContactUs</h3>\n <p>Contact us for any feedback, query and complaints.</p>\n</div>\n<script>\nfunction demo(pageName,elmnt,color) {\n var i, tabcontent, tablinks;\n tabcontent = document.getElementsByClassName(\"tabcontent\");\n for (i = 0; i < tabcontent.length; i++) {\n tabcontent[i].style.display = \"none\";\n }\n tablinks = document.getElementsByClassName(\"tablink\");\n for (i = 0; i < tablinks.length; i++) {\n tablinks[i].style.backgroundColor = \"\";\n }\n document.getElementById(pageName).style.display = \"block\";\n elmnt.style.backgroundColor = color;\n}\ndocument.getElementById(\"clickme\").click();\n</script>\n</body>\n</html>" }, { "code": null, "e": 2964, "s": 2923, "text": "This will produce the following output −" }, { "code": null, "e": 3002, "s": 2964, "text": "Let’s now click the “ContactUs” tab −" } ]
How to store XML data in a table in Oracle?
Problem Statement: You need to store native XML data into a relational table in your database. Solution: Oracle have several ways of storing XML documents. One way of storing data where our XML doesn’t need to be altered, or where a portion of the XML can be extracted with XSLT, is to use XMLTYPE data casting. We will use the XMLTYPE call to cast the text provided into the XMLTYPE datatype. In the background Oracle XMLTYPE supports CLOB datatype, because XML is stored internally as a CLOB. This means we can use the same approach to casting, passing the call to XMLTYPE a string up to 4GB in size. Casting to XMLTYPE enforces some rules for our XML data. If the column or a table is defined using an XML schema, the schema will be used to validate the data, ensuring that mandatory elements are present and the overall structure maps exactly to the schema. We will first create a table to store the XML. CREATE TABLE tmp_store_xml (result XMLTYPE); DECLARE result XMLTYPE; data VARCHAR2(10); BEGIN FOR CUR IN (SELECT department_id FROM departments) LOOP WITH tmp AS (SELECT XMLROOT(XMLFOREST( dept_t(department_id, department_name, CAST(MULTISET (SELECT student_id, first_name, last_name, phone_number FROM students e WHERE e.department_id = d.department_id ) AS stulist_t )) AS "Department"),version '1.0') AS dataxml FROM departments d WHERE d.department_id = '' || cur.department_id || '' ) SELECT XMLTYPE.CREATEXML(XMLSERIALIZE(CONTENT (dataxml) INDENT size=2)) INTO result FROM tmp; INSERT INTO tmp_store_xml VALUES(result); COMMIT; END LOOP; END; DECLARE result XMLTYPE; data VARCHAR2(10); BEGIN FOR CUR IN (SELECT department_id FROM departments) LOOP WITH tmp AS (SELECT XMLROOT(XMLFOREST( dept_t(department_id, department_name, CAST(MULTISET (SELECT student_id, first_name, last_name, phone_number FROM students e WHERE e.department_id = d.department_id ) AS stulist_t )) AS "Department"),version '1.0') AS dataxml FROM departments d WHERE d.department_id = '' || cur.department_id || '' ) SELECT XMLTYPE.CREATEXML(XMLSERIALIZE(CONTENT (dataxml) INDENT size=2)) INTO result FROM tmp; INSERT INTO tmp_store_xml VALUES(result); COMMIT; END LOOP; END; <Department DEPTNO="60"> <DNAME>IT</DNAME> <STU_LIST> <STU_T STUNO="103"> <FNAME>BROWN</FNAME> <LNAME>MICHAEL</LNAME> <PHONE>111.111.1248</PHONE> </STU_T> <STU_T STUNO="104"> <FNAME>JONES</FNAME> <LNAME>WILLIAM</LNAME> <PHONE>111.111.1249</PHONE> </STU_T> <STU_T STUNO="105"> <FNAME>MILLER</FNAME> <LNAME>DAVID</LNAME> <PHONE>111.111.1250</PHONE> </STU_T> <STU_T STUNO="106"> <FNAME>DAVIS</FNAME> <LNAME>RICHARD</LNAME> <PHONE>111.111.1251</PHONE> </STU_T> <STU_T STUNO="107"> <FNAME>GARCIA</FNAME> <LNAME>CHARLES</LNAME> <PHONE>111.111.1252</PHONE> </STU_T> </STU_LIST> </Department> <Department DEPTNO="60"> <DNAME>IT</DNAME> <STU_LIST> <STU_T STUNO="103"> <FNAME>BROWN</FNAME> <LNAME>MICHAEL</LNAME> <PHONE>111.111.1248</PHONE> </STU_T> <STU_T STUNO="104"> <FNAME>JONES</FNAME> <LNAME>WILLIAM</LNAME> <PHONE>111.111.1249</PHONE> </STU_T> <STU_T STUNO="105"> <FNAME>MILLER</FNAME> <LNAME>DAVID</LNAME> <PHONE>111.111.1250</PHONE> </STU_T> <STU_T STUNO="106"> <FNAME>DAVIS</FNAME> <LNAME>RICHARD</LNAME> <PHONE>111.111.1251</PHONE> </STU_T> <STU_T STUNO="107"> <FNAME>GARCIA</FNAME> <LNAME>CHARLES</LNAME> <PHONE>111.111.1252</PHONE> </STU_T> </STU_LIST> </Department> DROP TABLE students; COMMIT; CREATE TABLE students ( student_id NUMBER(6) , first_name VARCHAR2(20) , last_name VARCHAR2(25) , email VARCHAR2(40) , phone_number VARCHAR2(20) , join_date DATE , class_id VARCHAR2(20) , fees NUMBER(8,2) , professor_id NUMBER(6) , department_id NUMBER(4) ) ; CREATE UNIQUE INDEX stu_id_pk ON students (student_id) ; INSERT INTO students VALUES (100,'SMITH','JAMES','[email protected]','111.111.1245',TO_DATE('17-06-2003','DD-MM-YYYY'),'INS_CHAIRMAN',24000,NULL,NULL); INSERT INTO students VALUES (101,'JOHNSON','JOHN','[email protected]','111.111.1246',TO_DATE('21-09-2005','DD-MM-YYYY'),'INS_VP',17000,100,90); INSERT INTO students VALUES (102,'WILLIAMS','ROBERT','[email protected]','111.111.1247',TO_DATE('13-01-2001','DD-MM-YYYY'),'INS_VP',17000,100,90); INSERT INTO students VALUES (103,'BROWN','MICHAEL','[email protected]','111.111.1248',TO_DATE('03-01-2006','DD-MM-YYYY'),'INS_STAFF',9000,102,60); INSERT INTO students VALUES (104,'JONES','WILLIAM','[email protected]','111.111.1249',TO_DATE('21-05-2007','DD-MM-YYYY'),'INS_STAFF',6000,103,60); INSERT INTO students VALUES (105,'MILLER','DAVID','[email protected]','111.111.1250',TO_DATE('25-06-2005','DD-MM-YYYY'),'INS_STAFF',4800,103,60); INSERT INTO students VALUES (106,'DAVIS','RICHARD','[email protected]','111.111.1251',TO_DATE('05-02-2006','DD-MM-YYYY'),'INS_STAFF',4800,103,60); INSERT INTO students VALUES (107,'GARCIA','CHARLES','[email protected]','111.111.1252',TO_DATE('07-02-2007','DD-MM-YYYY'),'INS_STAFF',4200,103,60); INSERT INTO students VALUES (108,'RODRIGUEZ','JOSEPH','[email protected]','111.111.1253',TO_DATE('17-08-2002','DD-MM-YYYY'),'CL_PHY',12008,101,100); INSERT INTO students VALUES (109,'WILSON','THOMAS','[email protected]','111.111.1254',TO_DATE('16-08-2002','DD-MM-YYYY'),'CL_MATH',9000,108,100); INSERT INTO students VALUES (110,'MARTINEZ','CHRISTOPHER','[email protected]','111.111.1255',TO_DATE('28-09-2005','DD-MM-YYYY'),'CL_MATH',8200,108,100); INSERT INTO students VALUES (111,'ANDERSON','DANIEL','[email protected]','111.111.1256',TO_DATE('30-09-2005','DD-MM-YYYY'),'CL_MATH',7700,108,100); INSERT INTO students VALUES (112,'TAYLOR','PAUL','[email protected]','111.111.1257',TO_DATE('07-03-2006','DD-MM-YYYY'),'CL_MATH',7800,108,100); INSERT INTO students VALUES (113,'THOMAS','MARK','[email protected]','111.111.1258',TO_DATE('07-12-2007','DD-MM-YYYY'),'CL_MATH',6900,108,100); COMMIT; CREATE TABLE departments ( department_id NUMBER(4) , department_name VARCHAR2(30) CONSTRAINT dept_name_nn NOT NULL , professor_id NUMBER(6) , location_id NUMBER(4) ) ; INSERT INTO departments VALUES ( 10, 'Administration', 200, 1700); INSERT INTO departments VALUES ( 20, 'Teaching', 201, 1800); INSERT INTO departments VALUES ( 30 , 'Purchasing' , 114 , 1700 ); INSERT INTO departments VALUES ( 40 , 'Human Resources' , 203 , 2400 ); INSERT INTO departments VALUES ( 50 , 'Students' , 121 , 1500 ); INSERT INTO departments VALUES ( 60 , 'IT' , 103 , 1400 ); INSERT INTO departments VALUES ( 70 , 'Public Relations' , 204 , 2700 ); INSERT INTO departments VALUES ( 80 , 'Fee collectors' , 145 , 2500 ); INSERT INTO departments VALUES ( 90 , 'Executive' , 100 , 1700 ); INSERT INTO departments VALUES ( 100 , 'Finance' , 108 , 1700 ); INSERT INTO departments VALUES ( 110 , 'Accounting' , 205 , 1700 ); INSERT INTO departments VALUES ( 120 , 'Treasury' , NULL , 1700 ); INSERT INTO departments VALUES ( 130 , 'Corporate Tax' , NULL , 1700 ); INSERT INTO departments VALUES ( 140 , 'Control And Credit' , NULL , 1700 ); INSERT INTO departments VALUES ( 160 , 'Benefits' , NULL , 1700 ); INSERT INTO departments VALUES ( 230 , 'Helpdesk' , NULL , 1700 ); COMMIT;
[ { "code": null, "e": 1081, "s": 1062, "text": "Problem Statement:" }, { "code": null, "e": 1157, "s": 1081, "text": "You need to store native XML data into a relational table in your database." }, { "code": null, "e": 1167, "s": 1157, "text": "Solution:" }, { "code": null, "e": 1374, "s": 1167, "text": "Oracle have several ways of storing XML documents. One way of storing data where our XML doesn’t need to be altered, or where a portion of the XML can be extracted with XSLT, is to use XMLTYPE data casting." }, { "code": null, "e": 1665, "s": 1374, "text": "We will use the XMLTYPE call to cast the text provided into the XMLTYPE datatype. In the background Oracle XMLTYPE supports CLOB datatype, because XML is stored internally as a CLOB. This means we can use the same approach to casting, passing the call to XMLTYPE a string up to 4GB in size." }, { "code": null, "e": 1924, "s": 1665, "text": "Casting to XMLTYPE enforces some rules for our XML data. If the column or a table is defined using an XML schema, the schema will be used to validate the data, ensuring that mandatory elements are present and the overall structure maps exactly to the schema." }, { "code": null, "e": 1971, "s": 1924, "text": "We will first create a table to store the XML." }, { "code": null, "e": 2016, "s": 1971, "text": "CREATE TABLE tmp_store_xml (result XMLTYPE);" }, { "code": null, "e": 3018, "s": 2016, "text": "DECLARE\n result XMLTYPE;\n data VARCHAR2(10);\nBEGIN\n FOR CUR IN (SELECT department_id FROM departments)\n LOOP\n WITH tmp AS\n (SELECT XMLROOT(XMLFOREST( dept_t(department_id, department_name,\n CAST(MULTISET\n (SELECT student_id,\n first_name,\n last_name,\n phone_number\n FROM students e\n WHERE e.department_id = d.department_id\n ) AS stulist_t\n )) AS \"Department\"),version '1.0') AS dataxml\n FROM departments d\n WHERE d.department_id = '' || cur.department_id || ''\n )\n \n SELECT XMLTYPE.CREATEXML(XMLSERIALIZE(CONTENT (dataxml) INDENT size=2))\n INTO result\n FROM tmp;\n \n INSERT INTO tmp_store_xml VALUES(result);\n COMMIT;\n END LOOP;\nEND;" }, { "code": null, "e": 4020, "s": 3018, "text": "DECLARE\n result XMLTYPE;\n data VARCHAR2(10);\nBEGIN\n FOR CUR IN (SELECT department_id FROM departments)\n LOOP\n WITH tmp AS\n (SELECT XMLROOT(XMLFOREST( dept_t(department_id, department_name,\n CAST(MULTISET\n (SELECT student_id,\n first_name,\n last_name,\n phone_number\n FROM students e\n WHERE e.department_id = d.department_id\n ) AS stulist_t\n )) AS \"Department\"),version '1.0') AS dataxml\n FROM departments d\n WHERE d.department_id = '' || cur.department_id || ''\n )\n \n SELECT XMLTYPE.CREATEXML(XMLSERIALIZE(CONTENT (dataxml) INDENT size=2))\n INTO result\n FROM tmp;\n \n INSERT INTO tmp_store_xml VALUES(result);\n COMMIT;\n END LOOP;\nEND;" }, { "code": null, "e": 4741, "s": 4020, "text": "<Department DEPTNO=\"60\">\n <DNAME>IT</DNAME>\n <STU_LIST>\n <STU_T STUNO=\"103\">\n <FNAME>BROWN</FNAME>\n <LNAME>MICHAEL</LNAME>\n <PHONE>111.111.1248</PHONE>\n </STU_T>\n <STU_T STUNO=\"104\">\n <FNAME>JONES</FNAME>\n <LNAME>WILLIAM</LNAME>\n <PHONE>111.111.1249</PHONE>\n </STU_T>\n <STU_T STUNO=\"105\">\n <FNAME>MILLER</FNAME>\n <LNAME>DAVID</LNAME>\n <PHONE>111.111.1250</PHONE>\n </STU_T>\n <STU_T STUNO=\"106\">\n <FNAME>DAVIS</FNAME>\n <LNAME>RICHARD</LNAME>\n <PHONE>111.111.1251</PHONE>\n </STU_T>\n <STU_T STUNO=\"107\">\n <FNAME>GARCIA</FNAME>\n <LNAME>CHARLES</LNAME>\n <PHONE>111.111.1252</PHONE>\n </STU_T>\n </STU_LIST>\n</Department>" }, { "code": null, "e": 5462, "s": 4741, "text": "<Department DEPTNO=\"60\">\n <DNAME>IT</DNAME>\n <STU_LIST>\n <STU_T STUNO=\"103\">\n <FNAME>BROWN</FNAME>\n <LNAME>MICHAEL</LNAME>\n <PHONE>111.111.1248</PHONE>\n </STU_T>\n <STU_T STUNO=\"104\">\n <FNAME>JONES</FNAME>\n <LNAME>WILLIAM</LNAME>\n <PHONE>111.111.1249</PHONE>\n </STU_T>\n <STU_T STUNO=\"105\">\n <FNAME>MILLER</FNAME>\n <LNAME>DAVID</LNAME>\n <PHONE>111.111.1250</PHONE>\n </STU_T>\n <STU_T STUNO=\"106\">\n <FNAME>DAVIS</FNAME>\n <LNAME>RICHARD</LNAME>\n <PHONE>111.111.1251</PHONE>\n </STU_T>\n <STU_T STUNO=\"107\">\n <FNAME>GARCIA</FNAME>\n <LNAME>CHARLES</LNAME>\n <PHONE>111.111.1252</PHONE>\n </STU_T>\n </STU_LIST>\n</Department>" }, { "code": null, "e": 5846, "s": 5462, "text": "DROP TABLE students;\nCOMMIT;\n\nCREATE TABLE students\n ( student_id NUMBER(6)\n , first_name VARCHAR2(20)\n , last_name VARCHAR2(25)\n , email VARCHAR2(40)\n , phone_number VARCHAR2(20)\n , join_date DATE\n , class_id VARCHAR2(20) \n , fees NUMBER(8,2)\n , professor_id NUMBER(6)\n , department_id NUMBER(4)\n ) ;" }, { "code": null, "e": 8093, "s": 5846, "text": "CREATE UNIQUE INDEX stu_id_pk ON students (student_id) ;\nINSERT INTO students VALUES (100,'SMITH','JAMES','[email protected]','111.111.1245',TO_DATE('17-06-2003','DD-MM-YYYY'),'INS_CHAIRMAN',24000,NULL,NULL);\nINSERT INTO students VALUES (101,'JOHNSON','JOHN','[email protected]','111.111.1246',TO_DATE('21-09-2005','DD-MM-YYYY'),'INS_VP',17000,100,90);\nINSERT INTO students VALUES (102,'WILLIAMS','ROBERT','[email protected]','111.111.1247',TO_DATE('13-01-2001','DD-MM-YYYY'),'INS_VP',17000,100,90);\nINSERT INTO students VALUES (103,'BROWN','MICHAEL','[email protected]','111.111.1248',TO_DATE('03-01-2006','DD-MM-YYYY'),'INS_STAFF',9000,102,60);\nINSERT INTO students VALUES (104,'JONES','WILLIAM','[email protected]','111.111.1249',TO_DATE('21-05-2007','DD-MM-YYYY'),'INS_STAFF',6000,103,60);\nINSERT INTO students VALUES (105,'MILLER','DAVID','[email protected]','111.111.1250',TO_DATE('25-06-2005','DD-MM-YYYY'),'INS_STAFF',4800,103,60);\nINSERT INTO students VALUES (106,'DAVIS','RICHARD','[email protected]','111.111.1251',TO_DATE('05-02-2006','DD-MM-YYYY'),'INS_STAFF',4800,103,60);\nINSERT INTO students VALUES (107,'GARCIA','CHARLES','[email protected]','111.111.1252',TO_DATE('07-02-2007','DD-MM-YYYY'),'INS_STAFF',4200,103,60);\nINSERT INTO students VALUES (108,'RODRIGUEZ','JOSEPH','[email protected]','111.111.1253',TO_DATE('17-08-2002','DD-MM-YYYY'),'CL_PHY',12008,101,100);\nINSERT INTO students VALUES (109,'WILSON','THOMAS','[email protected]','111.111.1254',TO_DATE('16-08-2002','DD-MM-YYYY'),'CL_MATH',9000,108,100);\nINSERT INTO students VALUES (110,'MARTINEZ','CHRISTOPHER','[email protected]','111.111.1255',TO_DATE('28-09-2005','DD-MM-YYYY'),'CL_MATH',8200,108,100);\nINSERT INTO students VALUES (111,'ANDERSON','DANIEL','[email protected]','111.111.1256',TO_DATE('30-09-2005','DD-MM-YYYY'),'CL_MATH',7700,108,100);\nINSERT INTO students VALUES (112,'TAYLOR','PAUL','[email protected]','111.111.1257',TO_DATE('07-03-2006','DD-MM-YYYY'),'CL_MATH',7800,108,100);\nINSERT INTO students VALUES (113,'THOMAS','MARK','[email protected]','111.111.1258',TO_DATE('07-12-2007','DD-MM-YYYY'),'CL_MATH',6900,108,100);\n\nCOMMIT;" }, { "code": null, "e": 8302, "s": 8093, "text": "CREATE TABLE departments\n ( department_id NUMBER(4)\n , department_name VARCHAR2(30)\n CONSTRAINT dept_name_nn NOT NULL\n , professor_id NUMBER(6)\n , location_id NUMBER(4)\n ) ;" }, { "code": null, "e": 9493, "s": 8302, "text": "INSERT INTO departments VALUES ( 10, 'Administration', 200, 1700);\nINSERT INTO departments VALUES ( 20, 'Teaching', 201, 1800); \nINSERT INTO departments VALUES ( 30 , 'Purchasing' , 114 , 1700 );\nINSERT INTO departments VALUES ( 40 , 'Human Resources' , 203 , 2400 );\nINSERT INTO departments VALUES ( 50 , 'Students' , 121 , 1500 );\nINSERT INTO departments VALUES ( 60 , 'IT' , 103 , 1400 );\nINSERT INTO departments VALUES ( 70 , 'Public Relations' , 204 , 2700 );\nINSERT INTO departments VALUES ( 80 , 'Fee collectors' , 145 , 2500 ); \nINSERT INTO departments VALUES ( 90 , 'Executive' , 100 , 1700 );\nINSERT INTO departments VALUES ( 100 , 'Finance' , 108 , 1700 ); \nINSERT INTO departments VALUES ( 110 , 'Accounting' , 205 , 1700 );\nINSERT INTO departments VALUES ( 120 , 'Treasury' , NULL , 1700 );\nINSERT INTO departments VALUES ( 130 , 'Corporate Tax' , NULL , 1700 );\nINSERT INTO departments VALUES ( 140 , 'Control And Credit' , NULL , 1700 );\nINSERT INTO departments VALUES ( 160 , 'Benefits' , NULL , 1700 );\nINSERT INTO departments VALUES ( 230 , 'Helpdesk' , NULL , 1700 );\nCOMMIT;" } ]
Kotlin Booleans
Very often, in programming, you will need a data type that can only have one of two values, like: YES / NO ON / OFF TRUE / FALSE For this, Kotlin has a Boolean data type, which can take the values true or false. A boolean type can be declared with the Boolean keyword and can only take the values true or false: val isKotlinFun: Boolean = true val isFishTasty: Boolean = false println(isKotlinFun) // Outputs true println(isFishTasty) // Outputs false Just like you have learned with other data types in the previous chapters, the example above can also be written without specifying the type, as Kotlin is smart enough to understand that the variables are Booleans: val isKotlinFun = true val isFishTasty = false println(isKotlinFun) // Outputs true println(isFishTasty) // Outputs false A Boolean expression returns a Boolean value: true or false. You can use a comparison operator, such as the greater than (>) operator to find out if an expression (or a variable) is true: val x = 10 val y = 9println(x > y) // Returns true, because 10 is greater than 9 Or even easier: println(10 > 9) // Returns true, because 10 is greater than 9 In the examples below, we use the equal to (==) operator to evaluate an expression: val x = 10; println(x == 10); // Returns true, because the value of x is equal to 10 println(10 == 15); // Returns false, because 10 is not equal to 15 The Boolean value of an expression is the basis for all Kotlin comparisons and conditions. You will learn more about conditions in the next chapter. 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": 98, "s": 0, "text": "Very often, in programming, you will need a data type that can only have one of two values, like:" }, { "code": null, "e": 107, "s": 98, "text": "YES / NO" }, { "code": null, "e": 116, "s": 107, "text": "ON / OFF" }, { "code": null, "e": 129, "s": 116, "text": "TRUE / FALSE" }, { "code": null, "e": 212, "s": 129, "text": "For this, Kotlin has a Boolean data type, which can take the values true or false." }, { "code": null, "e": 312, "s": 212, "text": "A boolean type can be declared with the Boolean keyword and can only take the values true or false:" }, { "code": null, "e": 457, "s": 312, "text": "val isKotlinFun: Boolean = true\nval isFishTasty: Boolean = false\nprintln(isKotlinFun) // Outputs true\nprintln(isFishTasty) // Outputs false " }, { "code": null, "e": 672, "s": 457, "text": "Just like you have learned with other data types in the previous chapters, the example above can also be written without specifying the type, as Kotlin is smart enough to understand that the variables are Booleans:" }, { "code": null, "e": 799, "s": 672, "text": "val isKotlinFun = true\nval isFishTasty = false\nprintln(isKotlinFun) // Outputs true\nprintln(isFishTasty) // Outputs false " }, { "code": null, "e": 860, "s": 799, "text": "A Boolean expression returns a Boolean value: true or false." }, { "code": null, "e": 987, "s": 860, "text": "You can use a comparison operator, such as the greater than (>) operator to find out if an expression (or a variable) is true:" }, { "code": null, "e": 1068, "s": 987, "text": "val x = 10\nval y = 9println(x > y) // Returns true, because 10 is greater than 9" }, { "code": null, "e": 1084, "s": 1068, "text": "Or even easier:" }, { "code": null, "e": 1146, "s": 1084, "text": "println(10 > 9) // Returns true, because 10 is greater than 9" }, { "code": null, "e": 1230, "s": 1146, "text": "In the examples below, we use the equal to (==) operator to evaluate an expression:" }, { "code": null, "e": 1315, "s": 1230, "text": "val x = 10;\nprintln(x == 10); // Returns true, because the value of x is equal to 10" }, { "code": null, "e": 1382, "s": 1315, "text": "println(10 == 15); // Returns false, because 10 is not equal to 15" }, { "code": null, "e": 1473, "s": 1382, "text": "The Boolean value of an expression is the basis for all Kotlin comparisons and conditions." }, { "code": null, "e": 1531, "s": 1473, "text": "You will learn more about conditions in the next chapter." }, { "code": null, "e": 1564, "s": 1531, "text": "We just launchedW3Schools videos" }, { "code": null, "e": 1606, "s": 1564, "text": "Get certifiedby completinga course today!" }, { "code": null, "e": 1713, "s": 1606, "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": 1732, "s": 1713, "text": "[email protected]" } ]
How to remove everything before values starting after underscore from column values of an R data frame?
If a column in an R data frame contain string values that are separated with an underscore and stretches the size of the column values that also contain common values then it would be wise to remove underscore sign from all the values at once along with the values that is common. This will help us to read the data properly as well as analysis will become easy. For this purpose, we can use gsub function Consider the below data frame − Live Demo set.seed(191) ID<-c("ID_1","ID_2","ID_3","ID_4","ID_5","ID_6","ID_7","ID_8","ID_9","ID_10","ID_11","ID_12","ID_13","ID_14","ID_15","ID_16","ID_17","ID_18","ID_19","ID_20") Salary<-sample(20000:50000,20) df1<-data.frame(ID,Salary) df1 ID Salary 1 ID_1 33170 2 ID_2 22747 3 ID_3 42886 4 ID_4 22031 5 ID_5 45668 6 ID_6 32584 7 ID_7 34779 8 ID_8 20471 9 ID_9 38689 10 ID_10 29660 11 ID_11 49664 12 ID_12 24284 13 ID_13 36537 14 ID_14 37693 15 ID_15 30265 16 ID_16 36004 17 ID_17 48247 18 ID_18 20750 19 ID_19 27400 20 ID_20 20553 Removing everything before and including underscore sign from ID values in column ID − df1$ID<-gsub("^.*\\_","",df1$ID) df1 ID Salary 1 1 48769 2 2 26002 3 3 37231 4 4 24437 5 5 43311 6 6 47494 7 7 21029 8 8 28069 9 9 41108 10 10 29363 11 11 23371 12 12 25898 13 13 42434 14 14 22210 15 15 48969 16 16 21640 17 17 36175 18 18 21210 19 19 43374 20 20 29367 Let’s have a look at another example − Live Demo Group<-c("GRP_1","GRP_2","GRP_3","GRP_4","GRP_5","GRP_6","GRP_7","GRP_8","GRP_9","GRP_10","GRP_11","GRP_12","GRP_13","GRP_14","GRP_15","GRP_16","GRP_17","GRP_18","GRP_19","GRP_20") Ratings<-sample(0:10,20,replace=TRUE) df2<-data.frame(Group,Ratings) df2 Group Ratings 1 GRP_1 6 2 GRP_2 9 3 GRP_3 7 4 GRP_4 10 5 GRP_5 10 6 GRP_6 9 7 GRP_7 9 8 GRP_8 3 9 GRP_9 2 10 GRP_10 0 11 GRP_11 3 12 GRP_12 7 13 GRP_13 6 14 GRP_14 10 15 GRP_15 1 16 GRP_16 3 17 GRP_17 10 18 GRP_18 2 19 GRP_19 9 20 GRP_20 0 Removing everything before and including underscore sign from GRP values in column Group − df2$Group<-gsub("^.*\\_","",df2$Group) df2 Group Ratings 1 1 4 2 2 8 3 3 7 4 4 0 5 5 10 6 6 10 7 7 5 8 8 4 9 9 3 10 10 7 11 11 4 12 12 4 13 13 3 14 14 10 15 15 7 16 16 2 17 17 3 18 18 8 19 19 9 20 20 5
[ { "code": null, "e": 1468, "s": 1062, "text": "If a column in an R data frame contain string values that are separated with an underscore and stretches the size of the column values that also contain common values then it would be wise to remove underscore sign from all the values at once along with the values that is common. This will help us to read the data properly as well as analysis will become easy. For this purpose, we can use gsub function" }, { "code": null, "e": 1500, "s": 1468, "text": "Consider the below data frame −" }, { "code": null, "e": 1511, "s": 1500, "text": " Live Demo" }, { "code": null, "e": 1745, "s": 1511, "text": "set.seed(191)\nID<-c(\"ID_1\",\"ID_2\",\"ID_3\",\"ID_4\",\"ID_5\",\"ID_6\",\"ID_7\",\"ID_8\",\"ID_9\",\"ID_10\",\"ID_11\",\"ID_12\",\"ID_13\",\"ID_14\",\"ID_15\",\"ID_16\",\"ID_17\",\"ID_18\",\"ID_19\",\"ID_20\")\nSalary<-sample(20000:50000,20)\ndf1<-data.frame(ID,Salary)\ndf1" }, { "code": null, "e": 2060, "s": 1745, "text": " ID Salary\n1 ID_1 33170\n2 ID_2 22747\n3 ID_3 42886\n4 ID_4 22031\n5 ID_5 45668\n6 ID_6 32584\n7 ID_7 34779\n8 ID_8 20471\n9 ID_9 38689\n10 ID_10 29660\n11 ID_11 49664\n12 ID_12 24284\n13 ID_13 36537\n14 ID_14 37693\n15 ID_15 30265\n16 ID_16 36004\n17 ID_17 48247\n18 ID_18 20750\n19 ID_19 27400\n20 ID_20 20553" }, { "code": null, "e": 2147, "s": 2060, "text": "Removing everything before and including underscore sign from ID values in column ID −" }, { "code": null, "e": 2184, "s": 2147, "text": "df1$ID<-gsub(\"^.*\\\\_\",\"\",df1$ID)\ndf1" }, { "code": null, "e": 2437, "s": 2184, "text": " ID Salary\n1 1 48769\n2 2 26002\n3 3 37231\n4 4 24437\n5 5 43311\n6 6 47494\n7 7 21029\n8 8 28069\n9 9 41108\n10 10 29363\n11 11 23371\n12 12 25898\n13 13 42434\n14 14 22210\n15 15 48969\n16 16 21640\n17 17 36175\n18 18 21210\n19 19 43374\n20 20 29367" }, { "code": null, "e": 2476, "s": 2437, "text": "Let’s have a look at another example −" }, { "code": null, "e": 2487, "s": 2476, "text": " Live Demo" }, { "code": null, "e": 2742, "s": 2487, "text": "Group<-c(\"GRP_1\",\"GRP_2\",\"GRP_3\",\"GRP_4\",\"GRP_5\",\"GRP_6\",\"GRP_7\",\"GRP_8\",\"GRP_9\",\"GRP_10\",\"GRP_11\",\"GRP_12\",\"GRP_13\",\"GRP_14\",\"GRP_15\",\"GRP_16\",\"GRP_17\",\"GRP_18\",\"GRP_19\",\"GRP_20\")\n Ratings<-sample(0:10,20,replace=TRUE)\ndf2<-data.frame(Group,Ratings)\ndf2" }, { "code": null, "e": 2999, "s": 2742, "text": " Group Ratings\n1 GRP_1 6\n2 GRP_2 9\n3 GRP_3 7\n4 GRP_4 10\n5 GRP_5 10\n6 GRP_6 9\n7 GRP_7 9\n8 GRP_8 3\n9 GRP_9 2\n10 GRP_10 0\n11 GRP_11 3\n12 GRP_12 7\n13 GRP_13 6\n14 GRP_14 10\n15 GRP_15 1\n16 GRP_16 3\n17 GRP_17 10\n18 GRP_18 2\n19 GRP_19 9\n20 GRP_20 0" }, { "code": null, "e": 3090, "s": 2999, "text": "Removing everything before and including underscore sign from GRP values in column Group −" }, { "code": null, "e": 3133, "s": 3090, "text": "df2$Group<-gsub(\"^.*\\\\_\",\"\",df2$Group)\ndf2" }, { "code": null, "e": 3390, "s": 3133, "text": " Group Ratings\n1 1 4\n2 2 8\n3 3 7\n4 4 0\n5 5 10\n6 6 10\n7 7 5\n8 8 4\n9 9 3\n10 10 7\n11 11 4\n12 12 4\n13 13 3\n14 14 10\n15 15 7\n16 16 2\n17 17 3\n18 18 8\n19 19 9\n20 20 5" } ]
How to Beat the CartPole Game in 5 Lines | by Jian Xu | Towards Data Science
CartPole is a game in the Open-AI Gym reinforced learning environment. It is widely used in many text-books and articles to illustrate the power of machine learning. However, all these machine learning methods require a decent amount of coding and lots of computing power to train. Is there any simpler solution? The answer is yes. In this article, I will show an extremely simple solution. Although it is only 5 lines long, it performs better than any commonly found machine learning method and completely beats the CartPole game. Now let’s start! Review of the Cart-Pole problemAnalysis of some simple policiesArriving at the 5-Line solutionConclusion Review of the Cart-Pole problem Analysis of some simple policies Arriving at the 5-Line solution Conclusion The CartPole problem is also known as the “Inverted Pendulum” problem. It has a pole attached to a cart. Since the pole’s center of mass is above its pivot point, it’s an unstable system. The official full description can be found here on the Open-AI website. The pole starts in an upright position with a small perturbation. The goal is to move the cart left and right to keep the pole from falling. Following is a graphical illustration of the system (if you want to know how to set up the OpenAI Gym environment and render this illustration, this article can help). In the OpenAI CartPole environment, the status of the system is specified by an “observation” of four parameters (x, v, θ, ω), where x: the horizontal position of the cart (positive means to the right) v: the horizontal velocity of the cart (positive means moving to the right) θ: the angle between the pole and the vertical position (positive means clock-wise) ω: angular velocity of the pole (positive means rotating clock-wise) Given an observation, a player can perform either one of the following two possible “actions”: 0: pushing the cart to the left 1: pushing the cart to the right The game is “done” when the pole deviates more than 15 degrees from vertical (|θ| ≥ π/12 ≈0.26). In each time step, if the game is not “done”, then the cumulative “reward” increases by 1. The goal of the game is to have the cumulative reward as high as possible. Let’s take a look at the following example in details: The observation: x=0.018: the cart is on the right side of the origin O v=0.669: the cart is moving to the right θ=0.286: the pole is at (0.286/2π*360≈16.4 degrees) clockwise from vertical ω=0.618: the pole is rotating close-wise Action=1: the player is pushing the cart to the right Cumulative Reward=47: the player has successfully sustained 47 time steps in this game Done=1: this game is already “done” (because |θ| > 15 degrees) Now we understood the setup. Let’s see how to play this game to achieve high rewards. In the context of reinforced learning, a “policy” essentially means a function that takes an observation (or a series of observations) and outputs an action. Before we try to be smart, let’s first imagine a monkey randomly pushes the cart left and right, and see how well it performs. This can help us to establish a baseline. Its implementation is, of course very simple: def rand_policy(obs): return random.randint(0, 1) We played this “random policy” 1,000 times and plot the cumulative reward of each game. We can see the mean reward is 22.03, and the standard deviation is 8.00. Of course, we can do better than the monkey. In Géron, Aurélien’s book: Hands-On Machine Learning with Scikit-Learn, Keras, and TensorFlow (Chapter 18), there’s a very simple policy that only depends on the pole’s angle θ: def theta_policy(obs): theta = obs[2] return 0 if theta < 0 else 1 In plain language, it says that if the pole is tilted to the left (θ<0), then push the cart to the left, and vice versa. Very intuitive, isn’t it? It’s indeed better than the random policy, with the mean reward almost doubled to 41.67. And the following is one iteration to show how it performs. It indeed shows some intention to prevent the pole from falling. Although better a monkey, the Theta Policy is far from satisfactory. For those with some physics backgrounds, this policy is obviously flawed. Because when the cart is pushed to the left, the pole gets a clockwise angular acceleration, not a clock-wise angular velocity. The consequence of this action is that the pole can rotate clockwise as well as counter-clockwise. Also, when the pole is already moving towards the center, say θ>0 and ω < 0, the action (pushing to the right) will still accelerate the angular velocity towards the center rather than slow it down. Thus the pole over-shoots past the center. Base on the above mechanical analysis, a much more reasonable proposition is that when the pole is moving away from the vertical position (ω<0), push the cart to the left (action = 0). And vice versa. Since it only depends on the angular velocity ω, let’s name it “Omega Policy”. Its implementation is just as simple as the Theta Policy: def omega_policy(obs): w = obs[3] return 0 if w < 0 else 1 Surprise! Based on one simple law from physics, a one-line change turns the poor Theta Policy into a winner! This Omega Policy gets a mean reward of ~200! To appreciate the 200 average rewards, let’s compare the average rewards of some commonly found machine learning policies. Please keep in mind that these machine learning policies are much more complicated, much harder to explain, and requires long training times to achieve these result: Sequential Neural-Network (in Géron’s book): ~46 Deep Q-Learning (in article 1): ~130 Deep Q-Learning (in article 2): ~200 You can see that our two-liner Omega Policy already performs on par or better than the AI-powered Deep Q-Learning policy. The official CartPole webpage defines that the problem is “solved” if the average reward >195 over 100 consecutive trials. So our 2-line Omega Policy already solves the CartPole problem! Although the simple Omega Policy already solved the CartPole problem, I am still not satisfied. A quick visualization reveals why: We can see that the game ends not because the pole falls but because the cart deviates from the origin too far. This indicates the policy successfully “stabilizes” the pole (keeping angular velocity ω ≈ 0), but at a “tiled” position (angle θ ≠ 0). So the cart keeps moving in one direction. This is not surprising, because the Omega Policy does nothing about the angle θ. After identifying the problem, it’s easy to propose an improved policy: When the angle θ is “small”, we want to stabilize θ. This is the same as the Omega Policy. When the angle θ is “large”, we want to correct θ, i.e., give an angular acceleration towards the center. This is the same as the Theta Policy. As far as the criterion for “small” and “large”, it’s not well defined. But a reasonable starting point is 10% of the 15 degrees “done” threshold, i.e., ~0.026. In reality, the result is not very sensitive to this value. Anywhere from 0.02 to 0.04 can produce amazing results. Following is an example using 0.03 as the threshold: def theta_omega_policy(obs): theta, w = obs[2:4] if abs(theta) < 0.03: return 0 if w < 0 else 1 else: return 0 if theta < 0 else 1 How good is this simple 5-line policy? Bingo! The pole simply CANNOT fall! Not even once! The reason that the cumulative reward caps at 500 is just due to the limitation of the CartPol-v1 environment itself — when the game is played 500 time steps, it automatically stops. In other words, our Theta-Omega Policy not only “solves” the problem, but also “breaks” the game! Following is how this simple 5-line policy performs in real action: The full notebook of the system setup, analysis, and GIF generation is available here on GitHub. Obviously, this is not an artificial intelligence exercise. But by showing how to breaks the CartPole game in 5 lines, I hope you can appreciate how condense the law of physics is. Essentially, we utilized results from thousands of years of human learning, to replace the machine learning code, and got a far better, far simpler result. So the next time we apply any machine learning algorithm, it’s always better to check for existing knowledge first.
[ { "code": null, "e": 485, "s": 172, "text": "CartPole is a game in the Open-AI Gym reinforced learning environment. It is widely used in many text-books and articles to illustrate the power of machine learning. However, all these machine learning methods require a decent amount of coding and lots of computing power to train. Is there any simpler solution?" }, { "code": null, "e": 721, "s": 485, "text": "The answer is yes. In this article, I will show an extremely simple solution. Although it is only 5 lines long, it performs better than any commonly found machine learning method and completely beats the CartPole game. Now let’s start!" }, { "code": null, "e": 826, "s": 721, "text": "Review of the Cart-Pole problemAnalysis of some simple policiesArriving at the 5-Line solutionConclusion" }, { "code": null, "e": 858, "s": 826, "text": "Review of the Cart-Pole problem" }, { "code": null, "e": 891, "s": 858, "text": "Analysis of some simple policies" }, { "code": null, "e": 923, "s": 891, "text": "Arriving at the 5-Line solution" }, { "code": null, "e": 934, "s": 923, "text": "Conclusion" }, { "code": null, "e": 1194, "s": 934, "text": "The CartPole problem is also known as the “Inverted Pendulum” problem. It has a pole attached to a cart. Since the pole’s center of mass is above its pivot point, it’s an unstable system. The official full description can be found here on the Open-AI website." }, { "code": null, "e": 1335, "s": 1194, "text": "The pole starts in an upright position with a small perturbation. The goal is to move the cart left and right to keep the pole from falling." }, { "code": null, "e": 1503, "s": 1335, "text": "Following is a graphical illustration of the system (if you want to know how to set up the OpenAI Gym environment and render this illustration, this article can help)." }, { "code": null, "e": 1636, "s": 1503, "text": "In the OpenAI CartPole environment, the status of the system is specified by an “observation” of four parameters (x, v, θ, ω), where" }, { "code": null, "e": 1705, "s": 1636, "text": "x: the horizontal position of the cart (positive means to the right)" }, { "code": null, "e": 1781, "s": 1705, "text": "v: the horizontal velocity of the cart (positive means moving to the right)" }, { "code": null, "e": 1865, "s": 1781, "text": "θ: the angle between the pole and the vertical position (positive means clock-wise)" }, { "code": null, "e": 1934, "s": 1865, "text": "ω: angular velocity of the pole (positive means rotating clock-wise)" }, { "code": null, "e": 2029, "s": 1934, "text": "Given an observation, a player can perform either one of the following two possible “actions”:" }, { "code": null, "e": 2061, "s": 2029, "text": "0: pushing the cart to the left" }, { "code": null, "e": 2094, "s": 2061, "text": "1: pushing the cart to the right" }, { "code": null, "e": 2357, "s": 2094, "text": "The game is “done” when the pole deviates more than 15 degrees from vertical (|θ| ≥ π/12 ≈0.26). In each time step, if the game is not “done”, then the cumulative “reward” increases by 1. The goal of the game is to have the cumulative reward as high as possible." }, { "code": null, "e": 2412, "s": 2357, "text": "Let’s take a look at the following example in details:" }, { "code": null, "e": 2429, "s": 2412, "text": "The observation:" }, { "code": null, "e": 2484, "s": 2429, "text": "x=0.018: the cart is on the right side of the origin O" }, { "code": null, "e": 2525, "s": 2484, "text": "v=0.669: the cart is moving to the right" }, { "code": null, "e": 2601, "s": 2525, "text": "θ=0.286: the pole is at (0.286/2π*360≈16.4 degrees) clockwise from vertical" }, { "code": null, "e": 2642, "s": 2601, "text": "ω=0.618: the pole is rotating close-wise" }, { "code": null, "e": 2696, "s": 2642, "text": "Action=1: the player is pushing the cart to the right" }, { "code": null, "e": 2783, "s": 2696, "text": "Cumulative Reward=47: the player has successfully sustained 47 time steps in this game" }, { "code": null, "e": 2846, "s": 2783, "text": "Done=1: this game is already “done” (because |θ| > 15 degrees)" }, { "code": null, "e": 2932, "s": 2846, "text": "Now we understood the setup. Let’s see how to play this game to achieve high rewards." }, { "code": null, "e": 3090, "s": 2932, "text": "In the context of reinforced learning, a “policy” essentially means a function that takes an observation (or a series of observations) and outputs an action." }, { "code": null, "e": 3305, "s": 3090, "text": "Before we try to be smart, let’s first imagine a monkey randomly pushes the cart left and right, and see how well it performs. This can help us to establish a baseline. Its implementation is, of course very simple:" }, { "code": null, "e": 3358, "s": 3305, "text": "def rand_policy(obs): return random.randint(0, 1)" }, { "code": null, "e": 3519, "s": 3358, "text": "We played this “random policy” 1,000 times and plot the cumulative reward of each game. We can see the mean reward is 22.03, and the standard deviation is 8.00." }, { "code": null, "e": 3744, "s": 3519, "text": "Of course, we can do better than the monkey. In Géron, Aurélien’s book: Hands-On Machine Learning with Scikit-Learn, Keras, and TensorFlow (Chapter 18), there’s a very simple policy that only depends on the pole’s angle θ:" }, { "code": null, "e": 3817, "s": 3744, "text": "def theta_policy(obs): theta = obs[2] return 0 if theta < 0 else 1" }, { "code": null, "e": 4053, "s": 3817, "text": "In plain language, it says that if the pole is tilted to the left (θ<0), then push the cart to the left, and vice versa. Very intuitive, isn’t it? It’s indeed better than the random policy, with the mean reward almost doubled to 41.67." }, { "code": null, "e": 4178, "s": 4053, "text": "And the following is one iteration to show how it performs. It indeed shows some intention to prevent the pole from falling." }, { "code": null, "e": 4790, "s": 4178, "text": "Although better a monkey, the Theta Policy is far from satisfactory. For those with some physics backgrounds, this policy is obviously flawed. Because when the cart is pushed to the left, the pole gets a clockwise angular acceleration, not a clock-wise angular velocity. The consequence of this action is that the pole can rotate clockwise as well as counter-clockwise. Also, when the pole is already moving towards the center, say θ>0 and ω < 0, the action (pushing to the right) will still accelerate the angular velocity towards the center rather than slow it down. Thus the pole over-shoots past the center." }, { "code": null, "e": 5128, "s": 4790, "text": "Base on the above mechanical analysis, a much more reasonable proposition is that when the pole is moving away from the vertical position (ω<0), push the cart to the left (action = 0). And vice versa. Since it only depends on the angular velocity ω, let’s name it “Omega Policy”. Its implementation is just as simple as the Theta Policy:" }, { "code": null, "e": 5193, "s": 5128, "text": "def omega_policy(obs): w = obs[3] return 0 if w < 0 else 1" }, { "code": null, "e": 5348, "s": 5193, "text": "Surprise! Based on one simple law from physics, a one-line change turns the poor Theta Policy into a winner! This Omega Policy gets a mean reward of ~200!" }, { "code": null, "e": 5637, "s": 5348, "text": "To appreciate the 200 average rewards, let’s compare the average rewards of some commonly found machine learning policies. Please keep in mind that these machine learning policies are much more complicated, much harder to explain, and requires long training times to achieve these result:" }, { "code": null, "e": 5687, "s": 5637, "text": "Sequential Neural-Network (in Géron’s book): ~46" }, { "code": null, "e": 5724, "s": 5687, "text": "Deep Q-Learning (in article 1): ~130" }, { "code": null, "e": 5761, "s": 5724, "text": "Deep Q-Learning (in article 2): ~200" }, { "code": null, "e": 5883, "s": 5761, "text": "You can see that our two-liner Omega Policy already performs on par or better than the AI-powered Deep Q-Learning policy." }, { "code": null, "e": 6070, "s": 5883, "text": "The official CartPole webpage defines that the problem is “solved” if the average reward >195 over 100 consecutive trials. So our 2-line Omega Policy already solves the CartPole problem!" }, { "code": null, "e": 6201, "s": 6070, "text": "Although the simple Omega Policy already solved the CartPole problem, I am still not satisfied. A quick visualization reveals why:" }, { "code": null, "e": 6574, "s": 6201, "text": "We can see that the game ends not because the pole falls but because the cart deviates from the origin too far. This indicates the policy successfully “stabilizes” the pole (keeping angular velocity ω ≈ 0), but at a “tiled” position (angle θ ≠ 0). So the cart keeps moving in one direction. This is not surprising, because the Omega Policy does nothing about the angle θ." }, { "code": null, "e": 6646, "s": 6574, "text": "After identifying the problem, it’s easy to propose an improved policy:" }, { "code": null, "e": 6737, "s": 6646, "text": "When the angle θ is “small”, we want to stabilize θ. This is the same as the Omega Policy." }, { "code": null, "e": 6881, "s": 6737, "text": "When the angle θ is “large”, we want to correct θ, i.e., give an angular acceleration towards the center. This is the same as the Theta Policy." }, { "code": null, "e": 7211, "s": 6881, "text": "As far as the criterion for “small” and “large”, it’s not well defined. But a reasonable starting point is 10% of the 15 degrees “done” threshold, i.e., ~0.026. In reality, the result is not very sensitive to this value. Anywhere from 0.02 to 0.04 can produce amazing results. Following is an example using 0.03 as the threshold:" }, { "code": null, "e": 7365, "s": 7211, "text": "def theta_omega_policy(obs): theta, w = obs[2:4] if abs(theta) < 0.03: return 0 if w < 0 else 1 else: return 0 if theta < 0 else 1" }, { "code": null, "e": 7404, "s": 7365, "text": "How good is this simple 5-line policy?" }, { "code": null, "e": 7736, "s": 7404, "text": "Bingo! The pole simply CANNOT fall! Not even once! The reason that the cumulative reward caps at 500 is just due to the limitation of the CartPol-v1 environment itself — when the game is played 500 time steps, it automatically stops. In other words, our Theta-Omega Policy not only “solves” the problem, but also “breaks” the game!" }, { "code": null, "e": 7804, "s": 7736, "text": "Following is how this simple 5-line policy performs in real action:" }, { "code": null, "e": 7901, "s": 7804, "text": "The full notebook of the system setup, analysis, and GIF generation is available here on GitHub." }, { "code": null, "e": 8238, "s": 7901, "text": "Obviously, this is not an artificial intelligence exercise. But by showing how to breaks the CartPole game in 5 lines, I hope you can appreciate how condense the law of physics is. Essentially, we utilized results from thousands of years of human learning, to replace the machine learning code, and got a far better, far simpler result." } ]
Program to find largest perimeter triangle using Python
Suppose we have an array nums of positive lengths, we have to find the largest perimeter of a triangle, by taking three values from that array. When it is impossible to form any triangle of non-zero area, then return 0. So, if the input is like [8,3,6,4,2,5], then the output will be 19. To solve this, we will follow these steps − sort the list nums sort the list nums a := delete last element from nums a := delete last element from nums b := delete last element from nums b := delete last element from nums c := delete last element from nums c := delete last element from nums while b+c <= a, doif not nums is non-zero, thenreturn 0a := bb := cc := delete last element from nums while b+c <= a, do if not nums is non-zero, thenreturn 0 if not nums is non-zero, then return 0 return 0 a := b a := b b := c b := c c := delete last element from nums c := delete last element from nums return a+b+c return a+b+c Let us see the following implementation to get better understanding − Live Demo def solve(nums): nums.sort() a, b, c = nums.pop(), nums.pop(), nums.pop() while b+c<=a: if not nums: return 0 a, b, c = b, c, nums.pop() return a+b+c nums = [8,3,6,4,2,5] print(solve(nums)) [8,3,6,4,2,5] 19
[ { "code": null, "e": 1282, "s": 1062, "text": "Suppose we have an array nums of positive lengths, we have to find the largest perimeter of a triangle, by taking three values from that array. When it is impossible to form any triangle of non-zero area, then return 0." }, { "code": null, "e": 1350, "s": 1282, "text": "So, if the input is like [8,3,6,4,2,5], then the output will be 19." }, { "code": null, "e": 1394, "s": 1350, "text": "To solve this, we will follow these steps −" }, { "code": null, "e": 1413, "s": 1394, "text": "sort the list nums" }, { "code": null, "e": 1432, "s": 1413, "text": "sort the list nums" }, { "code": null, "e": 1467, "s": 1432, "text": "a := delete last element from nums" }, { "code": null, "e": 1502, "s": 1467, "text": "a := delete last element from nums" }, { "code": null, "e": 1537, "s": 1502, "text": "b := delete last element from nums" }, { "code": null, "e": 1572, "s": 1537, "text": "b := delete last element from nums" }, { "code": null, "e": 1607, "s": 1572, "text": "c := delete last element from nums" }, { "code": null, "e": 1642, "s": 1607, "text": "c := delete last element from nums" }, { "code": null, "e": 1744, "s": 1642, "text": "while b+c <= a, doif not nums is non-zero, thenreturn 0a := bb := cc := delete last element from nums" }, { "code": null, "e": 1763, "s": 1744, "text": "while b+c <= a, do" }, { "code": null, "e": 1801, "s": 1763, "text": "if not nums is non-zero, thenreturn 0" }, { "code": null, "e": 1831, "s": 1801, "text": "if not nums is non-zero, then" }, { "code": null, "e": 1840, "s": 1831, "text": "return 0" }, { "code": null, "e": 1849, "s": 1840, "text": "return 0" }, { "code": null, "e": 1856, "s": 1849, "text": "a := b" }, { "code": null, "e": 1863, "s": 1856, "text": "a := b" }, { "code": null, "e": 1870, "s": 1863, "text": "b := c" }, { "code": null, "e": 1877, "s": 1870, "text": "b := c" }, { "code": null, "e": 1912, "s": 1877, "text": "c := delete last element from nums" }, { "code": null, "e": 1947, "s": 1912, "text": "c := delete last element from nums" }, { "code": null, "e": 1960, "s": 1947, "text": "return a+b+c" }, { "code": null, "e": 1973, "s": 1960, "text": "return a+b+c" }, { "code": null, "e": 2043, "s": 1973, "text": "Let us see the following implementation to get better understanding −" }, { "code": null, "e": 2054, "s": 2043, "text": " Live Demo" }, { "code": null, "e": 2277, "s": 2054, "text": "def solve(nums):\n nums.sort()\n a, b, c = nums.pop(), nums.pop(), nums.pop()\n while b+c<=a:\n if not nums:\n return 0\n a, b, c = b, c, nums.pop()\n return a+b+c\nnums = [8,3,6,4,2,5]\nprint(solve(nums))" }, { "code": null, "e": 2291, "s": 2277, "text": "[8,3,6,4,2,5]" }, { "code": null, "e": 2294, "s": 2291, "text": "19" } ]
What are type specifiers in C++?
When you first declare a variable in a statically typed language such as C++ you must declare what that variable is going to hold. int number = 42; In that example, the "int" is a type specifier stating that the variable "number" can only hold integer numbers. In dynamically typed languages such as ruby or javascript, you can simply declare the variable. var number = 42; There are a lot of built-in type specifiers like double, char, float, etc in C++. You can also create your own specifiers by creating class and structs.
[ { "code": null, "e": 1193, "s": 1062, "text": "When you first declare a variable in a statically typed language such as C++ you must declare what that variable is going to hold." }, { "code": null, "e": 1210, "s": 1193, "text": "int number = 42;" }, { "code": null, "e": 1419, "s": 1210, "text": "In that example, the \"int\" is a type specifier stating that the variable \"number\" can only hold integer numbers. In dynamically typed languages such as ruby or javascript, you can simply declare the variable." }, { "code": null, "e": 1436, "s": 1419, "text": "var number = 42;" }, { "code": null, "e": 1589, "s": 1436, "text": "There are a lot of built-in type specifiers like double, char, float, etc in C++. You can also create your own specifiers by creating class and structs." } ]
Best way to find length of JSON object in JavaScript
Suppose we have an object like this − const obj = { name: "Ramesh", age: 34, occupation: "HR Manager", address: "Tilak Nagar, New Delhi", experience: 13 }; We are required to write a JavaScript function on Objects that computes their size (i.e., the number of properties in it). The code for this will be − const obj = { name: "Ramesh", age: 34, occupation: "HR Manager", address: "Tilak Nagar, New Delhi", experience: 13 }; Object.prototype.size = function(obj) { let size = 0, key; for (key in obj) { if (obj.hasOwnProperty(key)){ size++ }; }; return size; }; const size = Object.size(obj); console.log(size); The output in the console will be − 5
[ { "code": null, "e": 1100, "s": 1062, "text": "Suppose we have an object like this −" }, { "code": null, "e": 1233, "s": 1100, "text": "const obj = {\n name: \"Ramesh\",\n age: 34,\n occupation: \"HR Manager\",\n address: \"Tilak Nagar, New Delhi\",\n experience: 13\n};" }, { "code": null, "e": 1356, "s": 1233, "text": "We are required to write a JavaScript function on Objects that computes their size (i.e., the\nnumber of properties in it)." }, { "code": null, "e": 1384, "s": 1356, "text": "The code for this will be −" }, { "code": null, "e": 1737, "s": 1384, "text": "const obj = {\n name: \"Ramesh\",\n age: 34,\n occupation: \"HR Manager\",\n address: \"Tilak Nagar, New Delhi\",\n experience: 13\n};\nObject.prototype.size = function(obj) {\n let size = 0, key;\n for (key in obj) {\n if (obj.hasOwnProperty(key)){\n size++\n };\n };\n return size;\n};\nconst size = Object.size(obj);\nconsole.log(size);" }, { "code": null, "e": 1773, "s": 1737, "text": "The output in the console will be −" }, { "code": null, "e": 1775, "s": 1773, "text": "5" } ]
How to catch syntax errors in JavaScript?
You cannot use try-catch blocks for handling syntax errors in JavaScript since it is thrown while the code is being parsed. Use window.onerror as in the following code − <html> <head> <script> window.onerror = function(e) { document.write('Error: ', e, '</br>') }; </script> <script> document.write('x'x') </script> </head> <body> </body> </html> Note − Ensure that the error function is defined in a separate <script> tag.
[ { "code": null, "e": 1186, "s": 1062, "text": "You cannot use try-catch blocks for handling syntax errors in JavaScript since it is thrown while the code is being parsed." }, { "code": null, "e": 1232, "s": 1186, "text": "Use window.onerror as in the following code −" }, { "code": null, "e": 1492, "s": 1232, "text": "<html>\n <head>\n <script>\n window.onerror = function(e) {\n document.write('Error: ', e, '</br>')\n };\n </script>\n \n <script>\n document.write('x'x')\n </script>\n </head>\n \n <body>\n </body>\n</html>" }, { "code": null, "e": 1569, "s": 1492, "text": "Note − Ensure that the error function is defined in a separate <script> tag." } ]
C++ Library - <typeinfo>
It defines in header and related to operators typeid and dynamic_cast. Following is the declaration for std::type_info. class type_info; class type_info; It contains type information. It throws an exception on failure to dynamic cast. It throws an exception on typeid of null point. Print Add Notes Bookmark this page
[ { "code": null, "e": 2674, "s": 2603, "text": "It defines in header and related to operators typeid and dynamic_cast." }, { "code": null, "e": 2723, "s": 2674, "text": "Following is the declaration for std::type_info." }, { "code": null, "e": 2740, "s": 2723, "text": "class type_info;" }, { "code": null, "e": 2757, "s": 2740, "text": "class type_info;" }, { "code": null, "e": 2787, "s": 2757, "text": "It contains type information." }, { "code": null, "e": 2838, "s": 2787, "text": "It throws an exception on failure to dynamic cast." }, { "code": null, "e": 2886, "s": 2838, "text": "It throws an exception on typeid of null point." }, { "code": null, "e": 2893, "s": 2886, "text": " Print" }, { "code": null, "e": 2904, "s": 2893, "text": " Add Notes" } ]
Perl - Operators
Simple answer can be given using the expression 4 + 5 is equal to 9. Here 4 and 5 are called operands and + is called operator. Perl language supports many operator types, but following is a list of important and most frequently used operators − Arithmetic Operators Equality Operators Logical Operators Assignment Operators Bitwise Operators Logical Operators Quote-like Operators Miscellaneous Operators Lets have a look at all the operators one by one. Assume variable $a holds 10 and variable $b holds 20, then following are the Perl arithmatic operators − Show Example + ( Addition ) Adds values on either side of the operator Example − $a + $b will give 30 - (Subtraction) Subtracts right hand operand from left hand operand Example − $a - $b will give -10 * (Multiplication) Multiplies values on either side of the operator Example − $a * $b will give 200 / (Division) Divides left hand operand by right hand operand Example − $b / $a will give 2 % (Modulus) Divides left hand operand by right hand operand and returns remainder Example − $b % $a will give 0 ** (Exponent) Performs exponential (power) calculation on operators Example − $a**$b will give 10 to the power 20 These are also called relational operators. Assume variable $a holds 10 and variable $b holds 20 then, lets check the following numeric equality operators − Show Example == (equal to) Checks if the value of two operands are equal or not, if yes then condition becomes true. Example − ($a == $b) is not true. != (not equal to) Checks if the value of two operands are equal or not, if values are not equal then condition becomes true. Example − ($a != $b) is true. <=> Checks if the value of two operands are equal or not, and returns -1, 0, or 1 depending on whether the left argument is numerically less than, equal to, or greater than the right argument. Example − ($a <=> $b) returns -1. > (greater than) Checks if the value of left operand is greater than the value of right operand, if yes then condition becomes true. Example − ($a > $b) is not true. < (less than) Checks if the value of left operand is less than the value of right operand, if yes then condition becomes true. Example − ($a < $b) is true. >= (greater than or equal to) Checks if the value of left operand is greater than or equal to the value of right operand, if yes then condition becomes true. Example − ($a >= $b) is not true. <= (less than or equal to) Checks if the value of left operand is less than or equal to the value of right operand, if yes then condition becomes true. Example − ($a <= $b) is true. Below is a list of equity operators. Assume variable $a holds "abc" and variable $b holds "xyz" then, lets check the following string equality operators − Show Example lt Returns true if the left argument is stringwise less than the right argument. Example − ($a lt $b) is true. gt Returns true if the left argument is stringwise greater than the right argument. Example − ($a gt $b) is false. le Returns true if the left argument is stringwise less than or equal to the right argument. Example − ($a le $b) is true. ge Returns true if the left argument is stringwise greater than or equal to the right argument. Example − ($a ge $b) is false. eq Returns true if the left argument is stringwise equal to the right argument. Example − ($a eq $b) is false. ne Returns true if the left argument is stringwise not equal to the right argument. Example − ($a ne $b) is true. cmp Returns -1, 0, or 1 depending on whether the left argument is stringwise less than, equal to, or greater than the right argument. Example − ($a cmp $b) is -1. Assume variable $a holds 10 and variable $b holds 20, then below are the assignment operators available in Perl and their usage − Show Example = Simple assignment operator, Assigns values from right side operands to left side operand Example − $c = $a + $b will assigned value of $a + $b into $c += Add AND assignment operator, It adds right operand to the left operand and assign the result to left operand Example − $c += $a is equivalent to $c = $c + $a -= Subtract AND assignment operator, It subtracts right operand from the left operand and assign the result to left operand Example − $c -= $a is equivalent to $c = $c - $a *= Multiply AND assignment operator, It multiplies right operand with the left operand and assign the result to left operand Example − $c *= $a is equivalent to $c = $c * $a /= Divide AND assignment operator, It divides left operand with the right operand and assign the result to left operand Example − $c /= $a is equivalent to $c = $c / $a %= Modulus AND assignment operator, It takes modulus using two operands and assign the result to left operand Example − $c %= $a is equivalent to $c = $c % a **= Exponent AND assignment operator, Performs exponential (power) calculation on operators and assign value to the left operand Example − $c **= $a is equivalent to $c = $c ** $a Bitwise operator works on bits and perform bit by bit operation. Assume if $a = 60; and $b = 13; Now in binary format they will be as follows − $a = 0011 1100 $b = 0000 1101 ----------------- $a&$b = 0000 1100 $a|$b = 0011 1101 $a^$b = 0011 0001 ~$a = 1100 0011 There are following Bitwise operators supported by Perl language, assume if $a = 60; and $b = 13 Show Example & Binary AND Operator copies a bit to the result if it exists in both operands. Example − ($a & $b) will give 12 which is 0000 1100 | Binary OR Operator copies a bit if it exists in eather operand. Example − ($a | $b) will give 61 which is 0011 1101 ^ Binary XOR Operator copies the bit if it is set in one operand but not both. Example − ($a ^ $b) will give 49 which is 0011 0001 ~ Binary Ones Complement Operator is unary and has the efect of 'flipping' bits. Example − (~$a ) will give -61 which is 1100 0011 in 2's complement form due to a signed binary number. << Binary Left Shift Operator. The left operands value is moved left by the number of bits specified by the right operand. Example − $a << 2 will give 240 which is 1111 0000 >> Binary Right Shift Operator. The left operands value is moved right by the number of bits specified by the right operand. Example − $a >> 2 will give 15 which is 0000 1111 There are following logical operators supported by Perl language. Assume variable $a holds true and variable $b holds false then − Show Example and Called Logical AND operator. If both the operands are true then then condition becomes true. Example − ($a and $b) is false. && C-style Logical AND operator copies a bit to the result if it exists in both operands. Example − ($a && $b) is false. or Called Logical OR Operator. If any of the two operands are non zero then then condition becomes true. Example − ($a or $b) is true. || C-style Logical OR operator copies a bit if it exists in eather operand. Example − ($a || $b) is true. not Called Logical NOT Operator. Use to reverses the logical state of its operand. If a condition is true then Logical NOT operator will make false. Example − not($a and $b) is true. There are following Quote-like operators supported by Perl language. In the following table, a {} represents any pair of delimiters you choose. Show Example q{ } Encloses a string with-in single quotes Example − q{abcd} gives 'abcd' qq{ } Encloses a string with-in double quotes Example − qq{abcd} gives "abcd" qx{ } Encloses a string with-in invert quotes Example − qx{abcd} gives `abcd` There are following miscellaneous operators supported by Perl language. Assume variable a holds 10 and variable b holds 20 then − Show Example . Binary operator dot (.) concatenates two strings. Example − If $a = "abc", $b = "def" then $a.$b will give "abcdef" x The repetition operator x returns a string consisting of the left operand repeated the number of times specified by the right operand. Example − ('-' x 3) will give ---. .. The range operator .. returns a list of values counting (up by ones) from the left value to the right value Example − (2..5) will give (2, 3, 4, 5) ++ Auto Increment operator increases integer value by one Example − $a++ will give 11 -- Auto Decrement operator decreases integer value by one Example − $a-- will give 9 -> The arrow operator is mostly used in dereferencing a method or variable from an object or a class name Example − $obj->$a is an example to access variable $a from object $obj. The following table lists all operators from highest precedence to lowest. Show Example left terms and list operators (leftward) left -> nonassoc ++ -- right ** right ! ~ \ and unary + and - left =~ !~ left * / % x left + - . left << >> nonassoc named unary operators nonassoc < > <= >= lt gt le ge nonassoc == != <=> eq ne cmp ~~ left & left | ^ left && left || // nonassoc .. ... right ?: right = += -= *= etc. left , => nonassoc list operators (rightward) right not left and left or xor 46 Lectures 4.5 hours Devi Killada 11 Lectures 1.5 hours Harshit Srivastava 30 Lectures 6 hours TELCOMA Global 24 Lectures 2 hours Mohammad Nauman 68 Lectures 7 hours Stone River ELearning 58 Lectures 6.5 hours Stone River ELearning Print Add Notes Bookmark this page
[ { "code": null, "e": 2466, "s": 2220, "text": "Simple answer can be given using the expression 4 + 5 is equal to 9. Here 4 and 5 are called operands and + is called operator. Perl language supports many operator types, but following is a list of important and most frequently used operators −" }, { "code": null, "e": 2487, "s": 2466, "text": "Arithmetic Operators" }, { "code": null, "e": 2506, "s": 2487, "text": "Equality Operators" }, { "code": null, "e": 2524, "s": 2506, "text": "Logical Operators" }, { "code": null, "e": 2545, "s": 2524, "text": "Assignment Operators" }, { "code": null, "e": 2563, "s": 2545, "text": "Bitwise Operators" }, { "code": null, "e": 2581, "s": 2563, "text": "Logical Operators" }, { "code": null, "e": 2602, "s": 2581, "text": "Quote-like Operators" }, { "code": null, "e": 2626, "s": 2602, "text": "Miscellaneous Operators" }, { "code": null, "e": 2676, "s": 2626, "text": "Lets have a look at all the operators one by one." }, { "code": null, "e": 2781, "s": 2676, "text": "Assume variable $a holds 10 and variable $b holds 20, then following are the Perl arithmatic operators −" }, { "code": null, "e": 2794, "s": 2781, "text": "Show Example" }, { "code": null, "e": 2809, "s": 2794, "text": "+ ( Addition )" }, { "code": null, "e": 2852, "s": 2809, "text": "Adds values on either side of the operator" }, { "code": null, "e": 2883, "s": 2852, "text": "Example − $a + $b will give 30" }, { "code": null, "e": 2899, "s": 2883, "text": "- (Subtraction)" }, { "code": null, "e": 2951, "s": 2899, "text": "Subtracts right hand operand from left hand operand" }, { "code": null, "e": 2983, "s": 2951, "text": "Example − $a - $b will give -10" }, { "code": null, "e": 3002, "s": 2983, "text": "* (Multiplication)" }, { "code": null, "e": 3051, "s": 3002, "text": "Multiplies values on either side of the operator" }, { "code": null, "e": 3083, "s": 3051, "text": "Example − $a * $b will give 200" }, { "code": null, "e": 3096, "s": 3083, "text": "/ (Division)" }, { "code": null, "e": 3144, "s": 3096, "text": "Divides left hand operand by right hand operand" }, { "code": null, "e": 3174, "s": 3144, "text": "Example − $b / $a will give 2" }, { "code": null, "e": 3186, "s": 3174, "text": "% (Modulus)" }, { "code": null, "e": 3256, "s": 3186, "text": "Divides left hand operand by right hand operand and returns remainder" }, { "code": null, "e": 3286, "s": 3256, "text": "Example − $b % $a will give 0" }, { "code": null, "e": 3300, "s": 3286, "text": "** (Exponent)" }, { "code": null, "e": 3354, "s": 3300, "text": "Performs exponential (power) calculation on operators" }, { "code": null, "e": 3400, "s": 3354, "text": "Example − $a**$b will give 10 to the power 20" }, { "code": null, "e": 3557, "s": 3400, "text": "These are also called relational operators. Assume variable $a holds 10 and variable $b holds 20 then, lets check the following numeric equality operators −" }, { "code": null, "e": 3570, "s": 3557, "text": "Show Example" }, { "code": null, "e": 3584, "s": 3570, "text": "== (equal to)" }, { "code": null, "e": 3674, "s": 3584, "text": "Checks if the value of two operands are equal or not, if yes then condition becomes true." }, { "code": null, "e": 3708, "s": 3674, "text": "Example − ($a == $b) is not true." }, { "code": null, "e": 3726, "s": 3708, "text": "!= (not equal to)" }, { "code": null, "e": 3833, "s": 3726, "text": "Checks if the value of two operands are equal or not, if values are not equal then condition becomes true." }, { "code": null, "e": 3863, "s": 3833, "text": "Example − ($a != $b) is true." }, { "code": null, "e": 3867, "s": 3863, "text": "<=>" }, { "code": null, "e": 4056, "s": 3867, "text": "Checks if the value of two operands are equal or not, and returns -1, 0, or 1 depending on whether the left argument is numerically less than, equal to, or greater than the right argument." }, { "code": null, "e": 4090, "s": 4056, "text": "Example − ($a <=> $b) returns -1." }, { "code": null, "e": 4107, "s": 4090, "text": "> (greater than)" }, { "code": null, "e": 4223, "s": 4107, "text": "Checks if the value of left operand is greater than the value of right operand, if yes then condition becomes true." }, { "code": null, "e": 4256, "s": 4223, "text": "Example − ($a > $b) is not true." }, { "code": null, "e": 4270, "s": 4256, "text": "< (less than)" }, { "code": null, "e": 4383, "s": 4270, "text": "Checks if the value of left operand is less than the value of right operand, if yes then condition becomes true." }, { "code": null, "e": 4412, "s": 4383, "text": "Example − ($a < $b) is true." }, { "code": null, "e": 4442, "s": 4412, "text": ">= (greater than or equal to)" }, { "code": null, "e": 4570, "s": 4442, "text": "Checks if the value of left operand is greater than or equal to the value of right operand, if yes then condition becomes true." }, { "code": null, "e": 4604, "s": 4570, "text": "Example − ($a >= $b) is not true." }, { "code": null, "e": 4631, "s": 4604, "text": "<= (less than or equal to)" }, { "code": null, "e": 4756, "s": 4631, "text": "Checks if the value of left operand is less than or equal to the value of right operand, if yes then condition becomes true." }, { "code": null, "e": 4786, "s": 4756, "text": "Example − ($a <= $b) is true." }, { "code": null, "e": 4941, "s": 4786, "text": "Below is a list of equity operators. Assume variable $a holds \"abc\" and variable $b holds \"xyz\" then, lets check the following string equality operators −" }, { "code": null, "e": 4954, "s": 4941, "text": "Show Example" }, { "code": null, "e": 4957, "s": 4954, "text": "lt" }, { "code": null, "e": 5035, "s": 4957, "text": "Returns true if the left argument is stringwise less than the right argument." }, { "code": null, "e": 5065, "s": 5035, "text": "Example − ($a lt $b) is true." }, { "code": null, "e": 5068, "s": 5065, "text": "gt" }, { "code": null, "e": 5149, "s": 5068, "text": "Returns true if the left argument is stringwise greater than the right argument." }, { "code": null, "e": 5180, "s": 5149, "text": "Example − ($a gt $b) is false." }, { "code": null, "e": 5183, "s": 5180, "text": "le" }, { "code": null, "e": 5273, "s": 5183, "text": "Returns true if the left argument is stringwise less than or equal to the right argument." }, { "code": null, "e": 5303, "s": 5273, "text": "Example − ($a le $b) is true." }, { "code": null, "e": 5306, "s": 5303, "text": "ge" }, { "code": null, "e": 5399, "s": 5306, "text": "Returns true if the left argument is stringwise greater than or equal to the right argument." }, { "code": null, "e": 5430, "s": 5399, "text": "Example − ($a ge $b) is false." }, { "code": null, "e": 5433, "s": 5430, "text": "eq" }, { "code": null, "e": 5510, "s": 5433, "text": "Returns true if the left argument is stringwise equal to the right argument." }, { "code": null, "e": 5541, "s": 5510, "text": "Example − ($a eq $b) is false." }, { "code": null, "e": 5544, "s": 5541, "text": "ne" }, { "code": null, "e": 5625, "s": 5544, "text": "Returns true if the left argument is stringwise not equal to the right argument." }, { "code": null, "e": 5655, "s": 5625, "text": "Example − ($a ne $b) is true." }, { "code": null, "e": 5659, "s": 5655, "text": "cmp" }, { "code": null, "e": 5789, "s": 5659, "text": "Returns -1, 0, or 1 depending on whether the left argument is stringwise less than, equal to, or greater than the right argument." }, { "code": null, "e": 5818, "s": 5789, "text": "Example − ($a cmp $b) is -1." }, { "code": null, "e": 5948, "s": 5818, "text": "Assume variable $a holds 10 and variable $b holds 20, then below are the assignment operators available in Perl and their usage −" }, { "code": null, "e": 5961, "s": 5948, "text": "Show Example" }, { "code": null, "e": 5963, "s": 5961, "text": "=" }, { "code": null, "e": 6052, "s": 5963, "text": "Simple assignment operator, Assigns values from right side operands to left side operand" }, { "code": null, "e": 6114, "s": 6052, "text": "Example − $c = $a + $b will assigned value of $a + $b into $c" }, { "code": null, "e": 6117, "s": 6114, "text": "+=" }, { "code": null, "e": 6226, "s": 6117, "text": "Add AND assignment operator, It adds right operand to the left operand and assign the result to left operand" }, { "code": null, "e": 6275, "s": 6226, "text": "Example − $c += $a is equivalent to $c = $c + $a" }, { "code": null, "e": 6278, "s": 6275, "text": "-=" }, { "code": null, "e": 6399, "s": 6278, "text": "Subtract AND assignment operator, It subtracts right operand from the left operand and assign the result to left operand" }, { "code": null, "e": 6448, "s": 6399, "text": "Example − $c -= $a is equivalent to $c = $c - $a" }, { "code": null, "e": 6451, "s": 6448, "text": "*=" }, { "code": null, "e": 6573, "s": 6451, "text": "Multiply AND assignment operator, It multiplies right operand with the left operand and assign the result to left operand" }, { "code": null, "e": 6622, "s": 6573, "text": "Example − $c *= $a is equivalent to $c = $c * $a" }, { "code": null, "e": 6625, "s": 6622, "text": "/=" }, { "code": null, "e": 6742, "s": 6625, "text": "Divide AND assignment operator, It divides left operand with the right operand and assign the result to left operand" }, { "code": null, "e": 6791, "s": 6742, "text": "Example − $c /= $a is equivalent to $c = $c / $a" }, { "code": null, "e": 6794, "s": 6791, "text": "%=" }, { "code": null, "e": 6901, "s": 6794, "text": "Modulus AND assignment operator, It takes modulus using two operands and assign the result to left operand" }, { "code": null, "e": 6949, "s": 6901, "text": "Example − $c %= $a is equivalent to $c = $c % a" }, { "code": null, "e": 6953, "s": 6949, "text": "**=" }, { "code": null, "e": 7078, "s": 6953, "text": "Exponent AND assignment operator, Performs exponential (power) calculation on operators and assign value to the left operand" }, { "code": null, "e": 7129, "s": 7078, "text": "Example − $c **= $a is equivalent to $c = $c ** $a" }, { "code": null, "e": 7273, "s": 7129, "text": "Bitwise operator works on bits and perform bit by bit operation. Assume if $a = 60; and $b = 13; Now in binary format they will be as follows −" }, { "code": null, "e": 7288, "s": 7273, "text": "$a = 0011 1100" }, { "code": null, "e": 7303, "s": 7288, "text": "$b = 0000 1101" }, { "code": null, "e": 7321, "s": 7303, "text": "-----------------" }, { "code": null, "e": 7339, "s": 7321, "text": "$a&$b = 0000 1100" }, { "code": null, "e": 7357, "s": 7339, "text": "$a|$b = 0011 1101" }, { "code": null, "e": 7375, "s": 7357, "text": "$a^$b = 0011 0001" }, { "code": null, "e": 7392, "s": 7375, "text": "~$a = 1100 0011" }, { "code": null, "e": 7489, "s": 7392, "text": "There are following Bitwise operators supported by Perl language, assume if $a = 60; and $b = 13" }, { "code": null, "e": 7502, "s": 7489, "text": "Show Example" }, { "code": null, "e": 7504, "s": 7502, "text": "&" }, { "code": null, "e": 7582, "s": 7504, "text": "Binary AND Operator copies a bit to the result if it exists in both operands." }, { "code": null, "e": 7634, "s": 7582, "text": "Example − ($a & $b) will give 12 which is 0000 1100" }, { "code": null, "e": 7636, "s": 7634, "text": "|" }, { "code": null, "e": 7700, "s": 7636, "text": "Binary OR Operator copies a bit if it exists in eather operand." }, { "code": null, "e": 7752, "s": 7700, "text": "Example − ($a | $b) will give 61 which is 0011 1101" }, { "code": null, "e": 7754, "s": 7752, "text": "^" }, { "code": null, "e": 7831, "s": 7754, "text": "Binary XOR Operator copies the bit if it is set in one operand but not both." }, { "code": null, "e": 7883, "s": 7831, "text": "Example − ($a ^ $b) will give 49 which is 0011 0001" }, { "code": null, "e": 7885, "s": 7883, "text": "~" }, { "code": null, "e": 7964, "s": 7885, "text": "Binary Ones Complement Operator is unary and has the efect of 'flipping' bits." }, { "code": null, "e": 8068, "s": 7964, "text": "Example − (~$a ) will give -61 which is 1100 0011 in 2's complement form due to a signed binary number." }, { "code": null, "e": 8071, "s": 8068, "text": "<<" }, { "code": null, "e": 8191, "s": 8071, "text": "Binary Left Shift Operator. The left operands value is moved left by the number of bits specified by the right operand." }, { "code": null, "e": 8242, "s": 8191, "text": "Example − $a << 2 will give 240 which is 1111 0000" }, { "code": null, "e": 8245, "s": 8242, "text": ">>" }, { "code": null, "e": 8367, "s": 8245, "text": "Binary Right Shift Operator. The left operands value is moved right by the number of bits specified by the right operand." }, { "code": null, "e": 8417, "s": 8367, "text": "Example − $a >> 2 will give 15 which is 0000 1111" }, { "code": null, "e": 8548, "s": 8417, "text": "There are following logical operators supported by Perl language. Assume variable $a holds true and variable $b holds false then −" }, { "code": null, "e": 8561, "s": 8548, "text": "Show Example" }, { "code": null, "e": 8565, "s": 8561, "text": "and" }, { "code": null, "e": 8658, "s": 8565, "text": "Called Logical AND operator. If both the operands are true then then condition becomes true." }, { "code": null, "e": 8690, "s": 8658, "text": "Example − ($a and $b) is false." }, { "code": null, "e": 8693, "s": 8690, "text": "&&" }, { "code": null, "e": 8780, "s": 8693, "text": "C-style Logical AND operator copies a bit to the result if it exists in both operands." }, { "code": null, "e": 8811, "s": 8780, "text": "Example − ($a && $b) is false." }, { "code": null, "e": 8814, "s": 8811, "text": "or" }, { "code": null, "e": 8916, "s": 8814, "text": "Called Logical OR Operator. If any of the two operands are non zero then then condition becomes true." }, { "code": null, "e": 8946, "s": 8916, "text": "Example − ($a or $b) is true." }, { "code": null, "e": 8949, "s": 8946, "text": "||" }, { "code": null, "e": 9022, "s": 8949, "text": "C-style Logical OR operator copies a bit if it exists in eather operand." }, { "code": null, "e": 9052, "s": 9022, "text": "Example − ($a || $b) is true." }, { "code": null, "e": 9056, "s": 9052, "text": "not" }, { "code": null, "e": 9201, "s": 9056, "text": "Called Logical NOT Operator. Use to reverses the logical state of its operand. If a condition is true then Logical NOT operator will make false." }, { "code": null, "e": 9235, "s": 9201, "text": "Example − not($a and $b) is true." }, { "code": null, "e": 9379, "s": 9235, "text": "There are following Quote-like operators supported by Perl language. In the following table, a {} represents any pair of delimiters you choose." }, { "code": null, "e": 9392, "s": 9379, "text": "Show Example" }, { "code": null, "e": 9397, "s": 9392, "text": "q{ }" }, { "code": null, "e": 9437, "s": 9397, "text": "Encloses a string with-in single quotes" }, { "code": null, "e": 9468, "s": 9437, "text": "Example − q{abcd} gives 'abcd'" }, { "code": null, "e": 9474, "s": 9468, "text": "qq{ }" }, { "code": null, "e": 9514, "s": 9474, "text": "Encloses a string with-in double quotes" }, { "code": null, "e": 9546, "s": 9514, "text": "Example − qq{abcd} gives \"abcd\"" }, { "code": null, "e": 9552, "s": 9546, "text": "qx{ }" }, { "code": null, "e": 9592, "s": 9552, "text": "Encloses a string with-in invert quotes" }, { "code": null, "e": 9624, "s": 9592, "text": "Example − qx{abcd} gives `abcd`" }, { "code": null, "e": 9754, "s": 9624, "text": "There are following miscellaneous operators supported by Perl language. Assume variable a holds 10 and variable b holds 20 then −" }, { "code": null, "e": 9767, "s": 9754, "text": "Show Example" }, { "code": null, "e": 9769, "s": 9767, "text": "." }, { "code": null, "e": 9819, "s": 9769, "text": "Binary operator dot (.) concatenates two strings." }, { "code": null, "e": 9885, "s": 9819, "text": "Example − If $a = \"abc\", $b = \"def\" then $a.$b will give \"abcdef\"" }, { "code": null, "e": 9887, "s": 9885, "text": "x" }, { "code": null, "e": 10022, "s": 9887, "text": "The repetition operator x returns a string consisting of the left operand repeated the number of times specified by the right operand." }, { "code": null, "e": 10057, "s": 10022, "text": "Example − ('-' x 3) will give ---." }, { "code": null, "e": 10060, "s": 10057, "text": ".." }, { "code": null, "e": 10168, "s": 10060, "text": "The range operator .. returns a list of values counting (up by ones) from the left value to the right value" }, { "code": null, "e": 10208, "s": 10168, "text": "Example − (2..5) will give (2, 3, 4, 5)" }, { "code": null, "e": 10211, "s": 10208, "text": "++" }, { "code": null, "e": 10266, "s": 10211, "text": "Auto Increment operator increases integer value by one" }, { "code": null, "e": 10294, "s": 10266, "text": "Example − $a++ will give 11" }, { "code": null, "e": 10297, "s": 10294, "text": "--" }, { "code": null, "e": 10352, "s": 10297, "text": "Auto Decrement operator decreases integer value by one" }, { "code": null, "e": 10379, "s": 10352, "text": "Example − $a-- will give 9" }, { "code": null, "e": 10382, "s": 10379, "text": "->" }, { "code": null, "e": 10485, "s": 10382, "text": "The arrow operator is mostly used in dereferencing a method or variable from an object or a class name" }, { "code": null, "e": 10558, "s": 10485, "text": "Example − $obj->$a is an example to access variable $a from object $obj." }, { "code": null, "e": 10633, "s": 10558, "text": "The following table lists all operators from highest precedence to lowest." }, { "code": null, "e": 10646, "s": 10633, "text": "Show Example" }, { "code": null, "e": 11050, "s": 10646, "text": "left\tterms and list operators (leftward)\nleft\t->\nnonassoc\t++ --\nright\t**\nright\t! ~ \\ and unary + and -\nleft\t=~ !~\nleft\t* / % x\nleft\t+ - .\nleft\t<< >>\nnonassoc\tnamed unary operators\nnonassoc\t< > <= >= lt gt le ge\nnonassoc\t== != <=> eq ne cmp ~~\nleft\t&\nleft\t| ^\nleft\t&&\nleft\t|| //\nnonassoc\t.. ...\nright\t?:\nright\t= += -= *= etc.\nleft\t, =>\nnonassoc\tlist operators (rightward)\nright\tnot\nleft\tand\nleft\tor xor\n" }, { "code": null, "e": 11085, "s": 11050, "text": "\n 46 Lectures \n 4.5 hours \n" }, { "code": null, "e": 11099, "s": 11085, "text": " Devi Killada" }, { "code": null, "e": 11134, "s": 11099, "text": "\n 11 Lectures \n 1.5 hours \n" }, { "code": null, "e": 11154, "s": 11134, "text": " Harshit Srivastava" }, { "code": null, "e": 11187, "s": 11154, "text": "\n 30 Lectures \n 6 hours \n" }, { "code": null, "e": 11203, "s": 11187, "text": " TELCOMA Global" }, { "code": null, "e": 11236, "s": 11203, "text": "\n 24 Lectures \n 2 hours \n" }, { "code": null, "e": 11253, "s": 11236, "text": " Mohammad Nauman" }, { "code": null, "e": 11286, "s": 11253, "text": "\n 68 Lectures \n 7 hours \n" }, { "code": null, "e": 11309, "s": 11286, "text": " Stone River ELearning" }, { "code": null, "e": 11344, "s": 11309, "text": "\n 58 Lectures \n 6.5 hours \n" }, { "code": null, "e": 11367, "s": 11344, "text": " Stone River ELearning" }, { "code": null, "e": 11374, "s": 11367, "text": " Print" }, { "code": null, "e": 11385, "s": 11374, "text": " Add Notes" } ]
Python Number atan() Method
Python number method atan() returns the arc tangent of x, in radians. Following is the syntax for atan() method − atan(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. x − This must be a numeric value. This method returns arc tangent of x, in radians. The following example shows the usage of atan() method. #!/usr/bin/python import math print "atan(0.64) : ", math.atan(0.64) print "atan(0) : ", math.atan(0) print "atan(10) : ", math.atan(10) print "atan(-1) : ", math.atan(-1) print "atan(1) : ", math.atan(1) When we run above program, it produces following result − atan(0.64) : 0.569313191101 atan(0) : 0.0 atan(10) : 1.4711276743 atan(-1) : -0.785398163397 atan(1) : 0.785398163397 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": 2315, "s": 2244, "text": "Python number method atan() returns the arc tangent of x, in radians." }, { "code": null, "e": 2359, "s": 2315, "text": "Following is the syntax for atan() method −" }, { "code": null, "e": 2368, "s": 2359, "text": "atan(x)\n" }, { "code": null, "e": 2515, "s": 2368, "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": 2549, "s": 2515, "text": "x − This must be a numeric value." }, { "code": null, "e": 2583, "s": 2549, "text": "x − This must be a numeric value." }, { "code": null, "e": 2633, "s": 2583, "text": "This method returns arc tangent of x, in radians." }, { "code": null, "e": 2689, "s": 2633, "text": "The following example shows the usage of atan() method." }, { "code": null, "e": 2900, "s": 2689, "text": "#!/usr/bin/python\nimport math\n\nprint \"atan(0.64) : \", math.atan(0.64)\nprint \"atan(0) : \", math.atan(0)\nprint \"atan(10) : \", math.atan(10)\nprint \"atan(-1) : \", math.atan(-1)\nprint \"atan(1) : \", math.atan(1)" }, { "code": null, "e": 2958, "s": 2900, "text": "When we run above program, it produces following result −" }, { "code": null, "e": 3082, "s": 2958, "text": "atan(0.64) : 0.569313191101\natan(0) : 0.0\natan(10) : 1.4711276743\natan(-1) : -0.785398163397\natan(1) : 0.785398163397\n" }, { "code": null, "e": 3119, "s": 3082, "text": "\n 187 Lectures \n 17.5 hours \n" }, { "code": null, "e": 3135, "s": 3119, "text": " Malhar Lathkar" }, { "code": null, "e": 3168, "s": 3135, "text": "\n 55 Lectures \n 8 hours \n" }, { "code": null, "e": 3187, "s": 3168, "text": " Arnab Chakraborty" }, { "code": null, "e": 3222, "s": 3187, "text": "\n 136 Lectures \n 11 hours \n" }, { "code": null, "e": 3244, "s": 3222, "text": " In28Minutes Official" }, { "code": null, "e": 3278, "s": 3244, "text": "\n 75 Lectures \n 13 hours \n" }, { "code": null, "e": 3306, "s": 3278, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 3341, "s": 3306, "text": "\n 70 Lectures \n 8.5 hours \n" }, { "code": null, "e": 3355, "s": 3341, "text": " Lets Kode It" }, { "code": null, "e": 3388, "s": 3355, "text": "\n 63 Lectures \n 6 hours \n" }, { "code": null, "e": 3405, "s": 3388, "text": " Abhilash Nelson" }, { "code": null, "e": 3412, "s": 3405, "text": " Print" }, { "code": null, "e": 3423, "s": 3412, "text": " Add Notes" } ]
MFC - Edit Box
An Edit Box is a rectangular child window in which the user can enter text. It is represented by CEdit class. CanUndo Determines whether an edit-control operation can be undone. CharFromPos Retrieves the line and character indexes for the character closest to a specified position. Clear Deletes (clears) the current selection (if any) in the edit control. Copy Copies the current selection (if any) in the edit control to the Clipboard in CF_TEXT format. Create Creates the Windows edit control and attaches it to the CEdit object. Cut Deletes (cuts) the current selection (if any) in the edit control and copies the deleted text to the Clipboard in CF_TEXT format. EmptyUndoBuffer Resets (clears) the undo flag of an edit control. FmtLines Sets the inclusion of soft line-break characters on or off within a multiple-line edit control. GetCueBanner Retrieves the text that is displayed as the text cue, or tip, in an edit control when the control is empty and does not have focus. GetFirstVisibleLine Determines the topmost visible line in an edit control. GetHandle Retrieves a handle to the memory that is currently allocated for a multiple-line edit control. GetHighlight Gets the indexes of the starting and ending characters in a range of text that is highlighted in the current edit control. GetLimitText Gets the maximum amount of text this CEdit can contain. GetLine Retrieves a line of text from an edit control. GetLineCount Retrieves the number of lines in a multipleline edit control. GetMargins Gets the left and right margins for this CEdit. GetModify Determines whether the contents of an edit control have been modified. GetPasswordChar Retrieves the password character displayed in an edit control when the user enters text. GetRect Gets the formatting rectangle of an edit control. GetSel Gets the first and last character positions of the current selection in an edit control. HideBalloonTip Hides any balloon tip associated with the current edit control. LimitText Limits the length of the text that the user can enter into an edit control. LineFromChar Retrieves the line number of the line that contains the specified character index. LineIndex Retrieves the character index of a line within a multiple-line edit control. LineLength Retrieves the length of a line in an edit control. LineScroll Scrolls the text of a multiple-line edit control. Paste Inserts the data from the Clipboard into the edit control at the current cursor position. Data is inserted only if the Clipboard contains data in CF_TEXT format. PosFromChar Retrieves the coordinates of the upper-left corner of a specified character index. ReplaceSel Replaces the current selection in an edit control with the specified text. SetCueBanner Sets the text that is displayed as the text cue, or tip, in an edit control when the control is empty and does not have focus. SetHandle Sets the handle to the local memory that will be used by a multiple-line edit control. SetHighlight Highlights a range of text that is displayed in the current edit control. SetLimitText Sets the maximum amount of text this CEdit can contain. SetMargins Sets the left and right margins for this CEdit. SetModify Sets or clears the modification flag for an edit control. SetPasswordChar Sets or removes a password character displayed in an edit control when the user enters text. SetReadOnly Sets the read-only state of an edit control. SetRect Sets the formatting rectangle of a multipleline edit control and updates the control. SetRectNP Sets the formatting rectangle of a multipleline edit control without redrawing the control window. SetSel Selects a range of characters in an edit control. SetTabStops Sets the tab stops in a multiple-line edit control. ShowBalloonTip Displays a balloon tip that is associated with the current edit control. Undo Reverses the last edit-control operation. Let us into a simple example by creating a new MFC dialog based project. Step 1 − Remove the caption of Static Text control and drag one button and one Edit control. Step 2 − Add a control variable m_editCtrl for edit control and value variable m_strTextCtrl for Static text control. Step 3 − Add the event handler for button click event. Step 4 − Here is the implementation of event handler for button click event. void CMFCEditDlg::OnBnClickedButton1() { // TODO: Add your control notification handler code here CString str = _T(""); m_editCtrl.GetWindowTextW(str); if (!str.IsEmpty()) m_strTextCtrl = str; else m_strTextCtrl = _T("Write Something"); UpdateData(FALSE); } Step 5 − When the above code is compiled and executed, you will see the following. Step 6 − When you write text in the edit control and click Display, it will update that text on Static Text Control. Print Add Notes Bookmark this page
[ { "code": null, "e": 2177, "s": 2067, "text": "An Edit Box is a rectangular child window in which the user can enter text. It is represented by CEdit class." }, { "code": null, "e": 2185, "s": 2177, "text": "CanUndo" }, { "code": null, "e": 2245, "s": 2185, "text": "Determines whether an edit-control operation can be undone." }, { "code": null, "e": 2257, "s": 2245, "text": "CharFromPos" }, { "code": null, "e": 2349, "s": 2257, "text": "Retrieves the line and character indexes for the character closest to a specified position." }, { "code": null, "e": 2355, "s": 2349, "text": "Clear" }, { "code": null, "e": 2424, "s": 2355, "text": "Deletes (clears) the current selection (if any) in the edit control." }, { "code": null, "e": 2429, "s": 2424, "text": "Copy" }, { "code": null, "e": 2523, "s": 2429, "text": "Copies the current selection (if any) in the edit control to the Clipboard in CF_TEXT format." }, { "code": null, "e": 2530, "s": 2523, "text": "Create" }, { "code": null, "e": 2600, "s": 2530, "text": "Creates the Windows edit control and attaches it to the CEdit object." }, { "code": null, "e": 2604, "s": 2600, "text": "Cut" }, { "code": null, "e": 2734, "s": 2604, "text": "Deletes (cuts) the current selection (if any) in the edit control and copies the deleted text to the Clipboard in CF_TEXT format." }, { "code": null, "e": 2750, "s": 2734, "text": "EmptyUndoBuffer" }, { "code": null, "e": 2800, "s": 2750, "text": "Resets (clears) the undo flag of an edit control." }, { "code": null, "e": 2809, "s": 2800, "text": "FmtLines" }, { "code": null, "e": 2905, "s": 2809, "text": "Sets the inclusion of soft line-break characters on or off within a multiple-line edit control." }, { "code": null, "e": 2918, "s": 2905, "text": "GetCueBanner" }, { "code": null, "e": 3050, "s": 2918, "text": "Retrieves the text that is displayed as the text cue, or tip, in an edit control when the control is empty and does not have focus." }, { "code": null, "e": 3070, "s": 3050, "text": "GetFirstVisibleLine" }, { "code": null, "e": 3126, "s": 3070, "text": "Determines the topmost visible line in an edit control." }, { "code": null, "e": 3136, "s": 3126, "text": "GetHandle" }, { "code": null, "e": 3231, "s": 3136, "text": "Retrieves a handle to the memory that is currently allocated for a multiple-line edit control." }, { "code": null, "e": 3244, "s": 3231, "text": "GetHighlight" }, { "code": null, "e": 3367, "s": 3244, "text": "Gets the indexes of the starting and ending characters in a range of text that is highlighted in the current edit control." }, { "code": null, "e": 3380, "s": 3367, "text": "GetLimitText" }, { "code": null, "e": 3436, "s": 3380, "text": "Gets the maximum amount of text this CEdit can contain." }, { "code": null, "e": 3444, "s": 3436, "text": "GetLine" }, { "code": null, "e": 3491, "s": 3444, "text": "Retrieves a line of text from an edit control." }, { "code": null, "e": 3504, "s": 3491, "text": "GetLineCount" }, { "code": null, "e": 3566, "s": 3504, "text": "Retrieves the number of lines in a multipleline edit control." }, { "code": null, "e": 3577, "s": 3566, "text": "GetMargins" }, { "code": null, "e": 3625, "s": 3577, "text": "Gets the left and right margins for this CEdit." }, { "code": null, "e": 3635, "s": 3625, "text": "GetModify" }, { "code": null, "e": 3706, "s": 3635, "text": "Determines whether the contents of an edit control have been modified." }, { "code": null, "e": 3722, "s": 3706, "text": "GetPasswordChar" }, { "code": null, "e": 3811, "s": 3722, "text": "Retrieves the password character displayed in an edit control when the user enters text." }, { "code": null, "e": 3819, "s": 3811, "text": "GetRect" }, { "code": null, "e": 3869, "s": 3819, "text": "Gets the formatting rectangle of an edit control." }, { "code": null, "e": 3876, "s": 3869, "text": "GetSel" }, { "code": null, "e": 3965, "s": 3876, "text": "Gets the first and last character positions of the current selection in an edit control." }, { "code": null, "e": 3980, "s": 3965, "text": "HideBalloonTip" }, { "code": null, "e": 4044, "s": 3980, "text": "Hides any balloon tip associated with the current edit control." }, { "code": null, "e": 4054, "s": 4044, "text": "LimitText" }, { "code": null, "e": 4130, "s": 4054, "text": "Limits the length of the text that the user can enter into an edit control." }, { "code": null, "e": 4143, "s": 4130, "text": "LineFromChar" }, { "code": null, "e": 4226, "s": 4143, "text": "Retrieves the line number of the line that contains the specified character index." }, { "code": null, "e": 4236, "s": 4226, "text": "LineIndex" }, { "code": null, "e": 4313, "s": 4236, "text": "Retrieves the character index of a line within a multiple-line edit control." }, { "code": null, "e": 4324, "s": 4313, "text": "LineLength" }, { "code": null, "e": 4375, "s": 4324, "text": "Retrieves the length of a line in an edit control." }, { "code": null, "e": 4386, "s": 4375, "text": "LineScroll" }, { "code": null, "e": 4436, "s": 4386, "text": "Scrolls the text of a multiple-line edit control." }, { "code": null, "e": 4442, "s": 4436, "text": "Paste" }, { "code": null, "e": 4604, "s": 4442, "text": "Inserts the data from the Clipboard into the edit control at the current cursor position. Data is inserted only if the Clipboard contains data in CF_TEXT format." }, { "code": null, "e": 4616, "s": 4604, "text": "PosFromChar" }, { "code": null, "e": 4699, "s": 4616, "text": "Retrieves the coordinates of the upper-left corner of a specified character index." }, { "code": null, "e": 4710, "s": 4699, "text": "ReplaceSel" }, { "code": null, "e": 4785, "s": 4710, "text": "Replaces the current selection in an edit control with the specified text." }, { "code": null, "e": 4798, "s": 4785, "text": "SetCueBanner" }, { "code": null, "e": 4925, "s": 4798, "text": "Sets the text that is displayed as the text cue, or tip, in an edit control when the control is empty and does not have focus." }, { "code": null, "e": 4935, "s": 4925, "text": "SetHandle" }, { "code": null, "e": 5022, "s": 4935, "text": "Sets the handle to the local memory that will be used by a multiple-line edit control." }, { "code": null, "e": 5035, "s": 5022, "text": "SetHighlight" }, { "code": null, "e": 5109, "s": 5035, "text": "Highlights a range of text that is displayed in the current edit control." }, { "code": null, "e": 5122, "s": 5109, "text": "SetLimitText" }, { "code": null, "e": 5178, "s": 5122, "text": "Sets the maximum amount of text this CEdit can contain." }, { "code": null, "e": 5189, "s": 5178, "text": "SetMargins" }, { "code": null, "e": 5237, "s": 5189, "text": "Sets the left and right margins for this CEdit." }, { "code": null, "e": 5247, "s": 5237, "text": "SetModify" }, { "code": null, "e": 5305, "s": 5247, "text": "Sets or clears the modification flag for an edit control." }, { "code": null, "e": 5321, "s": 5305, "text": "SetPasswordChar" }, { "code": null, "e": 5414, "s": 5321, "text": "Sets or removes a password character displayed in an edit control when the user enters text." }, { "code": null, "e": 5426, "s": 5414, "text": "SetReadOnly" }, { "code": null, "e": 5471, "s": 5426, "text": "Sets the read-only state of an edit control." }, { "code": null, "e": 5479, "s": 5471, "text": "SetRect" }, { "code": null, "e": 5565, "s": 5479, "text": "Sets the formatting rectangle of a multipleline edit control and updates the control." }, { "code": null, "e": 5575, "s": 5565, "text": "SetRectNP" }, { "code": null, "e": 5674, "s": 5575, "text": "Sets the formatting rectangle of a multipleline edit control without redrawing the control window." }, { "code": null, "e": 5681, "s": 5674, "text": "SetSel" }, { "code": null, "e": 5731, "s": 5681, "text": "Selects a range of characters in an edit control." }, { "code": null, "e": 5743, "s": 5731, "text": "SetTabStops" }, { "code": null, "e": 5795, "s": 5743, "text": "Sets the tab stops in a multiple-line edit control." }, { "code": null, "e": 5810, "s": 5795, "text": "ShowBalloonTip" }, { "code": null, "e": 5883, "s": 5810, "text": "Displays a balloon tip that is associated with the current edit control." }, { "code": null, "e": 5888, "s": 5883, "text": "Undo" }, { "code": null, "e": 5930, "s": 5888, "text": "Reverses the last edit-control operation." }, { "code": null, "e": 6003, "s": 5930, "text": "Let us into a simple example by creating a new MFC dialog based project." }, { "code": null, "e": 6096, "s": 6003, "text": "Step 1 − Remove the caption of Static Text control and drag one button and one Edit control." }, { "code": null, "e": 6214, "s": 6096, "text": "Step 2 − Add a control variable m_editCtrl for edit control and value variable m_strTextCtrl for Static text control." }, { "code": null, "e": 6269, "s": 6214, "text": "Step 3 − Add the event handler for button click event." }, { "code": null, "e": 6346, "s": 6269, "text": "Step 4 − Here is the implementation of event handler for button click event." }, { "code": null, "e": 6638, "s": 6346, "text": "void CMFCEditDlg::OnBnClickedButton1() {\n // TODO: Add your control notification handler code here\n CString str = _T(\"\");\n m_editCtrl.GetWindowTextW(str);\n \n if (!str.IsEmpty())\n m_strTextCtrl = str;\n else\n m_strTextCtrl = _T(\"Write Something\");\n UpdateData(FALSE);\n}" }, { "code": null, "e": 6721, "s": 6638, "text": "Step 5 − When the above code is compiled and executed, you will see the following." }, { "code": null, "e": 6838, "s": 6721, "text": "Step 6 − When you write text in the edit control and click Display, it will update that text on Static Text Control." }, { "code": null, "e": 6845, "s": 6838, "text": " Print" }, { "code": null, "e": 6856, "s": 6845, "text": " Add Notes" } ]
C++ Program To Find Length Of The Longest Substring Without Repeating Characters
20 Dec, 2021 Given a string str, find the length of the longest substring without repeating characters. For “ABDEFGABEF”, the longest substring are “BDEFGA” and “DEFGAB”, with length 6. For “BBBB” the longest substring is “B”, with length 1. For “GEEKSFORGEEKS”, there are two longest substrings shown in the below diagrams, with length 7 The desired time complexity is O(n) where n is the length of the string. Method 1 (Simple : O(n3)): We can consider all substrings one by one and check for each substring whether it contains all unique characters or not. There will be n*(n+1)/2 substrings. Whether a substring contains all unique characters or not can be checked in linear time by scanning it from left to right and keeping a map of visited characters. Time complexity of this solution would be O(n^3). C++ // C++ program to find the length of the longest substring// without repeating characters#include <bits/stdc++.h>using namespace std; // This functionr eturns true if all characters in str[i..j]// are distinct, otherwise returns falsebool areDistinct(string str, int i, int j){ // Note : Default values in visited are false vector<bool> visited(26); for (int k = i; k <= j; k++) { if (visited[str[k] - 'a'] == true) return false; visited[str[k] - 'a'] = true; } return true;} // Returns length of the longest substring// with all distinct characters.int longestUniqueSubsttr(string str){ int n = str.size(); int res = 0; // result for (int i = 0; i < n; i++) for (int j = i; j < n; j++) if (areDistinct(str, i, j)) res = max(res, j - i + 1); return res;} // Driver codeint main(){ string str = "geeksforgeeks"; cout << "The input string is " << str << endl; int len = longestUniqueSubsttr(str); cout << "The length of the longest non-repeating " "character substring is " << len; return 0;} The input string is geeksforgeeks The length of the longest non-repeating character substring is 7 Method 2 (Better : O(n2)) The idea is to use window sliding. Whenever we see repetition, we remove the previous occurrence and slide the window. C++ // C++ program to find the length of the longest substring// without repeating characters#include <bits/stdc++.h>using namespace std; int longestUniqueSubsttr(string str){ int n = str.size(); int res = 0; // result for (int i = 0; i < n; i++) { // Note : Default values in visited are false vector<bool> visited(256); for (int j = i; j < n; j++) { // If current character is visited // Break the loop if (visited[str[j]] == true) break; // Else update the result if // this window is larger, and mark // current character as visited. else { res = max(res, j - i + 1); visited[str[j]] = true; } } // Remove the first character of previous // window visited[str[i]] = false; } return res;} // Driver codeint main(){ string str = "geeksforgeeks"; cout << "The input string is " << str << endl; int len = longestUniqueSubsttr(str); cout << "The length of the longest non-repeating " "character substring is " << len; return 0;} The input string is geeksforgeeks The length of the longest non-repeating character substring is 7 Method 4 (Linear Time): Let us talk about the linear time solution now. This solution uses extra space to store the last indexes of already visited characters. The idea is to scan the string from left to right, keep track of the maximum length Non-Repeating Character Substring seen so far in res. When we traverse the string, to know the length of current window we need two indexes. 1) Ending index ( j ) : We consider current index as ending index. 2) Starting index ( i ) : It is same as previous window if current character was not present in the previous window. To check if the current character was present in the previous window or not, we store last index of every character in an array lasIndex[]. If lastIndex[str[j]] + 1 is more than previous start, then we updated the start index i. Else we keep same i. Below is the implementation of the above approach : C++ // C++ program to find the length of the longest substring// without repeating characters#include <bits/stdc++.h>using namespace std;#define NO_OF_CHARS 256 int longestUniqueSubsttr(string str){ int n = str.size(); int res = 0; // result // last index of all characters is initialized // as -1 vector<int> lastIndex(NO_OF_CHARS, -1); // Initialize start of current window int i = 0; // Move end of current window for (int j = 0; j < n; j++) { // Find the last index of str[j] // Update i (starting index of current window) // as maximum of current value of i and last // index plus 1 i = max(i, lastIndex[str[j]] + 1); // Update result if we get a larger window res = max(res, j - i + 1); // Update last index of j. lastIndex[str[j]] = j; } return res;} // Driver codeint main(){ string str = "geeksforgeeks"; cout << "The input string is " << str << endl; int len = longestUniqueSubsttr(str); cout << "The length of the longest non-repeating " "character substring is " << len; return 0;} The input string is geeksforgeeks The length of the longest non-repeating character substring is 7 Time Complexity: O(n + d) where n is length of the input string and d is number of characters in input string alphabet. For example, if string consists of lowercase English characters then value of d is 26. Auxiliary Space: O(d) Alternate Implementation : C++ #include <bits/stdc++.h>using namespace std; int longestUniqueSubsttr(string s){ // Creating a set to store the last positions // of occurrence map<char, int> seen ; int maximum_length = 0; // Starting the initial point of window to index 0 int start = 0; for(int end = 0; end < s.length(); end++) { // Checking if we have already seen the element or // not if (seen.find(s[end]) != seen.end()) { // If we have seen the number, move the start // pointer to position after the last occurrence start = max(start, seen[s[end]] + 1); } // Updating the last seen value of the character seen[s[end]] = end; maximum_length = max(maximum_length, end - start + 1); } return maximum_length;} // Driver codeint main(){ string s = "geeksforgeeks"; cout << "The input String is " << s << endl; int length = longestUniqueSubsttr(s); cout<<"The length of the longest non-repeating character " <<"substring is " << length;} // This code is contributed by ukasp The input String is geeksforgeeks The length of the longest non-repeating character substring is 7 As an exercise, try the modified version of the above problem where you need to print the maximum length NRCS also (the above program only prints the length of it). Please refer complete article on Length of the longest substring without repeating characters for more details! Amazon Housing.com Microsoft Morgan Stanley C++ Programs Strings Morgan Stanley Amazon Microsoft Housing.com Strings Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n20 Dec, 2021" }, { "code": null, "e": 144, "s": 52, "text": "Given a string str, find the length of the longest substring without repeating characters. " }, { "code": null, "e": 226, "s": 144, "text": "For “ABDEFGABEF”, the longest substring are “BDEFGA” and “DEFGAB”, with length 6." }, { "code": null, "e": 282, "s": 226, "text": "For “BBBB” the longest substring is “B”, with length 1." }, { "code": null, "e": 379, "s": 282, "text": "For “GEEKSFORGEEKS”, there are two longest substrings shown in the below diagrams, with length 7" }, { "code": null, "e": 452, "s": 379, "text": "The desired time complexity is O(n) where n is the length of the string." }, { "code": null, "e": 849, "s": 452, "text": "Method 1 (Simple : O(n3)): We can consider all substrings one by one and check for each substring whether it contains all unique characters or not. There will be n*(n+1)/2 substrings. Whether a substring contains all unique characters or not can be checked in linear time by scanning it from left to right and keeping a map of visited characters. Time complexity of this solution would be O(n^3)." }, { "code": null, "e": 853, "s": 849, "text": "C++" }, { "code": "// C++ program to find the length of the longest substring// without repeating characters#include <bits/stdc++.h>using namespace std; // This functionr eturns true if all characters in str[i..j]// are distinct, otherwise returns falsebool areDistinct(string str, int i, int j){ // Note : Default values in visited are false vector<bool> visited(26); for (int k = i; k <= j; k++) { if (visited[str[k] - 'a'] == true) return false; visited[str[k] - 'a'] = true; } return true;} // Returns length of the longest substring// with all distinct characters.int longestUniqueSubsttr(string str){ int n = str.size(); int res = 0; // result for (int i = 0; i < n; i++) for (int j = i; j < n; j++) if (areDistinct(str, i, j)) res = max(res, j - i + 1); return res;} // Driver codeint main(){ string str = \"geeksforgeeks\"; cout << \"The input string is \" << str << endl; int len = longestUniqueSubsttr(str); cout << \"The length of the longest non-repeating \" \"character substring is \" << len; return 0;}", "e": 1970, "s": 853, "text": null }, { "code": null, "e": 2069, "s": 1970, "text": "The input string is geeksforgeeks\nThe length of the longest non-repeating character substring is 7" }, { "code": null, "e": 2214, "s": 2069, "text": "Method 2 (Better : O(n2)) The idea is to use window sliding. Whenever we see repetition, we remove the previous occurrence and slide the window." }, { "code": null, "e": 2218, "s": 2214, "text": "C++" }, { "code": "// C++ program to find the length of the longest substring// without repeating characters#include <bits/stdc++.h>using namespace std; int longestUniqueSubsttr(string str){ int n = str.size(); int res = 0; // result for (int i = 0; i < n; i++) { // Note : Default values in visited are false vector<bool> visited(256); for (int j = i; j < n; j++) { // If current character is visited // Break the loop if (visited[str[j]] == true) break; // Else update the result if // this window is larger, and mark // current character as visited. else { res = max(res, j - i + 1); visited[str[j]] = true; } } // Remove the first character of previous // window visited[str[i]] = false; } return res;} // Driver codeint main(){ string str = \"geeksforgeeks\"; cout << \"The input string is \" << str << endl; int len = longestUniqueSubsttr(str); cout << \"The length of the longest non-repeating \" \"character substring is \" << len; return 0;}", "e": 3398, "s": 2218, "text": null }, { "code": null, "e": 3497, "s": 3398, "text": "The input string is geeksforgeeks\nThe length of the longest non-repeating character substring is 7" }, { "code": null, "e": 4318, "s": 3497, "text": "Method 4 (Linear Time): Let us talk about the linear time solution now. This solution uses extra space to store the last indexes of already visited characters. The idea is to scan the string from left to right, keep track of the maximum length Non-Repeating Character Substring seen so far in res. When we traverse the string, to know the length of current window we need two indexes. 1) Ending index ( j ) : We consider current index as ending index. 2) Starting index ( i ) : It is same as previous window if current character was not present in the previous window. To check if the current character was present in the previous window or not, we store last index of every character in an array lasIndex[]. If lastIndex[str[j]] + 1 is more than previous start, then we updated the start index i. Else we keep same i. " }, { "code": null, "e": 4370, "s": 4318, "text": "Below is the implementation of the above approach :" }, { "code": null, "e": 4374, "s": 4370, "text": "C++" }, { "code": "// C++ program to find the length of the longest substring// without repeating characters#include <bits/stdc++.h>using namespace std;#define NO_OF_CHARS 256 int longestUniqueSubsttr(string str){ int n = str.size(); int res = 0; // result // last index of all characters is initialized // as -1 vector<int> lastIndex(NO_OF_CHARS, -1); // Initialize start of current window int i = 0; // Move end of current window for (int j = 0; j < n; j++) { // Find the last index of str[j] // Update i (starting index of current window) // as maximum of current value of i and last // index plus 1 i = max(i, lastIndex[str[j]] + 1); // Update result if we get a larger window res = max(res, j - i + 1); // Update last index of j. lastIndex[str[j]] = j; } return res;} // Driver codeint main(){ string str = \"geeksforgeeks\"; cout << \"The input string is \" << str << endl; int len = longestUniqueSubsttr(str); cout << \"The length of the longest non-repeating \" \"character substring is \" << len; return 0;}", "e": 5510, "s": 4374, "text": null }, { "code": null, "e": 5609, "s": 5510, "text": "The input string is geeksforgeeks\nThe length of the longest non-repeating character substring is 7" }, { "code": null, "e": 5839, "s": 5609, "text": "Time Complexity: O(n + d) where n is length of the input string and d is number of characters in input string alphabet. For example, if string consists of lowercase English characters then value of d is 26. Auxiliary Space: O(d) " }, { "code": null, "e": 5867, "s": 5839, "text": "Alternate Implementation : " }, { "code": null, "e": 5871, "s": 5867, "text": "C++" }, { "code": "#include <bits/stdc++.h>using namespace std; int longestUniqueSubsttr(string s){ // Creating a set to store the last positions // of occurrence map<char, int> seen ; int maximum_length = 0; // Starting the initial point of window to index 0 int start = 0; for(int end = 0; end < s.length(); end++) { // Checking if we have already seen the element or // not if (seen.find(s[end]) != seen.end()) { // If we have seen the number, move the start // pointer to position after the last occurrence start = max(start, seen[s[end]] + 1); } // Updating the last seen value of the character seen[s[end]] = end; maximum_length = max(maximum_length, end - start + 1); } return maximum_length;} // Driver codeint main(){ string s = \"geeksforgeeks\"; cout << \"The input String is \" << s << endl; int length = longestUniqueSubsttr(s); cout<<\"The length of the longest non-repeating character \" <<\"substring is \" << length;} // This code is contributed by ukasp", "e": 7037, "s": 5871, "text": null }, { "code": null, "e": 7136, "s": 7037, "text": "The input String is geeksforgeeks\nThe length of the longest non-repeating character substring is 7" }, { "code": null, "e": 7301, "s": 7136, "text": "As an exercise, try the modified version of the above problem where you need to print the maximum length NRCS also (the above program only prints the length of it)." }, { "code": null, "e": 7413, "s": 7301, "text": "Please refer complete article on Length of the longest substring without repeating characters for more details!" }, { "code": null, "e": 7420, "s": 7413, "text": "Amazon" }, { "code": null, "e": 7432, "s": 7420, "text": "Housing.com" }, { "code": null, "e": 7442, "s": 7432, "text": "Microsoft" }, { "code": null, "e": 7457, "s": 7442, "text": "Morgan Stanley" }, { "code": null, "e": 7470, "s": 7457, "text": "C++ Programs" }, { "code": null, "e": 7478, "s": 7470, "text": "Strings" }, { "code": null, "e": 7493, "s": 7478, "text": "Morgan Stanley" }, { "code": null, "e": 7500, "s": 7493, "text": "Amazon" }, { "code": null, "e": 7510, "s": 7500, "text": "Microsoft" }, { "code": null, "e": 7522, "s": 7510, "text": "Housing.com" }, { "code": null, "e": 7530, "s": 7522, "text": "Strings" } ]
How to trim all strings in an array in PHP ?
09 Jul, 2021 Given a string array with white spaces, the task is to remove all white spaces from every object of an array.Examples: Input: arr = ["Geeks ", " for", " Geeks "] Output: Geeks for Geeks Method 1: Using trim() and array_walk() function: trim() Function: The trim() function is an inbuilt function which removes whitespaces and also the predefined characters from both sides of a string that is left and right.Syntax: trim( $string, $charlist ) array_walk() Function: The array_walk() function is an inbuilt function in PHP which walks through the entire array regardless of pointer position and applies a callback function or user-defined function to every element of the array. The array element’s keys and values are parameters in the callback function.Syntax: boolean array_walk( $array, myFunction, $extraParam ) Example: php <?php // Create an array with whitespace$arr = array( "Geeks ", " for", " Geeks "); // Print original arrayecho "Original Array:\n";foreach($arr as $key => $value) print($arr[$key] . "\n"); // Iterate array through array_walk() function// and use trim() function to remove all// whitespaces from every array objectsarray_walk($arr, create_function('&$val', '$val = trim($val);')); // Print modify arrayecho "\nModified Array:\n";foreach($arr as $key => $value) print($arr[$key] . "\n"); ?> Original Array: Geeks for Geeks Modified Array: Geeks for Geeks Method 2: Using trim() and array_map() function: The array_map() function is an inbuilt function in PHP which helps to modify all elements one or more arrays according to some user-defined condition in an easy manner. It basically, sends each of the elements of an array to a user-defined function and returns an array with new values as modified by that function.Syntax: array_map(functionName, arr1, arr2...) Example: php <?php // Create an array with whitespace$arr = array( "Geeks ", " for", " Geeks "); // Print original arrayecho "Original Array:\n";foreach($arr as $key => $value) print($arr[$key] . "\n"); // Iterate array through array_map() function// Using trim() function to remove all// whitespaces from every array objects$arr = array_map('trim', $arr); // Print modify arrayecho "\nModified Array:\n";foreach($arr as $key => $value) print($arr[$key] . "\n"); ?> Original Array: Geeks for Geeks Modified Array: Geeks for Geeks Method 3: Basic method using for loop: Use for loop to traverse each element of array and then use trim() function to remove all white space from array elements.Example: php <?php // Create an array with whitespace$arr = array( "Geeks ", " for", " Geeks "); // Print original arrayecho "Original Array:\n";foreach($arr as $key => $value) print($arr[$key] . "\n"); // Print modify arrayecho "\nModified Array:\n"; // Iterate array through for loop// Using trim() function to remove all// whitespaces from every array objectsforeach($arr as $key => $value) { $arr[$key] = trim($value); // Print current object of array print($arr[$key] . "\n");} ?> Original Array: Geeks for Geeks Modified Array: Geeks for Geeks sagartomar9927 Picked PHP PHP Programs Web Technologies Web technologies Questions PHP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n09 Jul, 2021" }, { "code": null, "e": 173, "s": 52, "text": "Given a string array with white spaces, the task is to remove all white spaces from every object of an array.Examples: " }, { "code": null, "e": 245, "s": 173, "text": "Input: arr = [\"Geeks \", \" for\", \" Geeks \"]\nOutput:\nGeeks\nfor\nGeeks" }, { "code": null, "e": 297, "s": 245, "text": "Method 1: Using trim() and array_walk() function: " }, { "code": null, "e": 479, "s": 297, "text": "trim() Function: The trim() function is an inbuilt function which removes whitespaces and also the predefined characters from both sides of a string that is left and right.Syntax: " }, { "code": null, "e": 506, "s": 479, "text": "trim( $string, $charlist )" }, { "code": null, "e": 827, "s": 506, "text": "array_walk() Function: The array_walk() function is an inbuilt function in PHP which walks through the entire array regardless of pointer position and applies a callback function or user-defined function to every element of the array. The array element’s keys and values are parameters in the callback function.Syntax: " }, { "code": null, "e": 881, "s": 827, "text": "boolean array_walk( $array, myFunction, $extraParam )" }, { "code": null, "e": 892, "s": 881, "text": "Example: " }, { "code": null, "e": 896, "s": 892, "text": "php" }, { "code": "<?php // Create an array with whitespace$arr = array( \"Geeks \", \" for\", \" Geeks \"); // Print original arrayecho \"Original Array:\\n\";foreach($arr as $key => $value) print($arr[$key] . \"\\n\"); // Iterate array through array_walk() function// and use trim() function to remove all// whitespaces from every array objectsarray_walk($arr, create_function('&$val', '$val = trim($val);')); // Print modify arrayecho \"\\nModified Array:\\n\";foreach($arr as $key => $value) print($arr[$key] . \"\\n\"); ?>", "e": 1421, "s": 896, "text": null }, { "code": null, "e": 1496, "s": 1421, "text": "Original Array:\nGeeks \n for\n Geeks \n\nModified Array:\nGeeks\nfor\nGeeks" }, { "code": null, "e": 1549, "s": 1498, "text": "Method 2: Using trim() and array_map() function: " }, { "code": null, "e": 1874, "s": 1549, "text": "The array_map() function is an inbuilt function in PHP which helps to modify all elements one or more arrays according to some user-defined condition in an easy manner. It basically, sends each of the elements of an array to a user-defined function and returns an array with new values as modified by that function.Syntax: " }, { "code": null, "e": 1913, "s": 1874, "text": "array_map(functionName, arr1, arr2...)" }, { "code": null, "e": 1924, "s": 1913, "text": "Example: " }, { "code": null, "e": 1928, "s": 1924, "text": "php" }, { "code": "<?php // Create an array with whitespace$arr = array( \"Geeks \", \" for\", \" Geeks \"); // Print original arrayecho \"Original Array:\\n\";foreach($arr as $key => $value) print($arr[$key] . \"\\n\"); // Iterate array through array_map() function// Using trim() function to remove all// whitespaces from every array objects$arr = array_map('trim', $arr); // Print modify arrayecho \"\\nModified Array:\\n\";foreach($arr as $key => $value) print($arr[$key] . \"\\n\"); ?>", "e": 2398, "s": 1928, "text": null }, { "code": null, "e": 2473, "s": 2398, "text": "Original Array:\nGeeks \n for\n Geeks \n\nModified Array:\nGeeks\nfor\nGeeks" }, { "code": null, "e": 2647, "s": 2475, "text": "Method 3: Basic method using for loop: Use for loop to traverse each element of array and then use trim() function to remove all white space from array elements.Example: " }, { "code": null, "e": 2651, "s": 2647, "text": "php" }, { "code": "<?php // Create an array with whitespace$arr = array( \"Geeks \", \" for\", \" Geeks \"); // Print original arrayecho \"Original Array:\\n\";foreach($arr as $key => $value) print($arr[$key] . \"\\n\"); // Print modify arrayecho \"\\nModified Array:\\n\"; // Iterate array through for loop// Using trim() function to remove all// whitespaces from every array objectsforeach($arr as $key => $value) { $arr[$key] = trim($value); // Print current object of array print($arr[$key] . \"\\n\");} ?>", "e": 3153, "s": 2651, "text": null }, { "code": null, "e": 3228, "s": 3153, "text": "Original Array:\nGeeks \n for\n Geeks \n\nModified Array:\nGeeks\nfor\nGeeks" }, { "code": null, "e": 3245, "s": 3230, "text": "sagartomar9927" }, { "code": null, "e": 3252, "s": 3245, "text": "Picked" }, { "code": null, "e": 3256, "s": 3252, "text": "PHP" }, { "code": null, "e": 3269, "s": 3256, "text": "PHP Programs" }, { "code": null, "e": 3286, "s": 3269, "text": "Web Technologies" }, { "code": null, "e": 3313, "s": 3286, "text": "Web technologies Questions" }, { "code": null, "e": 3317, "s": 3313, "text": "PHP" } ]
Find k-th smallest element in BST (Order Statistics in BST)
16 Jun, 2022 Given the root of a binary search tree and K as input, find Kth smallest element in BST. For example, in the following BST, if k = 3, then the output should be 10, and if k = 5, then the output should be 14. Method 1: Using Inorder Traversal (O(n) time and O(h) auxiliary space) The Inorder Traversal of a BST traverses the nodes in increasing order. So the idea is to traverse the tree in Inorder. While traversing, keep track of the count of the nodes visited. If the count becomes k, print the node. C++ C Java Python3 C# Javascript // A simple inorder traversal based C++ program to find k-th// smallest element in a BST.#include <iostream> using namespace std; // A BST nodestruct Node { int data; Node *left, *right; Node(int x) { data = x; left = right = NULL; }}; // Recursive function to insert an key into BSTNode* insert(Node* root, int x){ if (root == NULL) return new Node(x); if (x < root->data) root->left = insert(root->left, x); else if (x > root->data) root->right = insert(root->right, x); return root;} // Function to find k'th smallest element in BST// Here count denotes the number of nodes processed so farint count = 0;Node* kthSmallest(Node* root, int& k){ // base case if (root == NULL) return NULL; // search in left subtree Node* left = kthSmallest(root->left, k); // if k'th smallest is found in left subtree, return it if (left != NULL) return left; // if current element is k'th smallest, return it count++; if (count == k) return root; // else search in right subtree return kthSmallest(root->right, k);} // Function to print k'th smallest element in BSTvoid printKthSmallest(Node* root, int k){ // maintain index to count number of nodes processed so far Node* res = kthSmallest(root, k); if (res == NULL) cout << "There are less than k nodes in the BST"; else cout << "K-th Smallest Element is " << res->data;} // main functionint main(){ Node* root = NULL; int keys[] = { 20, 8, 22, 4, 12, 10, 14 }; for (int x : keys) root = insert(root, x); int k = 3; printKthSmallest(root, k); return 0;} // This code is contributed by Aditya Kumar (adityakumar129) // A simple inorder traversal based C++ program to find k-th// smallest element in a BST.#include <stdio.h>#include <stdlib.h> // A BST nodetypedef struct Node { int data; struct Node *left, *right;} Node; struct Node* new_node(int x){ struct Node* p = malloc(sizeof(struct Node)); p->data = x; p->left = NULL; p->right = NULL; return p;} // Recursive function to insert an key into BSTNode* insert(Node* root, int x){ if (root == NULL) return new_node(x); if (x < root->data) root->left = insert(root->left, x); else if (x > root->data) root->right = insert(root->right, x); return root;} // Function to find k'th smallest element in BST// Here count denotes the number of nodes processed so farint count = 0;Node* kthSmallest(Node* root, int k){ // base case if (root == NULL) return NULL; // search in left subtree Node* left = kthSmallest(root->left, k); // if k'th smallest is found in left subtree, return it if (left != NULL) return left; // if current element is k'th smallest, return it count++; if (count == k) return root; // else search in right subtree return kthSmallest(root->right, k);} // Function to print k'th smallest element in BSTvoid printKthSmallest(Node* root, int k){ // maintain index to count number of nodes processed so far Node* res = kthSmallest(root, k); if (res == NULL) printf("There are less than k nodes in the BST"); else printf("K-th Smallest Element is %d", res->data);} // main functionint main(){ Node* root = NULL; int keys[] = { 20, 8, 22, 4, 12, 10, 14 }; int keys_size = sizeof(keys) / sizeof(keys[0]); for (int i = 0; i < keys_size; i++) root = insert(root, keys[i]); int k = 3; printKthSmallest(root, k); return 0;} // This code is contributed by Aditya Kumar (adityakumar129) // A simple inorder traversal based Java program// to find k-th smallest element in a BST. import java.io.*;// A BST nodeclass Node { int data; Node left, right; Node(int x) { data = x; left = right = null; }} class GFG { static int count = 0; // Recursive function to insert an key into BST public static Node insert(Node root, int x) { if (root == null) return new Node(x); if (x < root.data) root.left = insert(root.left, x); else if (x > root.data) root.right = insert(root.right, x); return root; } // Function to find k'th largest element in BST // Here count denotes the number of nodes processed so far public static Node kthSmallest(Node root, int k) { // base case if (root == null) return null; // search in left subtree Node left = kthSmallest(root.left, k); // if k'th smallest is found in left subtree, return it if (left != null) return left; // if current element is k'th smallest, return it count++; if (count == k) return root; // else search in right subtree return kthSmallest(root.right, k); } // Function to find k'th largest element in BST public static void printKthSmallest(Node root, int k) { Node res = kthSmallest(root, k); if (res == null) System.out.println("There are less than k nodes in the BST"); else System.out.println("K-th Smallest Element is " + res.data); } public static void main(String[] args) { Node root = null; int keys[] = { 20, 8, 22, 4, 12, 10, 14 }; for (int x : keys) root = insert(root, x); int k = 3; printKthSmallest(root, k); }} // This code is contributed by Aditya Kumar (adityakumar129) # A simple inorder traversal based Python3# program to find k-th smallest element# in a BST. # A BST nodeclass Node: def __init__(self, key): self.data = key self.left = None self.right = None # Recursive function to insert an key into BSTdef insert(root, x): if (root == None): return Node(x) if (x < root.data): root.left = insert(root.left, x) elif (x > root.data): root.right = insert(root.right, x) return root # Function to find k'th largest element# in BST. Here count denotes the number# of nodes processed so fardef kthSmallest(root): global k # Base case if (root == None): return None # Search in left subtree left = kthSmallest(root.left) # If k'th smallest is found in # left subtree, return it if (left != None): return left # If current element is k'th # smallest, return it k -= 1 if (k == 0): return root # Else search in right subtree return kthSmallest(root.right) # Function to find k'th largest element in BSTdef printKthSmallest(root): # Maintain index to count number # of nodes processed so far count = 0 res = kthSmallest(root) if (res == None): print("There are less than k nodes in the BST") else: print("K-th Smallest Element is ", res.data) # Driver codeif __name__ == '__main__': root = None keys = [ 20, 8, 22, 4, 12, 10, 14 ] for x in keys: root = insert(root, x) k = 3 printKthSmallest(root) # This code is contributed by mohit kumar 29 // A simple inorder traversal// based C# program to find// k-th smallest element in a BST.using System; // A BST nodeclass Node{ public int data;public Node left, right;public Node(int x){ data = x; left = right = null;}} class GFG{ static int count = 0; // Recursive function to // insert an key into BSTpublic static Node insert(Node root, int x){ if (root == null) return new Node(x); if (x < root.data) root.left = insert(root.left, x); else if (x > root.data) root.right = insert(root.right, x); return root;} // Function to find k'th largest// element in BST. Here count// denotes the number of nodes// processed so farpublic static Node kthSmallest(Node root, int k){ // base case if (root == null) return null; // search in left subtree Node left = kthSmallest(root.left, k); // if k'th smallest is found // in left subtree, return it if (left != null) return left; // if current element is // k'th smallest, return it count++; if (count == k) return root; // else search in right subtree return kthSmallest(root.right, k);} // Function to find k'th largest// element in BSTpublic static void printKthSmallest(Node root, int k){ // Maintain an index to // count number of nodes // processed so far count = 0; Node res = kthSmallest(root, k); if (res == null) Console.WriteLine("There are less " + "than k nodes in the BST"); else Console.WriteLine("K-th Smallest" + " Element is " + res.data);} // Driver codepublic static void Main(String[] args){ Node root = null; int []keys = {20, 8, 22, 4, 12, 10, 14}; foreach (int x in keys) root = insert(root, x); int k = 3; printKthSmallest(root, k);}} // This code is contributed by gauravrajput1 <script>// A simple inorder traversal based Javascript program// to find k-th smallest element in a BST. // A BST node class Node { constructor(x) { this.data = x; this.left = null; this.right = null; } } let count = 0; // Recursive function to insert an key into BST function insert(root,x) { if (root == null) return new Node(x); if (x < root.data) root.left = insert(root.left, x); else if (x > root.data) root.right = insert(root.right, x); return root; } // Function to find k'th largest element in BST // Here count denotes the number // of nodes processed so far function kthSmallest(root,k) { // base case if (root == null) return null; // search in left subtree let left = kthSmallest(root.left, k); // if k'th smallest is found in left subtree, return it if (left != null) return left; // if current element is k'th smallest, return it count++; if (count == k) return root; // else search in right subtree return kthSmallest(root.right, k); } // Function to find k'th largest element in BST function printKthSmallest(root,k) { // maintain an index to count number of // nodes processed so far count = 0; let res = kthSmallest(root, k); if (res == null) document.write("There are less " + "than k nodes in the BST"); else document.write("K-th Smallest" + " Element is " + res.data); } let root=null; let key=[20, 8, 22, 4, 12, 10, 14 ]; for(let i=0;i<key.length;i++) { root = insert(root, key[i]); } let k = 3; printKthSmallest(root, k); // This code is contributed by unknown2108</script> K-th Smallest Element is 10 We can optimize space using Morris Traversal. Please refer K’th smallest element in BST using O(1) Extra Space for details. Method 2: Augmented Tree Data Structure (O(h) Time Complexity and O(h) auxiliary space) The idea is to maintain the rank of each node. We can keep track of elements in the left subtree of every node while building the tree. Since we need the K-th smallest element, we can maintain the number of elements of the left subtree in every node.Assume that the root is having ‘lCount’ nodes in its left subtree. If K = lCount + 1, root is K-th node. If K < lCount + 1, we will continue our search (recursion) for the Kth smallest element in the left subtree of root. If K > lCount + 1, we continue our search in the right subtree for the (K – lCount – 1)-th smallest element. Note that we need the count of elements in the left subtree only. C++ C Java Python3 C# Javascript // A simple inorder traversal based C++ program to find k-th// smallest element in a BST.#include <iostream>using namespace std; // A BST nodestruct Node { int data; Node *left, *right; int lCount; Node(int x) { data = x; left = right = NULL; lCount = 0; }}; // Recursive function to insert an key into BSTNode* insert(Node* root, int x){ if (root == NULL) return new Node(x); // If a node is inserted in left subtree, then lCount of // this node is increased. For simplicity, we are // assuming that all keys (tried to be inserted) are // distinct. if (x < root->data) { root->left = insert(root->left, x); root->lCount++; } else if (x > root->data) root->right = insert(root->right, x); return root;} // Function to find k'th smallest element in BST// Here count denotes the number of nodes processed so farNode* kthSmallest(Node* root, int k){ // base case if (root == NULL) return NULL; int count = root->lCount + 1; if (count == k) return root; if (count > k) return kthSmallest(root->left, k); // else search in right subtree return kthSmallest(root->right, k - count);} // main functionint main(){ Node* root = NULL; int keys[] = { 20, 8, 22, 4, 12, 10, 14 }; for (int x : keys) root = insert(root, x); int k = 4; Node* res = kthSmallest(root, k); if (res == NULL) cout << "There are less than k nodes in the BST"; else cout << "K-th Smallest Element is " << res->data; return 0;} // This code is contributed by Aditya Kumar (adityakumar129) // A simple inorder traversal based C++ program to find k-th// smallest element in a BST.#include <stdio.h>#include <stdlib.h> // A BST nodetypedef struct Node { int data; struct Node *left, *right; int lCount;} Node; Node* new_node(int x){ Node* newNode = malloc(sizeof(Node)); newNode->data = x; newNode->left = NULL; newNode->right = NULL; return newNode;} // Recursive function to insert an key into BSTNode* insert(Node* root, int x){ if (root == NULL) return new_node(x); // If a node is inserted in left subtree, then lCount of // this node is increased. For simplicity, we are // assuming that all keys (tried to be inserted) are // distinct. if (x < root->data) { root->left = insert(root->left, x); root->lCount++; } else if (x > root->data) root->right = insert(root->right, x); return root;} // Function to find k'th smallest element in BST// Here count denotes the number of nodes processed so farNode* kthSmallest(Node* root, int k){ // base case if (root == NULL) return NULL; int count = root->lCount + 1; if (count == k) return root; if (count > k) return kthSmallest(root->left, k); // else search in right subtree return kthSmallest(root->right, k - count);} // main functionint main(){ Node* root = NULL; int keys[] = { 20, 8, 22, 4, 12, 10, 14 }; int keys_size = sizeof(keys) / sizeof(keys[0]); for (int i = 0; i < keys_size; i++) root = insert(root, keys[i]); int k = 4; Node* res = kthSmallest(root, k); if (res == NULL) printf("There are less than k nodes in the BST"); else printf("K-th Smallest Element is %d", res->data); return 0;} // This code is contributed by Aditya Kumar (adityakumar129) // A simple inorder traversal based Java program// to find k-th smallest element in a BST.import java.io.*;import java.util.*; // A BST nodeclass Node { int data; Node left, right; int lCount; Node(int x) { data = x; left = right = null; lCount = 0; }} class Gfg { // Recursive function to insert an key into BST public static Node insert(Node root, int x) { if (root == null) return new Node(x); // If a node is inserted in left subtree, then // lCount of this node is increased. For simplicity, // we are assuming that all keys (tried to be // inserted) are distinct. if (x < root.data) { root.left = insert(root.left, x); root.lCount++; } else if (x > root.data) root.right = insert(root.right, x); return root; } // Function to find k'th largest element in BST // Here count denotes the number of nodes processed so far public static Node kthSmallest(Node root, int k) { // base case if (root == null) return null; int count = root.lCount + 1; if (count == k) return root; if (count > k) return kthSmallest(root.left, k); // else search in right subtree return kthSmallest(root.right, k - count); } // main function public static void main(String args[]) { Node root = null; int keys[] = { 20, 8, 22, 4, 12, 10, 14 }; for (int x : keys) root = insert(root, x); int k = 4; Node res = kthSmallest(root, k); if (res == null) System.out.println("There are less than k nodes in the BST"); else System.out.println("K-th Smallest Element is " + res.data); }} // This code is contributed by Aditya Kumar (adityakumar129) # A simple inorder traversal based Python3# program to find k-th smallest element in a BST. # A BST nodeclass newNode: def __init__(self, x): self.data = x self.left = None self.right = None self.lCount = 0 # Recursive function to insert# an key into BSTdef insert(root, x): if (root == None): return newNode(x) # If a node is inserted in left subtree, # then lCount of this node is increased. # For simplicity, we are assuming that # all keys (tried to be inserted) are # distinct. if (x < root.data): root.left = insert(root.left, x) root.lCount += 1 elif (x > root.data): root.right = insert(root.right, x); return root # Function to find k'th largest element# in BST. Here count denotes the number# of nodes processed so fardef kthSmallest(root, k): # Base case if (root == None): return None count = root.lCount + 1 if (count == k): return root if (count > k): return kthSmallest(root.left, k) # Else search in right subtree return kthSmallest(root.right, k - count) # Driver codeif __name__ == '__main__': root = None keys = [ 20, 8, 22, 4, 12, 10, 14 ] for x in keys: root = insert(root, x) k = 4 res = kthSmallest(root, k) if (res == None): print("There are less than k nodes in the BST") else: print("K-th Smallest Element is", res.data) # This code is contributed by bgangwar59 // A simple inorder traversal based C# program// to find k-th smallest element in a BST.using System; // A BST nodepublic class Node{ public int data; public Node left, right; public int lCount; public Node(int x) { data = x; left = right = null; lCount = 0; }} class GFG{ // Recursive function to insert an key into BSTpublic static Node insert(Node root, int x){ if (root == null) return new Node(x); // If a node is inserted in left subtree, // then lCount of this node is increased. // For simplicity, we are assuming that // all keys (tried to be inserted) are // distinct. if (x < root.data) { root.left = insert(root.left, x); root.lCount++; } else if (x > root.data) root.right = insert(root.right, x); return root;} // Function to find k'th largest element// in BST. Here count denotes the number// of nodes processed so farpublic static Node kthSmallest(Node root, int k){ // Base case if (root == null) return null; int count = root.lCount + 1; if (count == k) return root; if (count > k) return kthSmallest(root.left, k); // Else search in right subtree return kthSmallest(root.right, k - count);} // Driver Codepublic static void Main(String[] args){ Node root = null; int[] keys = { 20, 8, 22, 4, 12, 10, 14 }; foreach(int x in keys) root = insert(root, x); int k = 4; Node res = kthSmallest(root, k); if (res == null) Console.WriteLine("There are less " + "than k nodes in the BST"); else Console.WriteLine("K-th Smallest" + " Element is " + res.data);}} // This code is contributed by aashish1995 <script> // A simple inorder traversal based// Javascript program to find k-th// smallest element in a BST. // A BST nodeclass Node{ constructor(x) { this.data = x; this.left = null; this.right = null; this.lCount = 0; }} // Recursive function to insert an key into BSTfunction insert(root, x){ if (root == null) return new Node(x); // If a node is inserted in left subtree, // then lCount of this node is increased. // For simplicity, we are assuming that // all keys (tried to be inserted) are // distinct. if (x < root.data) { root.left = insert(root.left, x); root.lCount++; } else if (x > root.data) root.right = insert(root.right, x); return root;} // Function to find k'th largest element// in BST. Here count denotes the number// of nodes processed so farfunction kthSmallest(root, k){ // Base case if (root == null) return null; let count = root.lCount + 1; if (count == k) return root; if (count > k) return kthSmallest(root.left, k); // Else search in right subtree return kthSmallest(root.right, k - count);} // Driver codelet root = null;let keys = [ 20, 8, 22, 4, 12, 10, 14 ]; for(let x = 0; x < keys.length; x++) root = insert(root, keys[x]); let k = 4;let res = kthSmallest(root, k); if (res == null) document.write("There are less than k " + "nodes in the BST" + "</br>");else document.write("K-th Smallest" + " Element is " + res.data); // This code is contributed by divyeshrabadiya07 </script> K-th Smallest Element is 12 Time complexity: O(h) where h is the height of the tree. Dheerain Jain Akanksha_Rai jaydipdushi RICHIK BHATTACHARJEE kushalvm GauravRajput1 bgangwar59 mohit kumar 29 aashish1995 unknown2108 divyeshrabadiya07 simmytarika5 debayanbiswas31 adityakumar129 hardikkoriintern Accolite Amazon Google Order-Statistics Binary Search Tree Accolite Amazon Google Binary Search Tree Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n16 Jun, 2022" }, { "code": null, "e": 262, "s": 54, "text": "Given the root of a binary search tree and K as input, find Kth smallest element in BST. For example, in the following BST, if k = 3, then the output should be 10, and if k = 5, then the output should be 14." }, { "code": null, "e": 334, "s": 262, "text": "Method 1: Using Inorder Traversal (O(n) time and O(h) auxiliary space) " }, { "code": null, "e": 559, "s": 334, "text": "The Inorder Traversal of a BST traverses the nodes in increasing order. So the idea is to traverse the tree in Inorder. While traversing, keep track of the count of the nodes visited. If the count becomes k, print the node. " }, { "code": null, "e": 563, "s": 559, "text": "C++" }, { "code": null, "e": 565, "s": 563, "text": "C" }, { "code": null, "e": 570, "s": 565, "text": "Java" }, { "code": null, "e": 578, "s": 570, "text": "Python3" }, { "code": null, "e": 581, "s": 578, "text": "C#" }, { "code": null, "e": 592, "s": 581, "text": "Javascript" }, { "code": "// A simple inorder traversal based C++ program to find k-th// smallest element in a BST.#include <iostream> using namespace std; // A BST nodestruct Node { int data; Node *left, *right; Node(int x) { data = x; left = right = NULL; }}; // Recursive function to insert an key into BSTNode* insert(Node* root, int x){ if (root == NULL) return new Node(x); if (x < root->data) root->left = insert(root->left, x); else if (x > root->data) root->right = insert(root->right, x); return root;} // Function to find k'th smallest element in BST// Here count denotes the number of nodes processed so farint count = 0;Node* kthSmallest(Node* root, int& k){ // base case if (root == NULL) return NULL; // search in left subtree Node* left = kthSmallest(root->left, k); // if k'th smallest is found in left subtree, return it if (left != NULL) return left; // if current element is k'th smallest, return it count++; if (count == k) return root; // else search in right subtree return kthSmallest(root->right, k);} // Function to print k'th smallest element in BSTvoid printKthSmallest(Node* root, int k){ // maintain index to count number of nodes processed so far Node* res = kthSmallest(root, k); if (res == NULL) cout << \"There are less than k nodes in the BST\"; else cout << \"K-th Smallest Element is \" << res->data;} // main functionint main(){ Node* root = NULL; int keys[] = { 20, 8, 22, 4, 12, 10, 14 }; for (int x : keys) root = insert(root, x); int k = 3; printKthSmallest(root, k); return 0;} // This code is contributed by Aditya Kumar (adityakumar129)", "e": 2318, "s": 592, "text": null }, { "code": "// A simple inorder traversal based C++ program to find k-th// smallest element in a BST.#include <stdio.h>#include <stdlib.h> // A BST nodetypedef struct Node { int data; struct Node *left, *right;} Node; struct Node* new_node(int x){ struct Node* p = malloc(sizeof(struct Node)); p->data = x; p->left = NULL; p->right = NULL; return p;} // Recursive function to insert an key into BSTNode* insert(Node* root, int x){ if (root == NULL) return new_node(x); if (x < root->data) root->left = insert(root->left, x); else if (x > root->data) root->right = insert(root->right, x); return root;} // Function to find k'th smallest element in BST// Here count denotes the number of nodes processed so farint count = 0;Node* kthSmallest(Node* root, int k){ // base case if (root == NULL) return NULL; // search in left subtree Node* left = kthSmallest(root->left, k); // if k'th smallest is found in left subtree, return it if (left != NULL) return left; // if current element is k'th smallest, return it count++; if (count == k) return root; // else search in right subtree return kthSmallest(root->right, k);} // Function to print k'th smallest element in BSTvoid printKthSmallest(Node* root, int k){ // maintain index to count number of nodes processed so far Node* res = kthSmallest(root, k); if (res == NULL) printf(\"There are less than k nodes in the BST\"); else printf(\"K-th Smallest Element is %d\", res->data);} // main functionint main(){ Node* root = NULL; int keys[] = { 20, 8, 22, 4, 12, 10, 14 }; int keys_size = sizeof(keys) / sizeof(keys[0]); for (int i = 0; i < keys_size; i++) root = insert(root, keys[i]); int k = 3; printKthSmallest(root, k); return 0;} // This code is contributed by Aditya Kumar (adityakumar129)", "e": 4211, "s": 2318, "text": null }, { "code": "// A simple inorder traversal based Java program// to find k-th smallest element in a BST. import java.io.*;// A BST nodeclass Node { int data; Node left, right; Node(int x) { data = x; left = right = null; }} class GFG { static int count = 0; // Recursive function to insert an key into BST public static Node insert(Node root, int x) { if (root == null) return new Node(x); if (x < root.data) root.left = insert(root.left, x); else if (x > root.data) root.right = insert(root.right, x); return root; } // Function to find k'th largest element in BST // Here count denotes the number of nodes processed so far public static Node kthSmallest(Node root, int k) { // base case if (root == null) return null; // search in left subtree Node left = kthSmallest(root.left, k); // if k'th smallest is found in left subtree, return it if (left != null) return left; // if current element is k'th smallest, return it count++; if (count == k) return root; // else search in right subtree return kthSmallest(root.right, k); } // Function to find k'th largest element in BST public static void printKthSmallest(Node root, int k) { Node res = kthSmallest(root, k); if (res == null) System.out.println(\"There are less than k nodes in the BST\"); else System.out.println(\"K-th Smallest Element is \" + res.data); } public static void main(String[] args) { Node root = null; int keys[] = { 20, 8, 22, 4, 12, 10, 14 }; for (int x : keys) root = insert(root, x); int k = 3; printKthSmallest(root, k); }} // This code is contributed by Aditya Kumar (adityakumar129)", "e": 6104, "s": 4211, "text": null }, { "code": "# A simple inorder traversal based Python3# program to find k-th smallest element# in a BST. # A BST nodeclass Node: def __init__(self, key): self.data = key self.left = None self.right = None # Recursive function to insert an key into BSTdef insert(root, x): if (root == None): return Node(x) if (x < root.data): root.left = insert(root.left, x) elif (x > root.data): root.right = insert(root.right, x) return root # Function to find k'th largest element# in BST. Here count denotes the number# of nodes processed so fardef kthSmallest(root): global k # Base case if (root == None): return None # Search in left subtree left = kthSmallest(root.left) # If k'th smallest is found in # left subtree, return it if (left != None): return left # If current element is k'th # smallest, return it k -= 1 if (k == 0): return root # Else search in right subtree return kthSmallest(root.right) # Function to find k'th largest element in BSTdef printKthSmallest(root): # Maintain index to count number # of nodes processed so far count = 0 res = kthSmallest(root) if (res == None): print(\"There are less than k nodes in the BST\") else: print(\"K-th Smallest Element is \", res.data) # Driver codeif __name__ == '__main__': root = None keys = [ 20, 8, 22, 4, 12, 10, 14 ] for x in keys: root = insert(root, x) k = 3 printKthSmallest(root) # This code is contributed by mohit kumar 29", "e": 7711, "s": 6104, "text": null }, { "code": "// A simple inorder traversal// based C# program to find// k-th smallest element in a BST.using System; // A BST nodeclass Node{ public int data;public Node left, right;public Node(int x){ data = x; left = right = null;}} class GFG{ static int count = 0; // Recursive function to // insert an key into BSTpublic static Node insert(Node root, int x){ if (root == null) return new Node(x); if (x < root.data) root.left = insert(root.left, x); else if (x > root.data) root.right = insert(root.right, x); return root;} // Function to find k'th largest// element in BST. Here count// denotes the number of nodes// processed so farpublic static Node kthSmallest(Node root, int k){ // base case if (root == null) return null; // search in left subtree Node left = kthSmallest(root.left, k); // if k'th smallest is found // in left subtree, return it if (left != null) return left; // if current element is // k'th smallest, return it count++; if (count == k) return root; // else search in right subtree return kthSmallest(root.right, k);} // Function to find k'th largest// element in BSTpublic static void printKthSmallest(Node root, int k){ // Maintain an index to // count number of nodes // processed so far count = 0; Node res = kthSmallest(root, k); if (res == null) Console.WriteLine(\"There are less \" + \"than k nodes in the BST\"); else Console.WriteLine(\"K-th Smallest\" + \" Element is \" + res.data);} // Driver codepublic static void Main(String[] args){ Node root = null; int []keys = {20, 8, 22, 4, 12, 10, 14}; foreach (int x in keys) root = insert(root, x); int k = 3; printKthSmallest(root, k);}} // This code is contributed by gauravrajput1", "e": 9586, "s": 7711, "text": null }, { "code": "<script>// A simple inorder traversal based Javascript program// to find k-th smallest element in a BST. // A BST node class Node { constructor(x) { this.data = x; this.left = null; this.right = null; } } let count = 0; // Recursive function to insert an key into BST function insert(root,x) { if (root == null) return new Node(x); if (x < root.data) root.left = insert(root.left, x); else if (x > root.data) root.right = insert(root.right, x); return root; } // Function to find k'th largest element in BST // Here count denotes the number // of nodes processed so far function kthSmallest(root,k) { // base case if (root == null) return null; // search in left subtree let left = kthSmallest(root.left, k); // if k'th smallest is found in left subtree, return it if (left != null) return left; // if current element is k'th smallest, return it count++; if (count == k) return root; // else search in right subtree return kthSmallest(root.right, k); } // Function to find k'th largest element in BST function printKthSmallest(root,k) { // maintain an index to count number of // nodes processed so far count = 0; let res = kthSmallest(root, k); if (res == null) document.write(\"There are less \" + \"than k nodes in the BST\"); else document.write(\"K-th Smallest\" + \" Element is \" + res.data); } let root=null; let key=[20, 8, 22, 4, 12, 10, 14 ]; for(let i=0;i<key.length;i++) { root = insert(root, key[i]); } let k = 3; printKthSmallest(root, k); // This code is contributed by unknown2108</script>", "e": 11586, "s": 9586, "text": null }, { "code": null, "e": 11614, "s": 11586, "text": "K-th Smallest Element is 10" }, { "code": null, "e": 11740, "s": 11616, "text": "We can optimize space using Morris Traversal. Please refer K’th smallest element in BST using O(1) Extra Space for details." }, { "code": null, "e": 11828, "s": 11740, "text": "Method 2: Augmented Tree Data Structure (O(h) Time Complexity and O(h) auxiliary space)" }, { "code": null, "e": 12475, "s": 11828, "text": "The idea is to maintain the rank of each node. We can keep track of elements in the left subtree of every node while building the tree. Since we need the K-th smallest element, we can maintain the number of elements of the left subtree in every node.Assume that the root is having ‘lCount’ nodes in its left subtree. If K = lCount + 1, root is K-th node. If K < lCount + 1, we will continue our search (recursion) for the Kth smallest element in the left subtree of root. If K > lCount + 1, we continue our search in the right subtree for the (K – lCount – 1)-th smallest element. Note that we need the count of elements in the left subtree only." }, { "code": null, "e": 12479, "s": 12475, "text": "C++" }, { "code": null, "e": 12481, "s": 12479, "text": "C" }, { "code": null, "e": 12486, "s": 12481, "text": "Java" }, { "code": null, "e": 12494, "s": 12486, "text": "Python3" }, { "code": null, "e": 12497, "s": 12494, "text": "C#" }, { "code": null, "e": 12508, "s": 12497, "text": "Javascript" }, { "code": "// A simple inorder traversal based C++ program to find k-th// smallest element in a BST.#include <iostream>using namespace std; // A BST nodestruct Node { int data; Node *left, *right; int lCount; Node(int x) { data = x; left = right = NULL; lCount = 0; }}; // Recursive function to insert an key into BSTNode* insert(Node* root, int x){ if (root == NULL) return new Node(x); // If a node is inserted in left subtree, then lCount of // this node is increased. For simplicity, we are // assuming that all keys (tried to be inserted) are // distinct. if (x < root->data) { root->left = insert(root->left, x); root->lCount++; } else if (x > root->data) root->right = insert(root->right, x); return root;} // Function to find k'th smallest element in BST// Here count denotes the number of nodes processed so farNode* kthSmallest(Node* root, int k){ // base case if (root == NULL) return NULL; int count = root->lCount + 1; if (count == k) return root; if (count > k) return kthSmallest(root->left, k); // else search in right subtree return kthSmallest(root->right, k - count);} // main functionint main(){ Node* root = NULL; int keys[] = { 20, 8, 22, 4, 12, 10, 14 }; for (int x : keys) root = insert(root, x); int k = 4; Node* res = kthSmallest(root, k); if (res == NULL) cout << \"There are less than k nodes in the BST\"; else cout << \"K-th Smallest Element is \" << res->data; return 0;} // This code is contributed by Aditya Kumar (adityakumar129)", "e": 14140, "s": 12508, "text": null }, { "code": "// A simple inorder traversal based C++ program to find k-th// smallest element in a BST.#include <stdio.h>#include <stdlib.h> // A BST nodetypedef struct Node { int data; struct Node *left, *right; int lCount;} Node; Node* new_node(int x){ Node* newNode = malloc(sizeof(Node)); newNode->data = x; newNode->left = NULL; newNode->right = NULL; return newNode;} // Recursive function to insert an key into BSTNode* insert(Node* root, int x){ if (root == NULL) return new_node(x); // If a node is inserted in left subtree, then lCount of // this node is increased. For simplicity, we are // assuming that all keys (tried to be inserted) are // distinct. if (x < root->data) { root->left = insert(root->left, x); root->lCount++; } else if (x > root->data) root->right = insert(root->right, x); return root;} // Function to find k'th smallest element in BST// Here count denotes the number of nodes processed so farNode* kthSmallest(Node* root, int k){ // base case if (root == NULL) return NULL; int count = root->lCount + 1; if (count == k) return root; if (count > k) return kthSmallest(root->left, k); // else search in right subtree return kthSmallest(root->right, k - count);} // main functionint main(){ Node* root = NULL; int keys[] = { 20, 8, 22, 4, 12, 10, 14 }; int keys_size = sizeof(keys) / sizeof(keys[0]); for (int i = 0; i < keys_size; i++) root = insert(root, keys[i]); int k = 4; Node* res = kthSmallest(root, k); if (res == NULL) printf(\"There are less than k nodes in the BST\"); else printf(\"K-th Smallest Element is %d\", res->data); return 0;} // This code is contributed by Aditya Kumar (adityakumar129)", "e": 15933, "s": 14140, "text": null }, { "code": "// A simple inorder traversal based Java program// to find k-th smallest element in a BST.import java.io.*;import java.util.*; // A BST nodeclass Node { int data; Node left, right; int lCount; Node(int x) { data = x; left = right = null; lCount = 0; }} class Gfg { // Recursive function to insert an key into BST public static Node insert(Node root, int x) { if (root == null) return new Node(x); // If a node is inserted in left subtree, then // lCount of this node is increased. For simplicity, // we are assuming that all keys (tried to be // inserted) are distinct. if (x < root.data) { root.left = insert(root.left, x); root.lCount++; } else if (x > root.data) root.right = insert(root.right, x); return root; } // Function to find k'th largest element in BST // Here count denotes the number of nodes processed so far public static Node kthSmallest(Node root, int k) { // base case if (root == null) return null; int count = root.lCount + 1; if (count == k) return root; if (count > k) return kthSmallest(root.left, k); // else search in right subtree return kthSmallest(root.right, k - count); } // main function public static void main(String args[]) { Node root = null; int keys[] = { 20, 8, 22, 4, 12, 10, 14 }; for (int x : keys) root = insert(root, x); int k = 4; Node res = kthSmallest(root, k); if (res == null) System.out.println(\"There are less than k nodes in the BST\"); else System.out.println(\"K-th Smallest Element is \" + res.data); }} // This code is contributed by Aditya Kumar (adityakumar129)", "e": 17808, "s": 15933, "text": null }, { "code": "# A simple inorder traversal based Python3# program to find k-th smallest element in a BST. # A BST nodeclass newNode: def __init__(self, x): self.data = x self.left = None self.right = None self.lCount = 0 # Recursive function to insert# an key into BSTdef insert(root, x): if (root == None): return newNode(x) # If a node is inserted in left subtree, # then lCount of this node is increased. # For simplicity, we are assuming that # all keys (tried to be inserted) are # distinct. if (x < root.data): root.left = insert(root.left, x) root.lCount += 1 elif (x > root.data): root.right = insert(root.right, x); return root # Function to find k'th largest element# in BST. Here count denotes the number# of nodes processed so fardef kthSmallest(root, k): # Base case if (root == None): return None count = root.lCount + 1 if (count == k): return root if (count > k): return kthSmallest(root.left, k) # Else search in right subtree return kthSmallest(root.right, k - count) # Driver codeif __name__ == '__main__': root = None keys = [ 20, 8, 22, 4, 12, 10, 14 ] for x in keys: root = insert(root, x) k = 4 res = kthSmallest(root, k) if (res == None): print(\"There are less than k nodes in the BST\") else: print(\"K-th Smallest Element is\", res.data) # This code is contributed by bgangwar59", "e": 19337, "s": 17808, "text": null }, { "code": "// A simple inorder traversal based C# program// to find k-th smallest element in a BST.using System; // A BST nodepublic class Node{ public int data; public Node left, right; public int lCount; public Node(int x) { data = x; left = right = null; lCount = 0; }} class GFG{ // Recursive function to insert an key into BSTpublic static Node insert(Node root, int x){ if (root == null) return new Node(x); // If a node is inserted in left subtree, // then lCount of this node is increased. // For simplicity, we are assuming that // all keys (tried to be inserted) are // distinct. if (x < root.data) { root.left = insert(root.left, x); root.lCount++; } else if (x > root.data) root.right = insert(root.right, x); return root;} // Function to find k'th largest element// in BST. Here count denotes the number// of nodes processed so farpublic static Node kthSmallest(Node root, int k){ // Base case if (root == null) return null; int count = root.lCount + 1; if (count == k) return root; if (count > k) return kthSmallest(root.left, k); // Else search in right subtree return kthSmallest(root.right, k - count);} // Driver Codepublic static void Main(String[] args){ Node root = null; int[] keys = { 20, 8, 22, 4, 12, 10, 14 }; foreach(int x in keys) root = insert(root, x); int k = 4; Node res = kthSmallest(root, k); if (res == null) Console.WriteLine(\"There are less \" + \"than k nodes in the BST\"); else Console.WriteLine(\"K-th Smallest\" + \" Element is \" + res.data);}} // This code is contributed by aashish1995", "e": 21127, "s": 19337, "text": null }, { "code": "<script> // A simple inorder traversal based// Javascript program to find k-th// smallest element in a BST. // A BST nodeclass Node{ constructor(x) { this.data = x; this.left = null; this.right = null; this.lCount = 0; }} // Recursive function to insert an key into BSTfunction insert(root, x){ if (root == null) return new Node(x); // If a node is inserted in left subtree, // then lCount of this node is increased. // For simplicity, we are assuming that // all keys (tried to be inserted) are // distinct. if (x < root.data) { root.left = insert(root.left, x); root.lCount++; } else if (x > root.data) root.right = insert(root.right, x); return root;} // Function to find k'th largest element// in BST. Here count denotes the number// of nodes processed so farfunction kthSmallest(root, k){ // Base case if (root == null) return null; let count = root.lCount + 1; if (count == k) return root; if (count > k) return kthSmallest(root.left, k); // Else search in right subtree return kthSmallest(root.right, k - count);} // Driver codelet root = null;let keys = [ 20, 8, 22, 4, 12, 10, 14 ]; for(let x = 0; x < keys.length; x++) root = insert(root, keys[x]); let k = 4;let res = kthSmallest(root, k); if (res == null) document.write(\"There are less than k \" + \"nodes in the BST\" + \"</br>\");else document.write(\"K-th Smallest\" + \" Element is \" + res.data); // This code is contributed by divyeshrabadiya07 </script>", "e": 22758, "s": 21127, "text": null }, { "code": null, "e": 22786, "s": 22758, "text": "K-th Smallest Element is 12" }, { "code": null, "e": 22845, "s": 22788, "text": "Time complexity: O(h) where h is the height of the tree." }, { "code": null, "e": 22859, "s": 22845, "text": "Dheerain Jain" }, { "code": null, "e": 22872, "s": 22859, "text": "Akanksha_Rai" }, { "code": null, "e": 22884, "s": 22872, "text": "jaydipdushi" }, { "code": null, "e": 22905, "s": 22884, "text": "RICHIK BHATTACHARJEE" }, { "code": null, "e": 22914, "s": 22905, "text": "kushalvm" }, { "code": null, "e": 22928, "s": 22914, "text": "GauravRajput1" }, { "code": null, "e": 22939, "s": 22928, "text": "bgangwar59" }, { "code": null, "e": 22954, "s": 22939, "text": "mohit kumar 29" }, { "code": null, "e": 22966, "s": 22954, "text": "aashish1995" }, { "code": null, "e": 22978, "s": 22966, "text": "unknown2108" }, { "code": null, "e": 22996, "s": 22978, "text": "divyeshrabadiya07" }, { "code": null, "e": 23009, "s": 22996, "text": "simmytarika5" }, { "code": null, "e": 23025, "s": 23009, "text": "debayanbiswas31" }, { "code": null, "e": 23040, "s": 23025, "text": "adityakumar129" }, { "code": null, "e": 23057, "s": 23040, "text": "hardikkoriintern" }, { "code": null, "e": 23066, "s": 23057, "text": "Accolite" }, { "code": null, "e": 23073, "s": 23066, "text": "Amazon" }, { "code": null, "e": 23080, "s": 23073, "text": "Google" }, { "code": null, "e": 23097, "s": 23080, "text": "Order-Statistics" }, { "code": null, "e": 23116, "s": 23097, "text": "Binary Search Tree" }, { "code": null, "e": 23125, "s": 23116, "text": "Accolite" }, { "code": null, "e": 23132, "s": 23125, "text": "Amazon" }, { "code": null, "e": 23139, "s": 23132, "text": "Google" }, { "code": null, "e": 23158, "s": 23139, "text": "Binary Search Tree" } ]
How to unzip a file using PHP ?
22 Jun, 2020 To unzip a file with PHP, we can use the ZipArchive class. ZipArchive is a simple utility class for zipping and unzipping files. We don’t require any extra additional plugins for working with zip files. ZipArchive class provides us a facility to create a zip file or to extract the existing zip file. The ZipArchive class has a method called extractTo to extract the contents of the complete archive or the given files to the specified destination. The ZipArchive class also has a lot of other methods and properties to help you get more information about the archive before extracting all its contents. Syntax: bool ZipArchive::extractTo( string $destination, mixed $entries ) Parameters: destination: The $destination parameter can be used to specify the location where to extract the files. entries: The $entries parameter can be used to specify a single file name which is to be extracted, or you can use it to pass an array of files. Example 1: This example unzip all the files from specific folder. <?php $zip = new ZipArchive; // Zip File Nameif ($zip->open('GeeksforGeeks.zip') === TRUE) { // Unzip Path $zip->extractTo('/Destination/Directory/'); $zip->close(); echo 'Unzipped Process Successful!';} else { echo 'Unzipped Process failed';}?> Description: Create an object of the ZipArchive class and open a given zip file using $zip->open() method. If it returns TRUE then extract the file to the specified path with extractTo() method by passing path address as an argument in it. Example 2: This example unzip the specific file from the folder. <?php $zip = new ZipArchive; // Zip File Name$res = $zip->open('GeeksForGeeks.zip'); if ($res === TRUE) { // Unzip Path $zip->extractTo('/Destination/Directory/', array('H_W.gif', 'helloworld.php')); $zip->close(); echo 'Unzipped Process Successful!';} else { echo 'Unzipped Process failed';} Description: With the file element, you can select the zip file that you want to extract. If a selected file is valid then pass to open() method and extract it to the specified path using extractTo() method. PHP-Misc Picked PHP Web Technologies Web technologies Questions PHP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n22 Jun, 2020" }, { "code": null, "e": 632, "s": 28, "text": "To unzip a file with PHP, we can use the ZipArchive class. ZipArchive is a simple utility class for zipping and unzipping files. We don’t require any extra additional plugins for working with zip files. ZipArchive class provides us a facility to create a zip file or to extract the existing zip file. The ZipArchive class has a method called extractTo to extract the contents of the complete archive or the given files to the specified destination. The ZipArchive class also has a lot of other methods and properties to help you get more information about the archive before extracting all its contents." }, { "code": null, "e": 640, "s": 632, "text": "Syntax:" }, { "code": null, "e": 706, "s": 640, "text": "bool ZipArchive::extractTo( string $destination, mixed $entries )" }, { "code": null, "e": 718, "s": 706, "text": "Parameters:" }, { "code": null, "e": 822, "s": 718, "text": "destination: The $destination parameter can be used to specify the location where to extract the files." }, { "code": null, "e": 967, "s": 822, "text": "entries: The $entries parameter can be used to specify a single file name which is to be extracted, or you can use it to pass an array of files." }, { "code": null, "e": 1033, "s": 967, "text": "Example 1: This example unzip all the files from specific folder." }, { "code": "<?php $zip = new ZipArchive; // Zip File Nameif ($zip->open('GeeksforGeeks.zip') === TRUE) { // Unzip Path $zip->extractTo('/Destination/Directory/'); $zip->close(); echo 'Unzipped Process Successful!';} else { echo 'Unzipped Process failed';}?>", "e": 1298, "s": 1033, "text": null }, { "code": null, "e": 1405, "s": 1298, "text": "Description: Create an object of the ZipArchive class and open a given zip file using $zip->open() method." }, { "code": null, "e": 1538, "s": 1405, "text": "If it returns TRUE then extract the file to the specified path with extractTo() method by passing path address as an argument in it." }, { "code": null, "e": 1603, "s": 1538, "text": "Example 2: This example unzip the specific file from the folder." }, { "code": "<?php $zip = new ZipArchive; // Zip File Name$res = $zip->open('GeeksForGeeks.zip'); if ($res === TRUE) { // Unzip Path $zip->extractTo('/Destination/Directory/', array('H_W.gif', 'helloworld.php')); $zip->close(); echo 'Unzipped Process Successful!';} else { echo 'Unzipped Process failed';}", "e": 1938, "s": 1603, "text": null }, { "code": null, "e": 2146, "s": 1938, "text": "Description: With the file element, you can select the zip file that you want to extract. If a selected file is valid then pass to open() method and extract it to the specified path using extractTo() method." }, { "code": null, "e": 2155, "s": 2146, "text": "PHP-Misc" }, { "code": null, "e": 2162, "s": 2155, "text": "Picked" }, { "code": null, "e": 2166, "s": 2162, "text": "PHP" }, { "code": null, "e": 2183, "s": 2166, "text": "Web Technologies" }, { "code": null, "e": 2210, "s": 2183, "text": "Web technologies Questions" }, { "code": null, "e": 2214, "s": 2210, "text": "PHP" } ]
C strings conversion to Python
02 Apr, 2019 For C strings represented as a pair char *, int, it is to decide whether or not – the string presented as a raw byte string or as a Unicode string. Byte objects can be built using Py_BuildValue() as // Pointer to C string datachar *s; // Length of data int len; // Make a bytes objectPyObject *obj = Py_BuildValue("y#", s, len); To create a Unicode string and is it is known that s points to data encoded as UTF-8, the code given below can be used as – PyObject *obj = Py_BuildValue("s#", s, len); If s is encoded in some other known encoding, a string using PyUnicode_Decode() can be made as: PyObject *obj = PyUnicode_Decode(s, len, "encoding", "errors"); // Exampleobj = PyUnicode_Decode(s, len, "latin-1", "strict");obj = PyUnicode_Decode(s, len, "ascii", "ignore"); If a wide string needs to be represented as wchar_t *, len pair. Then are few options as shown below – // Wide character stringwchar_t *w; // Lengthint len; // Option 1 - use Py_BuildValue()PyObject *obj = Py_BuildValue("u#", w, len); // Option 2 - use PyUnicode_FromWideChar()PyObject *obj = PyUnicode_FromWideChar(w, len); The data from C must be explicitly decoded into a string according to some codec Common encodings include ASCII, Latin-1, and UTF-8. If you’re encoding is not known, then it is best off to encode the string as bytes instead. Python always copies the string data (being provided) when making an object. Also, for better reliability, strings should be created using both a pointer and a size rather than relying on NULL-terminated data. Python-ctype Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n02 Apr, 2019" }, { "code": null, "e": 176, "s": 28, "text": "For C strings represented as a pair char *, int, it is to decide whether or not – the string presented as a raw byte string or as a Unicode string." }, { "code": null, "e": 227, "s": 176, "text": "Byte objects can be built using Py_BuildValue() as" }, { "code": "// Pointer to C string datachar *s; // Length of data int len; // Make a bytes objectPyObject *obj = Py_BuildValue(\"y#\", s, len);", "e": 361, "s": 227, "text": null }, { "code": null, "e": 486, "s": 361, "text": " To create a Unicode string and is it is known that s points to data encoded as UTF-8, the code given below can be used as –" }, { "code": "PyObject *obj = Py_BuildValue(\"s#\", s, len);", "e": 531, "s": 486, "text": null }, { "code": null, "e": 628, "s": 531, "text": " If s is encoded in some other known encoding, a string using PyUnicode_Decode() can be made as:" }, { "code": "PyObject *obj = PyUnicode_Decode(s, len, \"encoding\", \"errors\"); // Exampleobj = PyUnicode_Decode(s, len, \"latin-1\", \"strict\");obj = PyUnicode_Decode(s, len, \"ascii\", \"ignore\");", "e": 806, "s": 628, "text": null }, { "code": null, "e": 910, "s": 806, "text": " If a wide string needs to be represented as wchar_t *, len pair. Then are few options as shown below –" }, { "code": "// Wide character stringwchar_t *w; // Lengthint len; // Option 1 - use Py_BuildValue()PyObject *obj = Py_BuildValue(\"u#\", w, len); // Option 2 - use PyUnicode_FromWideChar()PyObject *obj = PyUnicode_FromWideChar(w, len);", "e": 1136, "s": 910, "text": null }, { "code": null, "e": 1217, "s": 1136, "text": "The data from C must be explicitly decoded into a string according to some codec" }, { "code": null, "e": 1269, "s": 1217, "text": "Common encodings include ASCII, Latin-1, and UTF-8." }, { "code": null, "e": 1361, "s": 1269, "text": "If you’re encoding is not known, then it is best off to encode the string as bytes instead." }, { "code": null, "e": 1438, "s": 1361, "text": "Python always copies the string data (being provided) when making an object." }, { "code": null, "e": 1571, "s": 1438, "text": "Also, for better reliability, strings should be created using both a pointer and a size rather than relying on NULL-terminated data." }, { "code": null, "e": 1584, "s": 1571, "text": "Python-ctype" }, { "code": null, "e": 1591, "s": 1584, "text": "Python" } ]
Why global array has a larger size than the local array?
09 Jul, 2021 An array in any programming language is a collection of similar data items stored at contiguous memory locations and elements can be accessed randomly using array indices. It can be used to store the collection of primitive data types such as int, float, double, char, etc of any particular type. For example, an array in C/C++ can store derived data types such as structures, pointers, etc. Below is the representation of an array. The arrays can be declared and initialized globally as well as locally(i.e., in the particular scope of the program) in the program. Below are examples to understand this concept better. Program 1: Below is the C++ program where a 1D array of size 107 is declared locally. C++ // C++ program to declare the array// of size 10^7 locally#include <bits/stdc++.h>using namespace std; // Driver Codeint main(){ const int N = 1e7; // Initialize the array a[] int a[N]; a[0] = 1; cout << a[0]; return 0;} Output: Explanation: In the above program, a segmentation fault error occurs when a 1-D array is declared locally, then the limit of that array size is the order of 105. It is not possible to declare the size of the array as more than 105. In this example, the array of size 107 is declared, hence an error has occurred. Program 2: Below is the program where a 1-D array of size 105 is initialized: C++ Java Python3 C# Javascript // C++ program to declare the array// of size 10^5 locally#include <bits/stdc++.h>using namespace std; // Driver codeint main(){ const int N = 1e5; // Declare array a[] int a[N]; a[0] = 1; cout << a[0]; return 0;} // Java program to declare the array// of size 10^5 locallyimport java.io.*; class GFG{ // Driver codepublic static void main(String[] arg){ int N = 1; // Declare array a[] int a[] = {N}; a[0] = 1; System.out.print(a[0]);}} // This code is contributed by shivani # Python program to declare the array# of size 10^5 locally# Driver codeN = 1e5 # Declare array a[]a = [N]a[0] = 1print(a[0]) # This code is contributed by shivanisinghss2110 // C# program to declare the array// of size 10^5 locallyusing System;class GFG{ // Driver codepublic static void Main(String[] arg){ int N = 1; // Declare array a[] int []a = {N}; a[0] = 1; Console.Write(a[0]);}} // This code is contributed by shivanisinghss2110 <script> // Javascript program to declare the array// of size 10^5 locallyvar N = 1; // Declare array a[]var a = [N];a[0] = 1; document.write(a[0]); // This code is contributed by shivani </script> 1 Explanation: In the above program, the code compilation is successful, and the output is 1. This is because the 1D array of size 105 is initialized locally and this is valid. Program 3: Below is the program where a 1-D array of size 107 is declared globally. C++ Java Python3 C# Javascript // C++ program to declare the array// of size 10^7 globally#include <bits/stdc++.h>using namespace std; // Variable N is initializedconst int N = 1e7; // Global array is declaredint a[N]; // Driver Codeint main(){ a[0] = 1; cout << a[0]; return 0;} // Java program to declare the array// of size 10^7 globallyimport java.io.*; class GFG{ // Driver Codepublic static void main(String[] arg){ // Variable N is initialized int N = 1; // Global array is declared int a[] = {N}; a[0] = 1; System.out.print(a[0]); }}// this code is contributed by shivani # Python3 program to declare the array# of size 10^7 globally # Variable N is initializedN = 1e7 # Global array is declareda = [N] # Driver Codea[0] = 1print(a[0]) # This code is contributed by shivanisinghss2110 // C# program to declare the array// of size 10^7 globallyusing System; class GFG{ // Driver Codepublic static void Main(String[] arg){ // Variable N is initialized int N = 1; // Global array is declared int []a = {N}; a[0] = 1; Console.Write(a[0]); }}// this code is contributed by shivanisinghss2110 <script> // Javascript program to declare the array// of size 10^7 globally // Variable N is initializedconst N = 1e7; // Global array is declaredlet a = new Array(N); // Driver Codea[0] = 1;document.write(a[0]); // This code is contributed by gfgking.</script> 1 Explanation: In the above code compilation is successful, and the output is 1. This is because a 1-D array of size 107 is declared globally and this is valid. Note: If a 1-D array of size 108 is declared globally, then again the segmentation fault error will be encountered because there is also a limit for global declaration of the 1-D array and that is, it is possible to only declare a 1-D array globally up to 107 sizes. Why global array has a larger size than the local array? When an array is declared locally, then it always initializes in the stack memory, and generally, stack memory has a size limit of around 8 MB. This size can vary according to different computer architecture. When an array is declared globally then it stores in the data segment, and the data segment has no size limit. Hence, when the array is declared of big size (i.e., more than 107) then the stack memory gets full and leads into the stack overflow error, and therefore, a segmentation fault error is encountered. Therefore, for declaring the array of larger size, it is good practice to declare it globally. simranarora5sos shivanisinghss2110 gfgking C Basics CPP-Basics Arrays C++ C++ Programs Arrays CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n09 Jul, 2021" }, { "code": null, "e": 487, "s": 54, "text": "An array in any programming language is a collection of similar data items stored at contiguous memory locations and elements can be accessed randomly using array indices. It can be used to store the collection of primitive data types such as int, float, double, char, etc of any particular type. For example, an array in C/C++ can store derived data types such as structures, pointers, etc. Below is the representation of an array." }, { "code": null, "e": 674, "s": 487, "text": "The arrays can be declared and initialized globally as well as locally(i.e., in the particular scope of the program) in the program. Below are examples to understand this concept better." }, { "code": null, "e": 760, "s": 674, "text": "Program 1: Below is the C++ program where a 1D array of size 107 is declared locally." }, { "code": null, "e": 764, "s": 760, "text": "C++" }, { "code": "// C++ program to declare the array// of size 10^7 locally#include <bits/stdc++.h>using namespace std; // Driver Codeint main(){ const int N = 1e7; // Initialize the array a[] int a[N]; a[0] = 1; cout << a[0]; return 0;}", "e": 1006, "s": 764, "text": null }, { "code": null, "e": 1014, "s": 1006, "text": "Output:" }, { "code": null, "e": 1327, "s": 1014, "text": "Explanation: In the above program, a segmentation fault error occurs when a 1-D array is declared locally, then the limit of that array size is the order of 105. It is not possible to declare the size of the array as more than 105. In this example, the array of size 107 is declared, hence an error has occurred." }, { "code": null, "e": 1405, "s": 1327, "text": "Program 2: Below is the program where a 1-D array of size 105 is initialized:" }, { "code": null, "e": 1409, "s": 1405, "text": "C++" }, { "code": null, "e": 1414, "s": 1409, "text": "Java" }, { "code": null, "e": 1422, "s": 1414, "text": "Python3" }, { "code": null, "e": 1425, "s": 1422, "text": "C#" }, { "code": null, "e": 1436, "s": 1425, "text": "Javascript" }, { "code": "// C++ program to declare the array// of size 10^5 locally#include <bits/stdc++.h>using namespace std; // Driver codeint main(){ const int N = 1e5; // Declare array a[] int a[N]; a[0] = 1; cout << a[0]; return 0;}", "e": 1671, "s": 1436, "text": null }, { "code": "// Java program to declare the array// of size 10^5 locallyimport java.io.*; class GFG{ // Driver codepublic static void main(String[] arg){ int N = 1; // Declare array a[] int a[] = {N}; a[0] = 1; System.out.print(a[0]);}} // This code is contributed by shivani", "e": 1959, "s": 1671, "text": null }, { "code": "# Python program to declare the array# of size 10^5 locally# Driver codeN = 1e5 # Declare array a[]a = [N]a[0] = 1print(a[0]) # This code is contributed by shivanisinghss2110", "e": 2136, "s": 1959, "text": null }, { "code": "// C# program to declare the array// of size 10^5 locallyusing System;class GFG{ // Driver codepublic static void Main(String[] arg){ int N = 1; // Declare array a[] int []a = {N}; a[0] = 1; Console.Write(a[0]);}} // This code is contributed by shivanisinghss2110", "e": 2425, "s": 2136, "text": null }, { "code": "<script> // Javascript program to declare the array// of size 10^5 locallyvar N = 1; // Declare array a[]var a = [N];a[0] = 1; document.write(a[0]); // This code is contributed by shivani </script>", "e": 2623, "s": 2425, "text": null }, { "code": null, "e": 2625, "s": 2623, "text": "1" }, { "code": null, "e": 2802, "s": 2627, "text": "Explanation: In the above program, the code compilation is successful, and the output is 1. This is because the 1D array of size 105 is initialized locally and this is valid." }, { "code": null, "e": 2886, "s": 2802, "text": "Program 3: Below is the program where a 1-D array of size 107 is declared globally." }, { "code": null, "e": 2890, "s": 2886, "text": "C++" }, { "code": null, "e": 2895, "s": 2890, "text": "Java" }, { "code": null, "e": 2903, "s": 2895, "text": "Python3" }, { "code": null, "e": 2906, "s": 2903, "text": "C#" }, { "code": null, "e": 2917, "s": 2906, "text": "Javascript" }, { "code": "// C++ program to declare the array// of size 10^7 globally#include <bits/stdc++.h>using namespace std; // Variable N is initializedconst int N = 1e7; // Global array is declaredint a[N]; // Driver Codeint main(){ a[0] = 1; cout << a[0]; return 0;}", "e": 3176, "s": 2917, "text": null }, { "code": "// Java program to declare the array// of size 10^7 globallyimport java.io.*; class GFG{ // Driver Codepublic static void main(String[] arg){ // Variable N is initialized int N = 1; // Global array is declared int a[] = {N}; a[0] = 1; System.out.print(a[0]); }}// this code is contributed by shivani", "e": 3515, "s": 3176, "text": null }, { "code": "# Python3 program to declare the array# of size 10^7 globally # Variable N is initializedN = 1e7 # Global array is declareda = [N] # Driver Codea[0] = 1print(a[0]) # This code is contributed by shivanisinghss2110", "e": 3728, "s": 3515, "text": null }, { "code": "// C# program to declare the array// of size 10^7 globallyusing System; class GFG{ // Driver Codepublic static void Main(String[] arg){ // Variable N is initialized int N = 1; // Global array is declared int []a = {N}; a[0] = 1; Console.Write(a[0]); }}// this code is contributed by shivanisinghss2110", "e": 4069, "s": 3728, "text": null }, { "code": "<script> // Javascript program to declare the array// of size 10^7 globally // Variable N is initializedconst N = 1e7; // Global array is declaredlet a = new Array(N); // Driver Codea[0] = 1;document.write(a[0]); // This code is contributed by gfgking.</script>", "e": 4331, "s": 4069, "text": null }, { "code": null, "e": 4333, "s": 4331, "text": "1" }, { "code": null, "e": 4495, "s": 4335, "text": "Explanation: In the above code compilation is successful, and the output is 1. This is because a 1-D array of size 107 is declared globally and this is valid. " }, { "code": null, "e": 4762, "s": 4495, "text": "Note: If a 1-D array of size 108 is declared globally, then again the segmentation fault error will be encountered because there is also a limit for global declaration of the 1-D array and that is, it is possible to only declare a 1-D array globally up to 107 sizes." }, { "code": null, "e": 4819, "s": 4762, "text": "Why global array has a larger size than the local array?" }, { "code": null, "e": 5028, "s": 4819, "text": "When an array is declared locally, then it always initializes in the stack memory, and generally, stack memory has a size limit of around 8 MB. This size can vary according to different computer architecture." }, { "code": null, "e": 5433, "s": 5028, "text": "When an array is declared globally then it stores in the data segment, and the data segment has no size limit. Hence, when the array is declared of big size (i.e., more than 107) then the stack memory gets full and leads into the stack overflow error, and therefore, a segmentation fault error is encountered. Therefore, for declaring the array of larger size, it is good practice to declare it globally." }, { "code": null, "e": 5449, "s": 5433, "text": "simranarora5sos" }, { "code": null, "e": 5468, "s": 5449, "text": "shivanisinghss2110" }, { "code": null, "e": 5476, "s": 5468, "text": "gfgking" }, { "code": null, "e": 5485, "s": 5476, "text": "C Basics" }, { "code": null, "e": 5496, "s": 5485, "text": "CPP-Basics" }, { "code": null, "e": 5503, "s": 5496, "text": "Arrays" }, { "code": null, "e": 5507, "s": 5503, "text": "C++" }, { "code": null, "e": 5520, "s": 5507, "text": "C++ Programs" }, { "code": null, "e": 5527, "s": 5520, "text": "Arrays" }, { "code": null, "e": 5531, "s": 5527, "text": "CPP" } ]
Convert to a string that is repetition of a substring of k length
06 Jul, 2022 Given a string, find if it is possible to convert it to a string that is the repetition of a substring with k characters. To convert, we can replace one substring of length k starting at index i (zero-based indexing) such that i is divisible by K, with k characters. Examples: Input: str = "bdac", k = 2 Output: True We can either replace "bd" with "ac" or "ac" with "bd". Input: str = "abcbedabcabc", k = 3 Output: True Replace "bed" with "abc" so that the whole string becomes repetition of "abc". Input: str = "bcacc", k = 3 Output: False k doesn't divide string length i.e. 5%3 != 0 Input: str = "bcacbcac", k = 2 Output: False Input: str = "bcdbcdabcedcbcd", k = 3 Output: False This can be used in compression. If we have a string where the complete string is repetition except one substring, then we can use this algorithm to compress the string. One observation is, length of string must be a multiple of k as we can replace only one substring. The idea is to declare a map mp which maps strings of length k to an integer denoting its count. So, if there are only two different sub-strings of length k in the map container and the count of one of the sub-string is 1 then the answer is true. Otherwise, answer is false. Implementation: C++ Java Python3 C# Javascript // C++ program to check if a string can be converted to// a string that has repeated substrings of length k.#include<bits/stdc++.h>using namespace std; // Returns true if str can be converted to a string// with k repeated substrings after replacing k// characters.bool checkString(string str, long k){ // Length of string must be a multiple of k int n = str.length(); if (n%k != 0) return false; // Map to store strings of length k and their counts unordered_map<string, int> mp; for (int i=0; i<n; i+=k) mp[str.substr(i, k)]++; // If string is already a repetition of k substrings, // return true. if (mp.size() == 1) return true; // If number of distinct substrings is not 2, then // not possible to replace a string. if (mp.size() != 2) return false; // One of the two distinct must appear exactly once. // Either the first entry appears once, or it appears // n/k-1 times to make other substring appear once. if ((mp.begin()->second == (n/k - 1)) || mp.begin()->second == 1) return true; return false;} // Driver codeint main(){ checkString("abababcd", 2)? cout << "Yes" : cout << "No"; return 0;} // Java program to check if a string// can be converted to a string that has// repeated substrings of length k.import java.util.HashMap;import java.util.Iterator; class GFG{ // Returns true if str can be converted // to a string with k repeated substrings // after replacing k characters. static boolean checkString(String str, int k) { // Length of string must be // a multiple of k int n = str.length(); if (n % k != 0) return false; // Map to store strings of // length k and their counts HashMap<String, Integer> mp = new HashMap<>(); try { for (int i = 0; i < n; i += k) mp.put(str.substring(i, k), mp.get(str.substring(i, k)) == null ? 1 : mp.get(str.substring(i, k)) + 1); } catch (Exception e) { } // If string is already a repetition // of k substrings, return true. if (mp.size() == 1) return true; // If number of distinct substrings is not 2, // then not possible to replace a string. if (mp.size() != 2) return false; HashMap.Entry<String, Integer> entry = mp.entrySet().iterator().next(); // One of the two distinct must appear // exactly once. Either the first entry // appears once, or it appears n/k-1 times // to make other substring appear once. if (entry.getValue() == (n / k - 1) || entry.getValue() == 1) return true; return false; } // Driver code public static void main(String[] args) { if (checkString("abababcd", 2)) System.out.println("Yes"); else System.out.println("No"); }} // This code is contributed by// sanjeev2552 # Python3 program to check if a can be converted to# a that has repeated subs of length k. # Returns True if S can be converted to a# with k repeated subs after replacing k# characters.def check( S, k): # Length of must be a multiple of k n = len(S) if (n % k != 0): return False # Map to store s of length k and their counts mp = {} for i in range(0, n, k): mp[S[i:k]] = mp.get(S[i:k], 0) + 1 # If is already a repetition of k subs, # return True. if (len(mp) == 1): return True # If number of distinct subs is not 2, then # not possible to replace a . if (len(mp) != 2): return False # One of the two distinct must appear exactly once. # Either the first entry appears once, or it appears # n/k-1 times to make other sub appear once. for i in mp: if i == (n//k - 1) or mp[i] == 1: return True return False # Driver code if check("abababcd", 2): print("Yes")else: print("No") # This code is contributed by mohit kumar 29 // C# program to check if a string// can be converted to a string that has// repeated substrings of length k.using System;using System.Collections.Generic; class GFG{ // Returns true if str can be converted // to a string with k repeated substrings // after replacing k characters. static bool checkString(String str, int k) { // Length of string must be // a multiple of k int n = str.Length; if (n % k != 0) return false; // Map to store strings of // length k and their counts Dictionary<String, int> mp = new Dictionary<String, int>(); for (int i = 0; i < n; i += k) { if(!mp.ContainsKey(str.Substring(i, k))) mp.Add(str.Substring(i, k), 1); else mp[str.Substring(i, k)] = mp[str.Substring(i, k)] + 1; } // If string is already a repetition // of k substrings, return true. if (mp.Count == 1) return true; // If number of distinct substrings is not 2, // then not possible to replace a string. if (mp.Count != 2) return false; foreach(KeyValuePair<String, int> entry in mp) { // One of the two distinct must appear // exactly once. Either the first entry // appears once, or it appears n/k-1 times // to make other substring appear once. if (entry.Value == (n / k - 1) || entry.Value == 1) return true; } return false; } // Driver code public static void Main(String[] args) { if (checkString("abababcd", 2)) Console.WriteLine("Yes"); else Console.WriteLine("No"); }} // This code is contributed by Princi Singh <script>// Javascript program to check if a string// can be converted to a string that has// repeated substrings of length k. // Returns true if str can be converted // to a string with k repeated substrings // after replacing k characters. function checkString(str,k) { // Length of string must be // a multiple of k let n = str.length; if (n % k != 0) return false; // Map to store strings of // length k and their counts let mp = new Map(); for (let i = 0; i < n; i += k) { if(mp.has(str.substring(i, i+k))) mp.set(str.substring(i, i+k),mp.get(str.substring(i, i+k)) + 1); else mp.set(str.substring(i, i+k),1); } // If string is already a repetition // of k substrings, return true. if (mp.size == 1) return true; // If number of distinct substrings is not 2, // then not possible to replace a string. if (mp.size != 2) { return false; } // One of the two distinct must appear // exactly once. Either the first entry // appears once, or it appears n/k-1 times // to make other substring appear once. for (let [key, value] of mp.entries()) { if(value == (Math.floor(n/k) - 1) || value == 1) return true; } return false; } // Driver code if (checkString("abababcd", 2)) document.write("Yes"); else document.write("No"); // This code is contributed by unknown2108</script> Yes Time complexity : O(n) Auxiliary Space : O(n) This article is contributed by Himanshu Gupta(Bagri). 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. mohit kumar 29 sanjeev2552 princi singh unknown2108 surindertarika1234 saurabh1990aror youmailmahibagi sangramjagaxcka hardikkoriintern Hash Strings Hash Strings Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n06 Jul, 2022" }, { "code": null, "e": 321, "s": 54, "text": "Given a string, find if it is possible to convert it to a string that is the repetition of a substring with k characters. To convert, we can replace one substring of length k starting at index i (zero-based indexing) such that i is divisible by K, with k characters." }, { "code": null, "e": 333, "s": 321, "text": "Examples: " }, { "code": null, "e": 748, "s": 333, "text": "Input: str = \"bdac\", k = 2\nOutput: True\nWe can either replace \"bd\" with \"ac\" or \n\"ac\" with \"bd\".\n\nInput: str = \"abcbedabcabc\", k = 3\nOutput: True\nReplace \"bed\" with \"abc\" so that the \nwhole string becomes repetition of \"abc\".\n\nInput: str = \"bcacc\", k = 3\nOutput: False\nk doesn't divide string length i.e. 5%3 != 0\n\nInput: str = \"bcacbcac\", k = 2\nOutput: False\n\nInput: str = \"bcdbcdabcedcbcd\", k = 3\nOutput: False" }, { "code": null, "e": 918, "s": 748, "text": "This can be used in compression. If we have a string where the complete string is repetition except one substring, then we can use this algorithm to compress the string." }, { "code": null, "e": 1018, "s": 918, "text": "One observation is, length of string must be a multiple of k as we can replace only one substring. " }, { "code": null, "e": 1294, "s": 1018, "text": "The idea is to declare a map mp which maps strings of length k to an integer denoting its count. So, if there are only two different sub-strings of length k in the map container and the count of one of the sub-string is 1 then the answer is true. Otherwise, answer is false. " }, { "code": null, "e": 1310, "s": 1294, "text": "Implementation:" }, { "code": null, "e": 1314, "s": 1310, "text": "C++" }, { "code": null, "e": 1319, "s": 1314, "text": "Java" }, { "code": null, "e": 1327, "s": 1319, "text": "Python3" }, { "code": null, "e": 1330, "s": 1327, "text": "C#" }, { "code": null, "e": 1341, "s": 1330, "text": "Javascript" }, { "code": "// C++ program to check if a string can be converted to// a string that has repeated substrings of length k.#include<bits/stdc++.h>using namespace std; // Returns true if str can be converted to a string// with k repeated substrings after replacing k// characters.bool checkString(string str, long k){ // Length of string must be a multiple of k int n = str.length(); if (n%k != 0) return false; // Map to store strings of length k and their counts unordered_map<string, int> mp; for (int i=0; i<n; i+=k) mp[str.substr(i, k)]++; // If string is already a repetition of k substrings, // return true. if (mp.size() == 1) return true; // If number of distinct substrings is not 2, then // not possible to replace a string. if (mp.size() != 2) return false; // One of the two distinct must appear exactly once. // Either the first entry appears once, or it appears // n/k-1 times to make other substring appear once. if ((mp.begin()->second == (n/k - 1)) || mp.begin()->second == 1) return true; return false;} // Driver codeint main(){ checkString(\"abababcd\", 2)? cout << \"Yes\" : cout << \"No\"; return 0;}", "e": 2589, "s": 1341, "text": null }, { "code": "// Java program to check if a string// can be converted to a string that has// repeated substrings of length k.import java.util.HashMap;import java.util.Iterator; class GFG{ // Returns true if str can be converted // to a string with k repeated substrings // after replacing k characters. static boolean checkString(String str, int k) { // Length of string must be // a multiple of k int n = str.length(); if (n % k != 0) return false; // Map to store strings of // length k and their counts HashMap<String, Integer> mp = new HashMap<>(); try { for (int i = 0; i < n; i += k) mp.put(str.substring(i, k), mp.get(str.substring(i, k)) == null ? 1 : mp.get(str.substring(i, k)) + 1); } catch (Exception e) { } // If string is already a repetition // of k substrings, return true. if (mp.size() == 1) return true; // If number of distinct substrings is not 2, // then not possible to replace a string. if (mp.size() != 2) return false; HashMap.Entry<String, Integer> entry = mp.entrySet().iterator().next(); // One of the two distinct must appear // exactly once. Either the first entry // appears once, or it appears n/k-1 times // to make other substring appear once. if (entry.getValue() == (n / k - 1) || entry.getValue() == 1) return true; return false; } // Driver code public static void main(String[] args) { if (checkString(\"abababcd\", 2)) System.out.println(\"Yes\"); else System.out.println(\"No\"); }} // This code is contributed by// sanjeev2552", "e": 4404, "s": 2589, "text": null }, { "code": "# Python3 program to check if a can be converted to# a that has repeated subs of length k. # Returns True if S can be converted to a# with k repeated subs after replacing k# characters.def check( S, k): # Length of must be a multiple of k n = len(S) if (n % k != 0): return False # Map to store s of length k and their counts mp = {} for i in range(0, n, k): mp[S[i:k]] = mp.get(S[i:k], 0) + 1 # If is already a repetition of k subs, # return True. if (len(mp) == 1): return True # If number of distinct subs is not 2, then # not possible to replace a . if (len(mp) != 2): return False # One of the two distinct must appear exactly once. # Either the first entry appears once, or it appears # n/k-1 times to make other sub appear once. for i in mp: if i == (n//k - 1) or mp[i] == 1: return True return False # Driver code if check(\"abababcd\", 2): print(\"Yes\")else: print(\"No\") # This code is contributed by mohit kumar 29 ", "e": 5452, "s": 4404, "text": null }, { "code": "// C# program to check if a string// can be converted to a string that has// repeated substrings of length k.using System;using System.Collections.Generic; class GFG{ // Returns true if str can be converted // to a string with k repeated substrings // after replacing k characters. static bool checkString(String str, int k) { // Length of string must be // a multiple of k int n = str.Length; if (n % k != 0) return false; // Map to store strings of // length k and their counts Dictionary<String, int> mp = new Dictionary<String, int>(); for (int i = 0; i < n; i += k) { if(!mp.ContainsKey(str.Substring(i, k))) mp.Add(str.Substring(i, k), 1); else mp[str.Substring(i, k)] = mp[str.Substring(i, k)] + 1; } // If string is already a repetition // of k substrings, return true. if (mp.Count == 1) return true; // If number of distinct substrings is not 2, // then not possible to replace a string. if (mp.Count != 2) return false; foreach(KeyValuePair<String, int> entry in mp) { // One of the two distinct must appear // exactly once. Either the first entry // appears once, or it appears n/k-1 times // to make other substring appear once. if (entry.Value == (n / k - 1) || entry.Value == 1) return true; } return false; } // Driver code public static void Main(String[] args) { if (checkString(\"abababcd\", 2)) Console.WriteLine(\"Yes\"); else Console.WriteLine(\"No\"); }} // This code is contributed by Princi Singh", "e": 7314, "s": 5452, "text": null }, { "code": "<script>// Javascript program to check if a string// can be converted to a string that has// repeated substrings of length k. // Returns true if str can be converted // to a string with k repeated substrings // after replacing k characters. function checkString(str,k) { // Length of string must be // a multiple of k let n = str.length; if (n % k != 0) return false; // Map to store strings of // length k and their counts let mp = new Map(); for (let i = 0; i < n; i += k) { if(mp.has(str.substring(i, i+k))) mp.set(str.substring(i, i+k),mp.get(str.substring(i, i+k)) + 1); else mp.set(str.substring(i, i+k),1); } // If string is already a repetition // of k substrings, return true. if (mp.size == 1) return true; // If number of distinct substrings is not 2, // then not possible to replace a string. if (mp.size != 2) { return false; } // One of the two distinct must appear // exactly once. Either the first entry // appears once, or it appears n/k-1 times // to make other substring appear once. for (let [key, value] of mp.entries()) { if(value == (Math.floor(n/k) - 1) || value == 1) return true; } return false; } // Driver code if (checkString(\"abababcd\", 2)) document.write(\"Yes\"); else document.write(\"No\"); // This code is contributed by unknown2108</script>", "e": 8998, "s": 7314, "text": null }, { "code": null, "e": 9002, "s": 8998, "text": "Yes" }, { "code": null, "e": 9048, "s": 9002, "text": "Time complexity : O(n) Auxiliary Space : O(n)" }, { "code": null, "e": 9354, "s": 9048, "text": "This article is contributed by Himanshu Gupta(Bagri). 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": 9369, "s": 9354, "text": "mohit kumar 29" }, { "code": null, "e": 9381, "s": 9369, "text": "sanjeev2552" }, { "code": null, "e": 9394, "s": 9381, "text": "princi singh" }, { "code": null, "e": 9406, "s": 9394, "text": "unknown2108" }, { "code": null, "e": 9425, "s": 9406, "text": "surindertarika1234" }, { "code": null, "e": 9441, "s": 9425, "text": "saurabh1990aror" }, { "code": null, "e": 9457, "s": 9441, "text": "youmailmahibagi" }, { "code": null, "e": 9473, "s": 9457, "text": "sangramjagaxcka" }, { "code": null, "e": 9490, "s": 9473, "text": "hardikkoriintern" }, { "code": null, "e": 9495, "s": 9490, "text": "Hash" }, { "code": null, "e": 9503, "s": 9495, "text": "Strings" }, { "code": null, "e": 9508, "s": 9503, "text": "Hash" }, { "code": null, "e": 9516, "s": 9508, "text": "Strings" } ]
Flutter – InkWell Widget
22 Mar, 2021 InkWell is the material widget in flutter. It responds to the touch action as performed by the user. Inkwell will respond when the user clicks the button. There are so many gestures like double-tap, long press, tap down, etc. Below are the so many properties of this widget. We can set the radius of the inkwell widget using radius and also border-radius using borderRadius. We can give the splash color using splashColor and can do a lot of things. InkWell({Key key, Widget child, GestureTapCallback onTap, GestureTapCallback onDoubleTap, GestureLongPressCallback onLongPress, GestureTapDownCallback onTapDown, GestureTapCancelCallback onTapCancel, ValueChanged<bool> onHighlightChanged, ValueChanged<bool> onHover, MouseCursor mouseCursor, Color focusColor, Color hoverColor, Color highlightColor, MaterialStateProperty<Color> overlayColor, Color splashColor, InteractiveInkFeatureFactory splashFactory, double radius, BorderRadius borderRadius, ShapeBorder customBorder, bool enableFeedback: true, bool excludeFromSemantics: false, FocusNode focusNode, bool canRequestFocus: true, ValueChanged<bool> onFocusChange, bool autofocus: false}) Example: main.dart Dart import 'package:flutter/material.dart'; void main() { runApp(MyApp());} class MyApp extends StatelessWidget { // This widget is the root of your application. @override Widget build(BuildContext context) { return MaterialApp( title: 'InkWell', theme: ThemeData( primarySwatch: Colors.blue, ), home: MyHomePage(), debugShowCheckedModeBanner: false, ); }} class MyHomePage extends StatefulWidget { @override _MyHomePageState createState() => _MyHomePageState();} class _MyHomePageState extends State<MyHomePage> { String inkwell=''; @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('InkWell Widget'), backgroundColor: Colors.green, actions: <Widget>[ Text( 'GFG', textScaleFactor: 3, ) ], ), backgroundColor: Colors.lightBlue[50], body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ InkWell( onTap: () { setState(() { inkwell='Inkwell Tapped'; }); }, onLongPress: () { setState(() { inkwell='InkWell Long Pressed'; }); }, child: Container( color: Colors.green, width: 120, height: 70, child: Center( child: Text( 'Inkwell', textScaleFactor: 2, style: TextStyle(fontWeight: FontWeight.bold), ))), ), Padding( padding: const EdgeInsets.all(8.0), child: Text(inkwell,textScaleFactor: 2,), ) ], ), ), ); }} Explanation: Create a Container and wrap it with the InkWell widget. When InkWell is tapped, it will display “InkWell Tapped” on the screen. When InkWell is LongPressed, it will display “InkWell Long Pressed” on the screen. Output: When the InkWell container is not tapped, it will result: When the InkWell Container is tapped, it will result: When the InkWell Container is Long Pressed, it will result: Flutter Flutter-widgets Articles Dart Flutter Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n22 Mar, 2021" }, { "code": null, "e": 502, "s": 52, "text": "InkWell is the material widget in flutter. It responds to the touch action as performed by the user. Inkwell will respond when the user clicks the button. There are so many gestures like double-tap, long press, tap down, etc. Below are the so many properties of this widget. We can set the radius of the inkwell widget using radius and also border-radius using borderRadius. We can give the splash color using splashColor and can do a lot of things." }, { "code": null, "e": 1218, "s": 502, "text": "InkWell({Key key, \nWidget child, \nGestureTapCallback onTap, \nGestureTapCallback onDoubleTap, \nGestureLongPressCallback onLongPress, \nGestureTapDownCallback onTapDown, \nGestureTapCancelCallback onTapCancel, \nValueChanged<bool> onHighlightChanged, \nValueChanged<bool> onHover, \nMouseCursor mouseCursor, \nColor focusColor, \nColor hoverColor, \nColor highlightColor, \nMaterialStateProperty<Color> overlayColor, \nColor splashColor, \nInteractiveInkFeatureFactory splashFactory, \ndouble radius, \nBorderRadius borderRadius, \nShapeBorder customBorder, \nbool enableFeedback: true, \nbool excludeFromSemantics: false, \nFocusNode focusNode, \nbool canRequestFocus: true, \nValueChanged<bool> onFocusChange, \nbool autofocus: false})" }, { "code": null, "e": 1227, "s": 1218, "text": "Example:" }, { "code": null, "e": 1237, "s": 1227, "text": "main.dart" }, { "code": null, "e": 1242, "s": 1237, "text": "Dart" }, { "code": "import 'package:flutter/material.dart'; void main() { runApp(MyApp());} class MyApp extends StatelessWidget { // This widget is the root of your application. @override Widget build(BuildContext context) { return MaterialApp( title: 'InkWell', theme: ThemeData( primarySwatch: Colors.blue, ), home: MyHomePage(), debugShowCheckedModeBanner: false, ); }} class MyHomePage extends StatefulWidget { @override _MyHomePageState createState() => _MyHomePageState();} class _MyHomePageState extends State<MyHomePage> { String inkwell=''; @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('InkWell Widget'), backgroundColor: Colors.green, actions: <Widget>[ Text( 'GFG', textScaleFactor: 3, ) ], ), backgroundColor: Colors.lightBlue[50], body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ InkWell( onTap: () { setState(() { inkwell='Inkwell Tapped'; }); }, onLongPress: () { setState(() { inkwell='InkWell Long Pressed'; }); }, child: Container( color: Colors.green, width: 120, height: 70, child: Center( child: Text( 'Inkwell', textScaleFactor: 2, style: TextStyle(fontWeight: FontWeight.bold), ))), ), Padding( padding: const EdgeInsets.all(8.0), child: Text(inkwell,textScaleFactor: 2,), ) ], ), ), ); }}", "e": 3138, "s": 1242, "text": null }, { "code": null, "e": 3151, "s": 3138, "text": "Explanation:" }, { "code": null, "e": 3207, "s": 3151, "text": "Create a Container and wrap it with the InkWell widget." }, { "code": null, "e": 3279, "s": 3207, "text": "When InkWell is tapped, it will display “InkWell Tapped” on the screen." }, { "code": null, "e": 3362, "s": 3279, "text": "When InkWell is LongPressed, it will display “InkWell Long Pressed” on the screen." }, { "code": null, "e": 3370, "s": 3362, "text": "Output:" }, { "code": null, "e": 3428, "s": 3370, "text": "When the InkWell container is not tapped, it will result:" }, { "code": null, "e": 3482, "s": 3428, "text": "When the InkWell Container is tapped, it will result:" }, { "code": null, "e": 3542, "s": 3482, "text": "When the InkWell Container is Long Pressed, it will result:" }, { "code": null, "e": 3550, "s": 3542, "text": "Flutter" }, { "code": null, "e": 3566, "s": 3550, "text": "Flutter-widgets" }, { "code": null, "e": 3575, "s": 3566, "text": "Articles" }, { "code": null, "e": 3580, "s": 3575, "text": "Dart" }, { "code": null, "e": 3588, "s": 3580, "text": "Flutter" } ]
Dynamic AutoCompleteTextView in Kotlin
28 Mar, 2022 Android AutoCompleteTextView is an editable text view which shows a list of suggestions when user starts typing text. When a user starts typing, a dropdown menu will be there based on the entered characters, defined in threshold limit and user can choose an item from list to replace the text. The AutoCompleteTextView is a subclass of EditText class so we can easily inherit all the properties of EditText as per our requirements. The dropdown list will be obtained suing data adaptor and these suggestions will be appeared only after entering the minimum number characters defined in the Threshold limit. The Threshold limit is used to define the minimum number of characters the user must type to see the dropdown list of suggestions. In android, we can create a AutoCompleteTextView control in two ways either manually in XML file or create it in Activity file programmatically. First we create a new project by following the below steps: Click on File, then New => New Project.After that include the Kotlin support and click on next.Select the minimum SDK as per convenience and click next button.Then select the Empty activity => next => finish. Click on File, then New => New Project. After that include the Kotlin support and click on next. Select the minimum SDK as per convenience and click next button. Then select the Empty activity => next => finish. In this file, we only use the LinearLayout and set it attributes. XML <?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent" android:id="@+id/linear_layout" android:gravity = "center"> </LinearLayout> Here, we will specify the name of the activity and define other strings which can be used at different places in our activity. Another important thing is that we will define string_array which contains the items for the suggestion list of AutoCompleteTextView. XML <resources> <string name="app_name">DynamicAutoCompleteTextView</string> <string name="hint">Please type language...</string> <string name="submit">Submit</string> <string name="submitted_lang">Submitted language:</string> <string-array name="Languages"> <item>Java</item> <item>Kotlin</item> <item>Swift</item> <item>Python</item> <item>Scala</item> <item>Perl</item> <item>Javascript</item> <item>Jquery</item> </string-array> </resources> First of all, we declare two variables autotextview and button to create the widgets and set their attributes. val autotextView = AutoCompleteTextView(this) val button = Button(this) and add both autotextview and button in LinearLayout using val linearLayout = findViewById(R.id.linear_layout) // Add AutoCompleteTextView and button to LinearLayout linearLayout?.addView(autotextView) linearLayout?.addView(button) then, we declare another variable languages to get the items of the string-array from the strings.xml file. val languages = resources.getStringArray(R.array.Languages) Create an adaptor and add into the AutoCompleteTextView of LinearLayout using val adapter = ArrayAdapter(this, android.R.layout.simple_list_item_1, languages) autotextView.setAdapter(adapter) Kotlin package com.geeksforgeeks.myfirstkotlinapp import android.os.Bundleimport android.view.Viewimport android.view.ViewGroupimport android.widget.*import androidx.appcompat.app.AppCompatActivity class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) //create AutoCompleteTextView and button val autotextView = AutoCompleteTextView(this) val button = Button(this) val layoutParams = LinearLayout.LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT) autotextView.layoutParams = layoutParams button.layoutParams = layoutParams layoutParams.setMargins(30, 30, 30, 30) autotextView.setHint(R.string.hint) button.setText("Submit") val linearLayout = findViewById<LinearLayout>(R.id.linear_layout) // Add AutoCompleteTextView and button to LinearLayout linearLayout?.addView(autotextView) linearLayout?.addView(button) // Get the array of languages val languages = resources.getStringArray(R.array.Languages) // Create adapter and add in AutoCompleteTextView val adapter = ArrayAdapter(this, android.R.layout.simple_list_item_1, languages) autotextView.setAdapter(adapter) if (button != null) { button?.setOnClickListener(View.OnClickListener { val enteredText = getString(R.string.submitted_lang)+ " " + autotextView.getText() Toast.makeText(this@MainActivity, enteredText, Toast.LENGTH_SHORT).show() }) } }} XML <?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android"package="com.geeksforgeeks.myfirstkotlinapp"> <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> ayushpandey3july Android-View Kotlin Android Android Kotlin Android Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n28 Mar, 2022" }, { "code": null, "e": 322, "s": 28, "text": "Android AutoCompleteTextView is an editable text view which shows a list of suggestions when user starts typing text. When a user starts typing, a dropdown menu will be there based on the entered characters, defined in threshold limit and user can choose an item from list to replace the text." }, { "code": null, "e": 460, "s": 322, "text": "The AutoCompleteTextView is a subclass of EditText class so we can easily inherit all the properties of EditText as per our requirements." }, { "code": null, "e": 766, "s": 460, "text": "The dropdown list will be obtained suing data adaptor and these suggestions will be appeared only after entering the minimum number characters defined in the Threshold limit. The Threshold limit is used to define the minimum number of characters the user must type to see the dropdown list of suggestions." }, { "code": null, "e": 911, "s": 766, "text": "In android, we can create a AutoCompleteTextView control in two ways either manually in XML file or create it in Activity file programmatically." }, { "code": null, "e": 971, "s": 911, "text": "First we create a new project by following the below steps:" }, { "code": null, "e": 1180, "s": 971, "text": "Click on File, then New => New Project.After that include the Kotlin support and click on next.Select the minimum SDK as per convenience and click next button.Then select the Empty activity => next => finish." }, { "code": null, "e": 1220, "s": 1180, "text": "Click on File, then New => New Project." }, { "code": null, "e": 1277, "s": 1220, "text": "After that include the Kotlin support and click on next." }, { "code": null, "e": 1342, "s": 1277, "text": "Select the minimum SDK as per convenience and click next button." }, { "code": null, "e": 1392, "s": 1342, "text": "Then select the Empty activity => next => finish." }, { "code": null, "e": 1458, "s": 1392, "text": "In this file, we only use the LinearLayout and set it attributes." }, { "code": null, "e": 1462, "s": 1458, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" android:orientation=\"vertical\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:id=\"@+id/linear_layout\" android:gravity = \"center\"> </LinearLayout>", "e": 1769, "s": 1462, "text": null }, { "code": null, "e": 2030, "s": 1769, "text": "Here, we will specify the name of the activity and define other strings which can be used at different places in our activity. Another important thing is that we will define string_array which contains the items for the suggestion list of AutoCompleteTextView." }, { "code": null, "e": 2034, "s": 2030, "text": "XML" }, { "code": "<resources> <string name=\"app_name\">DynamicAutoCompleteTextView</string> <string name=\"hint\">Please type language...</string> <string name=\"submit\">Submit</string> <string name=\"submitted_lang\">Submitted language:</string> <string-array name=\"Languages\"> <item>Java</item> <item>Kotlin</item> <item>Swift</item> <item>Python</item> <item>Scala</item> <item>Perl</item> <item>Javascript</item> <item>Jquery</item> </string-array> </resources>", "e": 2553, "s": 2034, "text": null }, { "code": null, "e": 2664, "s": 2553, "text": "First of all, we declare two variables autotextview and button to create the widgets and set their attributes." }, { "code": null, "e": 2737, "s": 2664, "text": "val autotextView = AutoCompleteTextView(this)\nval button = Button(this)\n" }, { "code": null, "e": 2796, "s": 2737, "text": "and add both autotextview and button in LinearLayout using" }, { "code": null, "e": 2983, "s": 2796, "text": "val linearLayout = findViewById(R.id.linear_layout)\n // Add AutoCompleteTextView and button to LinearLayout\n linearLayout?.addView(autotextView)\n linearLayout?.addView(button)\n" }, { "code": null, "e": 3091, "s": 2983, "text": "then, we declare another variable languages to get the items of the string-array from the strings.xml file." }, { "code": null, "e": 3151, "s": 3091, "text": "val languages = resources.getStringArray(R.array.Languages)" }, { "code": null, "e": 3229, "s": 3151, "text": "Create an adaptor and add into the AutoCompleteTextView of LinearLayout using" }, { "code": null, "e": 3358, "s": 3229, "text": "val adapter = ArrayAdapter(this,\n android.R.layout.simple_list_item_1, languages)\n autotextView.setAdapter(adapter)\n" }, { "code": null, "e": 3365, "s": 3358, "text": "Kotlin" }, { "code": "package com.geeksforgeeks.myfirstkotlinapp import android.os.Bundleimport android.view.Viewimport android.view.ViewGroupimport android.widget.*import androidx.appcompat.app.AppCompatActivity class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) //create AutoCompleteTextView and button val autotextView = AutoCompleteTextView(this) val button = Button(this) val layoutParams = LinearLayout.LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT) autotextView.layoutParams = layoutParams button.layoutParams = layoutParams layoutParams.setMargins(30, 30, 30, 30) autotextView.setHint(R.string.hint) button.setText(\"Submit\") val linearLayout = findViewById<LinearLayout>(R.id.linear_layout) // Add AutoCompleteTextView and button to LinearLayout linearLayout?.addView(autotextView) linearLayout?.addView(button) // Get the array of languages val languages = resources.getStringArray(R.array.Languages) // Create adapter and add in AutoCompleteTextView val adapter = ArrayAdapter(this, android.R.layout.simple_list_item_1, languages) autotextView.setAdapter(adapter) if (button != null) { button?.setOnClickListener(View.OnClickListener { val enteredText = getString(R.string.submitted_lang)+ \" \" + autotextView.getText() Toast.makeText(this@MainActivity, enteredText, Toast.LENGTH_SHORT).show() }) } }}", "e": 5121, "s": 3365, "text": null }, { "code": null, "e": 5125, "s": 5121, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><manifest xmlns:android=\"http://schemas.android.com/apk/res/android\"package=\"com.geeksforgeeks.myfirstkotlinapp\"> <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>", "e": 5780, "s": 5125, "text": null }, { "code": null, "e": 5799, "s": 5782, "text": "ayushpandey3july" }, { "code": null, "e": 5812, "s": 5799, "text": "Android-View" }, { "code": null, "e": 5827, "s": 5812, "text": "Kotlin Android" }, { "code": null, "e": 5835, "s": 5827, "text": "Android" }, { "code": null, "e": 5842, "s": 5835, "text": "Kotlin" }, { "code": null, "e": 5850, "s": 5842, "text": "Android" } ]
Runtime Errors
30 Sep, 2020 A runtime error in a program is an error that occurs while the program is running after being successfully compiled. Runtime errors are commonly called referred to as “bugs” and are often found during the debugging process before the software is released. When runtime errors occur after a program has been distributed to the public, developers often release patches, or small updates designed to fix the errors. Anyone can find the list of issues that they might face if they are a beginner in this article. While solving problems on online platforms, many run time errors can be faced, which are not clearly specified in the message that comes with them. There are a variety of runtime errors that occur such as logical errors, Input/Output errors, undefined object errors, division by zero errors, and many more. SIGFPE: SIGFPE is a floating-point error. It is virtually always caused by a division by 0. There can be mainly three main causes of SIGFPE error described as follows:Division by Zero.Modulo Operation by Zero.Integer Overflow.Below is the program to illustrate the SIGFPE error:C++C++// C++ program to illustrate// the SIGFPE error #include <iostream>using namespace std; // Driver Codeint main(){ int a = 5; // Division by Zero cout << a / 0; return 0;}Output: Division by Zero.Modulo Operation by Zero.Integer Overflow. Division by Zero. Modulo Operation by Zero. Integer Overflow. Below is the program to illustrate the SIGFPE error: C++ // C++ program to illustrate// the SIGFPE error #include <iostream>using namespace std; // Driver Codeint main(){ int a = 5; // Division by Zero cout << a / 0; return 0;} Output: SIGABRT: It is an error itself is detected by the program then this signal is generated using call to abort() function. This signal is also used by standard library to report an internal error. assert() function in C++ also uses abort() to generate this signal.Below is the program to illustrate the SIGBRT error:C++C++// C++ program to illustrate// the SIGBRT error #include <iostream>using namespace std; // Driver Codeint main(){ // Assigning excessive memory int a = 100000000000; int* arr = new int[a]; return 0;}Output: Below is the program to illustrate the SIGBRT error: C++ // C++ program to illustrate// the SIGBRT error #include <iostream>using namespace std; // Driver Codeint main(){ // Assigning excessive memory int a = 100000000000; int* arr = new int[a]; return 0;} Output: NZEC: This error denotes “Non-Zero Exit Code”. For C users, this error will be generated if the main() method does not have a return 0 statement. Java/C++ users could generate this error if they throw an exception. Below are the possible reasons of getting NZEC error:Infinite Recursion or if you run out of stack memory.Negative array index is accessed.ArrayIndexOutOfBounds Exception.StringIndexOutOfBounds Exception.Below is the program to illustrate the NZEC error:PythonPython# Python program to illustrate# the NZEC Error # Driver Codeif __name__ == "__main__": arr = [1, 2] # Runtime Error # Array Index out of Bounds print(arr[2])Output: Infinite Recursion or if you run out of stack memory.Negative array index is accessed.ArrayIndexOutOfBounds Exception.StringIndexOutOfBounds Exception. Infinite Recursion or if you run out of stack memory. Negative array index is accessed. ArrayIndexOutOfBounds Exception. StringIndexOutOfBounds Exception. Below is the program to illustrate the NZEC error: Python # Python program to illustrate# the NZEC Error # Driver Codeif __name__ == "__main__": arr = [1, 2] # Runtime Error # Array Index out of Bounds print(arr[2]) Output: SIGSEGV: This error is the most common error and is known as “Segmentation Fault“. It is generated when the program tries to access a memory that is not allowed to access or attempts to access a memory location in a way that is not allowed. List of some of the common reasons for segmentation faults are:Accessing an array out of bounds.Dereferencing NULL pointers.Dereferencing freed memory.Dereferencing uninitialized pointers.Incorrect use of the “&” (address of) and “*”(dereferencing) operators.Improper formatting specifiers in printf and scanf statements.Stack overflow.Writing to read-only memory.Below is the program to illustrate the SIGSEGV error:C++C++// C++ program to illustrate// the SIGSEGV error#include <bits/stdc++.h>using namespace std; // Function with infinite// Recursionvoid infiniteRecur(int a){ return infiniteRecur(a);} // Driver Codeint main(){ // Infinite Recursion infiniteRecur(5);}Output: Accessing an array out of bounds.Dereferencing NULL pointers.Dereferencing freed memory.Dereferencing uninitialized pointers.Incorrect use of the “&” (address of) and “*”(dereferencing) operators.Improper formatting specifiers in printf and scanf statements.Stack overflow.Writing to read-only memory. Accessing an array out of bounds. Dereferencing NULL pointers. Dereferencing freed memory. Dereferencing uninitialized pointers. Incorrect use of the “&” (address of) and “*”(dereferencing) operators. Improper formatting specifiers in printf and scanf statements. Stack overflow. Writing to read-only memory. Below is the program to illustrate the SIGSEGV error: C++ // C++ program to illustrate// the SIGSEGV error#include <bits/stdc++.h>using namespace std; // Function with infinite// Recursionvoid infiniteRecur(int a){ return infiniteRecur(a);} // Driver Codeint main(){ // Infinite Recursion infiniteRecur(5);} Output: Avoid using variables that have not been initialized. These may be set to 0 on your system but not on the coding platform. Check every single occurrence of an array element and ensure that it is not out of bounds. Avoid declaring too much memory. Check for the memory limit specified in the question. Avoid declaring too much Stack Memory. Large arrays should be declared globally outside the function. Use return as the end statement. Avoid referencing free memory or null pointers. Articles Competitive Programming Difference Between Program Output Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n30 Sep, 2020" }, { "code": null, "e": 169, "s": 52, "text": "A runtime error in a program is an error that occurs while the program is running after being successfully compiled." }, { "code": null, "e": 308, "s": 169, "text": "Runtime errors are commonly called referred to as “bugs” and are often found during the debugging process before the software is released." }, { "code": null, "e": 465, "s": 308, "text": "When runtime errors occur after a program has been distributed to the public, developers often release patches, or small updates designed to fix the errors." }, { "code": null, "e": 561, "s": 465, "text": "Anyone can find the list of issues that they might face if they are a beginner in this article." }, { "code": null, "e": 868, "s": 561, "text": "While solving problems on online platforms, many run time errors can be faced, which are not clearly specified in the message that comes with them. There are a variety of runtime errors that occur such as logical errors, Input/Output errors, undefined object errors, division by zero errors, and many more." }, { "code": null, "e": 1348, "s": 868, "text": "SIGFPE: SIGFPE is a floating-point error. It is virtually always caused by a division by 0. There can be mainly three main causes of SIGFPE error described as follows:Division by Zero.Modulo Operation by Zero.Integer Overflow.Below is the program to illustrate the SIGFPE error:C++C++// C++ program to illustrate// the SIGFPE error #include <iostream>using namespace std; // Driver Codeint main(){ int a = 5; // Division by Zero cout << a / 0; return 0;}Output:" }, { "code": null, "e": 1408, "s": 1348, "text": "Division by Zero.Modulo Operation by Zero.Integer Overflow." }, { "code": null, "e": 1426, "s": 1408, "text": "Division by Zero." }, { "code": null, "e": 1452, "s": 1426, "text": "Modulo Operation by Zero." }, { "code": null, "e": 1470, "s": 1452, "text": "Integer Overflow." }, { "code": null, "e": 1523, "s": 1470, "text": "Below is the program to illustrate the SIGFPE error:" }, { "code": null, "e": 1527, "s": 1523, "text": "C++" }, { "code": "// C++ program to illustrate// the SIGFPE error #include <iostream>using namespace std; // Driver Codeint main(){ int a = 5; // Division by Zero cout << a / 0; return 0;}", "e": 1716, "s": 1527, "text": null }, { "code": null, "e": 1724, "s": 1716, "text": "Output:" }, { "code": null, "e": 2266, "s": 1724, "text": "SIGABRT: It is an error itself is detected by the program then this signal is generated using call to abort() function. This signal is also used by standard library to report an internal error. assert() function in C++ also uses abort() to generate this signal.Below is the program to illustrate the SIGBRT error:C++C++// C++ program to illustrate// the SIGBRT error #include <iostream>using namespace std; // Driver Codeint main(){ // Assigning excessive memory int a = 100000000000; int* arr = new int[a]; return 0;}Output:" }, { "code": null, "e": 2319, "s": 2266, "text": "Below is the program to illustrate the SIGBRT error:" }, { "code": null, "e": 2323, "s": 2319, "text": "C++" }, { "code": "// C++ program to illustrate// the SIGBRT error #include <iostream>using namespace std; // Driver Codeint main(){ // Assigning excessive memory int a = 100000000000; int* arr = new int[a]; return 0;}", "e": 2539, "s": 2323, "text": null }, { "code": null, "e": 2547, "s": 2539, "text": "Output:" }, { "code": null, "e": 3212, "s": 2547, "text": "NZEC: This error denotes “Non-Zero Exit Code”. For C users, this error will be generated if the main() method does not have a return 0 statement. Java/C++ users could generate this error if they throw an exception. Below are the possible reasons of getting NZEC error:Infinite Recursion or if you run out of stack memory.Negative array index is accessed.ArrayIndexOutOfBounds Exception.StringIndexOutOfBounds Exception.Below is the program to illustrate the NZEC error:PythonPython# Python program to illustrate# the NZEC Error # Driver Codeif __name__ == \"__main__\": arr = [1, 2] # Runtime Error # Array Index out of Bounds print(arr[2])Output:" }, { "code": null, "e": 3364, "s": 3212, "text": "Infinite Recursion or if you run out of stack memory.Negative array index is accessed.ArrayIndexOutOfBounds Exception.StringIndexOutOfBounds Exception." }, { "code": null, "e": 3418, "s": 3364, "text": "Infinite Recursion or if you run out of stack memory." }, { "code": null, "e": 3452, "s": 3418, "text": "Negative array index is accessed." }, { "code": null, "e": 3485, "s": 3452, "text": "ArrayIndexOutOfBounds Exception." }, { "code": null, "e": 3519, "s": 3485, "text": "StringIndexOutOfBounds Exception." }, { "code": null, "e": 3570, "s": 3519, "text": "Below is the program to illustrate the NZEC error:" }, { "code": null, "e": 3577, "s": 3570, "text": "Python" }, { "code": "# Python program to illustrate# the NZEC Error # Driver Codeif __name__ == \"__main__\": arr = [1, 2] # Runtime Error # Array Index out of Bounds print(arr[2])", "e": 3754, "s": 3577, "text": null }, { "code": null, "e": 3762, "s": 3754, "text": "Output:" }, { "code": null, "e": 4696, "s": 3762, "text": "SIGSEGV: This error is the most common error and is known as “Segmentation Fault“. It is generated when the program tries to access a memory that is not allowed to access or attempts to access a memory location in a way that is not allowed. List of some of the common reasons for segmentation faults are:Accessing an array out of bounds.Dereferencing NULL pointers.Dereferencing freed memory.Dereferencing uninitialized pointers.Incorrect use of the “&” (address of) and “*”(dereferencing) operators.Improper formatting specifiers in printf and scanf statements.Stack overflow.Writing to read-only memory.Below is the program to illustrate the SIGSEGV error:C++C++// C++ program to illustrate// the SIGSEGV error#include <bits/stdc++.h>using namespace std; // Function with infinite// Recursionvoid infiniteRecur(int a){ return infiniteRecur(a);} // Driver Codeint main(){ // Infinite Recursion infiniteRecur(5);}Output:" }, { "code": null, "e": 4998, "s": 4696, "text": "Accessing an array out of bounds.Dereferencing NULL pointers.Dereferencing freed memory.Dereferencing uninitialized pointers.Incorrect use of the “&” (address of) and “*”(dereferencing) operators.Improper formatting specifiers in printf and scanf statements.Stack overflow.Writing to read-only memory." }, { "code": null, "e": 5032, "s": 4998, "text": "Accessing an array out of bounds." }, { "code": null, "e": 5061, "s": 5032, "text": "Dereferencing NULL pointers." }, { "code": null, "e": 5089, "s": 5061, "text": "Dereferencing freed memory." }, { "code": null, "e": 5127, "s": 5089, "text": "Dereferencing uninitialized pointers." }, { "code": null, "e": 5199, "s": 5127, "text": "Incorrect use of the “&” (address of) and “*”(dereferencing) operators." }, { "code": null, "e": 5262, "s": 5199, "text": "Improper formatting specifiers in printf and scanf statements." }, { "code": null, "e": 5278, "s": 5262, "text": "Stack overflow." }, { "code": null, "e": 5307, "s": 5278, "text": "Writing to read-only memory." }, { "code": null, "e": 5361, "s": 5307, "text": "Below is the program to illustrate the SIGSEGV error:" }, { "code": null, "e": 5365, "s": 5361, "text": "C++" }, { "code": "// C++ program to illustrate// the SIGSEGV error#include <bits/stdc++.h>using namespace std; // Function with infinite// Recursionvoid infiniteRecur(int a){ return infiniteRecur(a);} // Driver Codeint main(){ // Infinite Recursion infiniteRecur(5);}", "e": 5628, "s": 5365, "text": null }, { "code": null, "e": 5636, "s": 5628, "text": "Output:" }, { "code": null, "e": 5759, "s": 5636, "text": "Avoid using variables that have not been initialized. These may be set to 0 on your system but not on the coding platform." }, { "code": null, "e": 5850, "s": 5759, "text": "Check every single occurrence of an array element and ensure that it is not out of bounds." }, { "code": null, "e": 5937, "s": 5850, "text": "Avoid declaring too much memory. Check for the memory limit specified in the question." }, { "code": null, "e": 6039, "s": 5937, "text": "Avoid declaring too much Stack Memory. Large arrays should be declared globally outside the function." }, { "code": null, "e": 6072, "s": 6039, "text": "Use return as the end statement." }, { "code": null, "e": 6120, "s": 6072, "text": "Avoid referencing free memory or null pointers." }, { "code": null, "e": 6129, "s": 6120, "text": "Articles" }, { "code": null, "e": 6153, "s": 6129, "text": "Competitive Programming" }, { "code": null, "e": 6172, "s": 6153, "text": "Difference Between" }, { "code": null, "e": 6187, "s": 6172, "text": "Program Output" } ]
Minimum labelled node to be removed from undirected Graph such that there is no cycle
09 Aug, 2021 Given an undirected graph of N nodes labelled from 1 to N, the task is to find the minimum labelled node that should be removed from the graph such that the resulting graph has no cycle. Note: If the initial graph has no cycle, i.e. no node needs to be removed, print -1. Examples: Input: N = 5, edges[][] = {{5, 1}, {5, 2}, {1, 2}, {2, 3}, {2, 4}} Output: 1 Explanation: If node 1 is removed, the resultant graph has no cycle. Similarly, the cycle can be avoided by removing node 2 also. Since we have to find the minimum labelled node, the answer is 1. Input: N = 5, edges[][] = {{4, 5}, {4, 1}, {4, 2}, {4, 3}, {5, 1}, {5, 2}} Output: 4 Naive Approach: The naive approach for this problem would be to remove each vertex individually and check whether the resulting graph has a cycle or not. The time complexity for this approach is quadratic. Efficient Approach: The idea is to apply depth-first search on the given graph and observing the dfs tree formed. A Back Edge is referred to as the edge that is not part of the constructed DFS tree and is an edge between some node v and one of the ancestors of v. Clearly all those edges of the graph which are not a part of the DFS tree are back edges. If there are no back edges in the graph, then the graph has no cycle. So, the answer will be -1 in this case. If there are back edges in the graph, then we need to find the minimum edge. In order to do this, we need to check if the cycle is removed on removing a specific edge from the graph. Therefore, let v be a vertex which we are currently checking. Therefore, the following conditions must be followed by vertex v such that on removing, it would lead to no cycle: v must lie on the tree path connecting the endpoints of each back edge in the graph. Proof: Suppose there exists some back edge x-y, such that v doesn’t lie on the tree path. If we remove v, we would still be able to traverse from x to y, and back to x via the back edge, indicating that the cycle is not removed. The subtree of v must have at-most one back edge to any ancestor of v. Proof: Let the subtree S has to back edges w-x and y-z such that w and y are in S and x and z are ancestors of v. If we remove v, clearly a cycle still exists consisting of the path between w to y, the path from x to z and the two back edges w-x and y-z, i.e. cycle is not removed. Therefore, the idea is to keep a track of back edges, and an indicator for the number of back edges in the subtree of a node to any of its ancestors. To keep a track of back edges we will use a modified DFS graph colouring algorithm. In order to check if the subtree v has at-most one back edge to any ancestor of v or not, we implement dfs such that it returns the depth of two highest edges from the subtree of v. We maintain an array where every index ‘i’ in the array stores if the condition 2 from the above is satisfied by the node ‘i’ or not. Similarly, two arrays are implemented, one for the child and another for the parent to see if the node v lies on the tree path connecting the endpoints. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ implementation to find the// minimum labelled node to be// removed such that there is no// cycle in the undirected graph #include <bits/stdc++.h> using namespace std; const int MAX = 100005; int totBackEdges;int countAdj[MAX], small[MAX]; // Variables to store if a node V has// at-most one back edge and store the// depth of the node for the edgeint isPossible[MAX], depth[MAX]; vector<int> adj[MAX];int vis[MAX]; // Function to swap the pairs of the graphvoid change(pair<int, int>& p, int x){ // If the second value is // greater than x if (p.second > x) p.second = x; // Put the pair in the ascending // order internally if (p.first > p.second) swap(p.first, p.second);} // Function to perform the DFSpair<int, int> dfs(int v, int p = -1, int de = 0){ // Initialise with the large value pair<int, int> answer(100000000, 100000000); // Storing the depth of this vertex depth[v] = de; // Mark the vertex as visited vis[v] = 1; isPossible[v] = 1; // Iterating through the graph for (int u : adj[v]) { // If the node is a child node if (u ^ p) { // If the child node is unvisited if (!vis[u]) { // Move to the child and increase // the depth auto x = dfs(u, v, de + 1); // increase according to algorithm small[v] += small[u]; change(answer, x.second); change(answer, x.first); // If the node is not having // exactly K backedges if (x.second < de) isPossible[v] = 0; } // If the child is already visited // and in current dfs // (because colour is 1) // then this is a back edge else if (vis[u] == 1) { totBackEdges++; // Increase the countAdj values countAdj[v]++; countAdj[u]++; small[p]++; small[u]--; change(answer, depth[u]); } } } // Colour this vertex 2 as // we are exiting out of // dfs for this node vis[v] = 2; return answer;} // Function to find the minimum labelled// node to be removed such that// there is no cycle in the undirected graphint minNodetoRemove( int n, vector<pair<int, int> > edges){ // Construct the graph for (int i = 0; i < edges.size(); i++) { adj[edges[i].first] .push_back(edges[i].second); adj[edges[i].second] .push_back(edges[i].first); } // Mark visited as false for each node memset(vis, 0, sizeof(vis)); totBackEdges = 0; // Apply dfs on all unmarked nodes for (int v = 1; v <= n; v++) { if (!vis[v]) dfs(v); } // If no backedges in the initial graph // this means that there is no cycle // So, return -1 if (totBackEdges == 0) return -1; int node = -1; // Iterate through the vertices and // return the first node that // satisfies the condition for (int v = 1; v <= n; v++) { // Check whether the count sum of // small[v] and count is the same as // the total back edges and // if the vertex v can be removed if (countAdj[v] + small[v] == totBackEdges && isPossible[v]) { node = v; } if (node != -1) break; } return node;} // Driver codeint main(){ int N = 5; vector<pair<int, int> > edges; edges.push_back(make_pair(5, 1)); edges.push_back(make_pair(5, 2)); edges.push_back(make_pair(1, 2)); edges.push_back(make_pair(2, 3)); edges.push_back(make_pair(2, 4)); cout << minNodetoRemove(N, edges);} // Java implementation to find the// minimum labelled node to be// removed such that there is no// cycle in the undirected graphimport java.util.ArrayList;import java.util.Arrays; class Pair{ int first, second; public Pair(int first, int second) { this.first = first; this.second = second; }} class GFG{ static final int MAX = 100005; static int totBackEdges;static int[] countAdj = new int[MAX];static int[] small = new int[MAX]; // Variables to store if a node V has// at-most one back edge and store the// depth of the node for the edgestatic int[] isPossible = new int[MAX];static int[] depth = new int[MAX]; @SuppressWarnings("unchecked")static ArrayList<Integer>[] adj = new ArrayList[MAX]; static int[] vis = new int[MAX]; // Function to swap the pairs of the graphstatic void change(Pair p, int x){ // If the second value is // greater than x if (p.second > x) p.second = x; // Put the Pair in the ascending // order internally if (p.first > p.second) { int tmp = p.first; p.first = p.second; p.second = tmp; }} // Function to perform the DFSstatic Pair dfs(int v, int p, int de){ // Initialise with the large value Pair answer = new Pair(100000000, 100000000); // Storing the depth of this vertex depth[v] = de; // Mark the vertex as visited vis[v] = 1; isPossible[v] = 1; // Iterating through the graph for(int u : adj[v]) { // If the node is a child node if ((u ^ p) != 0) { // If the child node is unvisited if (vis[u] == 0) { // Move to the child and increase // the depth Pair x = dfs(u, v, de + 1); // increase according to algorithm small[v] += small[u]; change(answer, x.second); change(answer, x.first); // If the node is not having // exactly K backedges if (x.second < de) isPossible[v] = 0; } // If the child is already visited // and in current dfs // (because colour is 1) // then this is a back edge else if (vis[u] == 1) { totBackEdges++; // Increase the countAdj values countAdj[v]++; countAdj[u]++; small[p]++; small[u]--; change(answer, depth[u]); } } } // Colour this vertex 2 as // we are exiting out of // dfs for this node vis[v] = 2; return answer;} // Function to find the minimum labelled// node to be removed such that// there is no cycle in the undirected graphstatic int minNodetoRemove(int n, ArrayList<Pair> edges){ // Construct the graph for(int i = 0; i < edges.size(); i++) { adj[edges.get(i).first].add( edges.get(i).second); adj[edges.get(i).second].add( edges.get(i).first); } // Mark visited as false for each node Arrays.fill(vis, 0); totBackEdges = 0; // Apply dfs on all unmarked nodes for(int v = 1; v <= n; v++) { if (vis[v] == 0) dfs(v, -1, 0); } // If no backedges in the initial graph // this means that there is no cycle // So, return -1 if (totBackEdges == 0) return -1; int node = -1; // Iterate through the vertices and // return the first node that // satisfies the condition for(int v = 1; v <= n; v++) { // Check whether the count sum of // small[v] and count is the same as // the total back edges and // if the vertex v can be removed if ((countAdj[v] + small[v] == totBackEdges) && isPossible[v] != 0) { node = v; } if (node != -1) break; } return node;} // Driver codepublic static void main(String[] args){ int N = 5; ArrayList<Pair> edges = new ArrayList<>(); for(int i = 0; i < MAX; i++) { adj[i] = new ArrayList<>(); } edges.add(new Pair(5, 1)); edges.add(new Pair(5, 2)); edges.add(new Pair(1, 2)); edges.add(new Pair(2, 3)); edges.add(new Pair(2, 4)); System.out.println(minNodetoRemove(N, edges));}} // This code is contributed by sanjeev2552 # Python3 implementation to find the# minimum labelled node to be# removed such that there is no# cycle in the undirected graph MAX = 100005; totBackEdges = 0countAdj = [0 for i in range(MAX)]small = [0 for i in range(MAX)] # Variables to store if a node V has# at-most one back edge and store the# depth of the node for the edgeisPossible = [0 for i in range(MAX)]depth = [0 for i in range(MAX)]adj = [[] for i in range(MAX)]vis = [0 for i in range(MAX)] # Function to swap the pairs of the graphdef change(p, x): # If the second value is # greater than x if (p[1] > x): p[1] = x; # Put the pair in the ascending # order internally if (p[0] > p[1]): tmp = p[0]; p[0] = p[1]; p[1] = tmp; # Function to perform the DFSdef dfs(v, p = -1, de = 0): global vis, totBackEdges # Initialise with the large value answer = [100000000, 100000000] # Storing the depth of this vertex depth[v] = de; # Mark the vertex as visited vis[v] = 1; isPossible[v] = 1; # Iterating through the graph for u in adj[v]: # If the node is a child node if ((u ^ p) != 0): # If the child node is unvisited if (vis[u] == 0): # Move to the child and increase # the depth x = dfs(u, v, de + 1); # increase according to algorithm small[v] += small[u]; change(answer, x[1]); change(answer, x[0]); # If the node is not having # exactly K backedges if (x[1] < de): isPossible[v] = 0; # If the child is already visited # and in current dfs # (because colour is 1) # then this is a back edge elif (vis[u] == 1): totBackEdges += 1 # Increase the countAdj values countAdj[v] += 1 countAdj[u] += 1 small[p] += 1 small[u] -= 1 change(answer, depth[u]); # Colour this vertex 2 as # we are exiting out of # dfs for this node vis[v] = 2; return answer; # Function to find the minimum labelled# node to be removed such that# there is no cycle in the undirected graphdef minNodetoRemove( n, edges): # Construct the graph for i in range(len(edges)): adj[edges[i][0]].append(edges[i][1]); adj[edges[i][1]].append(edges[i][0]); global vis, totBackEdges # Mark visited as false for each node vis = [0 for i in range(len(vis))] totBackEdges = 0; # Apply dfs on all unmarked nodes for v in range(1, n + 1): if (vis[v] == 0): dfs(v); # If no backedges in the initial graph # this means that there is no cycle # So, return -1 if (totBackEdges == 0): return -1; node = -1; # Iterate through the vertices and # return the first node that # satisfies the condition for v in range(1, n + 1): # Check whether the count sum of # small[v] and count is the same as # the total back edges and # if the vertex v can be removed if ((countAdj[v] + small[v] == totBackEdges) and isPossible[v] != 0): node = v; if (node != -1): break; return node; # Driver codeif __name__=='__main__': N = 5; edges = [] edges.append([5, 1]); edges.append([5, 2]); edges.append([1, 2]); edges.append([2, 3]); edges.append([2, 4]); print(minNodetoRemove(N, edges)); # This code is contributed by Pratham76 // C# implementation to find the// minimum labelled node to be// removed such that there is no// cycle in the undirected graph using System;using System.Collections;using System.Collections.Generic; class GFG{ static int MAX = 100005; static int totBackEdges;static int []countAdj = new int[MAX];static int []small = new int[MAX]; // Variables to store if a node V has// at-most one back edge and store the// depth of the node for the edgestatic int []isPossible = new int[MAX];static int []depth = new int[MAX]; static ArrayList adj = new ArrayList(); static int []vis = new int[MAX]; class pair{ public int first, second; public pair(int first, int second) { this.first = first; this.second = second; }} // Function to swap the pairs of the graphstatic void change(ref pair p, int x){ // If the second value is // greater than x if (p.second > x) p.second = x; // Put the pair in the ascending // order internally if (p.first > p.second) { int tmp = p.first; p.first = p.second; p.second = tmp; }} // Function to perform the DFSstatic pair dfs(int v, int p = -1, int de = 0){ // Initialise with the large value pair answer = new pair(100000000, 100000000); // Storing the depth of this vertex depth[v] = de; // Mark the vertex as visited vis[v] = 1; isPossible[v] = 1; // Iterating through the graph foreach (int u in (ArrayList)adj[v]) { // If the node is a child node if ((u ^ p) != 0) { // If the child node is unvisited if (vis[u] == 0) { // Move to the child and increase // the depth pair x = dfs(u, v, de + 1); // increase according to algorithm small[v] += small[u]; change(ref answer, x.second); change(ref answer, x.first); // If the node is not having // exactly K backedges if (x.second < de) isPossible[v] = 0; } // If the child is already visited // and in current dfs // (because colour is 1) // then this is a back edge else if (vis[u] == 1) { totBackEdges++; // Increase the countAdj values countAdj[v]++; countAdj[u]++; small[p]++; small[u]--; change(ref answer, depth[u]); } } } // Colour this vertex 2 as // we are exiting out of // dfs for this node vis[v] = 2; return answer;} // Function to find the minimum labelled// node to be removed such that// there is no cycle in the undirected graphstatic int minNodetoRemove( int n, ArrayList edges){ // Construct the graph for (int i = 0; i < edges.Count; i++) { ((ArrayList)adj[((pair)edges[i]).first]) .Add(((pair)edges[i]).second); ((ArrayList)adj[((pair)edges[i]).second]) .Add(((pair)edges[i]).first); } // Mark visited as false for each node Array.Fill(vis, 0); totBackEdges = 0; // Apply dfs on all unmarked nodes for (int v = 1; v <= n; v++) { if (vis[v] == 0) dfs(v); } // If no backedges in the initial graph // this means that there is no cycle // So, return -1 if (totBackEdges == 0) return -1; int node = -1; // Iterate through the vertices and // return the first node that // satisfies the condition for (int v = 1; v <= n; v++) { // Check whether the count sum of // small[v] and count is the same as // the total back edges and // if the vertex v can be removed if ((countAdj[v] + small[v] == totBackEdges) && isPossible[v] != 0) { node = v; } if (node != -1) break; } return node;} // Driver codestatic void Main(){ int N = 5; ArrayList edges = new ArrayList(); for(int i = 0; i < MAX; i++) { adj.Add(new ArrayList()); } edges.Add(new pair(5, 1)); edges.Add(new pair(5, 2)); edges.Add(new pair(1, 2)); edges.Add(new pair(2, 3)); edges.Add(new pair(2, 4)); Console.Write(minNodetoRemove(N, edges)); }} // This code is contributed by rutvik_56 <script> // Javascript implementation to find the// minimum labelled node to be// removed such that there is no// cycle in the undirected graphvar MAX = 100005;var totBackEdges;var countAdj = Array(MAX).fill(0);var small = Array(MAX).fill(0); // Variables to store if a node V has// at-most one back edge and store the// depth of the node for the edgevar isPossible = Array(MAX).fill(0);var depth = Array(MAX).fill(0); var adj = [];var vis = Array(MAX).fill(0); class pair{ constructor(first, second) { this.first = first; this.second = second; }} // Function to swap the pairs of the graphfunction change(p, x){ // If the second value is // greater than x if (p.second > x) p.second = x; // Put the pair in the ascending // order internally if (p.first > p.second) { var tmp = p.first; p.first = p.second; p.second = tmp; }} // Function to perform the DFSfunction dfs(v, p = -1, de = 0){ // Initialise with the large value var answer = new pair(100000000, 100000000); // Storing the depth of this vertex depth[v] = de; // Mark the vertex as visited vis[v] = 1; isPossible[v] = 1; // Iterating through the graph for(var u of adj[v]) { // If the node is a child node if ((u ^ p) != 0) { // If the child node is unvisited if (vis[u] == 0) { // Move to the child and increase // the depth var x = dfs(u, v, de + 1); // Increase according to algorithm small[v] += small[u]; change(answer, x.second); change(answer, x.first); // If the node is not having // exactly K backedges if (x.second < de) isPossible[v] = 0; } // If the child is already visited // and in current dfs // (because colour is 1) // then this is a back edge else if (vis[u] == 1) { totBackEdges++; // Increase the countAdj values countAdj[v]++; countAdj[u]++; small[p]++; small[u]--; change(answer, depth[u]); } } } // Colour this vertex 2 as // we are exiting out of // dfs for this node vis[v] = 2; return answer;} // Function to find the minimum labelled// node to be removed such that// there is no cycle in the undirected graphfunction minNodetoRemove(n, edges){ // Construct the graph for(var i = 0; i < edges.length; i++) { (adj[(edges[i]).first]).push( (edges[i]).second); (adj[(edges[i]).second]).push( (edges[i]).first); } // Mark visited as false for each node vis = Array(MAX).fill(0); totBackEdges = 0; // Apply dfs on all unmarked nodes for(var v = 1; v <= n; v++) { if (vis[v] == 0) dfs(v); } // If no backedges in the initial graph // this means that there is no cycle // So, return -1 if (totBackEdges == 0) return -1; var node = -1; // Iterate through the vertices and // return the first node that // satisfies the condition for(var v = 1; v <= n; v++) { // Check whether the count sum of // small[v] and count is the same as // the total back edges and // if the vertex v can be removed if ((countAdj[v] + small[v] == totBackEdges) && isPossible[v] != 0) { node = v; } if (node != -1) break; } return node;} // Driver codevar N = 5;var edges = [];for(var i = 0; i < MAX; i++){ adj.push(new Array());} edges.push(new pair(5, 1));edges.push(new pair(5, 2));edges.push(new pair(1, 2));edges.push(new pair(2, 3));edges.push(new pair(2, 4)); document.write(minNodetoRemove(N, edges)); // This code is contributed by rrrtnx </script> 1 Time Complexity: O(N + M), where N is the number of nodes and M is the number of edges.Auxiliary Space: O(N + M). rutvik_56 sanjeev2552 khushboogoyal499 pratham76 rrrtnx pankajsharmagfg DFS Graph Coloring graph-cycle Algorithms Competitive Programming Dynamic Programming Graph Dynamic Programming DFS Graph Algorithms Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. DSA Sheet by Love Babbar SDE SHEET - A Complete Guide for SDE Preparation What is Hashing | A Complete Tutorial Find if there is a path between two vertices in an undirected graph CPU Scheduling in Operating Systems Competitive Programming - A Complete Guide Practice for cracking any coding interview Modulo 10^9+7 (1000000007) Arrow operator -> in C/C++ with Examples Fast I/O for Competitive Programming
[ { "code": null, "e": 54, "s": 26, "text": "\n09 Aug, 2021" }, { "code": null, "e": 242, "s": 54, "text": "Given an undirected graph of N nodes labelled from 1 to N, the task is to find the minimum labelled node that should be removed from the graph such that the resulting graph has no cycle. " }, { "code": null, "e": 327, "s": 242, "text": "Note: If the initial graph has no cycle, i.e. no node needs to be removed, print -1." }, { "code": null, "e": 339, "s": 327, "text": "Examples: " }, { "code": null, "e": 612, "s": 339, "text": "Input: N = 5, edges[][] = {{5, 1}, {5, 2}, {1, 2}, {2, 3}, {2, 4}} Output: 1 Explanation: If node 1 is removed, the resultant graph has no cycle. Similarly, the cycle can be avoided by removing node 2 also. Since we have to find the minimum labelled node, the answer is 1." }, { "code": null, "e": 699, "s": 612, "text": "Input: N = 5, edges[][] = {{4, 5}, {4, 1}, {4, 2}, {4, 3}, {5, 1}, {5, 2}} Output: 4 " }, { "code": null, "e": 906, "s": 699, "text": "Naive Approach: The naive approach for this problem would be to remove each vertex individually and check whether the resulting graph has a cycle or not. The time complexity for this approach is quadratic. " }, { "code": null, "e": 1022, "s": 906, "text": "Efficient Approach: The idea is to apply depth-first search on the given graph and observing the dfs tree formed. " }, { "code": null, "e": 1172, "s": 1022, "text": "A Back Edge is referred to as the edge that is not part of the constructed DFS tree and is an edge between some node v and one of the ancestors of v." }, { "code": null, "e": 1262, "s": 1172, "text": "Clearly all those edges of the graph which are not a part of the DFS tree are back edges." }, { "code": null, "e": 1372, "s": 1262, "text": "If there are no back edges in the graph, then the graph has no cycle. So, the answer will be -1 in this case." }, { "code": null, "e": 1734, "s": 1372, "text": "If there are back edges in the graph, then we need to find the minimum edge. In order to do this, we need to check if the cycle is removed on removing a specific edge from the graph. Therefore, let v be a vertex which we are currently checking. Therefore, the following conditions must be followed by vertex v such that on removing, it would lead to no cycle: " }, { "code": null, "e": 2048, "s": 1734, "text": "v must lie on the tree path connecting the endpoints of each back edge in the graph. Proof: Suppose there exists some back edge x-y, such that v doesn’t lie on the tree path. If we remove v, we would still be able to traverse from x to y, and back to x via the back edge, indicating that the cycle is not removed." }, { "code": null, "e": 2401, "s": 2048, "text": "The subtree of v must have at-most one back edge to any ancestor of v. Proof: Let the subtree S has to back edges w-x and y-z such that w and y are in S and x and z are ancestors of v. If we remove v, clearly a cycle still exists consisting of the path between w to y, the path from x to z and the two back edges w-x and y-z, i.e. cycle is not removed." }, { "code": null, "e": 3105, "s": 2401, "text": "Therefore, the idea is to keep a track of back edges, and an indicator for the number of back edges in the subtree of a node to any of its ancestors. To keep a track of back edges we will use a modified DFS graph colouring algorithm. In order to check if the subtree v has at-most one back edge to any ancestor of v or not, we implement dfs such that it returns the depth of two highest edges from the subtree of v. We maintain an array where every index ‘i’ in the array stores if the condition 2 from the above is satisfied by the node ‘i’ or not. Similarly, two arrays are implemented, one for the child and another for the parent to see if the node v lies on the tree path connecting the endpoints. " }, { "code": null, "e": 3157, "s": 3105, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 3161, "s": 3157, "text": "C++" }, { "code": null, "e": 3166, "s": 3161, "text": "Java" }, { "code": null, "e": 3174, "s": 3166, "text": "Python3" }, { "code": null, "e": 3177, "s": 3174, "text": "C#" }, { "code": null, "e": 3188, "s": 3177, "text": "Javascript" }, { "code": "// C++ implementation to find the// minimum labelled node to be// removed such that there is no// cycle in the undirected graph #include <bits/stdc++.h> using namespace std; const int MAX = 100005; int totBackEdges;int countAdj[MAX], small[MAX]; // Variables to store if a node V has// at-most one back edge and store the// depth of the node for the edgeint isPossible[MAX], depth[MAX]; vector<int> adj[MAX];int vis[MAX]; // Function to swap the pairs of the graphvoid change(pair<int, int>& p, int x){ // If the second value is // greater than x if (p.second > x) p.second = x; // Put the pair in the ascending // order internally if (p.first > p.second) swap(p.first, p.second);} // Function to perform the DFSpair<int, int> dfs(int v, int p = -1, int de = 0){ // Initialise with the large value pair<int, int> answer(100000000, 100000000); // Storing the depth of this vertex depth[v] = de; // Mark the vertex as visited vis[v] = 1; isPossible[v] = 1; // Iterating through the graph for (int u : adj[v]) { // If the node is a child node if (u ^ p) { // If the child node is unvisited if (!vis[u]) { // Move to the child and increase // the depth auto x = dfs(u, v, de + 1); // increase according to algorithm small[v] += small[u]; change(answer, x.second); change(answer, x.first); // If the node is not having // exactly K backedges if (x.second < de) isPossible[v] = 0; } // If the child is already visited // and in current dfs // (because colour is 1) // then this is a back edge else if (vis[u] == 1) { totBackEdges++; // Increase the countAdj values countAdj[v]++; countAdj[u]++; small[p]++; small[u]--; change(answer, depth[u]); } } } // Colour this vertex 2 as // we are exiting out of // dfs for this node vis[v] = 2; return answer;} // Function to find the minimum labelled// node to be removed such that// there is no cycle in the undirected graphint minNodetoRemove( int n, vector<pair<int, int> > edges){ // Construct the graph for (int i = 0; i < edges.size(); i++) { adj[edges[i].first] .push_back(edges[i].second); adj[edges[i].second] .push_back(edges[i].first); } // Mark visited as false for each node memset(vis, 0, sizeof(vis)); totBackEdges = 0; // Apply dfs on all unmarked nodes for (int v = 1; v <= n; v++) { if (!vis[v]) dfs(v); } // If no backedges in the initial graph // this means that there is no cycle // So, return -1 if (totBackEdges == 0) return -1; int node = -1; // Iterate through the vertices and // return the first node that // satisfies the condition for (int v = 1; v <= n; v++) { // Check whether the count sum of // small[v] and count is the same as // the total back edges and // if the vertex v can be removed if (countAdj[v] + small[v] == totBackEdges && isPossible[v]) { node = v; } if (node != -1) break; } return node;} // Driver codeint main(){ int N = 5; vector<pair<int, int> > edges; edges.push_back(make_pair(5, 1)); edges.push_back(make_pair(5, 2)); edges.push_back(make_pair(1, 2)); edges.push_back(make_pair(2, 3)); edges.push_back(make_pair(2, 4)); cout << minNodetoRemove(N, edges);}", "e": 6978, "s": 3188, "text": null }, { "code": "// Java implementation to find the// minimum labelled node to be// removed such that there is no// cycle in the undirected graphimport java.util.ArrayList;import java.util.Arrays; class Pair{ int first, second; public Pair(int first, int second) { this.first = first; this.second = second; }} class GFG{ static final int MAX = 100005; static int totBackEdges;static int[] countAdj = new int[MAX];static int[] small = new int[MAX]; // Variables to store if a node V has// at-most one back edge and store the// depth of the node for the edgestatic int[] isPossible = new int[MAX];static int[] depth = new int[MAX]; @SuppressWarnings(\"unchecked\")static ArrayList<Integer>[] adj = new ArrayList[MAX]; static int[] vis = new int[MAX]; // Function to swap the pairs of the graphstatic void change(Pair p, int x){ // If the second value is // greater than x if (p.second > x) p.second = x; // Put the Pair in the ascending // order internally if (p.first > p.second) { int tmp = p.first; p.first = p.second; p.second = tmp; }} // Function to perform the DFSstatic Pair dfs(int v, int p, int de){ // Initialise with the large value Pair answer = new Pair(100000000, 100000000); // Storing the depth of this vertex depth[v] = de; // Mark the vertex as visited vis[v] = 1; isPossible[v] = 1; // Iterating through the graph for(int u : adj[v]) { // If the node is a child node if ((u ^ p) != 0) { // If the child node is unvisited if (vis[u] == 0) { // Move to the child and increase // the depth Pair x = dfs(u, v, de + 1); // increase according to algorithm small[v] += small[u]; change(answer, x.second); change(answer, x.first); // If the node is not having // exactly K backedges if (x.second < de) isPossible[v] = 0; } // If the child is already visited // and in current dfs // (because colour is 1) // then this is a back edge else if (vis[u] == 1) { totBackEdges++; // Increase the countAdj values countAdj[v]++; countAdj[u]++; small[p]++; small[u]--; change(answer, depth[u]); } } } // Colour this vertex 2 as // we are exiting out of // dfs for this node vis[v] = 2; return answer;} // Function to find the minimum labelled// node to be removed such that// there is no cycle in the undirected graphstatic int minNodetoRemove(int n, ArrayList<Pair> edges){ // Construct the graph for(int i = 0; i < edges.size(); i++) { adj[edges.get(i).first].add( edges.get(i).second); adj[edges.get(i).second].add( edges.get(i).first); } // Mark visited as false for each node Arrays.fill(vis, 0); totBackEdges = 0; // Apply dfs on all unmarked nodes for(int v = 1; v <= n; v++) { if (vis[v] == 0) dfs(v, -1, 0); } // If no backedges in the initial graph // this means that there is no cycle // So, return -1 if (totBackEdges == 0) return -1; int node = -1; // Iterate through the vertices and // return the first node that // satisfies the condition for(int v = 1; v <= n; v++) { // Check whether the count sum of // small[v] and count is the same as // the total back edges and // if the vertex v can be removed if ((countAdj[v] + small[v] == totBackEdges) && isPossible[v] != 0) { node = v; } if (node != -1) break; } return node;} // Driver codepublic static void main(String[] args){ int N = 5; ArrayList<Pair> edges = new ArrayList<>(); for(int i = 0; i < MAX; i++) { adj[i] = new ArrayList<>(); } edges.add(new Pair(5, 1)); edges.add(new Pair(5, 2)); edges.add(new Pair(1, 2)); edges.add(new Pair(2, 3)); edges.add(new Pair(2, 4)); System.out.println(minNodetoRemove(N, edges));}} // This code is contributed by sanjeev2552", "e": 11401, "s": 6978, "text": null }, { "code": "# Python3 implementation to find the# minimum labelled node to be# removed such that there is no# cycle in the undirected graph MAX = 100005; totBackEdges = 0countAdj = [0 for i in range(MAX)]small = [0 for i in range(MAX)] # Variables to store if a node V has# at-most one back edge and store the# depth of the node for the edgeisPossible = [0 for i in range(MAX)]depth = [0 for i in range(MAX)]adj = [[] for i in range(MAX)]vis = [0 for i in range(MAX)] # Function to swap the pairs of the graphdef change(p, x): # If the second value is # greater than x if (p[1] > x): p[1] = x; # Put the pair in the ascending # order internally if (p[0] > p[1]): tmp = p[0]; p[0] = p[1]; p[1] = tmp; # Function to perform the DFSdef dfs(v, p = -1, de = 0): global vis, totBackEdges # Initialise with the large value answer = [100000000, 100000000] # Storing the depth of this vertex depth[v] = de; # Mark the vertex as visited vis[v] = 1; isPossible[v] = 1; # Iterating through the graph for u in adj[v]: # If the node is a child node if ((u ^ p) != 0): # If the child node is unvisited if (vis[u] == 0): # Move to the child and increase # the depth x = dfs(u, v, de + 1); # increase according to algorithm small[v] += small[u]; change(answer, x[1]); change(answer, x[0]); # If the node is not having # exactly K backedges if (x[1] < de): isPossible[v] = 0; # If the child is already visited # and in current dfs # (because colour is 1) # then this is a back edge elif (vis[u] == 1): totBackEdges += 1 # Increase the countAdj values countAdj[v] += 1 countAdj[u] += 1 small[p] += 1 small[u] -= 1 change(answer, depth[u]); # Colour this vertex 2 as # we are exiting out of # dfs for this node vis[v] = 2; return answer; # Function to find the minimum labelled# node to be removed such that# there is no cycle in the undirected graphdef minNodetoRemove( n, edges): # Construct the graph for i in range(len(edges)): adj[edges[i][0]].append(edges[i][1]); adj[edges[i][1]].append(edges[i][0]); global vis, totBackEdges # Mark visited as false for each node vis = [0 for i in range(len(vis))] totBackEdges = 0; # Apply dfs on all unmarked nodes for v in range(1, n + 1): if (vis[v] == 0): dfs(v); # If no backedges in the initial graph # this means that there is no cycle # So, return -1 if (totBackEdges == 0): return -1; node = -1; # Iterate through the vertices and # return the first node that # satisfies the condition for v in range(1, n + 1): # Check whether the count sum of # small[v] and count is the same as # the total back edges and # if the vertex v can be removed if ((countAdj[v] + small[v] == totBackEdges) and isPossible[v] != 0): node = v; if (node != -1): break; return node; # Driver codeif __name__=='__main__': N = 5; edges = [] edges.append([5, 1]); edges.append([5, 2]); edges.append([1, 2]); edges.append([2, 3]); edges.append([2, 4]); print(minNodetoRemove(N, edges)); # This code is contributed by Pratham76", "e": 15081, "s": 11401, "text": null }, { "code": "// C# implementation to find the// minimum labelled node to be// removed such that there is no// cycle in the undirected graph using System;using System.Collections;using System.Collections.Generic; class GFG{ static int MAX = 100005; static int totBackEdges;static int []countAdj = new int[MAX];static int []small = new int[MAX]; // Variables to store if a node V has// at-most one back edge and store the// depth of the node for the edgestatic int []isPossible = new int[MAX];static int []depth = new int[MAX]; static ArrayList adj = new ArrayList(); static int []vis = new int[MAX]; class pair{ public int first, second; public pair(int first, int second) { this.first = first; this.second = second; }} // Function to swap the pairs of the graphstatic void change(ref pair p, int x){ // If the second value is // greater than x if (p.second > x) p.second = x; // Put the pair in the ascending // order internally if (p.first > p.second) { int tmp = p.first; p.first = p.second; p.second = tmp; }} // Function to perform the DFSstatic pair dfs(int v, int p = -1, int de = 0){ // Initialise with the large value pair answer = new pair(100000000, 100000000); // Storing the depth of this vertex depth[v] = de; // Mark the vertex as visited vis[v] = 1; isPossible[v] = 1; // Iterating through the graph foreach (int u in (ArrayList)adj[v]) { // If the node is a child node if ((u ^ p) != 0) { // If the child node is unvisited if (vis[u] == 0) { // Move to the child and increase // the depth pair x = dfs(u, v, de + 1); // increase according to algorithm small[v] += small[u]; change(ref answer, x.second); change(ref answer, x.first); // If the node is not having // exactly K backedges if (x.second < de) isPossible[v] = 0; } // If the child is already visited // and in current dfs // (because colour is 1) // then this is a back edge else if (vis[u] == 1) { totBackEdges++; // Increase the countAdj values countAdj[v]++; countAdj[u]++; small[p]++; small[u]--; change(ref answer, depth[u]); } } } // Colour this vertex 2 as // we are exiting out of // dfs for this node vis[v] = 2; return answer;} // Function to find the minimum labelled// node to be removed such that// there is no cycle in the undirected graphstatic int minNodetoRemove( int n, ArrayList edges){ // Construct the graph for (int i = 0; i < edges.Count; i++) { ((ArrayList)adj[((pair)edges[i]).first]) .Add(((pair)edges[i]).second); ((ArrayList)adj[((pair)edges[i]).second]) .Add(((pair)edges[i]).first); } // Mark visited as false for each node Array.Fill(vis, 0); totBackEdges = 0; // Apply dfs on all unmarked nodes for (int v = 1; v <= n; v++) { if (vis[v] == 0) dfs(v); } // If no backedges in the initial graph // this means that there is no cycle // So, return -1 if (totBackEdges == 0) return -1; int node = -1; // Iterate through the vertices and // return the first node that // satisfies the condition for (int v = 1; v <= n; v++) { // Check whether the count sum of // small[v] and count is the same as // the total back edges and // if the vertex v can be removed if ((countAdj[v] + small[v] == totBackEdges) && isPossible[v] != 0) { node = v; } if (node != -1) break; } return node;} // Driver codestatic void Main(){ int N = 5; ArrayList edges = new ArrayList(); for(int i = 0; i < MAX; i++) { adj.Add(new ArrayList()); } edges.Add(new pair(5, 1)); edges.Add(new pair(5, 2)); edges.Add(new pair(1, 2)); edges.Add(new pair(2, 3)); edges.Add(new pair(2, 4)); Console.Write(minNodetoRemove(N, edges)); }} // This code is contributed by rutvik_56", "e": 19418, "s": 15081, "text": null }, { "code": "<script> // Javascript implementation to find the// minimum labelled node to be// removed such that there is no// cycle in the undirected graphvar MAX = 100005;var totBackEdges;var countAdj = Array(MAX).fill(0);var small = Array(MAX).fill(0); // Variables to store if a node V has// at-most one back edge and store the// depth of the node for the edgevar isPossible = Array(MAX).fill(0);var depth = Array(MAX).fill(0); var adj = [];var vis = Array(MAX).fill(0); class pair{ constructor(first, second) { this.first = first; this.second = second; }} // Function to swap the pairs of the graphfunction change(p, x){ // If the second value is // greater than x if (p.second > x) p.second = x; // Put the pair in the ascending // order internally if (p.first > p.second) { var tmp = p.first; p.first = p.second; p.second = tmp; }} // Function to perform the DFSfunction dfs(v, p = -1, de = 0){ // Initialise with the large value var answer = new pair(100000000, 100000000); // Storing the depth of this vertex depth[v] = de; // Mark the vertex as visited vis[v] = 1; isPossible[v] = 1; // Iterating through the graph for(var u of adj[v]) { // If the node is a child node if ((u ^ p) != 0) { // If the child node is unvisited if (vis[u] == 0) { // Move to the child and increase // the depth var x = dfs(u, v, de + 1); // Increase according to algorithm small[v] += small[u]; change(answer, x.second); change(answer, x.first); // If the node is not having // exactly K backedges if (x.second < de) isPossible[v] = 0; } // If the child is already visited // and in current dfs // (because colour is 1) // then this is a back edge else if (vis[u] == 1) { totBackEdges++; // Increase the countAdj values countAdj[v]++; countAdj[u]++; small[p]++; small[u]--; change(answer, depth[u]); } } } // Colour this vertex 2 as // we are exiting out of // dfs for this node vis[v] = 2; return answer;} // Function to find the minimum labelled// node to be removed such that// there is no cycle in the undirected graphfunction minNodetoRemove(n, edges){ // Construct the graph for(var i = 0; i < edges.length; i++) { (adj[(edges[i]).first]).push( (edges[i]).second); (adj[(edges[i]).second]).push( (edges[i]).first); } // Mark visited as false for each node vis = Array(MAX).fill(0); totBackEdges = 0; // Apply dfs on all unmarked nodes for(var v = 1; v <= n; v++) { if (vis[v] == 0) dfs(v); } // If no backedges in the initial graph // this means that there is no cycle // So, return -1 if (totBackEdges == 0) return -1; var node = -1; // Iterate through the vertices and // return the first node that // satisfies the condition for(var v = 1; v <= n; v++) { // Check whether the count sum of // small[v] and count is the same as // the total back edges and // if the vertex v can be removed if ((countAdj[v] + small[v] == totBackEdges) && isPossible[v] != 0) { node = v; } if (node != -1) break; } return node;} // Driver codevar N = 5;var edges = [];for(var i = 0; i < MAX; i++){ adj.push(new Array());} edges.push(new pair(5, 1));edges.push(new pair(5, 2));edges.push(new pair(1, 2));edges.push(new pair(2, 3));edges.push(new pair(2, 4)); document.write(minNodetoRemove(N, edges)); // This code is contributed by rrrtnx </script>", "e": 23498, "s": 19418, "text": null }, { "code": null, "e": 23500, "s": 23498, "text": "1" }, { "code": null, "e": 23616, "s": 23502, "text": "Time Complexity: O(N + M), where N is the number of nodes and M is the number of edges.Auxiliary Space: O(N + M)." }, { "code": null, "e": 23626, "s": 23616, "text": "rutvik_56" }, { "code": null, "e": 23638, "s": 23626, "text": "sanjeev2552" }, { "code": null, "e": 23655, "s": 23638, "text": "khushboogoyal499" }, { "code": null, "e": 23665, "s": 23655, "text": "pratham76" }, { "code": null, "e": 23672, "s": 23665, "text": "rrrtnx" }, { "code": null, "e": 23688, "s": 23672, "text": "pankajsharmagfg" }, { "code": null, "e": 23692, "s": 23688, "text": "DFS" }, { "code": null, "e": 23707, "s": 23692, "text": "Graph Coloring" }, { "code": null, "e": 23719, "s": 23707, "text": "graph-cycle" }, { "code": null, "e": 23730, "s": 23719, "text": "Algorithms" }, { "code": null, "e": 23754, "s": 23730, "text": "Competitive Programming" }, { "code": null, "e": 23774, "s": 23754, "text": "Dynamic Programming" }, { "code": null, "e": 23780, "s": 23774, "text": "Graph" }, { "code": null, "e": 23800, "s": 23780, "text": "Dynamic Programming" }, { "code": null, "e": 23804, "s": 23800, "text": "DFS" }, { "code": null, "e": 23810, "s": 23804, "text": "Graph" }, { "code": null, "e": 23821, "s": 23810, "text": "Algorithms" }, { "code": null, "e": 23919, "s": 23821, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 23944, "s": 23919, "text": "DSA Sheet by Love Babbar" }, { "code": null, "e": 23993, "s": 23944, "text": "SDE SHEET - A Complete Guide for SDE Preparation" }, { "code": null, "e": 24031, "s": 23993, "text": "What is Hashing | A Complete Tutorial" }, { "code": null, "e": 24099, "s": 24031, "text": "Find if there is a path between two vertices in an undirected graph" }, { "code": null, "e": 24135, "s": 24099, "text": "CPU Scheduling in Operating Systems" }, { "code": null, "e": 24178, "s": 24135, "text": "Competitive Programming - A Complete Guide" }, { "code": null, "e": 24221, "s": 24178, "text": "Practice for cracking any coding interview" }, { "code": null, "e": 24248, "s": 24221, "text": "Modulo 10^9+7 (1000000007)" }, { "code": null, "e": 24289, "s": 24248, "text": "Arrow operator -> in C/C++ with Examples" } ]
Creating a C/C++ Code Formatting tool with help of Clang tools
16 Jul, 2020 Today we are going to discuss formatting files in the user’s workspace by their extension. For this we are going to make use of Clang’s format tools. Prerequisites: Linux Machine Python Clang Tool Setup: Install Python using the following command:sudo apt-get install python sudo apt-get install python Install Clang Format Toolssudo apt-get install clang-format-3.5 sudo apt-get install clang-format-3.5 Create a python file named format-code.py at any location where you have read and write permissions. In this example we are going to create it in /home/user/. It shall contain the following code:# Python program to format C/C++ files using clang-formatimport os # File Extension filter. You can add new extensioncpp_extensions = (".cxx",".cpp",".c", ".hxx", ".hh", ".cc", ".hpp") # Set the current working directory for scanning c/c++ sources (including# header files) and apply the clang formatting# Please note "-style" is for standard style options# and "-i" is in-place editingfor root, dirs, files in os.walk(os.getcwd()): for file in files: if file.endswith(cpp_extensions): os.system("clang-format-3.5 -i -style=file " + root + "/" + file) # Python program to format C/C++ files using clang-formatimport os # File Extension filter. You can add new extensioncpp_extensions = (".cxx",".cpp",".c", ".hxx", ".hh", ".cc", ".hpp") # Set the current working directory for scanning c/c++ sources (including# header files) and apply the clang formatting# Please note "-style" is for standard style options# and "-i" is in-place editingfor root, dirs, files in os.walk(os.getcwd()): for file in files: if file.endswith(cpp_extensions): os.system("clang-format-3.5 -i -style=file " + root + "/" + file) Create format specification file and copy it to project’s top level directory , e.g., /home/user/myproject/Create formatting file (in example, we are creating google coding style tool)clang-format-3.5 -style=google -dump-config > .clang-format Copy it to project’s directory i.e., it’s location becomes: /home/user/myproject/.clang-format Create formatting file (in example, we are creating google coding style tool)clang-format-3.5 -style=google -dump-config > .clang-format Copy it to project’s directory i.e., it’s location becomes: /home/user/myproject/.clang-format Create formatting file (in example, we are creating google coding style tool)clang-format-3.5 -style=google -dump-config > .clang-format clang-format-3.5 -style=google -dump-config > .clang-format Copy it to project’s directory i.e., it’s location becomes: /home/user/myproject/.clang-format How to use it? Navigate to the directory whose files you want to format, e.g.,cd /home/user/myproject/c-source/ cd /home/user/myproject/c-source/ Run the format-code file that you created earlierpython /home/user/format-code.py python /home/user/format-code.py This shall format all the files in our source directory with the extension same as that mentioned in the code. This article is contributed by Nitin Deokate .If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.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. Python-projects Project Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n16 Jul, 2020" }, { "code": null, "e": 202, "s": 52, "text": "Today we are going to discuss formatting files in the user’s workspace by their extension. For this we are going to make use of Clang’s format tools." }, { "code": null, "e": 217, "s": 202, "text": "Prerequisites:" }, { "code": null, "e": 231, "s": 217, "text": "Linux Machine" }, { "code": null, "e": 238, "s": 231, "text": "Python" }, { "code": null, "e": 249, "s": 238, "text": "Clang Tool" }, { "code": null, "e": 256, "s": 249, "text": "Setup:" }, { "code": null, "e": 327, "s": 256, "text": "Install Python using the following command:sudo apt-get install python" }, { "code": null, "e": 355, "s": 327, "text": "sudo apt-get install python" }, { "code": null, "e": 419, "s": 355, "text": "Install Clang Format Toolssudo apt-get install clang-format-3.5" }, { "code": null, "e": 457, "s": 419, "text": "sudo apt-get install clang-format-3.5" }, { "code": null, "e": 1227, "s": 457, "text": "Create a python file named format-code.py at any location where you have read and write permissions. In this example we are going to create it in /home/user/. It shall contain the following code:# Python program to format C/C++ files using clang-formatimport os # File Extension filter. You can add new extensioncpp_extensions = (\".cxx\",\".cpp\",\".c\", \".hxx\", \".hh\", \".cc\", \".hpp\") # Set the current working directory for scanning c/c++ sources (including# header files) and apply the clang formatting# Please note \"-style\" is for standard style options# and \"-i\" is in-place editingfor root, dirs, files in os.walk(os.getcwd()): for file in files: if file.endswith(cpp_extensions): os.system(\"clang-format-3.5 -i -style=file \" + root + \"/\" + file)" }, { "code": "# Python program to format C/C++ files using clang-formatimport os # File Extension filter. You can add new extensioncpp_extensions = (\".cxx\",\".cpp\",\".c\", \".hxx\", \".hh\", \".cc\", \".hpp\") # Set the current working directory for scanning c/c++ sources (including# header files) and apply the clang formatting# Please note \"-style\" is for standard style options# and \"-i\" is in-place editingfor root, dirs, files in os.walk(os.getcwd()): for file in files: if file.endswith(cpp_extensions): os.system(\"clang-format-3.5 -i -style=file \" + root + \"/\" + file)", "e": 1802, "s": 1227, "text": null }, { "code": null, "e": 2141, "s": 1802, "text": "Create format specification file and copy it to project’s top level directory , e.g., /home/user/myproject/Create formatting file (in example, we are creating google coding style tool)clang-format-3.5 -style=google -dump-config > .clang-format Copy it to project’s directory i.e., it’s location becomes: /home/user/myproject/.clang-format" }, { "code": null, "e": 2373, "s": 2141, "text": "Create formatting file (in example, we are creating google coding style tool)clang-format-3.5 -style=google -dump-config > .clang-format Copy it to project’s directory i.e., it’s location becomes: /home/user/myproject/.clang-format" }, { "code": null, "e": 2511, "s": 2373, "text": "Create formatting file (in example, we are creating google coding style tool)clang-format-3.5 -style=google -dump-config > .clang-format " }, { "code": null, "e": 2572, "s": 2511, "text": "clang-format-3.5 -style=google -dump-config > .clang-format " }, { "code": null, "e": 2667, "s": 2572, "text": "Copy it to project’s directory i.e., it’s location becomes: /home/user/myproject/.clang-format" }, { "code": null, "e": 2682, "s": 2667, "text": "How to use it?" }, { "code": null, "e": 2780, "s": 2682, "text": "Navigate to the directory whose files you want to format, e.g.,cd /home/user/myproject/c-source/" }, { "code": null, "e": 2815, "s": 2780, "text": "cd /home/user/myproject/c-source/" }, { "code": null, "e": 2897, "s": 2815, "text": "Run the format-code file that you created earlierpython /home/user/format-code.py" }, { "code": null, "e": 2930, "s": 2897, "text": "python /home/user/format-code.py" }, { "code": null, "e": 3041, "s": 2930, "text": "This shall format all the files in our source directory with the extension same as that mentioned in the code." }, { "code": null, "e": 3342, "s": 3041, "text": "This article is contributed by Nitin Deokate .If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.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": 3467, "s": 3342, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 3483, "s": 3467, "text": "Python-projects" }, { "code": null, "e": 3491, "s": 3483, "text": "Project" } ]
Difference between Information and Knowledge
04 Oct, 2019 Information:Information is delineate because the structured, organized and processed data, conferred inside context, that makes it relevant and helpful to the one who desires it. Data suggests that raw facts and figures regarding individuals, places, or the other issue, that is expressed within the type of numbers, letters or symbols. Information is that the knowledge that is remodeled and classified into an intelligible type, which may be utilized in the method of deciding. In short, once knowledge end up to be purposeful when conversion, it’s referred to as info. it’s one thing that informs, in essence, it provides a solution to a specific question. It may be obtained from numerous sources like newspaper, internet, television, people, books etc. Knowledge:Knowledge refers to the familiarity and awareness of a person, place, events, thoughts, issues, things or anything that is gathered through learning, knowing or discovering. it’s the state of knowing one thing with cognizance through the understanding of ideas, study and skill. Knowledge pointed at the assured theoretical or sensible understanding of associate entity together with the potential of exploitation it for a selected purpose. Combination of information, expertise and intuition ends up in knowledge that has the potential to draw inferences and develop insights, supported our expertise and so it will assist in higher cognitive process and taking actions. Difference between Information and Knowledge: Difference Between Misc Misc Misc Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n04 Oct, 2019" }, { "code": null, "e": 391, "s": 54, "text": "Information:Information is delineate because the structured, organized and processed data, conferred inside context, that makes it relevant and helpful to the one who desires it. Data suggests that raw facts and figures regarding individuals, places, or the other issue, that is expressed within the type of numbers, letters or symbols." }, { "code": null, "e": 812, "s": 391, "text": "Information is that the knowledge that is remodeled and classified into an intelligible type, which may be utilized in the method of deciding. In short, once knowledge end up to be purposeful when conversion, it’s referred to as info. it’s one thing that informs, in essence, it provides a solution to a specific question. It may be obtained from numerous sources like newspaper, internet, television, people, books etc." }, { "code": null, "e": 1101, "s": 812, "text": "Knowledge:Knowledge refers to the familiarity and awareness of a person, place, events, thoughts, issues, things or anything that is gathered through learning, knowing or discovering. it’s the state of knowing one thing with cognizance through the understanding of ideas, study and skill." }, { "code": null, "e": 1494, "s": 1101, "text": "Knowledge pointed at the assured theoretical or sensible understanding of associate entity together with the potential of exploitation it for a selected purpose. Combination of information, expertise and intuition ends up in knowledge that has the potential to draw inferences and develop insights, supported our expertise and so it will assist in higher cognitive process and taking actions." }, { "code": null, "e": 1540, "s": 1494, "text": "Difference between Information and Knowledge:" }, { "code": null, "e": 1559, "s": 1540, "text": "Difference Between" }, { "code": null, "e": 1564, "s": 1559, "text": "Misc" }, { "code": null, "e": 1569, "s": 1564, "text": "Misc" }, { "code": null, "e": 1574, "s": 1569, "text": "Misc" } ]
PostgreSQL – User Defined Functions
28 Aug, 2020 PostgreSQL uses the CREATE FUNCTION statement to develop user-defined functions. Syntax: CREATE FUNCTION function_name(p1 type, p2 type) RETURNS type AS BEGIN -- logic END; LANGUAGE language_name; Let’s analyze the above syntax: First, specify the name of the function after the CREATE FUNCTION keywords. Then, put a comma-separated list of parameters inside the parentheses following the function name. Next, specify the return type of the function after the RETURNS keyword. After that, place the code inside the BEGIN and END block. The function always ends with a semicolon (;) followed by the END keyword. Finally, indicate the procedural language of the function e.g., plpgsql in case PL/pgSQL is used. Example 1: In this example, we will develop a very simple function named inc that increases an integer by 1 and returns the result. First, launch pgAdmin and connect to the dvdrental sample database. Second, enter the following commands to create the inc function. CREATE FUNCTION inc(val integer) RETURNS integer AS $$ BEGIN RETURN val + 1; END; $$ LANGUAGE PLPGSQL; Third, click the Execute button to create the function: The entire function definition that you provide to the CREATE FUNCTION must be a single quoted string. It means that if the function has any single quote (‘), you have to escape it. Fortunately, from version 8.0, PostgreSQL provides a feature called dollar quoting that allows you to choose a suitable string that does not appear in the function so that you don’t have to escape it. A dollar quote is a string of characters between $ characters. If the function is valid, PostgreSQL will create the function and return the CREATE FUNCTION statement as shown above. Let’s test the inc function. You can call the inc function like any built-in functions as follows: SELECT inc(20); SELECT inc(inc(20)); It worked as expected. n PostgreSQL, functions that have different parameters can share the same name. This is called function overloading, which is similar to function overloading in C++ or Java. We can create a new function named inc that accepts two arguments. In the function, we will increase the value of the first argument by the second argument. The following steps show you how to create a function from the pgAdmin. First, launch pgAdmin and connect to the dvdrental database. Second, right-click on the Functions and select Create > Function... menu item. A new window will display. Third, enter inc in the name of the function: Fourth, in the Definition tab, click the + button to add two arguments i and val with bigint as the data type. Fifth in the same tab change language to plpgsql: Now it time to define the function and to do so shift to Code tab and define it as shown below: Sixth, click the SQL tab to see the generated code and click the Save button to create the function: Seventh, there are more options in the like Security and Options. However, we just need the basic options for now. The function may not display in the function list. To see the new inc function, right-click the Functions and click Refresh... menu item: Here is the new inc function: Now let’s test the function with the below query: SELECT inc(10, 20); Output: PostgreSQL-function PostgreSQL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n28 Aug, 2020" }, { "code": null, "e": 109, "s": 28, "text": "PostgreSQL uses the CREATE FUNCTION statement to develop user-defined functions." }, { "code": null, "e": 228, "s": 109, "text": "Syntax: \nCREATE FUNCTION function_name(p1 type, p2 type)\n RETURNS type AS\nBEGIN\n -- logic\nEND;\nLANGUAGE language_name;" }, { "code": null, "e": 260, "s": 228, "text": "Let’s analyze the above syntax:" }, { "code": null, "e": 336, "s": 260, "text": "First, specify the name of the function after the CREATE FUNCTION keywords." }, { "code": null, "e": 435, "s": 336, "text": "Then, put a comma-separated list of parameters inside the parentheses following the function name." }, { "code": null, "e": 508, "s": 435, "text": "Next, specify the return type of the function after the RETURNS keyword." }, { "code": null, "e": 642, "s": 508, "text": "After that, place the code inside the BEGIN and END block. The function always ends with a semicolon (;) followed by the END keyword." }, { "code": null, "e": 740, "s": 642, "text": "Finally, indicate the procedural language of the function e.g., plpgsql in case PL/pgSQL is used." }, { "code": null, "e": 751, "s": 740, "text": "Example 1:" }, { "code": null, "e": 872, "s": 751, "text": "In this example, we will develop a very simple function named inc that increases an integer by 1 and returns the result." }, { "code": null, "e": 940, "s": 872, "text": "First, launch pgAdmin and connect to the dvdrental sample database." }, { "code": null, "e": 1005, "s": 940, "text": "Second, enter the following commands to create the inc function." }, { "code": null, "e": 1108, "s": 1005, "text": "CREATE FUNCTION inc(val integer) RETURNS integer AS $$\nBEGIN\nRETURN val + 1;\nEND; $$\nLANGUAGE PLPGSQL;" }, { "code": null, "e": 1164, "s": 1108, "text": "Third, click the Execute button to create the function:" }, { "code": null, "e": 1346, "s": 1164, "text": "The entire function definition that you provide to the CREATE FUNCTION must be a single quoted string. It means that if the function has any single quote (‘), you have to escape it." }, { "code": null, "e": 1610, "s": 1346, "text": "Fortunately, from version 8.0, PostgreSQL provides a feature called dollar quoting that allows you to choose a suitable string that does not appear in the function so that you don’t have to escape it. A dollar quote is a string of characters between $ characters." }, { "code": null, "e": 1729, "s": 1610, "text": "If the function is valid, PostgreSQL will create the function and return the CREATE FUNCTION statement as shown above." }, { "code": null, "e": 1758, "s": 1729, "text": "Let’s test the inc function." }, { "code": null, "e": 1829, "s": 1758, "text": "You can call the inc function like any built-in functions as follows:" }, { "code": null, "e": 1845, "s": 1829, "text": "SELECT inc(20);" }, { "code": null, "e": 1866, "s": 1845, "text": "SELECT inc(inc(20));" }, { "code": null, "e": 1889, "s": 1866, "text": "It worked as expected." }, { "code": null, "e": 2063, "s": 1889, "text": "n PostgreSQL, functions that have different parameters can share the same name. This is called function overloading, which is similar to function overloading in C++ or Java." }, { "code": null, "e": 2220, "s": 2063, "text": "We can create a new function named inc that accepts two arguments. In the function, we will increase the value of the first argument by the second argument." }, { "code": null, "e": 2292, "s": 2220, "text": "The following steps show you how to create a function from the pgAdmin." }, { "code": null, "e": 2353, "s": 2292, "text": "First, launch pgAdmin and connect to the dvdrental database." }, { "code": null, "e": 2460, "s": 2353, "text": "Second, right-click on the Functions and select Create > Function... menu item. A new window will display." }, { "code": null, "e": 2506, "s": 2460, "text": "Third, enter inc in the name of the function:" }, { "code": null, "e": 2617, "s": 2506, "text": "Fourth, in the Definition tab, click the + button to add two arguments i and val with bigint as the data type." }, { "code": null, "e": 2667, "s": 2617, "text": "Fifth in the same tab change language to plpgsql:" }, { "code": null, "e": 2763, "s": 2667, "text": "Now it time to define the function and to do so shift to Code tab and define it as shown below:" }, { "code": null, "e": 2864, "s": 2763, "text": "Sixth, click the SQL tab to see the generated code and click the Save button to create the function:" }, { "code": null, "e": 3117, "s": 2864, "text": "Seventh, there are more options in the like Security and Options. However, we just need the basic options for now. The function may not display in the function list. To see the new inc function, right-click the Functions and click Refresh... menu item:" }, { "code": null, "e": 3147, "s": 3117, "text": "Here is the new inc function:" }, { "code": null, "e": 3197, "s": 3147, "text": "Now let’s test the function with the below query:" }, { "code": null, "e": 3217, "s": 3197, "text": "SELECT inc(10, 20);" }, { "code": null, "e": 3225, "s": 3217, "text": "Output:" }, { "code": null, "e": 3245, "s": 3225, "text": "PostgreSQL-function" }, { "code": null, "e": 3256, "s": 3245, "text": "PostgreSQL" } ]
MySQL Select Multiple VALUES?
To select multiple values, you can use where clause with OR and IN operator. The syntax is as follows − select *from yourTablename where yourColumnName = value1 or yourColumnName = value2 or yourColumnName = value3,.........N; select *from yourTableName where yourColumnName IN(value1,value2,....N); To understand the above syntax, let us create a table. The following is the query to create a table − mysql> create table selectMultipleValues −> ( −> BookId int, −> BookName varchar(200) −> ); Query OK, 0 rows affected (1.68 sec) Now you can insert some records in the table with the help of insert command. The query to insert records is as follows − mysql> insert into selectMultipleValues values(100,'Introduction to C'); Query OK, 1 row affected (0.18 sec) mysql> insert into selectMultipleValues values(101,'Introduction to C++'); Query OK, 1 row affected (0.19 sec) mysql> insert into selectMultipleValues values(103,'Introduction to java'); Query OK, 1 row affected (0.14 sec) mysql> insert into selectMultipleValues values(104,'Introduction to Python'); Query OK, 1 row affected (0.14 sec) mysql> insert into selectMultipleValues values(105,'Introduction to C#'); Query OK, 1 row affected (0.13 sec) mysql> insert into selectMultipleValues values(106,'C in Depth'); Query OK, 1 row affected (0.15 sec) Display all records from the table with the help of select statement. The query is as follows − mysql> select *from selectMultipleValues; The following is the output − +--------+------------------------+ | BookId | BookName | +--------+------------------------+ | 100 | Introduction to C | | 101 | Introduction to C++ | | 103 | Introduction to java | | 104 | Introduction to Python | | 105 | Introduction to C# | | 106 | C in Depth | +--------+------------------------+ 6 rows in set (0.00 sec) The following is the query to select multiple values with the help of OR operator. mysql> select *from selectMultipleValues where BookId = 104 or BookId = 106; The following is the output − +--------+------------------------+ | BookId | BookName | +--------+------------------------+ | 104 | Introduction to Python | | 106 | C in Depth | +--------+------------------------+ 2 rows in set (0.00 sec) The following is the query to select multiple values with the help of IN operator. mysql> select *from selectMultipleValues where BookId in(104,106); The following is the output − +--------+------------------------+ | BookId | BookName | +--------+------------------------+ | 104 | Introduction to Python | | 106 | C in Depth | +--------+------------------------+ 2 rows in set (0.00 sec)
[ { "code": null, "e": 1139, "s": 1062, "text": "To select multiple values, you can use where clause with OR and IN operator." }, { "code": null, "e": 1166, "s": 1139, "text": "The syntax is as follows −" }, { "code": null, "e": 1289, "s": 1166, "text": "select *from yourTablename where yourColumnName = value1 or yourColumnName = value2 or yourColumnName = value3,.........N;" }, { "code": null, "e": 1362, "s": 1289, "text": "select *from yourTableName where yourColumnName IN(value1,value2,....N);" }, { "code": null, "e": 1464, "s": 1362, "text": "To understand the above syntax, let us create a table. The following is the query to create a table −" }, { "code": null, "e": 1593, "s": 1464, "text": "mysql> create table selectMultipleValues\n−> (\n−> BookId int,\n−> BookName varchar(200)\n−> );\nQuery OK, 0 rows affected (1.68 sec)" }, { "code": null, "e": 1715, "s": 1593, "text": "Now you can insert some records in the table with the help of insert command. The query to insert records is as follows −" }, { "code": null, "e": 2378, "s": 1715, "text": "mysql> insert into selectMultipleValues values(100,'Introduction to C');\nQuery OK, 1 row affected (0.18 sec)\n\nmysql> insert into selectMultipleValues values(101,'Introduction to C++');\nQuery OK, 1 row affected (0.19 sec)\n\nmysql> insert into selectMultipleValues values(103,'Introduction to java');\nQuery OK, 1 row affected (0.14 sec)\n\nmysql> insert into selectMultipleValues values(104,'Introduction to Python');\nQuery OK, 1 row affected (0.14 sec)\n\nmysql> insert into selectMultipleValues values(105,'Introduction to C#');\nQuery OK, 1 row affected (0.13 sec)\n\nmysql> insert into selectMultipleValues values(106,'C in Depth');\nQuery OK, 1 row affected (0.15 sec)" }, { "code": null, "e": 2474, "s": 2378, "text": "Display all records from the table with the help of select statement. The query is as follows −" }, { "code": null, "e": 2516, "s": 2474, "text": "mysql> select *from selectMultipleValues;" }, { "code": null, "e": 2546, "s": 2516, "text": "The following is the output −" }, { "code": null, "e": 2933, "s": 2546, "text": "+--------+------------------------+\n| BookId | BookName |\n+--------+------------------------+\n| 100 | Introduction to C |\n| 101 | Introduction to C++ |\n| 103 | Introduction to java |\n| 104 | Introduction to Python |\n| 105 | Introduction to C# | \n| 106 | C in Depth |\n+--------+------------------------+\n6 rows in set (0.00 sec)" }, { "code": null, "e": 3016, "s": 2933, "text": "The following is the query to select multiple values with the help of OR operator." }, { "code": null, "e": 3093, "s": 3016, "text": "mysql> select *from selectMultipleValues where BookId = 104 or BookId = 106;" }, { "code": null, "e": 3123, "s": 3093, "text": "The following is the output −" }, { "code": null, "e": 3332, "s": 3123, "text": "+--------+------------------------+\n| BookId | BookName |\n+--------+------------------------+\n| 104 | Introduction to Python |\n| 106 | C in Depth |\n+--------+------------------------+\n2 rows in set (0.00 sec)" }, { "code": null, "e": 3415, "s": 3332, "text": "The following is the query to select multiple values with the help of IN operator." }, { "code": null, "e": 3482, "s": 3415, "text": "mysql> select *from selectMultipleValues where BookId in(104,106);" }, { "code": null, "e": 3512, "s": 3482, "text": "The following is the output −" }, { "code": null, "e": 3755, "s": 3512, "text": "+--------+------------------------+\n| BookId | BookName |\n+--------+------------------------+\n| 104 | Introduction to Python |\n| 106 | C in Depth | \n+--------+------------------------+\n2 rows in set (0.00 sec)" } ]
A hard lesson on Filter Context with Power BI and DAX | by Salvatore Cagliari | Towards Data Science
Last week a client asked me to analyse a difference between the displayed total in a Power BI report and the sum of the values after exporting them to Excel. This task turned out to be very challenging, and in the end, the difference was due to how Power BI and DAX works and how it calculates the numbers. In short: how the Filter Context works. The Client is a firm that sells building materials. It has an Order Backlog. The Sales Amount in the Order Backlog is calculated every day and loaded into the Datawarehouse database. This Amount is a so-called semi-additive measure. Semi-additive means that it is impossible to aggregate the Amount over time, as the Stock in a Warehouse or a bank account’s standing. The user selects a month, and the report shows the list of Order-numbers and the corresponding Sales-Amount for each order. The total shows the Sales Amount for all Orders for the selected Month. As a Snapshot of the Sales Order Backlog is loaded every day into the Datawarehouse Database, only the selected Month’s last day must be considered for the Sales Amount. The users get a list of Order Number with the corresponding Cost-Center and the Sales Amount. One of the Users wanted to perform a deeper analysis of the data with an export of the Data from the Power BI report to Excel. He noticed a big difference when he compared the sum of all single orders with the sum Displayed on the Power BI report. This result was the point when I started with my investigations. The customer used the following DAX measure: Last Sales Amount = CALCULATE ( SUM ( ‘SalesOrderBacklog’[SalesAmount] ), FILTER ( ‘SalesOrderBacklog’, ‘SalesOrderBacklog’[Snapshot_Date] = MAX ( ‘SalesOrderBacklog’[Snapshot_Date] ) ) ) At first sight, this Measure looks OK. It calculates the sum of the SalesAmount column considering only the highest date in the table. But when you look deeper into the formula, you start noticing that the mechanism is slightly different from what you expect: You need to look at each row in the report at onceThen you will see that the Measure performs an iteration over each combination of order-number and cost-centre and performs the calculation for each combinationYou need to consider the selected Month as a filter You need to look at each row in the report at once Then you will see that the Measure performs an iteration over each combination of order-number and cost-centre and performs the calculation for each combination You need to consider the selected Month as a filter When you combine these steps, you start understanding that the Measure is doing the following: It gets the first row. Let’s say the combination of cost-centre 2130 and the order-number 781731701The Measure will get the rows with the latest date for this combination in the selected Montha. These rows don’t need to be the last date in the selected MonthAfter selecting these rows, it will calculate to sum of the SalesAmoun columns, and it will return the value. In this case, 20'078.38 It gets the first row. Let’s say the combination of cost-centre 2130 and the order-number 781731701 The Measure will get the rows with the latest date for this combination in the selected Montha. These rows don’t need to be the last date in the selected Month After selecting these rows, it will calculate to sum of the SalesAmoun columns, and it will return the value. In this case, 20'078.38 Now, we need to take a look at how the Measure calculates the total. The Measure doesn’t know which order-number or cost-centre has been considered in the table in the total row. This means that the Measure will get the rows with the latest date in the selected Month. After this selection, it will calculate the sum of the SalesAmount column over all of these rows, and it will return the value, which in this case is:9'036'744.8601 for the last day in the selected Month! The calculated result is based on a completed different rows selection than the rows considered in the rows above. This process is the reason why the sum of all rows leads to a total of 10'183'398.1177. In DAX, I can use another method to calculate a Stock value. I can use the LASTNONBLANK(), or LASTNONBLANKVALUE() functions instead of using a custom formula. When using one of these function, the Measure looks completely different: Last Sales Amount = VAR LastDateWithData = LASTNONBLANK(‘Date ‘[Date] ,SUM ( ‘SalesOrderBacklog’[SalesAmount] ) ) RETURN CALCULATE( SUM ( ‘SalesOrderBacklog’[SalesAmount] ) ,LastDateWithData ) Here, I go through a two-step approach: I use the LASTNONBLANK() function to get the latest date, for which there are Values in the SalesAmount column.This step considers the selected MonthThen, the sum of the SalesAmount column is calculated for all rows, which have this date I use the LASTNONBLANK() function to get the latest date, for which there are Values in the SalesAmount column.This step considers the selected Month Then, the sum of the SalesAmount column is calculated for all rows, which have this date Now, I use a date table, which I added to the model. But using the ‘SalesOrderBacklog’[Snapshot_Date] instead will not make any difference. With this approach, DAX calculates a result only for those rows, which has data for the selected Month’s last date. When I export the data now, I get the correct result when I export the data and calculate all rows’ sum. Now, we need to understand the exact requirements of the users. We can pose the following two questions: Do you need to get the list of orders per the last the of the selected Month orDo you need the list of all orders, which were open during the selected Month, regardless is these orders were still on the Backlog list at the end of the Month or not? Do you need to get the list of orders per the last the of the selected Month or Do you need the list of all orders, which were open during the selected Month, regardless is these orders were still on the Backlog list at the end of the Month or not? If the users say yes to the first question, then the Measure with the LASTNONBLANK() function is the correct one. If the users say yes to the second question, then we need to change the Measure to calculate the correct sum with an additional part to fulfil this requirement. One way to do it is to precalculate all rows in a variable and check if the current filter context is the total-row or not: Sales (Order Backlog) Extd = VAR SelectedMonth = SELECTEDVALUE(‘Date’[YearMonthShort]) VAR ListOfValues = CALCULATETABLE( SUMMARIZE( ‘SalesOrderBacklog’ ,’SalesOrderBacklog’[Order No] ,’SalesOrderBacklog’[Costcenter] ,”SalesOrderBacklog”, [Last Sales Amount Custom] ) ,FILTER( ‘Date’ ,’Date’[YearMonthShort] = [Selected Month] ) ) RETURN IF(OR(HASONEFILTER(‘SalesOrderBacklog’[Order No]) ,HASONEFILTER(‘SalesOrderBacklog’[CostCenter]) ) ,[Last Sales Amount] ,SUMX( ListOfValues ,SUM ( [SalesOrderBacklog] ) ) ) This Measure works in the following way: The selected Month is retrieved with the SELECTEDVALUE() function and stored in the SelectedMonth variableThe variable ListOfValues gets a table with all combinations of the order-numbers and cost-centres, plus the sum of the Sales Amount for each combinationa. This table is restricted by the selected month (FILTER() function)An IF function checks if the currents filter-context contains a value for the order-number or the cost-centre.a. If yes, then the Base Measure is called to return the Sales Amount for the actual rowb. If no, then the sum is calculated over all rows in the table variable ListOfValues. The selected Month is retrieved with the SELECTEDVALUE() function and stored in the SelectedMonth variable The variable ListOfValues gets a table with all combinations of the order-numbers and cost-centres, plus the sum of the Sales Amount for each combinationa. This table is restricted by the selected month (FILTER() function) An IF function checks if the currents filter-context contains a value for the order-number or the cost-centre.a. If yes, then the Base Measure is called to return the Sales Amount for the actual rowb. If no, then the sum is calculated over all rows in the table variable ListOfValues. Power BI calculated the correct row-by-row result and the right total row. But it has two major draw-back: Performance: It is very slow. I waited for several minutes for the result over ~2 million rowsNot scalable: You can use this Measure only for this specific table as it asks just for the two columns order-number and cost-centre. Performance: It is very slow. I waited for several minutes for the result over ~2 million rows Not scalable: You can use this Measure only for this specific table as it asks just for the two columns order-number and cost-centre. My Client decided to use the generalized Measure and not the last variant described above. Because of his decision, I didn’t spend any time trying to optimize this variant. The biggest lesson I had to learn is not to lose sight of the crucial details when troubleshooting results from DAX Measures. The Filter Context is the most crucial factor when working with DAX. The user’s question misled me, and it took me a lot of time to go back to the basics to understand what goes on. I hope that you found this article interesting and valuable. Leave a comment if you have questions on this topic.
[ { "code": null, "e": 519, "s": 172, "text": "Last week a client asked me to analyse a difference between the displayed total in a Power BI report and the sum of the values after exporting them to Excel. This task turned out to be very challenging, and in the end, the difference was due to how Power BI and DAX works and how it calculates the numbers. In short: how the Filter Context works." }, { "code": null, "e": 702, "s": 519, "text": "The Client is a firm that sells building materials. It has an Order Backlog. The Sales Amount in the Order Backlog is calculated every day and loaded into the Datawarehouse database." }, { "code": null, "e": 887, "s": 702, "text": "This Amount is a so-called semi-additive measure. Semi-additive means that it is impossible to aggregate the Amount over time, as the Stock in a Warehouse or a bank account’s standing." }, { "code": null, "e": 1011, "s": 887, "text": "The user selects a month, and the report shows the list of Order-numbers and the corresponding Sales-Amount for each order." }, { "code": null, "e": 1083, "s": 1011, "text": "The total shows the Sales Amount for all Orders for the selected Month." }, { "code": null, "e": 1253, "s": 1083, "text": "As a Snapshot of the Sales Order Backlog is loaded every day into the Datawarehouse Database, only the selected Month’s last day must be considered for the Sales Amount." }, { "code": null, "e": 1347, "s": 1253, "text": "The users get a list of Order Number with the corresponding Cost-Center and the Sales Amount." }, { "code": null, "e": 1474, "s": 1347, "text": "One of the Users wanted to perform a deeper analysis of the data with an export of the Data from the Power BI report to Excel." }, { "code": null, "e": 1595, "s": 1474, "text": "He noticed a big difference when he compared the sum of all single orders with the sum Displayed on the Power BI report." }, { "code": null, "e": 1660, "s": 1595, "text": "This result was the point when I started with my investigations." }, { "code": null, "e": 1705, "s": 1660, "text": "The customer used the following DAX measure:" }, { "code": null, "e": 1894, "s": 1705, "text": "Last Sales Amount = CALCULATE ( SUM ( ‘SalesOrderBacklog’[SalesAmount] ), FILTER ( ‘SalesOrderBacklog’, ‘SalesOrderBacklog’[Snapshot_Date] = MAX ( ‘SalesOrderBacklog’[Snapshot_Date] ) ) )" }, { "code": null, "e": 1933, "s": 1894, "text": "At first sight, this Measure looks OK." }, { "code": null, "e": 2029, "s": 1933, "text": "It calculates the sum of the SalesAmount column considering only the highest date in the table." }, { "code": null, "e": 2154, "s": 2029, "text": "But when you look deeper into the formula, you start noticing that the mechanism is slightly different from what you expect:" }, { "code": null, "e": 2416, "s": 2154, "text": "You need to look at each row in the report at onceThen you will see that the Measure performs an iteration over each combination of order-number and cost-centre and performs the calculation for each combinationYou need to consider the selected Month as a filter" }, { "code": null, "e": 2467, "s": 2416, "text": "You need to look at each row in the report at once" }, { "code": null, "e": 2628, "s": 2467, "text": "Then you will see that the Measure performs an iteration over each combination of order-number and cost-centre and performs the calculation for each combination" }, { "code": null, "e": 2680, "s": 2628, "text": "You need to consider the selected Month as a filter" }, { "code": null, "e": 2775, "s": 2680, "text": "When you combine these steps, you start understanding that the Measure is doing the following:" }, { "code": null, "e": 3167, "s": 2775, "text": "It gets the first row. Let’s say the combination of cost-centre 2130 and the order-number 781731701The Measure will get the rows with the latest date for this combination in the selected Montha. These rows don’t need to be the last date in the selected MonthAfter selecting these rows, it will calculate to sum of the SalesAmoun columns, and it will return the value. In this case, 20'078.38" }, { "code": null, "e": 3267, "s": 3167, "text": "It gets the first row. Let’s say the combination of cost-centre 2130 and the order-number 781731701" }, { "code": null, "e": 3427, "s": 3267, "text": "The Measure will get the rows with the latest date for this combination in the selected Montha. These rows don’t need to be the last date in the selected Month" }, { "code": null, "e": 3561, "s": 3427, "text": "After selecting these rows, it will calculate to sum of the SalesAmoun columns, and it will return the value. In this case, 20'078.38" }, { "code": null, "e": 3630, "s": 3561, "text": "Now, we need to take a look at how the Measure calculates the total." }, { "code": null, "e": 3740, "s": 3630, "text": "The Measure doesn’t know which order-number or cost-centre has been considered in the table in the total row." }, { "code": null, "e": 4035, "s": 3740, "text": "This means that the Measure will get the rows with the latest date in the selected Month. After this selection, it will calculate the sum of the SalesAmount column over all of these rows, and it will return the value, which in this case is:9'036'744.8601 for the last day in the selected Month!" }, { "code": null, "e": 4150, "s": 4035, "text": "The calculated result is based on a completed different rows selection than the rows considered in the rows above." }, { "code": null, "e": 4238, "s": 4150, "text": "This process is the reason why the sum of all rows leads to a total of 10'183'398.1177." }, { "code": null, "e": 4397, "s": 4238, "text": "In DAX, I can use another method to calculate a Stock value. I can use the LASTNONBLANK(), or LASTNONBLANKVALUE() functions instead of using a custom formula." }, { "code": null, "e": 4471, "s": 4397, "text": "When using one of these function, the Measure looks completely different:" }, { "code": null, "e": 4665, "s": 4471, "text": "Last Sales Amount = VAR LastDateWithData = LASTNONBLANK(‘Date ‘[Date] ,SUM ( ‘SalesOrderBacklog’[SalesAmount] ) ) RETURN CALCULATE( SUM ( ‘SalesOrderBacklog’[SalesAmount] ) ,LastDateWithData )" }, { "code": null, "e": 4705, "s": 4665, "text": "Here, I go through a two-step approach:" }, { "code": null, "e": 4943, "s": 4705, "text": "I use the LASTNONBLANK() function to get the latest date, for which there are Values in the SalesAmount column.This step considers the selected MonthThen, the sum of the SalesAmount column is calculated for all rows, which have this date" }, { "code": null, "e": 5093, "s": 4943, "text": "I use the LASTNONBLANK() function to get the latest date, for which there are Values in the SalesAmount column.This step considers the selected Month" }, { "code": null, "e": 5182, "s": 5093, "text": "Then, the sum of the SalesAmount column is calculated for all rows, which have this date" }, { "code": null, "e": 5322, "s": 5182, "text": "Now, I use a date table, which I added to the model. But using the ‘SalesOrderBacklog’[Snapshot_Date] instead will not make any difference." }, { "code": null, "e": 5438, "s": 5322, "text": "With this approach, DAX calculates a result only for those rows, which has data for the selected Month’s last date." }, { "code": null, "e": 5543, "s": 5438, "text": "When I export the data now, I get the correct result when I export the data and calculate all rows’ sum." }, { "code": null, "e": 5607, "s": 5543, "text": "Now, we need to understand the exact requirements of the users." }, { "code": null, "e": 5648, "s": 5607, "text": "We can pose the following two questions:" }, { "code": null, "e": 5896, "s": 5648, "text": "Do you need to get the list of orders per the last the of the selected Month orDo you need the list of all orders, which were open during the selected Month, regardless is these orders were still on the Backlog list at the end of the Month or not?" }, { "code": null, "e": 5976, "s": 5896, "text": "Do you need to get the list of orders per the last the of the selected Month or" }, { "code": null, "e": 6145, "s": 5976, "text": "Do you need the list of all orders, which were open during the selected Month, regardless is these orders were still on the Backlog list at the end of the Month or not?" }, { "code": null, "e": 6259, "s": 6145, "text": "If the users say yes to the first question, then the Measure with the LASTNONBLANK() function is the correct one." }, { "code": null, "e": 6420, "s": 6259, "text": "If the users say yes to the second question, then we need to change the Measure to calculate the correct sum with an additional part to fulfil this requirement." }, { "code": null, "e": 6544, "s": 6420, "text": "One way to do it is to precalculate all rows in a variable and check if the current filter context is the total-row or not:" }, { "code": null, "e": 7059, "s": 6544, "text": "Sales (Order Backlog) Extd = VAR SelectedMonth = SELECTEDVALUE(‘Date’[YearMonthShort]) VAR ListOfValues = CALCULATETABLE( SUMMARIZE( ‘SalesOrderBacklog’ ,’SalesOrderBacklog’[Order No] ,’SalesOrderBacklog’[Costcenter] ,”SalesOrderBacklog”, [Last Sales Amount Custom] ) ,FILTER( ‘Date’ ,’Date’[YearMonthShort] = [Selected Month] ) ) RETURN IF(OR(HASONEFILTER(‘SalesOrderBacklog’[Order No]) ,HASONEFILTER(‘SalesOrderBacklog’[CostCenter]) ) ,[Last Sales Amount] ,SUMX( ListOfValues ,SUM ( [SalesOrderBacklog] ) ) )" }, { "code": null, "e": 7100, "s": 7059, "text": "This Measure works in the following way:" }, { "code": null, "e": 7713, "s": 7100, "text": "The selected Month is retrieved with the SELECTEDVALUE() function and stored in the SelectedMonth variableThe variable ListOfValues gets a table with all combinations of the order-numbers and cost-centres, plus the sum of the Sales Amount for each combinationa. This table is restricted by the selected month (FILTER() function)An IF function checks if the currents filter-context contains a value for the order-number or the cost-centre.a. If yes, then the Base Measure is called to return the Sales Amount for the actual rowb. If no, then the sum is calculated over all rows in the table variable ListOfValues." }, { "code": null, "e": 7820, "s": 7713, "text": "The selected Month is retrieved with the SELECTEDVALUE() function and stored in the SelectedMonth variable" }, { "code": null, "e": 8043, "s": 7820, "text": "The variable ListOfValues gets a table with all combinations of the order-numbers and cost-centres, plus the sum of the Sales Amount for each combinationa. This table is restricted by the selected month (FILTER() function)" }, { "code": null, "e": 8328, "s": 8043, "text": "An IF function checks if the currents filter-context contains a value for the order-number or the cost-centre.a. If yes, then the Base Measure is called to return the Sales Amount for the actual rowb. If no, then the sum is calculated over all rows in the table variable ListOfValues." }, { "code": null, "e": 8435, "s": 8328, "text": "Power BI calculated the correct row-by-row result and the right total row. But it has two major draw-back:" }, { "code": null, "e": 8663, "s": 8435, "text": "Performance: It is very slow. I waited for several minutes for the result over ~2 million rowsNot scalable: You can use this Measure only for this specific table as it asks just for the two columns order-number and cost-centre." }, { "code": null, "e": 8758, "s": 8663, "text": "Performance: It is very slow. I waited for several minutes for the result over ~2 million rows" }, { "code": null, "e": 8892, "s": 8758, "text": "Not scalable: You can use this Measure only for this specific table as it asks just for the two columns order-number and cost-centre." }, { "code": null, "e": 8983, "s": 8892, "text": "My Client decided to use the generalized Measure and not the last variant described above." }, { "code": null, "e": 9065, "s": 8983, "text": "Because of his decision, I didn’t spend any time trying to optimize this variant." }, { "code": null, "e": 9191, "s": 9065, "text": "The biggest lesson I had to learn is not to lose sight of the crucial details when troubleshooting results from DAX Measures." }, { "code": null, "e": 9260, "s": 9191, "text": "The Filter Context is the most crucial factor when working with DAX." }, { "code": null, "e": 9373, "s": 9260, "text": "The user’s question misled me, and it took me a lot of time to go back to the basics to understand what goes on." } ]
Binary Search Tree insert with Parent Pointer - GeeksforGeeks
25 Oct, 2021 We have discussed simple BST insert. How to insert in a tree where parent pointer needs to be maintained. Parent pointers are helpful to quickly find ancestors of a node, LCA of two nodes, successor of a node, etc. In recursive calls of simple insertion, we return pointer of root of subtree created in a subtree. So the idea is to store this pointer for left and right subtrees. We set parent pointers of this returned pointers after the recursive calls. This makes sure that all parent pointers are set during insertion. Parent of root is set to NULL. We handle this by assigning parent as NULL by default to all newly allocated nodes. C++ Java Python3 C# Javascript // C++ program to demonstrate insert operation// in binary search tree with parent pointer#include<bits/stdc++.h> struct Node{ int key; struct Node *left, *right, *parent;}; // A utility function to create a new BST Nodestruct Node *newNode(int item){ struct Node *temp = new Node; temp->key = item; temp->left = temp->right = NULL; temp->parent = NULL; return temp;} // A utility function to do inorder traversal of BSTvoid inorder(struct Node *root){ if (root != NULL) { inorder(root->left); printf("Node : %d, ", root->key); if (root->parent == NULL) printf("Parent : NULL \n"); else printf("Parent : %d \n", root->parent->key); inorder(root->right); }} /* A utility function to insert a new Node with given key in BST */struct Node* insert(struct Node* node, int key){ /* If the tree is empty, return a new Node */ if (node == NULL) return newNode(key); /* Otherwise, recur down the tree */ if (key < node->key) { Node *lchild = insert(node->left, key); node->left = lchild; // Set parent of root of left subtree lchild->parent = node; } else if (key > node->key) { Node *rchild = insert(node->right, key); node->right = rchild; // Set parent of root of right subtree rchild->parent = node; } /* return the (unchanged) Node pointer */ return node;} // Driver Program to test above functionsint main(){ /* Let us create following BST 50 / \ 30 70 / \ / \ 20 40 60 80 */ struct Node *root = NULL; root = insert(root, 50); insert(root, 30); insert(root, 20); insert(root, 40); insert(root, 70); insert(root, 60); insert(root, 80); // print inorder traversal of the BST inorder(root); return 0;} // Java program to demonstrate insert operation// in binary search tree with parent pointerclass GfG { static class Node{ int key; Node left, right, parent;} // A utility function to create a new BST Nodestatic Node newNode(int item){ Node temp = new Node(); temp.key = item; temp.left = null; temp.right = null; temp.parent = null; return temp;} // A utility function to do inorder traversal of BSTstatic void inorder(Node root){ if (root != null) { inorder(root.left); System.out.print("Node : "+ root.key + " , "); if (root.parent == null) System.out.println("Parent : NULL"); else System.out.println("Parent : " + root.parent.key); inorder(root.right); }} /* A utility function to insert a new Node withgiven key in BST */static Node insert(Node node, int key){ /* If the tree is empty, return a new Node */ if (node == null) return newNode(key); /* Otherwise, recur down the tree */ if (key < node.key) { Node lchild = insert(node.left, key); node.left = lchild; // Set parent of root of left subtree lchild.parent = node; } else if (key > node.key) { Node rchild = insert(node.right, key); node.right = rchild; // Set parent of root of right subtree rchild.parent = node; } /* return the (unchanged) Node pointer */ return node;} // Driver Program to test above functionspublic static void main(String[] args){ /* Let us create following BST 50 / \ 30 70 / \ / \ 20 40 60 80 */ Node root = null; root = insert(root, 50); insert(root, 30); insert(root, 20); insert(root, 40); insert(root, 70); insert(root, 60); insert(root, 80); // print iNorder traversal of the BST inorder(root);}} # Python3 program to demonstrate insert operation# in binary search tree with parent pointer # A utility function to create a new BST Nodeclass newNode: def __init__(self, item): self.key = item self.left = self.right = None self.parent = None # A utility function to do inorder# traversal of BSTdef inorder(root): if root != None: inorder(root.left) print("Node :", root.key, ", ", end = "") if root.parent == None: print("Parent : NULL") else: print("Parent : ", root.parent.key) inorder(root.right) # A utility function to insert a new# Node with given key in BSTdef insert(node, key): # If the tree is empty, return a new Node if node == None: return newNode(key) # Otherwise, recur down the tree if key < node.key: lchild = insert(node.left, key) node.left = lchild # Set parent of root of left subtree lchild.parent = node elif key > node.key: rchild = insert(node.right, key) node.right = rchild # Set parent of root of right subtree rchild.parent = node # return the (unchanged) Node pointer return node # Driver Codeif __name__ == '__main__': # Let us create following BST # 50 # / \ # 30 70 # / \ / \ # 20 40 60 80 root = None root = insert(root, 50) insert(root, 30) insert(root, 20) insert(root, 40) insert(root, 70) insert(root, 60) insert(root, 80) # print iNorder traversal of the BST inorder(root) # This code is contributed by PranchalK // C# program to demonstrate insert operation// in binary search tree with parent pointerusing System; class GfG{ class Node { public int key; public Node left, right, parent; } // A utility function to create a new BST Node static Node newNode(int item) { Node temp = new Node(); temp.key = item; temp.left = null; temp.right = null; temp.parent = null; return temp; } // A utility function to do // inorder traversal of BST static void inorder(Node root) { if (root != null) { inorder(root.left); Console.Write("Node : "+ root.key + " , "); if (root.parent == null) Console.WriteLine("Parent : NULL"); else Console.WriteLine("Parent : " + root.parent.key); inorder(root.right); } } /* A utility function to insert a new Node with given key in BST */ static Node insert(Node node, int key) { /* If the tree is empty, return a new Node */ if (node == null) return newNode(key); /* Otherwise, recur down the tree */ if (key < node.key) { Node lchild = insert(node.left, key); node.left = lchild; // Set parent of root of left subtree lchild.parent = node; } else if (key > node.key) { Node rchild = insert(node.right, key); node.right = rchild; // Set parent of root of right subtree rchild.parent = node; } /* return the (unchanged) Node pointer */ return node; } // Driver code public static void Main(String[] args) { /* Let us create following BST 50 / \ 30 70 / \ / \ 20 40 60 80 */ Node root = null; root = insert(root, 50); insert(root, 30); insert(root, 20); insert(root, 40); insert(root, 70); insert(root, 60); insert(root, 80); // print iNorder traversal of the BST inorder(root); }} // This code is contributed 29AjayKumar <script>// javascript program to demonstrate insert operation// in binary search tree with parent pointer class Node { constructor() { this.key = 0; this.left = null; this.right = null; this.parent = null; } } // A utility function to create a new BST Nodefunction newNode(item){ var temp = new Node(); temp.key = item; temp.left = null; temp.right = null; temp.parent = null; return temp;} // A utility function to do inorder traversal of BSTfunction inorder(root){ if (root != null) { inorder(root.left); document.write("Node : "+ root.key + " , "); if (root.parent == null) document.write("Parent : NULL<br/>"); else document.write("Parent : " + root.parent.key+"<br/>"); inorder(root.right); }} /* A utility function to insert a new Node withgiven key in BST */function insert(node , key){ /* If the tree is empty, return a new Node */ if (node == null) return newNode(key); /* Otherwise, recur down the tree */ if (key < node.key) { var lchild = insert(node.left, key); node.left = lchild; // Set parent of root of left subtree lchild.parent = node; } else if (key > node.key) { var rchild = insert(node.right, key); node.right = rchild; // Set parent of root of right subtree rchild.parent = node; } /* return the (unchanged) Node pointer */ return node;} // Driver Program to test above functions /* Let us create following BST 50 / \ 30 70 / \ / \ 20 40 60 80 */ var root = null; root = insert(root, 50); insert(root, 30); insert(root, 20); insert(root, 40); insert(root, 70); insert(root, 60); insert(root, 80); // print iNorder traversal of the BST inorder(root); // This code contributed by umadevi9616</script> Output : Node : 20, Parent : 30 Node : 30, Parent : 50 Node : 40, Parent : 30 Node : 50, Parent : NULL Node : 60, Parent : 70 Node : 70, Parent : 50 Node : 80, Parent : 70 Exercise: How to maintain parent pointer during deletion.This article is contributed by Shubham Gupta. If you like GeeksforGeeks and would like to contribute, you can also write an article and 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 prerna saini PranchalKatiyar 29AjayKumar umadevi9616 adnanirshad158 ankita_saini Binary Search Tree Binary Search Tree Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Print BST keys in the given range Find the node with maximum value in a Binary Search Tree set vs unordered_set in C++ STL Threaded Binary Tree | Insertion Floor and Ceil from a BST Construct BST from given preorder traversal | Set 2 Red Black Tree vs AVL Tree How to check if a given array represents a Binary Heap? Construct a Binary Search Tree from given postorder Find the largest BST subtree in a given Binary Tree | Set 1
[ { "code": null, "e": 25226, "s": 25198, "text": "\n25 Oct, 2021" }, { "code": null, "e": 25442, "s": 25226, "text": "We have discussed simple BST insert. How to insert in a tree where parent pointer needs to be maintained. Parent pointers are helpful to quickly find ancestors of a node, LCA of two nodes, successor of a node, etc. " }, { "code": null, "e": 25867, "s": 25442, "text": "In recursive calls of simple insertion, we return pointer of root of subtree created in a subtree. So the idea is to store this pointer for left and right subtrees. We set parent pointers of this returned pointers after the recursive calls. This makes sure that all parent pointers are set during insertion. Parent of root is set to NULL. We handle this by assigning parent as NULL by default to all newly allocated nodes. " }, { "code": null, "e": 25871, "s": 25867, "text": "C++" }, { "code": null, "e": 25876, "s": 25871, "text": "Java" }, { "code": null, "e": 25884, "s": 25876, "text": "Python3" }, { "code": null, "e": 25887, "s": 25884, "text": "C#" }, { "code": null, "e": 25898, "s": 25887, "text": "Javascript" }, { "code": "// C++ program to demonstrate insert operation// in binary search tree with parent pointer#include<bits/stdc++.h> struct Node{ int key; struct Node *left, *right, *parent;}; // A utility function to create a new BST Nodestruct Node *newNode(int item){ struct Node *temp = new Node; temp->key = item; temp->left = temp->right = NULL; temp->parent = NULL; return temp;} // A utility function to do inorder traversal of BSTvoid inorder(struct Node *root){ if (root != NULL) { inorder(root->left); printf(\"Node : %d, \", root->key); if (root->parent == NULL) printf(\"Parent : NULL \\n\"); else printf(\"Parent : %d \\n\", root->parent->key); inorder(root->right); }} /* A utility function to insert a new Node with given key in BST */struct Node* insert(struct Node* node, int key){ /* If the tree is empty, return a new Node */ if (node == NULL) return newNode(key); /* Otherwise, recur down the tree */ if (key < node->key) { Node *lchild = insert(node->left, key); node->left = lchild; // Set parent of root of left subtree lchild->parent = node; } else if (key > node->key) { Node *rchild = insert(node->right, key); node->right = rchild; // Set parent of root of right subtree rchild->parent = node; } /* return the (unchanged) Node pointer */ return node;} // Driver Program to test above functionsint main(){ /* Let us create following BST 50 / \\ 30 70 / \\ / \\ 20 40 60 80 */ struct Node *root = NULL; root = insert(root, 50); insert(root, 30); insert(root, 20); insert(root, 40); insert(root, 70); insert(root, 60); insert(root, 80); // print inorder traversal of the BST inorder(root); return 0;}", "e": 27778, "s": 25898, "text": null }, { "code": "// Java program to demonstrate insert operation// in binary search tree with parent pointerclass GfG { static class Node{ int key; Node left, right, parent;} // A utility function to create a new BST Nodestatic Node newNode(int item){ Node temp = new Node(); temp.key = item; temp.left = null; temp.right = null; temp.parent = null; return temp;} // A utility function to do inorder traversal of BSTstatic void inorder(Node root){ if (root != null) { inorder(root.left); System.out.print(\"Node : \"+ root.key + \" , \"); if (root.parent == null) System.out.println(\"Parent : NULL\"); else System.out.println(\"Parent : \" + root.parent.key); inorder(root.right); }} /* A utility function to insert a new Node withgiven key in BST */static Node insert(Node node, int key){ /* If the tree is empty, return a new Node */ if (node == null) return newNode(key); /* Otherwise, recur down the tree */ if (key < node.key) { Node lchild = insert(node.left, key); node.left = lchild; // Set parent of root of left subtree lchild.parent = node; } else if (key > node.key) { Node rchild = insert(node.right, key); node.right = rchild; // Set parent of root of right subtree rchild.parent = node; } /* return the (unchanged) Node pointer */ return node;} // Driver Program to test above functionspublic static void main(String[] args){ /* Let us create following BST 50 / \\ 30 70 / \\ / \\ 20 40 60 80 */ Node root = null; root = insert(root, 50); insert(root, 30); insert(root, 20); insert(root, 40); insert(root, 70); insert(root, 60); insert(root, 80); // print iNorder traversal of the BST inorder(root);}}", "e": 29620, "s": 27778, "text": null }, { "code": "# Python3 program to demonstrate insert operation# in binary search tree with parent pointer # A utility function to create a new BST Nodeclass newNode: def __init__(self, item): self.key = item self.left = self.right = None self.parent = None # A utility function to do inorder# traversal of BSTdef inorder(root): if root != None: inorder(root.left) print(\"Node :\", root.key, \", \", end = \"\") if root.parent == None: print(\"Parent : NULL\") else: print(\"Parent : \", root.parent.key) inorder(root.right) # A utility function to insert a new# Node with given key in BSTdef insert(node, key): # If the tree is empty, return a new Node if node == None: return newNode(key) # Otherwise, recur down the tree if key < node.key: lchild = insert(node.left, key) node.left = lchild # Set parent of root of left subtree lchild.parent = node elif key > node.key: rchild = insert(node.right, key) node.right = rchild # Set parent of root of right subtree rchild.parent = node # return the (unchanged) Node pointer return node # Driver Codeif __name__ == '__main__': # Let us create following BST # 50 # / \\ # 30 70 # / \\ / \\ # 20 40 60 80 root = None root = insert(root, 50) insert(root, 30) insert(root, 20) insert(root, 40) insert(root, 70) insert(root, 60) insert(root, 80) # print iNorder traversal of the BST inorder(root) # This code is contributed by PranchalK", "e": 31233, "s": 29620, "text": null }, { "code": "// C# program to demonstrate insert operation// in binary search tree with parent pointerusing System; class GfG{ class Node { public int key; public Node left, right, parent; } // A utility function to create a new BST Node static Node newNode(int item) { Node temp = new Node(); temp.key = item; temp.left = null; temp.right = null; temp.parent = null; return temp; } // A utility function to do // inorder traversal of BST static void inorder(Node root) { if (root != null) { inorder(root.left); Console.Write(\"Node : \"+ root.key + \" , \"); if (root.parent == null) Console.WriteLine(\"Parent : NULL\"); else Console.WriteLine(\"Parent : \" + root.parent.key); inorder(root.right); } } /* A utility function to insert a new Node with given key in BST */ static Node insert(Node node, int key) { /* If the tree is empty, return a new Node */ if (node == null) return newNode(key); /* Otherwise, recur down the tree */ if (key < node.key) { Node lchild = insert(node.left, key); node.left = lchild; // Set parent of root of left subtree lchild.parent = node; } else if (key > node.key) { Node rchild = insert(node.right, key); node.right = rchild; // Set parent of root of right subtree rchild.parent = node; } /* return the (unchanged) Node pointer */ return node; } // Driver code public static void Main(String[] args) { /* Let us create following BST 50 / \\ 30 70 / \\ / \\ 20 40 60 80 */ Node root = null; root = insert(root, 50); insert(root, 30); insert(root, 20); insert(root, 40); insert(root, 70); insert(root, 60); insert(root, 80); // print iNorder traversal of the BST inorder(root); }} // This code is contributed 29AjayKumar", "e": 33421, "s": 31233, "text": null }, { "code": "<script>// javascript program to demonstrate insert operation// in binary search tree with parent pointer class Node { constructor() { this.key = 0; this.left = null; this.right = null; this.parent = null; } } // A utility function to create a new BST Nodefunction newNode(item){ var temp = new Node(); temp.key = item; temp.left = null; temp.right = null; temp.parent = null; return temp;} // A utility function to do inorder traversal of BSTfunction inorder(root){ if (root != null) { inorder(root.left); document.write(\"Node : \"+ root.key + \" , \"); if (root.parent == null) document.write(\"Parent : NULL<br/>\"); else document.write(\"Parent : \" + root.parent.key+\"<br/>\"); inorder(root.right); }} /* A utility function to insert a new Node withgiven key in BST */function insert(node , key){ /* If the tree is empty, return a new Node */ if (node == null) return newNode(key); /* Otherwise, recur down the tree */ if (key < node.key) { var lchild = insert(node.left, key); node.left = lchild; // Set parent of root of left subtree lchild.parent = node; } else if (key > node.key) { var rchild = insert(node.right, key); node.right = rchild; // Set parent of root of right subtree rchild.parent = node; } /* return the (unchanged) Node pointer */ return node;} // Driver Program to test above functions /* Let us create following BST 50 / \\ 30 70 / \\ / \\ 20 40 60 80 */ var root = null; root = insert(root, 50); insert(root, 30); insert(root, 20); insert(root, 40); insert(root, 70); insert(root, 60); insert(root, 80); // print iNorder traversal of the BST inorder(root); // This code contributed by umadevi9616</script>", "e": 35387, "s": 33421, "text": null }, { "code": null, "e": 35397, "s": 35387, "text": "Output : " }, { "code": null, "e": 35567, "s": 35397, "text": "Node : 20, Parent : 30 \nNode : 30, Parent : 50 \nNode : 40, Parent : 30 \nNode : 50, Parent : NULL \nNode : 60, Parent : 70 \nNode : 70, Parent : 50 \nNode : 80, Parent : 70 " }, { "code": null, "e": 36016, "s": 35567, "text": "Exercise: How to maintain parent pointer during deletion.This article is contributed by Shubham Gupta. If you like GeeksforGeeks and would like to contribute, you can also write an article and 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": 36029, "s": 36016, "text": "prerna saini" }, { "code": null, "e": 36045, "s": 36029, "text": "PranchalKatiyar" }, { "code": null, "e": 36057, "s": 36045, "text": "29AjayKumar" }, { "code": null, "e": 36069, "s": 36057, "text": "umadevi9616" }, { "code": null, "e": 36084, "s": 36069, "text": "adnanirshad158" }, { "code": null, "e": 36097, "s": 36084, "text": "ankita_saini" }, { "code": null, "e": 36116, "s": 36097, "text": "Binary Search Tree" }, { "code": null, "e": 36135, "s": 36116, "text": "Binary Search Tree" }, { "code": null, "e": 36233, "s": 36135, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 36267, "s": 36233, "text": "Print BST keys in the given range" }, { "code": null, "e": 36324, "s": 36267, "text": "Find the node with maximum value in a Binary Search Tree" }, { "code": null, "e": 36356, "s": 36324, "text": "set vs unordered_set in C++ STL" }, { "code": null, "e": 36389, "s": 36356, "text": "Threaded Binary Tree | Insertion" }, { "code": null, "e": 36415, "s": 36389, "text": "Floor and Ceil from a BST" }, { "code": null, "e": 36467, "s": 36415, "text": "Construct BST from given preorder traversal | Set 2" }, { "code": null, "e": 36494, "s": 36467, "text": "Red Black Tree vs AVL Tree" }, { "code": null, "e": 36550, "s": 36494, "text": "How to check if a given array represents a Binary Heap?" }, { "code": null, "e": 36602, "s": 36550, "text": "Construct a Binary Search Tree from given postorder" } ]
Binary Indexed Tree or Fenwick Tree - GeeksforGeeks
14 Jan, 2022 Let us consider the following problem to understand Binary Indexed Tree.We have an array arr[0 . . . n-1]. We would like to 1 Compute the sum of the first i elements. 2 Modify the value of a specified element of the array arr[i] = x where 0 <= i <= n-1.A simple solution is to run a loop from 0 to i-1 and calculate the sum of the elements. To update a value, simply do arr[i] = x. The first operation takes O(n) time and the second operation takes O(1) time. Another simple solution is to create an extra array and store the sum of the first i-th elements at the i-th index in this new array. The sum of a given range can now be calculated in O(1) time, but the update operation takes O(n) time now. This works well if there are a large number of query operations but a very few number of update operations.Could we perform both the query and update operations in O(log n) time? One efficient solution is to use Segment Tree that performs both operations in O(Logn) time.An alternative solution is Binary Indexed Tree, which also achieves O(Logn) time complexity for both operations. Compared with Segment Tree, Binary Indexed Tree requires less space and is easier to implement..Representation Binary Indexed Tree is represented as an array. Let the array be BITree[]. Each node of the Binary Indexed Tree stores the sum of some elements of the input array. The size of the Binary Indexed Tree is equal to the size of the input array, denoted as n. In the code below, we use a size of n+1 for ease of implementation.Construction We initialize all the values in BITree[] as 0. Then we call update() for all the indexes, the update() operation is discussed below.Operations getSum(x): Returns the sum of the sub-array arr[0,...,x] // Returns the sum of the sub-array arr[0,...,x] using BITree[0..n], which is constructed from arr[0..n-1] 1) Initialize the output sum as 0, the current index as x+1. 2) Do following while the current index is greater than 0. ...a) Add BITree[index] to sum ...b) Go to the parent of BITree[index]. The parent can be obtained by removing the last set bit from the current index, i.e., index = index – (index & (-index)) 3) Return sum. The diagram above provides an example of how getSum() is working. Here are some important observations.BITree[0] is a dummy node. BITree[y] is the parent of BITree[x], if and only if y can be obtained by removing the last set bit from the binary representation of x, that is y = x – (x & (-x)).The child node BITree[x] of the node BITree[y] stores the sum of the elements between y(inclusive) and x(exclusive): arr[y,...,x). update(x, val): Updates the Binary Indexed Tree (BIT) by performing arr[index] += val // Note that the update(x, val) operation will not change arr[]. It only makes changes to BITree[] 1) Initialize the current index as x+1. 2) Do the following while the current index is smaller than or equal to n. ...a) Add the val to BITree[index] ...b) Go to next element of BITree[index]. The next element can be obtained by incrementing the last set bit of the current index, i.e., index = index + (index & (-index)) The update function needs to make sure that all the BITree nodes which contain arr[i] within their ranges being updated. We loop over such nodes in the BITree by repeatedly adding the decimal number corresponding to the last set bit of the current index.How does Binary Indexed Tree work? The idea is based on the fact that all positive integers can be represented as the sum of powers of 2. For example 19 can be represented as 16 + 2 + 1. Every node of the BITree stores the sum of n elements where n is a power of 2. For example, in the first diagram above (the diagram for getSum()), the sum of the first 12 elements can be obtained by the sum of the last 4 elements (from 9 to 12) plus the sum of 8 elements (from 1 to 8). The number of set bits in the binary representation of a number n is O(Logn). Therefore, we traverse at-most O(Logn) nodes in both getSum() and update() operations. The time complexity of the construction is O(nLogn) as it calls update() for all n elements. Implementation: Following are the implementations of Binary Indexed Tree. C++ Java Python3 C# Javascript // C++ code to demonstrate operations of Binary Index Tree#include <iostream> using namespace std; /* n --> No. of elements present in input array. BITree[0..n] --> Array that represents Binary Indexed Tree. arr[0..n-1] --> Input array for which prefix sum is evaluated. */ // Returns sum of arr[0..index]. This function assumes// that the array is preprocessed and partial sums of// array elements are stored in BITree[].int getSum(int BITree[], int index){ int sum = 0; // Initialize result // index in BITree[] is 1 more than the index in arr[] index = index + 1; // Traverse ancestors of BITree[index] while (index>0) { // Add current element of BITree to sum sum += BITree[index]; // Move index to parent node in getSum View index -= index & (-index); } return sum;} // Updates a node in Binary Index Tree (BITree) at given index// in BITree. The given value 'val' is added to BITree[i] and// all of its ancestors in tree.void updateBIT(int BITree[], int n, int index, int val){ // index in BITree[] is 1 more than the index in arr[] index = index + 1; // Traverse all ancestors and add 'val' while (index <= n) { // Add 'val' to current node of BI Tree BITree[index] += val; // Update index to that of parent in update View index += index & (-index); }} // Constructs and returns a Binary Indexed Tree for given// array of size n.int *constructBITree(int arr[], int n){ // Create and initialize BITree[] as 0 int *BITree = new int[n+1]; for (int i=1; i<=n; i++) BITree[i] = 0; // Store the actual values in BITree[] using update() for (int i=0; i<n; i++) updateBIT(BITree, n, i, arr[i]); // Uncomment below lines to see contents of BITree[] //for (int i=1; i<=n; i++) // cout << BITree[i] << " "; return BITree;} // Driver program to test above functionsint main(){ int freq[] = {2, 1, 1, 3, 2, 3, 4, 5, 6, 7, 8, 9}; int n = sizeof(freq)/sizeof(freq[0]); int *BITree = constructBITree(freq, n); cout << "Sum of elements in arr[0..5] is " << getSum(BITree, 5); // Let use test the update operation freq[3] += 6; updateBIT(BITree, n, 3, 6); //Update BIT for above change in arr[] cout << "\nSum of elements in arr[0..5] after update is " << getSum(BITree, 5); return 0;} // Java program to demonstrate lazy// propagation in segment treeimport java.util.*;import java.lang.*;import java.io.*; class BinaryIndexedTree{ // Max tree size final static int MAX = 1000; static int BITree[] = new int[MAX]; /* n --> No. of elements present in input array. BITree[0..n] --> Array that represents Binary Indexed Tree. arr[0..n-1] --> Input array for which prefix sum is evaluated. */ // Returns sum of arr[0..index]. This function // assumes that the array is preprocessed and // partial sums of array elements are stored // in BITree[]. int getSum(int index) { int sum = 0; // Initialize result // index in BITree[] is 1 more than // the index in arr[] index = index + 1; // Traverse ancestors of BITree[index] while(index>0) { // Add current element of BITree // to sum sum += BITree[index]; // Move index to parent node in // getSum View index -= index & (-index); } return sum; } // Updates a node in Binary Index Tree (BITree) // at given index in BITree. The given value // 'val' is added to BITree[i] and all of // its ancestors in tree. public static void updateBIT(int n, int index, int val) { // index in BITree[] is 1 more than // the index in arr[] index = index + 1; // Traverse all ancestors and add 'val' while(index <= n) { // Add 'val' to current node of BIT Tree BITree[index] += val; // Update index to that of parent // in update View index += index & (-index); } } /* Function to construct fenwick tree from given array.*/ void constructBITree(int arr[], int n) { // Initialize BITree[] as 0 for(int i=1; i<=n; i++) BITree[i] = 0; // Store the actual values in BITree[] // using update() for(int i = 0; i < n; i++) updateBIT(n, i, arr[i]); } // Main function public static void main(String args[]) { int freq[] = {2, 1, 1, 3, 2, 3, 4, 5, 6, 7, 8, 9}; int n = freq.length; BinaryIndexedTree tree = new BinaryIndexedTree(); // Build fenwick tree from given array tree.constructBITree(freq, n); System.out.println("Sum of elements in arr[0..5]"+ " is "+ tree.getSum(5)); // Let use test the update operation freq[3] += 6; // Update BIT for above change in arr[] updateBIT(n, 3, 6); // Find sum after the value is updated System.out.println("Sum of elements in arr[0..5]"+ " after update is " + tree.getSum(5)); }} // This code is contributed by Ranjan Binwani # Python implementation of Binary Indexed Tree # Returns sum of arr[0..index]. This function assumes# that the array is preprocessed and partial sums of# array elements are stored in BITree[].def getsum(BITTree,i): s = 0 #initialize result # index in BITree[] is 1 more than the index in arr[] i = i+1 # Traverse ancestors of BITree[index] while i > 0: # Add current element of BITree to sum s += BITTree[i] # Move index to parent node in getSum View i -= i & (-i) return s # Updates a node in Binary Index Tree (BITree) at given index# in BITree. The given value 'val' is added to BITree[i] and# all of its ancestors in tree.def updatebit(BITTree , n , i ,v): # index in BITree[] is 1 more than the index in arr[] i += 1 # Traverse all ancestors and add 'val' while i <= n: # Add 'val' to current node of BI Tree BITTree[i] += v # Update index to that of parent in update View i += i & (-i) # Constructs and returns a Binary Indexed Tree for given# array of size n.def construct(arr, n): # Create and initialize BITree[] as 0 BITTree = [0]*(n+1) # Store the actual values in BITree[] using update() for i in range(n): updatebit(BITTree, n, i, arr[i]) # Uncomment below lines to see contents of BITree[] #for i in range(1,n+1): # print BITTree[i], return BITTree # Driver code to test above methodsfreq = [2, 1, 1, 3, 2, 3, 4, 5, 6, 7, 8, 9]BITTree = construct(freq,len(freq))print("Sum of elements in arr[0..5] is " + str(getsum(BITTree,5)))freq[3] += 6updatebit(BITTree, len(freq), 3, 6)print("Sum of elements in arr[0..5]"+ " after update is " + str(getsum(BITTree,5))) # This code is contributed by Raju Varshney // C# program to demonstrate lazy// propagation in segment treeusing System; public class BinaryIndexedTree{ // Max tree size readonly static int MAX = 1000; static int []BITree = new int[MAX]; /* n --> No. of elements present in input array. BITree[0..n] --> Array that represents Binary Indexed Tree. arr[0..n-1] --> Input array for which prefix sum is evaluated. */ // Returns sum of arr[0..index]. This function // assumes that the array is preprocessed and // partial sums of array elements are stored // in BITree[]. int getSum(int index) { int sum = 0; // Initialize result // index in BITree[] is 1 more than // the index in arr[] index = index + 1; // Traverse ancestors of BITree[index] while(index>0) { // Add current element of BITree // to sum sum += BITree[index]; // Move index to parent node in // getSum View index -= index & (-index); } return sum; } // Updates a node in Binary Index Tree (BITree) // at given index in BITree. The given value // 'val' is added to BITree[i] and all of // its ancestors in tree. public static void updateBIT(int n, int index, int val) { // index in BITree[] is 1 more than // the index in arr[] index = index + 1; // Traverse all ancestors and add 'val' while(index <= n) { // Add 'val' to current node of BIT Tree BITree[index] += val; // Update index to that of parent // in update View index += index & (-index); } } /* Function to construct fenwick tree from given array.*/ void constructBITree(int []arr, int n) { // Initialize BITree[] as 0 for(int i = 1; i <= n; i++) BITree[i] = 0; // Store the actual values in BITree[] // using update() for(int i = 0; i < n; i++) updateBIT(n, i, arr[i]); } // Driver code public static void Main(String []args) { int []freq = {2, 1, 1, 3, 2, 3, 4, 5, 6, 7, 8, 9}; int n = freq.Length; BinaryIndexedTree tree = new BinaryIndexedTree(); // Build fenwick tree from given array tree.constructBITree(freq, n); Console.WriteLine("Sum of elements in arr[0..5]"+ " is "+ tree.getSum(5)); // Let use test the update operation freq[3] += 6; // Update BIT for above change in arr[] updateBIT(n, 3, 6); // Find sum after the value is updated Console.WriteLine("Sum of elements in arr[0..5]"+ " after update is " + tree.getSum(5)); }} // This code is contributed by PrinciRaj1992 <script>// Javascript program to demonstrate lazy// propagation in segment tree // Max tree sizelet MAX = 1000; let BITree=new Array(MAX); /* n --> No. of elements present in input array. BITree[0..n] --> Array that represents Binary Indexed Tree. arr[0..n-1] --> Input array for which prefix sum is evaluated. */ // Returns sum of arr[0..index]. This function // assumes that the array is preprocessed and // partial sums of array elements are stored // in BITree[].function getSum( index){ let sum = 0; // Initialize result // index in BITree[] is 1 more than // the index in arr[] index = index + 1; // Traverse ancestors of BITree[index] while(index>0) { // Add current element of BITree // to sum sum += BITree[index]; // Move index to parent node in // getSum View index -= index & (-index); } return sum;} // Updates a node in Binary Index Tree (BITree) // at given index in BITree. The given value // 'val' is added to BITree[i] and all of // its ancestors in tree.function updateBIT(n,index,val){ // index in BITree[] is 1 more than // the index in arr[] index = index + 1; // Traverse all ancestors and add 'val' while(index <= n) { // Add 'val' to current node of BIT Tree BITree[index] += val; // Update index to that of parent // in update View index += index & (-index); }} /* Function to construct fenwick tree from given array.*/function constructBITree(arr,n){ // Initialize BITree[] as 0 for(let i=1; i<=n; i++) BITree[i] = 0; // Store the actual values in BITree[] // using update() for(let i = 0; i < n; i++) updateBIT(n, i, arr[i]);} // Main functionlet freq=[2, 1, 1, 3, 2, 3, 4, 5, 6, 7, 8, 9]; let n = freq.length; // Build fenwick tree from given arrayconstructBITree(freq, n); document.write("Sum of elements in arr[0..5]"+ " is "+ getSum(5)+"<br>"); // Let use test the update operationfreq[3] += 6; // Update BIT for above change in arr[]updateBIT(n, 3, 6); // Find sum after the value is updateddocument.write("Sum of elements in arr[0..5]"+ " after update is " + getSum(5)); // This code is contributed by patel2127</script> Output: Sum of elements in arr[0..5] is 12 Sum of elements in arr[0..5] after update is 18 Can we extend the Binary Indexed Tree to computing the sum of a range in O(Logn) time? Yes. rangeSum(l, r) = getSum(r) – getSum(l-1).Applications: The implementation of the arithmetic coding algorithm. The development of the Binary Indexed Tree was primarily motivated by its application in this case. See this for more details.Example Problems: Count inversions in an array | Set 3 (Using BIT) Two Dimensional Binary Indexed Tree or Fenwick Tree Counting Triangles in a Rectangular space using BIT YouTubeGeeksforGeeks502K subscribersBinary Indexed Tree or Fenwick Tree | Construction and Operations | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 4:43•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=4SNzC4uNmTA" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div> References: http://en.wikipedia.org/wiki/Fenwick_tree http://community.topcoder.com/tc?module=Static&d1=tutorials&d2=binaryIndexedTreesPlease write comments if you find anything incorrect, or you want to share more information about the topic discussed above Sai Krishna Chowrigari BRAGHUNATHAN fuwentan princiraj1992 SahilSingh ManasChhabra2 kapoorsagar226 patel2127 Anirudh Goel amartyaghoshgfg array-range-queries Binary Indexed Tree Advanced Data Structure Binary Indexed Tree Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Agents in Artificial Intelligence Decision Tree Introduction with example Disjoint Set Data Structures Red-Black Tree | Set 2 (Insert) AVL Tree | Set 2 (Deletion) Insert Operation in B-Tree Design a Chess Game Red-Black Tree | Set 3 (Delete) Binomial Heap Design a data structure that supports insert, delete, search and getRandom in constant time
[ { "code": null, "e": 24666, "s": 24638, "text": "\n14 Jan, 2022" }, { "code": null, "e": 26342, "s": 24666, "text": "Let us consider the following problem to understand Binary Indexed Tree.We have an array arr[0 . . . n-1]. We would like to 1 Compute the sum of the first i elements. 2 Modify the value of a specified element of the array arr[i] = x where 0 <= i <= n-1.A simple solution is to run a loop from 0 to i-1 and calculate the sum of the elements. To update a value, simply do arr[i] = x. The first operation takes O(n) time and the second operation takes O(1) time. Another simple solution is to create an extra array and store the sum of the first i-th elements at the i-th index in this new array. The sum of a given range can now be calculated in O(1) time, but the update operation takes O(n) time now. This works well if there are a large number of query operations but a very few number of update operations.Could we perform both the query and update operations in O(log n) time? One efficient solution is to use Segment Tree that performs both operations in O(Logn) time.An alternative solution is Binary Indexed Tree, which also achieves O(Logn) time complexity for both operations. Compared with Segment Tree, Binary Indexed Tree requires less space and is easier to implement..Representation Binary Indexed Tree is represented as an array. Let the array be BITree[]. Each node of the Binary Indexed Tree stores the sum of some elements of the input array. The size of the Binary Indexed Tree is equal to the size of the input array, denoted as n. In the code below, we use a size of n+1 for ease of implementation.Construction We initialize all the values in BITree[] as 0. Then we call update() for all the indexes, the update() operation is discussed below.Operations " }, { "code": null, "e": 26834, "s": 26342, "text": "getSum(x): Returns the sum of the sub-array arr[0,...,x] // Returns the sum of the sub-array arr[0,...,x] using BITree[0..n], which is constructed from arr[0..n-1] 1) Initialize the output sum as 0, the current index as x+1. 2) Do following while the current index is greater than 0. ...a) Add BITree[index] to sum ...b) Go to the parent of BITree[index]. The parent can be obtained by removing the last set bit from the current index, i.e., index = index – (index & (-index)) 3) Return sum." }, { "code": null, "e": 27263, "s": 26836, "text": "The diagram above provides an example of how getSum() is working. Here are some important observations.BITree[0] is a dummy node. BITree[y] is the parent of BITree[x], if and only if y can be obtained by removing the last set bit from the binary representation of x, that is y = x – (x & (-x)).The child node BITree[x] of the node BITree[y] stores the sum of the elements between y(inclusive) and x(exclusive): arr[y,...,x). " }, { "code": null, "e": 27770, "s": 27263, "text": "update(x, val): Updates the Binary Indexed Tree (BIT) by performing arr[index] += val // Note that the update(x, val) operation will not change arr[]. It only makes changes to BITree[] 1) Initialize the current index as x+1. 2) Do the following while the current index is smaller than or equal to n. ...a) Add the val to BITree[index] ...b) Go to next element of BITree[index]. The next element can be obtained by incrementing the last set bit of the current index, i.e., index = index + (index & (-index))" }, { "code": null, "e": 28833, "s": 27772, "text": "The update function needs to make sure that all the BITree nodes which contain arr[i] within their ranges being updated. We loop over such nodes in the BITree by repeatedly adding the decimal number corresponding to the last set bit of the current index.How does Binary Indexed Tree work? The idea is based on the fact that all positive integers can be represented as the sum of powers of 2. For example 19 can be represented as 16 + 2 + 1. Every node of the BITree stores the sum of n elements where n is a power of 2. For example, in the first diagram above (the diagram for getSum()), the sum of the first 12 elements can be obtained by the sum of the last 4 elements (from 9 to 12) plus the sum of 8 elements (from 1 to 8). The number of set bits in the binary representation of a number n is O(Logn). Therefore, we traverse at-most O(Logn) nodes in both getSum() and update() operations. The time complexity of the construction is O(nLogn) as it calls update() for all n elements. Implementation: Following are the implementations of Binary Indexed Tree. " }, { "code": null, "e": 28837, "s": 28833, "text": "C++" }, { "code": null, "e": 28842, "s": 28837, "text": "Java" }, { "code": null, "e": 28850, "s": 28842, "text": "Python3" }, { "code": null, "e": 28853, "s": 28850, "text": "C#" }, { "code": null, "e": 28864, "s": 28853, "text": "Javascript" }, { "code": "// C++ code to demonstrate operations of Binary Index Tree#include <iostream> using namespace std; /* n --> No. of elements present in input array. BITree[0..n] --> Array that represents Binary Indexed Tree. arr[0..n-1] --> Input array for which prefix sum is evaluated. */ // Returns sum of arr[0..index]. This function assumes// that the array is preprocessed and partial sums of// array elements are stored in BITree[].int getSum(int BITree[], int index){ int sum = 0; // Initialize result // index in BITree[] is 1 more than the index in arr[] index = index + 1; // Traverse ancestors of BITree[index] while (index>0) { // Add current element of BITree to sum sum += BITree[index]; // Move index to parent node in getSum View index -= index & (-index); } return sum;} // Updates a node in Binary Index Tree (BITree) at given index// in BITree. The given value 'val' is added to BITree[i] and// all of its ancestors in tree.void updateBIT(int BITree[], int n, int index, int val){ // index in BITree[] is 1 more than the index in arr[] index = index + 1; // Traverse all ancestors and add 'val' while (index <= n) { // Add 'val' to current node of BI Tree BITree[index] += val; // Update index to that of parent in update View index += index & (-index); }} // Constructs and returns a Binary Indexed Tree for given// array of size n.int *constructBITree(int arr[], int n){ // Create and initialize BITree[] as 0 int *BITree = new int[n+1]; for (int i=1; i<=n; i++) BITree[i] = 0; // Store the actual values in BITree[] using update() for (int i=0; i<n; i++) updateBIT(BITree, n, i, arr[i]); // Uncomment below lines to see contents of BITree[] //for (int i=1; i<=n; i++) // cout << BITree[i] << \" \"; return BITree;} // Driver program to test above functionsint main(){ int freq[] = {2, 1, 1, 3, 2, 3, 4, 5, 6, 7, 8, 9}; int n = sizeof(freq)/sizeof(freq[0]); int *BITree = constructBITree(freq, n); cout << \"Sum of elements in arr[0..5] is \" << getSum(BITree, 5); // Let use test the update operation freq[3] += 6; updateBIT(BITree, n, 3, 6); //Update BIT for above change in arr[] cout << \"\\nSum of elements in arr[0..5] after update is \" << getSum(BITree, 5); return 0;}", "e": 31233, "s": 28864, "text": null }, { "code": "// Java program to demonstrate lazy// propagation in segment treeimport java.util.*;import java.lang.*;import java.io.*; class BinaryIndexedTree{ // Max tree size final static int MAX = 1000; static int BITree[] = new int[MAX]; /* n --> No. of elements present in input array. BITree[0..n] --> Array that represents Binary Indexed Tree. arr[0..n-1] --> Input array for which prefix sum is evaluated. */ // Returns sum of arr[0..index]. This function // assumes that the array is preprocessed and // partial sums of array elements are stored // in BITree[]. int getSum(int index) { int sum = 0; // Initialize result // index in BITree[] is 1 more than // the index in arr[] index = index + 1; // Traverse ancestors of BITree[index] while(index>0) { // Add current element of BITree // to sum sum += BITree[index]; // Move index to parent node in // getSum View index -= index & (-index); } return sum; } // Updates a node in Binary Index Tree (BITree) // at given index in BITree. The given value // 'val' is added to BITree[i] and all of // its ancestors in tree. public static void updateBIT(int n, int index, int val) { // index in BITree[] is 1 more than // the index in arr[] index = index + 1; // Traverse all ancestors and add 'val' while(index <= n) { // Add 'val' to current node of BIT Tree BITree[index] += val; // Update index to that of parent // in update View index += index & (-index); } } /* Function to construct fenwick tree from given array.*/ void constructBITree(int arr[], int n) { // Initialize BITree[] as 0 for(int i=1; i<=n; i++) BITree[i] = 0; // Store the actual values in BITree[] // using update() for(int i = 0; i < n; i++) updateBIT(n, i, arr[i]); } // Main function public static void main(String args[]) { int freq[] = {2, 1, 1, 3, 2, 3, 4, 5, 6, 7, 8, 9}; int n = freq.length; BinaryIndexedTree tree = new BinaryIndexedTree(); // Build fenwick tree from given array tree.constructBITree(freq, n); System.out.println(\"Sum of elements in arr[0..5]\"+ \" is \"+ tree.getSum(5)); // Let use test the update operation freq[3] += 6; // Update BIT for above change in arr[] updateBIT(n, 3, 6); // Find sum after the value is updated System.out.println(\"Sum of elements in arr[0..5]\"+ \" after update is \" + tree.getSum(5)); }} // This code is contributed by Ranjan Binwani", "e": 34174, "s": 31233, "text": null }, { "code": "# Python implementation of Binary Indexed Tree # Returns sum of arr[0..index]. This function assumes# that the array is preprocessed and partial sums of# array elements are stored in BITree[].def getsum(BITTree,i): s = 0 #initialize result # index in BITree[] is 1 more than the index in arr[] i = i+1 # Traverse ancestors of BITree[index] while i > 0: # Add current element of BITree to sum s += BITTree[i] # Move index to parent node in getSum View i -= i & (-i) return s # Updates a node in Binary Index Tree (BITree) at given index# in BITree. The given value 'val' is added to BITree[i] and# all of its ancestors in tree.def updatebit(BITTree , n , i ,v): # index in BITree[] is 1 more than the index in arr[] i += 1 # Traverse all ancestors and add 'val' while i <= n: # Add 'val' to current node of BI Tree BITTree[i] += v # Update index to that of parent in update View i += i & (-i) # Constructs and returns a Binary Indexed Tree for given# array of size n.def construct(arr, n): # Create and initialize BITree[] as 0 BITTree = [0]*(n+1) # Store the actual values in BITree[] using update() for i in range(n): updatebit(BITTree, n, i, arr[i]) # Uncomment below lines to see contents of BITree[] #for i in range(1,n+1): # print BITTree[i], return BITTree # Driver code to test above methodsfreq = [2, 1, 1, 3, 2, 3, 4, 5, 6, 7, 8, 9]BITTree = construct(freq,len(freq))print(\"Sum of elements in arr[0..5] is \" + str(getsum(BITTree,5)))freq[3] += 6updatebit(BITTree, len(freq), 3, 6)print(\"Sum of elements in arr[0..5]\"+ \" after update is \" + str(getsum(BITTree,5))) # This code is contributed by Raju Varshney", "e": 35944, "s": 34174, "text": null }, { "code": "// C# program to demonstrate lazy// propagation in segment treeusing System; public class BinaryIndexedTree{ // Max tree size readonly static int MAX = 1000; static int []BITree = new int[MAX]; /* n --> No. of elements present in input array. BITree[0..n] --> Array that represents Binary Indexed Tree. arr[0..n-1] --> Input array for which prefix sum is evaluated. */ // Returns sum of arr[0..index]. This function // assumes that the array is preprocessed and // partial sums of array elements are stored // in BITree[]. int getSum(int index) { int sum = 0; // Initialize result // index in BITree[] is 1 more than // the index in arr[] index = index + 1; // Traverse ancestors of BITree[index] while(index>0) { // Add current element of BITree // to sum sum += BITree[index]; // Move index to parent node in // getSum View index -= index & (-index); } return sum; } // Updates a node in Binary Index Tree (BITree) // at given index in BITree. The given value // 'val' is added to BITree[i] and all of // its ancestors in tree. public static void updateBIT(int n, int index, int val) { // index in BITree[] is 1 more than // the index in arr[] index = index + 1; // Traverse all ancestors and add 'val' while(index <= n) { // Add 'val' to current node of BIT Tree BITree[index] += val; // Update index to that of parent // in update View index += index & (-index); } } /* Function to construct fenwick tree from given array.*/ void constructBITree(int []arr, int n) { // Initialize BITree[] as 0 for(int i = 1; i <= n; i++) BITree[i] = 0; // Store the actual values in BITree[] // using update() for(int i = 0; i < n; i++) updateBIT(n, i, arr[i]); } // Driver code public static void Main(String []args) { int []freq = {2, 1, 1, 3, 2, 3, 4, 5, 6, 7, 8, 9}; int n = freq.Length; BinaryIndexedTree tree = new BinaryIndexedTree(); // Build fenwick tree from given array tree.constructBITree(freq, n); Console.WriteLine(\"Sum of elements in arr[0..5]\"+ \" is \"+ tree.getSum(5)); // Let use test the update operation freq[3] += 6; // Update BIT for above change in arr[] updateBIT(n, 3, 6); // Find sum after the value is updated Console.WriteLine(\"Sum of elements in arr[0..5]\"+ \" after update is \" + tree.getSum(5)); }} // This code is contributed by PrinciRaj1992", "e": 38879, "s": 35944, "text": null }, { "code": "<script>// Javascript program to demonstrate lazy// propagation in segment tree // Max tree sizelet MAX = 1000; let BITree=new Array(MAX); /* n --> No. of elements present in input array. BITree[0..n] --> Array that represents Binary Indexed Tree. arr[0..n-1] --> Input array for which prefix sum is evaluated. */ // Returns sum of arr[0..index]. This function // assumes that the array is preprocessed and // partial sums of array elements are stored // in BITree[].function getSum( index){ let sum = 0; // Initialize result // index in BITree[] is 1 more than // the index in arr[] index = index + 1; // Traverse ancestors of BITree[index] while(index>0) { // Add current element of BITree // to sum sum += BITree[index]; // Move index to parent node in // getSum View index -= index & (-index); } return sum;} // Updates a node in Binary Index Tree (BITree) // at given index in BITree. The given value // 'val' is added to BITree[i] and all of // its ancestors in tree.function updateBIT(n,index,val){ // index in BITree[] is 1 more than // the index in arr[] index = index + 1; // Traverse all ancestors and add 'val' while(index <= n) { // Add 'val' to current node of BIT Tree BITree[index] += val; // Update index to that of parent // in update View index += index & (-index); }} /* Function to construct fenwick tree from given array.*/function constructBITree(arr,n){ // Initialize BITree[] as 0 for(let i=1; i<=n; i++) BITree[i] = 0; // Store the actual values in BITree[] // using update() for(let i = 0; i < n; i++) updateBIT(n, i, arr[i]);} // Main functionlet freq=[2, 1, 1, 3, 2, 3, 4, 5, 6, 7, 8, 9]; let n = freq.length; // Build fenwick tree from given arrayconstructBITree(freq, n); document.write(\"Sum of elements in arr[0..5]\"+ \" is \"+ getSum(5)+\"<br>\"); // Let use test the update operationfreq[3] += 6; // Update BIT for above change in arr[]updateBIT(n, 3, 6); // Find sum after the value is updateddocument.write(\"Sum of elements in arr[0..5]\"+ \" after update is \" + getSum(5)); // This code is contributed by patel2127</script>", "e": 41374, "s": 38879, "text": null }, { "code": null, "e": 41384, "s": 41374, "text": "Output: " }, { "code": null, "e": 41467, "s": 41384, "text": "Sum of elements in arr[0..5] is 12\nSum of elements in arr[0..5] after update is 18" }, { "code": null, "e": 41967, "s": 41467, "text": "Can we extend the Binary Indexed Tree to computing the sum of a range in O(Logn) time? Yes. rangeSum(l, r) = getSum(r) – getSum(l-1).Applications: The implementation of the arithmetic coding algorithm. The development of the Binary Indexed Tree was primarily motivated by its application in this case. See this for more details.Example Problems: Count inversions in an array | Set 3 (Using BIT) Two Dimensional Binary Indexed Tree or Fenwick Tree Counting Triangles in a Rectangular space using BIT " }, { "code": null, "e": 42831, "s": 41967, "text": "YouTubeGeeksforGeeks502K subscribersBinary Indexed Tree or Fenwick Tree | Construction and Operations | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 4:43•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=4SNzC4uNmTA\" target=\"_blank\">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>" }, { "code": null, "e": 43091, "s": 42831, "text": "References: http://en.wikipedia.org/wiki/Fenwick_tree http://community.topcoder.com/tc?module=Static&d1=tutorials&d2=binaryIndexedTreesPlease write comments if you find anything incorrect, or you want to share more information about the topic discussed above " }, { "code": null, "e": 43114, "s": 43091, "text": "Sai Krishna Chowrigari" }, { "code": null, "e": 43127, "s": 43114, "text": "BRAGHUNATHAN" }, { "code": null, "e": 43136, "s": 43127, "text": "fuwentan" }, { "code": null, "e": 43150, "s": 43136, "text": "princiraj1992" }, { "code": null, "e": 43161, "s": 43150, "text": "SahilSingh" }, { "code": null, "e": 43175, "s": 43161, "text": "ManasChhabra2" }, { "code": null, "e": 43190, "s": 43175, "text": "kapoorsagar226" }, { "code": null, "e": 43200, "s": 43190, "text": "patel2127" }, { "code": null, "e": 43213, "s": 43200, "text": "Anirudh Goel" }, { "code": null, "e": 43229, "s": 43213, "text": "amartyaghoshgfg" }, { "code": null, "e": 43249, "s": 43229, "text": "array-range-queries" }, { "code": null, "e": 43269, "s": 43249, "text": "Binary Indexed Tree" }, { "code": null, "e": 43293, "s": 43269, "text": "Advanced Data Structure" }, { "code": null, "e": 43313, "s": 43293, "text": "Binary Indexed Tree" }, { "code": null, "e": 43411, "s": 43313, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 43445, "s": 43411, "text": "Agents in Artificial Intelligence" }, { "code": null, "e": 43485, "s": 43445, "text": "Decision Tree Introduction with example" }, { "code": null, "e": 43514, "s": 43485, "text": "Disjoint Set Data Structures" }, { "code": null, "e": 43546, "s": 43514, "text": "Red-Black Tree | Set 2 (Insert)" }, { "code": null, "e": 43574, "s": 43546, "text": "AVL Tree | Set 2 (Deletion)" }, { "code": null, "e": 43601, "s": 43574, "text": "Insert Operation in B-Tree" }, { "code": null, "e": 43621, "s": 43601, "text": "Design a Chess Game" }, { "code": null, "e": 43653, "s": 43621, "text": "Red-Black Tree | Set 3 (Delete)" }, { "code": null, "e": 43667, "s": 43653, "text": "Binomial Heap" } ]
Sparse Set - GeeksforGeeks
11 Oct, 2021 How to do the following operations efficiently if there are large number of queries for them. InsertionDeletionSearchingClearing/Removing all the elements. Insertion Deletion Searching Clearing/Removing all the elements. One solution is to use a Self-Balancing Binary Search Tree like Red-Black Tree, AVL Tree, etc. Time complexity of this solution for insertion, deletion and searching is O(Log n).We can also use Hashing. With hashing, time complexity of first three operations is O(1). But time complexity of the fourth operation is O(n). We can also use bit-vector (or direct access table), but bit-vector also requires O(n) time for clearing. Sparse Set outperforms all BST, Hashing and bit vector. We assume that we are given range of data (or maximum value an element can have) and maximum number of elements that can be stored in set. The idea is to maintain two arrays: sparse[] and dense[]. dense[] ==> Stores the actual elements sparse[] ==> This is like bit-vector where we use elements as index. Here values are not binary, but indexes of dense array. maxVal ==> Maximum value this set can store. Size of sparse[] is equal to maxVal + 1. capacity ==> Capacity of Set. Size of sparse is equal to capacity. n ==> Current number of elements in Set. insert(x): Let x be the element to be inserted. If x is greater than maxVal or n (current number of elements) is greater than equal to capacity, we return. If none of the above conditions is true, we insert x in dense[] at index n (position after last element in a 0 based indexed array), increment n by one (Current number of elements) and store n (index of x in dense[]) at sparse[x]. search(x): To search an element x, we use x as index in sparse[]. The value sparse[x] is used as index in dense[]. And if value of dense[sparse[x]] is equal to x, we return dense[x]. Else we return -1.delete(x): To delete an element x, we replace it with last element in dense[] and update index of last element in sparse[]. Finally decrement n by 1.clear(): Set n = 0.print(): We can print all elements by simply traversing dense[]. Illustration: Let there be a set with two elements {3, 5}, maximum value as 10 and capacity as 4. The set would be represented as below. Initially: maxVal = 10 // Size of sparse capacity = 4 // Size of dense n = 2 // Current number of elements in set // dense[] Stores actual elements dense[] = {3, 5, _, _} // Uses actual elements as index and stores // indexes of dense[] sparse[] = {_, _, _, 0, _, 1, _, _, _, _,} '_' means it can be any value and not used in sparse set Insert 7: n = 3 dense[] = {3, 5, 7, _} sparse[] = {_, _, _, 0, _, 1, _, 2, _, _,} Insert 4: n = 4 dense[] = {3, 5, 7, 4} sparse[] = {_, _, _, 0, 3, 1, _, 2, _, _,} Delete 3: n = 3 dense[] = {4, 5, 7, _} sparse[] = {_, _, _, _, 0, 1, _, 2, _, _,} Clear (Remove All): n = 0 dense[] = {_, _, _, _} sparse[] = {_, _, _, _, _, _, _, _, _, _,} Below is C++ implementation of above functions. C /* A C program to implement Sparse Set and its operations */#include<bits/stdc++.h>using namespace std; // A structure to hold the three parameters required to// represent a sparse set.class SSet{ int *sparse; // To store indexes of actual elements int *dense; // To store actual set elements int n; // Current number of elements int capacity; // Capacity of set or size of dense[] int maxValue; /* Maximum value in set or size of sparse[] */ public: // Constructor SSet(int maxV, int cap) { sparse = new int[maxV+1]; dense = new int[cap]; capacity = cap; maxValue = maxV; n = 0; // No elements initially } // Destructor ~SSet() { delete[] sparse; delete[] dense; } // If element is present, returns index of // element in dense[]. Else returns -1. int search(int x); // Inserts a new element into set void insert(int x); // Deletes an element void deletion(int x); // Prints contents of set void print(); // Removes all elements from set void clear() { n = 0; } // Finds intersection of this set with s // and returns pointer to result. SSet* intersection(SSet &s); // A function to find union of two sets // Time Complexity-O(n1+n2) SSet *setUnion(SSet &s);}; // If x is present in set, then returns index// of it in dense[], else returns -1.int SSet::search(int x){ // Searched element must be in range if (x > maxValue) return -1; // The first condition verifies that 'x' is // within 'n' in this set and the second // condition tells us that it is present in // the data structure. if (sparse[x] < n && dense[sparse[x]] == x) return (sparse[x]); // Not found return -1;} // Inserts a new element into setvoid SSet::insert(int x){ // Corner cases, x must not be out of // range, dense[] should not be full and // x should not already be present if (x > maxValue) return; if (n >= capacity) return; if (search(x) != -1) return; // Inserting into array-dense[] at index 'n'. dense[n] = x; // Mapping it to sparse[] array. sparse[x] = n; // Increment count of elements in set n++;} // A function that deletes 'x' if present in this data// structure, else it does nothing (just returns).// By deleting 'x', we unset 'x' from this set.void SSet::deletion(int x){ // If x is not present if (search(x) == -1) return; int temp = dense[n-1]; // Take an element from end dense[sparse[x]] = temp; // Overwrite. sparse[temp] = sparse[x]; // Overwrite. // Since one element has been deleted, we // decrement 'n' by 1. n--;} // prints contents of set which are also content// of dense[]void SSet::print(){ for (int i=0; i<n; i++) printf("%d ", dense[i]); printf("\n");} // A function to find intersection of two setsSSet* SSet::intersection(SSet &s){ // Capacity and max value of result set int iCap = min(n, s.n); int iMaxVal = max(s.maxValue, maxValue); // Create result set SSet *result = new SSet(iMaxVal, iCap); // Find the smaller of two sets // If this set is smaller if (n < s.n) { // Search every element of this set in 's'. // If found, add it to result for (int i = 0; i < n; i++) if (s.search(dense[i]) != -1) result->insert(dense[i]); } else { // Search every element of 's' in this set. // If found, add it to result for (int i = 0; i < s.n; i++) if (search(s.dense[i]) != -1) result->insert(s.dense[i]); } return result;} // A function to find union of two sets// Time Complexity-O(n1+n2)SSet* SSet::setUnion(SSet &s){ // Find capacity and maximum value for result // set. int uCap = s.n + n; int uMaxVal = max(s.maxValue, maxValue); // Create result set SSet *result = new SSet(uMaxVal, uCap); // Traverse the first set and insert all // elements of it in result. for (int i = 0; i < n; i++) result->insert(dense[i]); // Traverse the second set and insert all // elements of it in result (Note that sparse // set doesn't insert an entry if it is already // present) for (int i = 0; i < s.n; i++) result->insert(s.dense[i]); return result;} // Driver programint main(){ // Create a set set1 with capacity 5 and max // value 100 SSet s1(100, 5); // Insert elements into the set set1 s1.insert(5); s1.insert(3); s1.insert(9); s1.insert(10); // Printing the elements in the data structure. printf("The elements in set1 are\n"); s1.print(); int index = s1.search(3); // 'index' variable stores the index of the number to // be searched. if (index != -1) // 3 exists printf("\n3 is found at index %d in set1\n",index); else // 3 doesn't exist printf("\n3 doesn't exists in set1\n"); // Delete 9 and print set1 s1.deletion(9); s1.print(); // Create a set with capacity 6 and max value // 1000 SSet s2(1000, 6); // Insert elements into the set s2.insert(4); s2.insert(3); s2.insert(7); s2.insert(200); // Printing set 2. printf("\nThe elements in set2 are\n"); s2.print(); // Printing the intersection of the two sets SSet *intersect = s2.intersection(s1); printf("\nIntersection of set1 and set2\n"); intersect->print(); // Printing the union of the two sets SSet *unionset = s1.setUnion(s2); printf("\nUnion of set1 and set2\n"); unionset->print(); return 0;} Output : The elements in set1 are 5 3 9 10 3 is found at index 1 in set1 5 3 10 The elements in set2 are- 4 3 7 200 Intersection of set1 and set2 3 Union of set1 and set2 5 3 10 4 7 200 Additional Operations: The following are operations are also efficiently implemented using sparse set. It outperforms all the solutions discussed here and bit vector based solution, under the assumptions that range and maximum number of elements are known. union(): 1) Create an empty sparse set, say result. 2) Traverse the first set and insert all elements of it in result. 3) Traverse the second set and insert all elements of it in result (Note that sparse set doesn’t insert an entry if it is already present) 4) Return result. intersection(): 1) Create an empty sparse set, say result. 2) Let the smaller of two given sets be first set and larger be second. 3) Consider the smaller set and search every element of it in second. If element is found, add it to result. 4) Return result.A common use of this data structure is with register allocation algorithms in compilers, which have a fixed universe(the number of registers in the machine) and are updated and cleared frequently (just like- Q queries) during a single processing run. References: http://research.switch.com/sparse http://codingplayground.blogspot.in/2009/03/sparse-sets-with-o1-insert-delete.htmlThis article is contributed by Rachit Belwariar. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above sweetyty varshagumber28 Advanced Data Structure Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Proof that Dominant Set of a Graph is NP-Complete 2-3 Trees | (Search, Insert and Deletion) Quad Tree String hashing using Polynomial rolling hash function Ternary Search Tree C++ Program to implement Symbol Table Find the k most frequent words from a file Maximum distance between two points in coordinate plane using Rotating Caliper's Method Self-Balancing-Binary-Search-Trees (Comparisons) Advantages of Trie Data Structure
[ { "code": null, "e": 24097, "s": 24069, "text": "\n11 Oct, 2021" }, { "code": null, "e": 24192, "s": 24097, "text": "How to do the following operations efficiently if there are large number of queries for them. " }, { "code": null, "e": 24254, "s": 24192, "text": "InsertionDeletionSearchingClearing/Removing all the elements." }, { "code": null, "e": 24264, "s": 24254, "text": "Insertion" }, { "code": null, "e": 24273, "s": 24264, "text": "Deletion" }, { "code": null, "e": 24283, "s": 24273, "text": "Searching" }, { "code": null, "e": 24319, "s": 24283, "text": "Clearing/Removing all the elements." }, { "code": null, "e": 24746, "s": 24319, "text": "One solution is to use a Self-Balancing Binary Search Tree like Red-Black Tree, AVL Tree, etc. Time complexity of this solution for insertion, deletion and searching is O(Log n).We can also use Hashing. With hashing, time complexity of first three operations is O(1). But time complexity of the fourth operation is O(n). We can also use bit-vector (or direct access table), but bit-vector also requires O(n) time for clearing." }, { "code": null, "e": 25000, "s": 24746, "text": "Sparse Set outperforms all BST, Hashing and bit vector. We assume that we are given range of data (or maximum value an element can have) and maximum number of elements that can be stored in set. The idea is to maintain two arrays: sparse[] and dense[]. " }, { "code": null, "e": 25476, "s": 25000, "text": "dense[] ==> Stores the actual elements\nsparse[] ==> This is like bit-vector where \n we use elements as index. Here \n values are not binary, but\n indexes of dense array.\nmaxVal ==> Maximum value this set can \n store. Size of sparse[] is\n equal to maxVal + 1.\ncapacity ==> Capacity of Set. Size of sparse\n is equal to capacity. \nn ==> Current number of elements in\n Set." }, { "code": null, "e": 26298, "s": 25476, "text": "insert(x): Let x be the element to be inserted. If x is greater than maxVal or n (current number of elements) is greater than equal to capacity, we return. If none of the above conditions is true, we insert x in dense[] at index n (position after last element in a 0 based indexed array), increment n by one (Current number of elements) and store n (index of x in dense[]) at sparse[x]. search(x): To search an element x, we use x as index in sparse[]. The value sparse[x] is used as index in dense[]. And if value of dense[sparse[x]] is equal to x, we return dense[x]. Else we return -1.delete(x): To delete an element x, we replace it with last element in dense[] and update index of last element in sparse[]. Finally decrement n by 1.clear(): Set n = 0.print(): We can print all elements by simply traversing dense[]. " }, { "code": null, "e": 26313, "s": 26298, "text": "Illustration: " }, { "code": null, "e": 27167, "s": 26313, "text": "Let there be a set with two elements {3, 5}, maximum\nvalue as 10 and capacity as 4. The set would be \nrepresented as below.\n\nInitially:\nmaxVal = 10 // Size of sparse\ncapacity = 4 // Size of dense\nn = 2 // Current number of elements in set\n\n// dense[] Stores actual elements\ndense[] = {3, 5, _, _}\n\n// Uses actual elements as index and stores\n// indexes of dense[]\nsparse[] = {_, _, _, 0, _, 1, _, _, _, _,}\n\n'_' means it can be any value and not used in \nsparse set\n\n\nInsert 7:\nn = 3\ndense[] = {3, 5, 7, _}\nsparse[] = {_, _, _, 0, _, 1, _, 2, _, _,}\n\nInsert 4:\nn = 4\ndense[] = {3, 5, 7, 4}\nsparse[] = {_, _, _, 0, 3, 1, _, 2, _, _,}\n\nDelete 3:\nn = 3\ndense[] = {4, 5, 7, _}\nsparse[] = {_, _, _, _, 0, 1, _, 2, _, _,}\n\nClear (Remove All):\nn = 0\ndense[] = {_, _, _, _}\nsparse[] = {_, _, _, _, _, _, _, _, _, _,}" }, { "code": null, "e": 27216, "s": 27167, "text": "Below is C++ implementation of above functions. " }, { "code": null, "e": 27218, "s": 27216, "text": "C" }, { "code": "/* A C program to implement Sparse Set and its operations */#include<bits/stdc++.h>using namespace std; // A structure to hold the three parameters required to// represent a sparse set.class SSet{ int *sparse; // To store indexes of actual elements int *dense; // To store actual set elements int n; // Current number of elements int capacity; // Capacity of set or size of dense[] int maxValue; /* Maximum value in set or size of sparse[] */ public: // Constructor SSet(int maxV, int cap) { sparse = new int[maxV+1]; dense = new int[cap]; capacity = cap; maxValue = maxV; n = 0; // No elements initially } // Destructor ~SSet() { delete[] sparse; delete[] dense; } // If element is present, returns index of // element in dense[]. Else returns -1. int search(int x); // Inserts a new element into set void insert(int x); // Deletes an element void deletion(int x); // Prints contents of set void print(); // Removes all elements from set void clear() { n = 0; } // Finds intersection of this set with s // and returns pointer to result. SSet* intersection(SSet &s); // A function to find union of two sets // Time Complexity-O(n1+n2) SSet *setUnion(SSet &s);}; // If x is present in set, then returns index// of it in dense[], else returns -1.int SSet::search(int x){ // Searched element must be in range if (x > maxValue) return -1; // The first condition verifies that 'x' is // within 'n' in this set and the second // condition tells us that it is present in // the data structure. if (sparse[x] < n && dense[sparse[x]] == x) return (sparse[x]); // Not found return -1;} // Inserts a new element into setvoid SSet::insert(int x){ // Corner cases, x must not be out of // range, dense[] should not be full and // x should not already be present if (x > maxValue) return; if (n >= capacity) return; if (search(x) != -1) return; // Inserting into array-dense[] at index 'n'. dense[n] = x; // Mapping it to sparse[] array. sparse[x] = n; // Increment count of elements in set n++;} // A function that deletes 'x' if present in this data// structure, else it does nothing (just returns).// By deleting 'x', we unset 'x' from this set.void SSet::deletion(int x){ // If x is not present if (search(x) == -1) return; int temp = dense[n-1]; // Take an element from end dense[sparse[x]] = temp; // Overwrite. sparse[temp] = sparse[x]; // Overwrite. // Since one element has been deleted, we // decrement 'n' by 1. n--;} // prints contents of set which are also content// of dense[]void SSet::print(){ for (int i=0; i<n; i++) printf(\"%d \", dense[i]); printf(\"\\n\");} // A function to find intersection of two setsSSet* SSet::intersection(SSet &s){ // Capacity and max value of result set int iCap = min(n, s.n); int iMaxVal = max(s.maxValue, maxValue); // Create result set SSet *result = new SSet(iMaxVal, iCap); // Find the smaller of two sets // If this set is smaller if (n < s.n) { // Search every element of this set in 's'. // If found, add it to result for (int i = 0; i < n; i++) if (s.search(dense[i]) != -1) result->insert(dense[i]); } else { // Search every element of 's' in this set. // If found, add it to result for (int i = 0; i < s.n; i++) if (search(s.dense[i]) != -1) result->insert(s.dense[i]); } return result;} // A function to find union of two sets// Time Complexity-O(n1+n2)SSet* SSet::setUnion(SSet &s){ // Find capacity and maximum value for result // set. int uCap = s.n + n; int uMaxVal = max(s.maxValue, maxValue); // Create result set SSet *result = new SSet(uMaxVal, uCap); // Traverse the first set and insert all // elements of it in result. for (int i = 0; i < n; i++) result->insert(dense[i]); // Traverse the second set and insert all // elements of it in result (Note that sparse // set doesn't insert an entry if it is already // present) for (int i = 0; i < s.n; i++) result->insert(s.dense[i]); return result;} // Driver programint main(){ // Create a set set1 with capacity 5 and max // value 100 SSet s1(100, 5); // Insert elements into the set set1 s1.insert(5); s1.insert(3); s1.insert(9); s1.insert(10); // Printing the elements in the data structure. printf(\"The elements in set1 are\\n\"); s1.print(); int index = s1.search(3); // 'index' variable stores the index of the number to // be searched. if (index != -1) // 3 exists printf(\"\\n3 is found at index %d in set1\\n\",index); else // 3 doesn't exist printf(\"\\n3 doesn't exists in set1\\n\"); // Delete 9 and print set1 s1.deletion(9); s1.print(); // Create a set with capacity 6 and max value // 1000 SSet s2(1000, 6); // Insert elements into the set s2.insert(4); s2.insert(3); s2.insert(7); s2.insert(200); // Printing set 2. printf(\"\\nThe elements in set2 are\\n\"); s2.print(); // Printing the intersection of the two sets SSet *intersect = s2.intersection(s1); printf(\"\\nIntersection of set1 and set2\\n\"); intersect->print(); // Printing the union of the two sets SSet *unionset = s1.setUnion(s2); printf(\"\\nUnion of set1 and set2\\n\"); unionset->print(); return 0;}", "e": 32880, "s": 27218, "text": null }, { "code": null, "e": 32890, "s": 32880, "text": "Output : " }, { "code": null, "e": 33076, "s": 32890, "text": "The elements in set1 are\n5 3 9 10 \n\n3 is found at index 1 in set1\n5 3 10 \n\nThe elements in set2 are-\n4 3 7 200 \n\nIntersection of set1 and set2\n3 \n\nUnion of set1 and set2\n5 3 10 4 7 200 " }, { "code": null, "e": 33334, "s": 33076, "text": "Additional Operations: The following are operations are also efficiently implemented using sparse set. It outperforms all the solutions discussed here and bit vector based solution, under the assumptions that range and maximum number of elements are known. " }, { "code": null, "e": 33611, "s": 33334, "text": "union(): 1) Create an empty sparse set, say result. 2) Traverse the first set and insert all elements of it in result. 3) Traverse the second set and insert all elements of it in result (Note that sparse set doesn’t insert an entry if it is already present) 4) Return result. " }, { "code": null, "e": 34119, "s": 33611, "text": "intersection(): 1) Create an empty sparse set, say result. 2) Let the smaller of two given sets be first set and larger be second. 3) Consider the smaller set and search every element of it in second. If element is found, add it to result. 4) Return result.A common use of this data structure is with register allocation algorithms in compilers, which have a fixed universe(the number of registers in the machine) and are updated and cleared frequently (just like- Q queries) during a single processing run." }, { "code": null, "e": 34422, "s": 34119, "text": "References: http://research.switch.com/sparse http://codingplayground.blogspot.in/2009/03/sparse-sets-with-o1-insert-delete.htmlThis article is contributed by Rachit Belwariar. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above " }, { "code": null, "e": 34431, "s": 34422, "text": "sweetyty" }, { "code": null, "e": 34446, "s": 34431, "text": "varshagumber28" }, { "code": null, "e": 34470, "s": 34446, "text": "Advanced Data Structure" }, { "code": null, "e": 34568, "s": 34470, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 34577, "s": 34568, "text": "Comments" }, { "code": null, "e": 34590, "s": 34577, "text": "Old Comments" }, { "code": null, "e": 34640, "s": 34590, "text": "Proof that Dominant Set of a Graph is NP-Complete" }, { "code": null, "e": 34682, "s": 34640, "text": "2-3 Trees | (Search, Insert and Deletion)" }, { "code": null, "e": 34692, "s": 34682, "text": "Quad Tree" }, { "code": null, "e": 34746, "s": 34692, "text": "String hashing using Polynomial rolling hash function" }, { "code": null, "e": 34766, "s": 34746, "text": "Ternary Search Tree" }, { "code": null, "e": 34804, "s": 34766, "text": "C++ Program to implement Symbol Table" }, { "code": null, "e": 34847, "s": 34804, "text": "Find the k most frequent words from a file" }, { "code": null, "e": 34935, "s": 34847, "text": "Maximum distance between two points in coordinate plane using Rotating Caliper's Method" }, { "code": null, "e": 34984, "s": 34935, "text": "Self-Balancing-Binary-Search-Trees (Comparisons)" } ]
Convert a String to a Singly Linked List - GeeksforGeeks
19 Jul, 2021 Given string str, the task is to convert it into a singly Linked List.Examples: Input: str = "ABCDABC" Output: A -> B -> C -> D -> A -> B -> C Input: str = "GEEKS" Output: G -> E -> E -> K -> S Approach: Create a Linked List Fetch each character of the string and insert into a new node in the Linked List Print the Linked List Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ program to Convert a String// to a Singly Linked List #include <iostream>using namespace std; // Structure for a Singly Linked Liststruct node { char data; node* next;}; // Function to add a new node to the Linked Listnode* add(char data){ node* newnode = new node; newnode->data = data; newnode->next = NULL; return newnode;} // Function to convert the string to Linked List.node* string_to_SLL(string text, node* head){ head = add(text[0]); node* curr = head; // curr pointer points to the current node // where the insertion should take place for (int i = 1; i < text.size(); i++) { curr->next = add(text[i]); curr = curr->next; } return head;} // Function to print the data present in all the nodesvoid print(node* head){ node* curr = head; while (curr != NULL) { cout << curr->data << " -> "; curr = curr->next; }} // Driver codeint main(){ string text = "GEEKS"; node* head = NULL; head = string_to_SLL(text, head); print(head); return 0;} // This code is contributed by code_freak // Java program to Convert a String// to a Singly Linked Listclass GFG{ // Structure for a Singly Linked Liststatic class node{ char data; node next;}; // Function to add a new node to the Linked Liststatic node add(char data){ node newnode = new node(); newnode.data = data; newnode.next = null; return newnode;} // Function to convert the string// to Linked List.static node string_to_SLL(String text, node head){ head = add(text.charAt(0)); node curr = head; // curr pointer points to the current node // where the insertion should take place for (int i = 1; i < text.length(); i++) { curr.next = add(text.charAt(i)); curr = curr.next; } return head;} // Function to print the data// present in all the nodesstatic void print(node head){ node curr = head; while (curr != null) { System.out.print(curr.data + " -> "); curr = curr.next; }} // Driver codepublic static void main(String[] args){ String text = "GEEKS"; node head = null; head = string_to_SLL(text, head); print(head);}} // This code is contributed by PrinciRaj1992 # Python3 program to Convert a String# to a Singly Linked List # Structure for a Singly Linked Listclass node: def __init__(self): data = None next = None # Function to add a node to the Linked Listdef add(data): newnode = node() newnode.data = data newnode.next = None return newnode # Function to convert the string# to Linked List.def string_to_SLL(text,head): head = add(text[0]) curr = head # curr pointer points to the current node # where the insertion should take place for i in range(len(text) - 1): curr.next = add(text[i + 1]) curr = curr.next return head # Function to print the data# present in all the nodesdef print_(head): curr = head while (curr != None) : print ((curr.data), end = " - > " ) curr = curr.next # Driver codetext = "GEEKS"head = Nonehead = string_to_SLL(text, head)print_(head) # This code is contributed by Arnab Kundu // C# program to Convert a String// to a Singly Linked Listusing System; class GFG{ // Structure for a Singly Linked Listclass node{ public char data; public node next;}; // Function to add a new node// to the Linked Liststatic node add(char data){ node newnode = new node(); newnode.data = data; newnode.next = null; return newnode;} // Function to convert the string// to Linked List.static node string_to_SLL(String text, node head){ head = add(text[0]); node curr = head; // curr pointer points to the current node // where the insertion should take place for (int i = 1; i < text.Length; i++) { curr.next = add(text[i]); curr = curr.next; } return head;} // Function to print the data// present in all the nodesstatic void print(node head){ node curr = head; while (curr != null) { Console.Write(curr.data + " -> "); curr = curr.next; }} // Driver codepublic static void Main(String[] args){ String text = "GEEKS"; node head = null; head = string_to_SLL(text, head); print(head);}} // This code is contributed by 29AjayKumar <script>// Javascript program to Convert a String// to a Singly Linked List class node{ constructor() { this.data=''; this.next=null; }} // Function to add a new node to the Linked List function add(data){ let newnode = new node(); newnode.data = data; newnode.next = null; return newnode;} // Function to convert the string// to Linked List.function string_to_SLL(text,head){ head = add(text[0]); let curr = head; // curr pointer points to the current node // where the insertion should take place for (let i = 1; i < text.length; i++) { curr.next = add(text[i]); curr = curr.next; } return head;} // Function to print the data// present in all the nodesfunction print(head){ let curr = head; while (curr != null) { document.write(curr.data + " -> "); curr = curr.next; }} // Driver codelet text = "GEEKS"; let head = null;head = string_to_SLL(text, head); print(head); // This code is contributed by avanitrachhadiya2155</script> G -> E -> E -> K -> S -> princiraj1992 29AjayKumar ManasChhabra2 andrew1234 avanitrachhadiya2155 Data Structures-Linked List Strings Technical Scripter Strings Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Top 50 String Coding Problems for Interviews Naive algorithm for Pattern Searching Vigenère Cipher Hill Cipher Count words in a given string How to Append a Character to a String in C Convert character array to string in C++ Program to count occurrence of a given character in a string sprintf() in C Converting Roman Numerals to Decimal lying between 1 to 3999
[ { "code": null, "e": 24828, "s": 24800, "text": "\n19 Jul, 2021" }, { "code": null, "e": 24910, "s": 24828, "text": "Given string str, the task is to convert it into a singly Linked List.Examples: " }, { "code": null, "e": 25025, "s": 24910, "text": "Input: str = \"ABCDABC\"\nOutput: A -> B -> C -> D -> A -> B -> C\n\nInput: str = \"GEEKS\"\nOutput: G -> E -> E -> K -> S" }, { "code": null, "e": 25039, "s": 25027, "text": "Approach: " }, { "code": null, "e": 25060, "s": 25039, "text": "Create a Linked List" }, { "code": null, "e": 25141, "s": 25060, "text": "Fetch each character of the string and insert into a new node in the Linked List" }, { "code": null, "e": 25163, "s": 25141, "text": "Print the Linked List" }, { "code": null, "e": 25216, "s": 25163, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 25220, "s": 25216, "text": "C++" }, { "code": null, "e": 25225, "s": 25220, "text": "Java" }, { "code": null, "e": 25233, "s": 25225, "text": "Python3" }, { "code": null, "e": 25236, "s": 25233, "text": "C#" }, { "code": null, "e": 25247, "s": 25236, "text": "Javascript" }, { "code": "// C++ program to Convert a String// to a Singly Linked List #include <iostream>using namespace std; // Structure for a Singly Linked Liststruct node { char data; node* next;}; // Function to add a new node to the Linked Listnode* add(char data){ node* newnode = new node; newnode->data = data; newnode->next = NULL; return newnode;} // Function to convert the string to Linked List.node* string_to_SLL(string text, node* head){ head = add(text[0]); node* curr = head; // curr pointer points to the current node // where the insertion should take place for (int i = 1; i < text.size(); i++) { curr->next = add(text[i]); curr = curr->next; } return head;} // Function to print the data present in all the nodesvoid print(node* head){ node* curr = head; while (curr != NULL) { cout << curr->data << \" -> \"; curr = curr->next; }} // Driver codeint main(){ string text = \"GEEKS\"; node* head = NULL; head = string_to_SLL(text, head); print(head); return 0;} // This code is contributed by code_freak", "e": 26337, "s": 25247, "text": null }, { "code": "// Java program to Convert a String// to a Singly Linked Listclass GFG{ // Structure for a Singly Linked Liststatic class node{ char data; node next;}; // Function to add a new node to the Linked Liststatic node add(char data){ node newnode = new node(); newnode.data = data; newnode.next = null; return newnode;} // Function to convert the string// to Linked List.static node string_to_SLL(String text, node head){ head = add(text.charAt(0)); node curr = head; // curr pointer points to the current node // where the insertion should take place for (int i = 1; i < text.length(); i++) { curr.next = add(text.charAt(i)); curr = curr.next; } return head;} // Function to print the data// present in all the nodesstatic void print(node head){ node curr = head; while (curr != null) { System.out.print(curr.data + \" -> \"); curr = curr.next; }} // Driver codepublic static void main(String[] args){ String text = \"GEEKS\"; node head = null; head = string_to_SLL(text, head); print(head);}} // This code is contributed by PrinciRaj1992", "e": 27491, "s": 26337, "text": null }, { "code": "# Python3 program to Convert a String# to a Singly Linked List # Structure for a Singly Linked Listclass node: def __init__(self): data = None next = None # Function to add a node to the Linked Listdef add(data): newnode = node() newnode.data = data newnode.next = None return newnode # Function to convert the string# to Linked List.def string_to_SLL(text,head): head = add(text[0]) curr = head # curr pointer points to the current node # where the insertion should take place for i in range(len(text) - 1): curr.next = add(text[i + 1]) curr = curr.next return head # Function to print the data# present in all the nodesdef print_(head): curr = head while (curr != None) : print ((curr.data), end = \" - > \" ) curr = curr.next # Driver codetext = \"GEEKS\"head = Nonehead = string_to_SLL(text, head)print_(head) # This code is contributed by Arnab Kundu", "e": 28447, "s": 27491, "text": null }, { "code": "// C# program to Convert a String// to a Singly Linked Listusing System; class GFG{ // Structure for a Singly Linked Listclass node{ public char data; public node next;}; // Function to add a new node// to the Linked Liststatic node add(char data){ node newnode = new node(); newnode.data = data; newnode.next = null; return newnode;} // Function to convert the string// to Linked List.static node string_to_SLL(String text, node head){ head = add(text[0]); node curr = head; // curr pointer points to the current node // where the insertion should take place for (int i = 1; i < text.Length; i++) { curr.next = add(text[i]); curr = curr.next; } return head;} // Function to print the data// present in all the nodesstatic void print(node head){ node curr = head; while (curr != null) { Console.Write(curr.data + \" -> \"); curr = curr.next; }} // Driver codepublic static void Main(String[] args){ String text = \"GEEKS\"; node head = null; head = string_to_SLL(text, head); print(head);}} // This code is contributed by 29AjayKumar", "e": 29601, "s": 28447, "text": null }, { "code": "<script>// Javascript program to Convert a String// to a Singly Linked List class node{ constructor() { this.data=''; this.next=null; }} // Function to add a new node to the Linked List function add(data){ let newnode = new node(); newnode.data = data; newnode.next = null; return newnode;} // Function to convert the string// to Linked List.function string_to_SLL(text,head){ head = add(text[0]); let curr = head; // curr pointer points to the current node // where the insertion should take place for (let i = 1; i < text.length; i++) { curr.next = add(text[i]); curr = curr.next; } return head;} // Function to print the data// present in all the nodesfunction print(head){ let curr = head; while (curr != null) { document.write(curr.data + \" -> \"); curr = curr.next; }} // Driver codelet text = \"GEEKS\"; let head = null;head = string_to_SLL(text, head); print(head); // This code is contributed by avanitrachhadiya2155</script>", "e": 30635, "s": 29601, "text": null }, { "code": null, "e": 30660, "s": 30635, "text": "G -> E -> E -> K -> S ->" }, { "code": null, "e": 30676, "s": 30662, "text": "princiraj1992" }, { "code": null, "e": 30688, "s": 30676, "text": "29AjayKumar" }, { "code": null, "e": 30702, "s": 30688, "text": "ManasChhabra2" }, { "code": null, "e": 30713, "s": 30702, "text": "andrew1234" }, { "code": null, "e": 30734, "s": 30713, "text": "avanitrachhadiya2155" }, { "code": null, "e": 30762, "s": 30734, "text": "Data Structures-Linked List" }, { "code": null, "e": 30770, "s": 30762, "text": "Strings" }, { "code": null, "e": 30789, "s": 30770, "text": "Technical Scripter" }, { "code": null, "e": 30797, "s": 30789, "text": "Strings" }, { "code": null, "e": 30895, "s": 30797, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30940, "s": 30895, "text": "Top 50 String Coding Problems for Interviews" }, { "code": null, "e": 30978, "s": 30940, "text": "Naive algorithm for Pattern Searching" }, { "code": null, "e": 30995, "s": 30978, "text": "Vigenère Cipher" }, { "code": null, "e": 31007, "s": 30995, "text": "Hill Cipher" }, { "code": null, "e": 31037, "s": 31007, "text": "Count words in a given string" }, { "code": null, "e": 31080, "s": 31037, "text": "How to Append a Character to a String in C" }, { "code": null, "e": 31121, "s": 31080, "text": "Convert character array to string in C++" }, { "code": null, "e": 31182, "s": 31121, "text": "Program to count occurrence of a given character in a string" }, { "code": null, "e": 31197, "s": 31182, "text": "sprintf() in C" } ]
An Introduction to Clustering Algorithms in Python | by Jake Huneycutt | Towards Data Science
In data science, we often think about how to use data to make predictions on new data points. This is called “supervised learning.” Sometimes, however, rather than ‘making predictions’, we instead want to categorize data into buckets. This is termed “unsupervised learning.” To illustrate the difference, let’s say we’re at a major pizza chain and we’ve been tasked with creating a feature in the order management software that will predict delivery times for customers. In order to achieve this, we are given a dataset that has delivery times, distances traveled, day of week, time of day, staff on hand, and volume of sales for several deliveries in the past. From this data, we can make predictions on future delivery times. This is a good example of supervised learning. Now, let’s say the pizza chain wants to send out targeted coupons to customers. It wants to segment its customers into 4 groups: large families, small families, singles, and college students. We are given prior ordering data (e.g. size of order, price, frequency, etc) and we’re tasked with putting each customer into one of the four buckets. This would be an example of “unsupervised learning” since we’re not making predictions; we’re merely categorizing the customers into groups. Clustering is one of the most frequently utilized forms of unsupervised learning. In this article, we’ll explore two of the most common forms of clustering: k-means and hierarchical. Understanding the K-Means Clustering Algorithm Let’s look at how k-means clustering works. First, let me introduce you to my good friend, blobby; i.e. the make_blobs function in Python’s sci-kit learn library. We’ll create four random clusters using make_blobs to aid in our task. # import statementsfrom sklearn.datasets import make_blobsimport numpy as npimport matplotlib.pyplot as plt# create blobsdata = make_blobs(n_samples=200, n_features=2, centers=4, cluster_std=1.6, random_state=50)# create np array for data pointspoints = data[0]# create scatter plotplt.scatter(data[0][:,0], data[0][:,1], c=data[1], cmap='viridis')plt.xlim(-15,15)plt.ylim(-15,15) You can see our “blobs” below: We have four colored clusters, but there is some overlap with the two clusters on top, as well as the two clusters on the bottom. The first step in k-means clustering is to select random centroids. Since our k=4 in this instance, we’ll need 4 random centroids. Here is how it looked in my implementation from scratch. Next, we take each point and find the nearest centroid. There are different ways to measure distance, but I used Euclidean distance, which can be measured using np.linalg.norm in Python. Now that we have 4 clusters, we find the new centroids of the clusters. Then we match each point to the closest centroid again, repeating the process, until we can improve the clusters no more. In this case, when the process finished, I ended up with the result below. Note that these clusters are a bit different than my original clusters. This is the result of the random initialization trap. Essentially, our starting centroids can dictate the location of our clusters in k-mean clustering. This isn’t the result we wanted, but one way to combat this is with the k-means ++ algorithm, which provides better initial seeding in order to find the best clusters. Fortunately, this is automatically done in k-means implementation we’ll be using in Python. Implementing K-Means Clustering in Python To run k-means in Python, we’ll need to import KMeans from sci-kit learn. # import KMeansfrom sklearn.cluster import KMeans Note that in the documentation, k-means ++ is the default, so we don’t need to make any changes in order to run this improved methodology. Now, let’s run k-means on our blobs (which were put into a numpy array called ‘points’). # create kmeans objectkmeans = KMeans(n_clusters=4)# fit kmeans object to datakmeans.fit(points)# print location of clusters learned by kmeans objectprint(kmeans.cluster_centers_)# save new clusters for charty_km = kmeans.fit_predict(points) Now, we can see the results by running the following code in matplotlib. plt.scatter(points[y_km ==0,0], points[y_km == 0,1], s=100, c='red')plt.scatter(points[y_km ==1,0], points[y_km == 1,1], s=100, c='black')plt.scatter(points[y_km ==2,0], points[y_km == 2,1], s=100, c='blue')plt.scatter(points[y_km ==3,0], points[y_km == 3,1], s=100, c='cyan') And voila! We have our 4 clusters. Note that the k-means++ algorithm did a better job than the plain ole’ k-means I ran in the example, as it nearly perfectly captured the boundaries of the initial clusters we created. K-means is the most frequently used form of clustering due to its speed and simplicity. Another very common clustering method is hierarchical clustering. Implementing Agglomerative Hierarchical Clustering Agglomerative hierarchical clustering differs from k-means in a key way. Rather than choosing a number of clusters and starting out with random centroids, we instead begin with every point in our dataset as a “cluster.” Then we find the two closest points and combine them into a cluster. Then, we find the next closest points, and those become a cluster. We repeat the process until we only have one big giant cluster. Along the way, we create what’s called a dendrogram. This is our “history.” You can see the dendrogram for our data points below to get a sense of what’s happening. The dendrogram plots out each cluster and the distance. We can use the dendrogram to find the clusters for any number we chose. In the dendrogram above, it’s easy to see the starting points for the first cluster (blue), the second cluster (red), and the third cluster (green). Only the first 3 are color-coded here, but if you look over at the red side of the dendrogram, you can spot the starting point for the 4th cluster as well. The dendrogram runs all the way until every point is its own individual cluster. Let’s see how agglomerative hierarchical clustering works in Python. First, let’s import the necessary libraries from scipy.cluster.hierarchy and sklearn.clustering. # import hierarchical clustering librariesimport scipy.cluster.hierarchy as schfrom sklearn.cluster import AgglomerativeClustering Now, let’s create our dendrogram (which I’ve already shown you above), determine how many clusters we want, and save the data points from those clusters to chart them out. # create dendrogramdendrogram = sch.dendrogram(sch.linkage(points, method='ward'))# create clustershc = AgglomerativeClustering(n_clusters=4, affinity = 'euclidean', linkage = 'ward')# save clusters for charty_hc = hc.fit_predict(points) Now, we’ll do as we did with the k-means algorithm and see our clusters using matplotlib. plt.scatter(points[y_hc ==0,0], points[y_hc == 0,1], s=100, c='red')plt.scatter(points[y_hc==1,0], points[y_hc == 1,1], s=100, c='black')plt.scatter(points[y_hc ==2,0], points[y_hc == 2,1], s=100, c='blue')plt.scatter(points[y_hc ==3,0], points[y_hc == 3,1], s=100, c='cyan') Here are the results: In this instance, the results between k-means and hierarchical clustering were pretty similar. This is not always the case, however. In general, the advantage of agglomerative hierarchical clustering is that it tends to produce more accurate results. The downside is that hierarchical clustering is more difficult to implement and more time/resource consuming than k-means. Further Reading If you want to know more about clustering, I highly recommend George Seif’s article, “The 5 Clustering Algorithms Data Scientists Need to Know.” Additional Resources G. James, D. Witten, et. al. Introduction to Statistical Learning, Chapter 10: Unsupervised Learning, Link (PDF)Andrea Trevino, Introduction to K-Means Clustering, LinkKirill Eremenko, Machine Learning A-Z (Udemy course), Link G. James, D. Witten, et. al. Introduction to Statistical Learning, Chapter 10: Unsupervised Learning, Link (PDF) Andrea Trevino, Introduction to K-Means Clustering, Link Kirill Eremenko, Machine Learning A-Z (Udemy course), Link
[ { "code": null, "e": 447, "s": 172, "text": "In data science, we often think about how to use data to make predictions on new data points. This is called “supervised learning.” Sometimes, however, rather than ‘making predictions’, we instead want to categorize data into buckets. This is termed “unsupervised learning.”" }, { "code": null, "e": 947, "s": 447, "text": "To illustrate the difference, let’s say we’re at a major pizza chain and we’ve been tasked with creating a feature in the order management software that will predict delivery times for customers. In order to achieve this, we are given a dataset that has delivery times, distances traveled, day of week, time of day, staff on hand, and volume of sales for several deliveries in the past. From this data, we can make predictions on future delivery times. This is a good example of supervised learning." }, { "code": null, "e": 1431, "s": 947, "text": "Now, let’s say the pizza chain wants to send out targeted coupons to customers. It wants to segment its customers into 4 groups: large families, small families, singles, and college students. We are given prior ordering data (e.g. size of order, price, frequency, etc) and we’re tasked with putting each customer into one of the four buckets. This would be an example of “unsupervised learning” since we’re not making predictions; we’re merely categorizing the customers into groups." }, { "code": null, "e": 1614, "s": 1431, "text": "Clustering is one of the most frequently utilized forms of unsupervised learning. In this article, we’ll explore two of the most common forms of clustering: k-means and hierarchical." }, { "code": null, "e": 1661, "s": 1614, "text": "Understanding the K-Means Clustering Algorithm" }, { "code": null, "e": 1895, "s": 1661, "text": "Let’s look at how k-means clustering works. First, let me introduce you to my good friend, blobby; i.e. the make_blobs function in Python’s sci-kit learn library. We’ll create four random clusters using make_blobs to aid in our task." }, { "code": null, "e": 2276, "s": 1895, "text": "# import statementsfrom sklearn.datasets import make_blobsimport numpy as npimport matplotlib.pyplot as plt# create blobsdata = make_blobs(n_samples=200, n_features=2, centers=4, cluster_std=1.6, random_state=50)# create np array for data pointspoints = data[0]# create scatter plotplt.scatter(data[0][:,0], data[0][:,1], c=data[1], cmap='viridis')plt.xlim(-15,15)plt.ylim(-15,15)" }, { "code": null, "e": 2307, "s": 2276, "text": "You can see our “blobs” below:" }, { "code": null, "e": 2625, "s": 2307, "text": "We have four colored clusters, but there is some overlap with the two clusters on top, as well as the two clusters on the bottom. The first step in k-means clustering is to select random centroids. Since our k=4 in this instance, we’ll need 4 random centroids. Here is how it looked in my implementation from scratch." }, { "code": null, "e": 2812, "s": 2625, "text": "Next, we take each point and find the nearest centroid. There are different ways to measure distance, but I used Euclidean distance, which can be measured using np.linalg.norm in Python." }, { "code": null, "e": 2884, "s": 2812, "text": "Now that we have 4 clusters, we find the new centroids of the clusters." }, { "code": null, "e": 3081, "s": 2884, "text": "Then we match each point to the closest centroid again, repeating the process, until we can improve the clusters no more. In this case, when the process finished, I ended up with the result below." }, { "code": null, "e": 3306, "s": 3081, "text": "Note that these clusters are a bit different than my original clusters. This is the result of the random initialization trap. Essentially, our starting centroids can dictate the location of our clusters in k-mean clustering." }, { "code": null, "e": 3566, "s": 3306, "text": "This isn’t the result we wanted, but one way to combat this is with the k-means ++ algorithm, which provides better initial seeding in order to find the best clusters. Fortunately, this is automatically done in k-means implementation we’ll be using in Python." }, { "code": null, "e": 3608, "s": 3566, "text": "Implementing K-Means Clustering in Python" }, { "code": null, "e": 3682, "s": 3608, "text": "To run k-means in Python, we’ll need to import KMeans from sci-kit learn." }, { "code": null, "e": 3732, "s": 3682, "text": "# import KMeansfrom sklearn.cluster import KMeans" }, { "code": null, "e": 3960, "s": 3732, "text": "Note that in the documentation, k-means ++ is the default, so we don’t need to make any changes in order to run this improved methodology. Now, let’s run k-means on our blobs (which were put into a numpy array called ‘points’)." }, { "code": null, "e": 4202, "s": 3960, "text": "# create kmeans objectkmeans = KMeans(n_clusters=4)# fit kmeans object to datakmeans.fit(points)# print location of clusters learned by kmeans objectprint(kmeans.cluster_centers_)# save new clusters for charty_km = kmeans.fit_predict(points)" }, { "code": null, "e": 4275, "s": 4202, "text": "Now, we can see the results by running the following code in matplotlib." }, { "code": null, "e": 4552, "s": 4275, "text": "plt.scatter(points[y_km ==0,0], points[y_km == 0,1], s=100, c='red')plt.scatter(points[y_km ==1,0], points[y_km == 1,1], s=100, c='black')plt.scatter(points[y_km ==2,0], points[y_km == 2,1], s=100, c='blue')plt.scatter(points[y_km ==3,0], points[y_km == 3,1], s=100, c='cyan')" }, { "code": null, "e": 4771, "s": 4552, "text": "And voila! We have our 4 clusters. Note that the k-means++ algorithm did a better job than the plain ole’ k-means I ran in the example, as it nearly perfectly captured the boundaries of the initial clusters we created." }, { "code": null, "e": 4925, "s": 4771, "text": "K-means is the most frequently used form of clustering due to its speed and simplicity. Another very common clustering method is hierarchical clustering." }, { "code": null, "e": 4976, "s": 4925, "text": "Implementing Agglomerative Hierarchical Clustering" }, { "code": null, "e": 5396, "s": 4976, "text": "Agglomerative hierarchical clustering differs from k-means in a key way. Rather than choosing a number of clusters and starting out with random centroids, we instead begin with every point in our dataset as a “cluster.” Then we find the two closest points and combine them into a cluster. Then, we find the next closest points, and those become a cluster. We repeat the process until we only have one big giant cluster." }, { "code": null, "e": 5561, "s": 5396, "text": "Along the way, we create what’s called a dendrogram. This is our “history.” You can see the dendrogram for our data points below to get a sense of what’s happening." }, { "code": null, "e": 6075, "s": 5561, "text": "The dendrogram plots out each cluster and the distance. We can use the dendrogram to find the clusters for any number we chose. In the dendrogram above, it’s easy to see the starting points for the first cluster (blue), the second cluster (red), and the third cluster (green). Only the first 3 are color-coded here, but if you look over at the red side of the dendrogram, you can spot the starting point for the 4th cluster as well. The dendrogram runs all the way until every point is its own individual cluster." }, { "code": null, "e": 6241, "s": 6075, "text": "Let’s see how agglomerative hierarchical clustering works in Python. First, let’s import the necessary libraries from scipy.cluster.hierarchy and sklearn.clustering." }, { "code": null, "e": 6372, "s": 6241, "text": "# import hierarchical clustering librariesimport scipy.cluster.hierarchy as schfrom sklearn.cluster import AgglomerativeClustering" }, { "code": null, "e": 6544, "s": 6372, "text": "Now, let’s create our dendrogram (which I’ve already shown you above), determine how many clusters we want, and save the data points from those clusters to chart them out." }, { "code": null, "e": 6782, "s": 6544, "text": "# create dendrogramdendrogram = sch.dendrogram(sch.linkage(points, method='ward'))# create clustershc = AgglomerativeClustering(n_clusters=4, affinity = 'euclidean', linkage = 'ward')# save clusters for charty_hc = hc.fit_predict(points)" }, { "code": null, "e": 6872, "s": 6782, "text": "Now, we’ll do as we did with the k-means algorithm and see our clusters using matplotlib." }, { "code": null, "e": 7148, "s": 6872, "text": "plt.scatter(points[y_hc ==0,0], points[y_hc == 0,1], s=100, c='red')plt.scatter(points[y_hc==1,0], points[y_hc == 1,1], s=100, c='black')plt.scatter(points[y_hc ==2,0], points[y_hc == 2,1], s=100, c='blue')plt.scatter(points[y_hc ==3,0], points[y_hc == 3,1], s=100, c='cyan')" }, { "code": null, "e": 7170, "s": 7148, "text": "Here are the results:" }, { "code": null, "e": 7544, "s": 7170, "text": "In this instance, the results between k-means and hierarchical clustering were pretty similar. This is not always the case, however. In general, the advantage of agglomerative hierarchical clustering is that it tends to produce more accurate results. The downside is that hierarchical clustering is more difficult to implement and more time/resource consuming than k-means." }, { "code": null, "e": 7560, "s": 7544, "text": "Further Reading" }, { "code": null, "e": 7705, "s": 7560, "text": "If you want to know more about clustering, I highly recommend George Seif’s article, “The 5 Clustering Algorithms Data Scientists Need to Know.”" }, { "code": null, "e": 7726, "s": 7705, "text": "Additional Resources" }, { "code": null, "e": 7953, "s": 7726, "text": "G. James, D. Witten, et. al. Introduction to Statistical Learning, Chapter 10: Unsupervised Learning, Link (PDF)Andrea Trevino, Introduction to K-Means Clustering, LinkKirill Eremenko, Machine Learning A-Z (Udemy course), Link" }, { "code": null, "e": 8066, "s": 7953, "text": "G. James, D. Witten, et. al. Introduction to Statistical Learning, Chapter 10: Unsupervised Learning, Link (PDF)" }, { "code": null, "e": 8123, "s": 8066, "text": "Andrea Trevino, Introduction to K-Means Clustering, Link" } ]
Insert more than one element at once in a C# List
Use the InsertRange() method to insert a list in between the existing lists in C#. Through this, you can easily add more than one element to the existing list. Let us first set a list − List<int> arr1 = new List<int>(); arr1.Add(10); arr1.Add(20); arr1.Add(30); arr1.Add(40); arr1.Add(50); Now, let us set an array. The elements of this array are what we will add to the above list − int[] arr2 = new int[4]; arr2[0] = 60; arr2[1] = 70; arr2[2] = 80; arr2[3] = 90; We will add the above elements to the list − arr1.InsertRange(5, arr2); Here is the complete code − Live Demo using System; using System.Collections.Generic; public class Demo { public static void Main() { List<int> arr1 = new List<int>(); arr1.Add(10); arr1.Add(20); arr1.Add(30); arr1.Add(40); arr1.Add(50); Console.WriteLine("Initial List ..."); foreach (int i in arr1) { Console.WriteLine(i); } int[] arr2 = new int[4]; arr2[0] = 60; arr2[1] = 70; arr2[2] = 80; arr2[3] = 90; arr1.InsertRange(5, arr2); Console.WriteLine("After adding elements ..."); foreach (int i in arr1) { Console.WriteLine(i); } } } Initial List ... 10 20 30 40 50 After adding elements ... 10 20 30 40 50 60 70 80 90
[ { "code": null, "e": 1222, "s": 1062, "text": "Use the InsertRange() method to insert a list in between the existing lists in C#. Through this, you can easily add more than one element to the existing list." }, { "code": null, "e": 1248, "s": 1222, "text": "Let us first set a list −" }, { "code": null, "e": 1352, "s": 1248, "text": "List<int> arr1 = new List<int>();\narr1.Add(10);\narr1.Add(20);\narr1.Add(30);\narr1.Add(40);\narr1.Add(50);" }, { "code": null, "e": 1446, "s": 1352, "text": "Now, let us set an array. The elements of this array are what we will add to the above list −" }, { "code": null, "e": 1527, "s": 1446, "text": "int[] arr2 = new int[4];\narr2[0] = 60;\narr2[1] = 70;\narr2[2] = 80;\narr2[3] = 90;" }, { "code": null, "e": 1572, "s": 1527, "text": "We will add the above elements to the list −" }, { "code": null, "e": 1599, "s": 1572, "text": "arr1.InsertRange(5, arr2);" }, { "code": null, "e": 1627, "s": 1599, "text": "Here is the complete code −" }, { "code": null, "e": 1638, "s": 1627, "text": " Live Demo" }, { "code": null, "e": 2269, "s": 1638, "text": "using System;\nusing System.Collections.Generic;\npublic class Demo {\n public static void Main() {\n List<int> arr1 = new List<int>();\n arr1.Add(10);\n arr1.Add(20);\n arr1.Add(30);\n arr1.Add(40);\n arr1.Add(50);\n Console.WriteLine(\"Initial List ...\");\n foreach (int i in arr1) {\n Console.WriteLine(i);\n }\n int[] arr2 = new int[4];\n arr2[0] = 60;\n arr2[1] = 70;\n arr2[2] = 80;\n arr2[3] = 90;\n arr1.InsertRange(5, arr2);\n Console.WriteLine(\"After adding elements ...\");\n foreach (int i in arr1) {\n Console.WriteLine(i);\n }\n }\n}" }, { "code": null, "e": 2354, "s": 2269, "text": "Initial List ...\n10\n20\n30\n40\n50\nAfter adding elements ...\n10\n20\n30\n40\n50\n60\n70\n80\n90" } ]
Three Ways to Create Dockernized LaTeX Environment | by Shinichi Okada | Towards Data Science
Table of ContentsIntroduction1. Setup2. Method 1: tianon/latex3. Method 2: Remote-Containers4. Method 3: Creating your container5. How to switch Remote containers6. Opening a PDFConclusion We can run a Docker application in any environment, Linux, Windows, or Mac. Docker provides a set of official base images for the most used operating systems and apps. Docker allows you to take full control of your environment, installing what you need, removing, and installing from Dockerfile. In this article, I will show you three ways how to use LaTeX on Docker and VSCode Remote Containers extension. In the first part, we use tianon/latex image and qmcgaw/latexdevcontainer Docker image in the second part. In the end, we create our image based on the qmcgaw/latexdevcontainer Docker image. If you wish, you can delete LaTeX from your computer. For me I needed to run: $ brew uninstall mactex Please install Docker Desktop and VSCode’s Remote-Containers and LaTeX-Workshop VSCode extension. towardsdatascience.com Pull tianon/latex image: $ docker pull tianon/latex Open settings.json by SHIFT+CMD+P: And add the following: { // ... YOUR OTHER SETTINGS ... // latex "latex-workshop.docker.enabled": true, "latex-workshop.latex.outDir": "./out", "latex-workshop.synctex.afterBuild.enabled": true, "latex-workshop.view.pdf.viewer": "tab", "latex-workshop.docker.image.latex": "tianon/latex", // End } Create a tex file and enter the following: \documentclass{article}\begin{document}An Example for a very \tiny{tiny} \normalsize \LaTeX \ document.\end{document} You can build a LaTeX file either by clicking the build icon or using OPTION+CMD+B on Mac. After that whenever you save a file, it will automatically update the PDF. Now you are running LaTeX on Docker. The Visual Studio Code Remote — Containers extension lets you use a Docker container as a full-featured development environment. It allows you to open any folder inside (or mounted into) a container and take advantage of Visual Studio Code’s full feature set. A devcontainer.json file in your project tells VS Code how to access (or create) a development container with a well-defined tool and runtime stack. — from Developing inside a Container In your directory, create .devcontainer/devcontainer.json and add the following: { "name": "project-dev", "dockerComposeFile": ["docker-compose.yml"], "service": "vscode", "runServices": ["vscode"], "shutdownAction": "stopCompose", "workspaceFolder": "/workspace", "postCreateCommand": "", "extensions": [ "james-yu.latex-workshop", // Git "eamodio.gitlens", // Other helpers "shardulm94.trailing-spaces", "stkb.rewrap", // rewrap comments after n characters on one line // Other "vscode-icons-team.vscode-icons", ], "settings": { // General settings "files.eol": "\n", // Latex settings "latex-workshop.chktex.enabled": true, "latex-workshop.latex.clean.subfolder.enabled": true, "latex-workshop.latex.autoClean.run": "onBuilt", "editor.formatOnSave": true, "files.associations": { "*.tex": "latex" }, "latex-workshop.latexindent.args": [ "-c", "%DIR%/", "%TMPFILE%", "-y=\"defaultIndent: '%INDENT%',onlyOneBackUp: 1\"", ] }} In the setting, we enable listing LaTeX with ChkTeX, deleting LaTeX auxiliary files recursively in sub-folders, and we delete LaTeX auxiliary files on built. If you wish, you can see more setting in VSCode > Preferences > Settings > Extensions > LaTeX. Create .devcontainer/docker-compose.yml and add the following: version: "3.7"services: vscode: image: qmcgaw/latexdevcontainer volumes: - ../:/workspace - ~/.ssh:/home/vscode/.ssh:ro - ~/.ssh:/root/.ssh:ro - /var/run/docker.sock:/var/run/docker.sock environment: - TZ= cap_add: - SYS_PTRACE security_opt: - seccomp:unconfined entrypoint: zsh -c "while sleep 1000; do :; done" We use qmcgaw/latexdevcontainer as the image. It uses texlive 2020 basic scheme and latexmk for LaTeX compilation to PDF. It formats on save using latexindent and uses chktex for LaTeX linting. You have the following structure: Click the green icon at the left-bottom, or open the command palette in Visual Studio Code (CMD/CTRL+SHIFT+P), and select Remote-Containers: Open Folder in Container... and choose your project. It will pull the Docker image, in this case qmcgaw/latexdevcontainer, and run a container behind the scene. Once it is done, you will see “Dev Container” at the bottom left in VSCode. If you need to install LaTeX packages you can use tlmgr in the VSCode terminal: $/workspace tlmgr update --self$/workspace sudo apk add xz$/workspace tlmgr install lastpage$/workspace texhash Create a simple tex file: \documentclass{article} \usepackage{lastpage}\begin{document}An Example document.\[ \frac{4}{12}\]\end{document} And when you save it, it will create a PDF file. qmcgaw/latexdevcontainer is a great starting point to create your Dockerfile and install all packages in your image. Here is an example. Create a new directory and a Dockerfile in it: FROM qmcgaw/latexdevcontainerARG USERNAME=vscodeUSER rootRUN tlmgr update --self && \ tlmgr install latexindent latexmk && \ tlmgr install mathexam setspace adjustbox xkeyval collectbox enumitem lastpage && \ texhashUSER ${USERNAME} This will update tlmgr and install all packages I need. We can add any LaTeX packages using tlmgr install .... We build an image from this Dockerfile. $ docker build -t shinokada/latexexam . I am running this command from the same directory I have the Docker file. Let’s check the image we just created. $ docker imagesREPOSITORY TAG IMAGE ID CREATED SIZEshinokada/latexexam latest 7035f718823c 32 seconds ago 401MBqmcgaw/latexdevcontainer latest 85b911aaea3e 3 weeks ago 382MB It has 19 MB more than qmcgaw/latexdevcontainer. You can push to Docker Hub so that you can use it in the future and share it with others. $ docker login...$ docker push shinokada/latexexam... We will update .devcontainer/docker-compose.yml file so that VSCode uses our new Docker image. version: "3.7"services: vscode: image: shinokada/latexexam volumes: - ../:/workspace - ~/.ssh:/home/vscode/.ssh:ro - ~/.ssh:/root/.ssh:ro - /var/run/docker.sock:/var/run/docker.sock environment: - TZ= cap_add: - SYS_PTRACE security_opt: - seccomp:unconfined entrypoint: zsh -c "while sleep 1000; do :; done" The only difference is image: shinokada/latexexam. Let’s update .devcontainer/devcontainer.json. We are going to output PDF to the /out directory. We use the same file as before and add a line: ..."settings": { // General settings "files.eol": "\n", // Latex settings "latex-workshop.chktex.enabled": true, "latex-workshop.latex.outDir": "./out", ... Let’s create a sample tex file called percent.tex. Your directory structure is like this: Then select “Open Folder in Container” as we did before. It will start Dev Container. Save the percent.tex file and see a PDF is created in the out directory. When you change files in .devcontainer directory, you need to rebuild a container. Select “Remote-Containers: Rebuild Container”. If the above method doesn’t work, you may need to select “Remote-Containers: Reopen Locally” first then select “Remote-Containers: Open Folder in Container”. You can view a tex file in the VSCode tab or web browser. Please note you need to do it from a tex file. If you try to open it from another type of file, it won’t work. The size of qmcgaw/latexdevcontainer is 382MB and it is much smaller than tianon/latex. You can customize your image by creating your Dockerfile and using the FROM instruction to specify the parent image from which you are building. Even though the file size of tianon/latex is big, the advantage of using it is that you don’t need to install packages. It already has most of the standard packages. Get full access to every story on Medium by becoming a member. latexcontainer Easy Docker LaTeX Setup with vscode and Grammarly Developing inside a Container
[ { "code": null, "e": 361, "s": 172, "text": "Table of ContentsIntroduction1. Setup2. Method 1: tianon/latex3. Method 2: Remote-Containers4. Method 3: Creating your container5. How to switch Remote containers6. Opening a PDFConclusion" }, { "code": null, "e": 657, "s": 361, "text": "We can run a Docker application in any environment, Linux, Windows, or Mac. Docker provides a set of official base images for the most used operating systems and apps. Docker allows you to take full control of your environment, installing what you need, removing, and installing from Dockerfile." }, { "code": null, "e": 959, "s": 657, "text": "In this article, I will show you three ways how to use LaTeX on Docker and VSCode Remote Containers extension. In the first part, we use tianon/latex image and qmcgaw/latexdevcontainer Docker image in the second part. In the end, we create our image based on the qmcgaw/latexdevcontainer Docker image." }, { "code": null, "e": 1013, "s": 959, "text": "If you wish, you can delete LaTeX from your computer." }, { "code": null, "e": 1037, "s": 1013, "text": "For me I needed to run:" }, { "code": null, "e": 1061, "s": 1037, "text": "$ brew uninstall mactex" }, { "code": null, "e": 1159, "s": 1061, "text": "Please install Docker Desktop and VSCode’s Remote-Containers and LaTeX-Workshop VSCode extension." }, { "code": null, "e": 1182, "s": 1159, "text": "towardsdatascience.com" }, { "code": null, "e": 1207, "s": 1182, "text": "Pull tianon/latex image:" }, { "code": null, "e": 1234, "s": 1207, "text": "$ docker pull tianon/latex" }, { "code": null, "e": 1269, "s": 1234, "text": "Open settings.json by SHIFT+CMD+P:" }, { "code": null, "e": 1292, "s": 1269, "text": "And add the following:" }, { "code": null, "e": 1592, "s": 1292, "text": "{ // ... YOUR OTHER SETTINGS ... // latex \"latex-workshop.docker.enabled\": true, \"latex-workshop.latex.outDir\": \"./out\", \"latex-workshop.synctex.afterBuild.enabled\": true, \"latex-workshop.view.pdf.viewer\": \"tab\", \"latex-workshop.docker.image.latex\": \"tianon/latex\", // End }" }, { "code": null, "e": 1635, "s": 1592, "text": "Create a tex file and enter the following:" }, { "code": null, "e": 1753, "s": 1635, "text": "\\documentclass{article}\\begin{document}An Example for a very \\tiny{tiny} \\normalsize \\LaTeX \\ document.\\end{document}" }, { "code": null, "e": 1844, "s": 1753, "text": "You can build a LaTeX file either by clicking the build icon or using OPTION+CMD+B on Mac." }, { "code": null, "e": 1919, "s": 1844, "text": "After that whenever you save a file, it will automatically update the PDF." }, { "code": null, "e": 1956, "s": 1919, "text": "Now you are running LaTeX on Docker." }, { "code": null, "e": 2402, "s": 1956, "text": "The Visual Studio Code Remote — Containers extension lets you use a Docker container as a full-featured development environment. It allows you to open any folder inside (or mounted into) a container and take advantage of Visual Studio Code’s full feature set. A devcontainer.json file in your project tells VS Code how to access (or create) a development container with a well-defined tool and runtime stack. — from Developing inside a Container" }, { "code": null, "e": 2483, "s": 2402, "text": "In your directory, create .devcontainer/devcontainer.json and add the following:" }, { "code": null, "e": 3550, "s": 2483, "text": "{ \"name\": \"project-dev\", \"dockerComposeFile\": [\"docker-compose.yml\"], \"service\": \"vscode\", \"runServices\": [\"vscode\"], \"shutdownAction\": \"stopCompose\", \"workspaceFolder\": \"/workspace\", \"postCreateCommand\": \"\", \"extensions\": [ \"james-yu.latex-workshop\", // Git \"eamodio.gitlens\", // Other helpers \"shardulm94.trailing-spaces\", \"stkb.rewrap\", // rewrap comments after n characters on one line // Other \"vscode-icons-team.vscode-icons\", ], \"settings\": { // General settings \"files.eol\": \"\\n\", // Latex settings \"latex-workshop.chktex.enabled\": true, \"latex-workshop.latex.clean.subfolder.enabled\": true, \"latex-workshop.latex.autoClean.run\": \"onBuilt\", \"editor.formatOnSave\": true, \"files.associations\": { \"*.tex\": \"latex\" }, \"latex-workshop.latexindent.args\": [ \"-c\", \"%DIR%/\", \"%TMPFILE%\", \"-y=\\\"defaultIndent: '%INDENT%',onlyOneBackUp: 1\\\"\", ] }}" }, { "code": null, "e": 3708, "s": 3550, "text": "In the setting, we enable listing LaTeX with ChkTeX, deleting LaTeX auxiliary files recursively in sub-folders, and we delete LaTeX auxiliary files on built." }, { "code": null, "e": 3803, "s": 3708, "text": "If you wish, you can see more setting in VSCode > Preferences > Settings > Extensions > LaTeX." }, { "code": null, "e": 3866, "s": 3803, "text": "Create .devcontainer/docker-compose.yml and add the following:" }, { "code": null, "e": 4233, "s": 3866, "text": "version: \"3.7\"services: vscode: image: qmcgaw/latexdevcontainer volumes: - ../:/workspace - ~/.ssh:/home/vscode/.ssh:ro - ~/.ssh:/root/.ssh:ro - /var/run/docker.sock:/var/run/docker.sock environment: - TZ= cap_add: - SYS_PTRACE security_opt: - seccomp:unconfined entrypoint: zsh -c \"while sleep 1000; do :; done\"" }, { "code": null, "e": 4427, "s": 4233, "text": "We use qmcgaw/latexdevcontainer as the image. It uses texlive 2020 basic scheme and latexmk for LaTeX compilation to PDF. It formats on save using latexindent and uses chktex for LaTeX linting." }, { "code": null, "e": 4461, "s": 4427, "text": "You have the following structure:" }, { "code": null, "e": 4655, "s": 4461, "text": "Click the green icon at the left-bottom, or open the command palette in Visual Studio Code (CMD/CTRL+SHIFT+P), and select Remote-Containers: Open Folder in Container... and choose your project." }, { "code": null, "e": 4763, "s": 4655, "text": "It will pull the Docker image, in this case qmcgaw/latexdevcontainer, and run a container behind the scene." }, { "code": null, "e": 4839, "s": 4763, "text": "Once it is done, you will see “Dev Container” at the bottom left in VSCode." }, { "code": null, "e": 4919, "s": 4839, "text": "If you need to install LaTeX packages you can use tlmgr in the VSCode terminal:" }, { "code": null, "e": 5031, "s": 4919, "text": "$/workspace tlmgr update --self$/workspace sudo apk add xz$/workspace tlmgr install lastpage$/workspace texhash" }, { "code": null, "e": 5057, "s": 5031, "text": "Create a simple tex file:" }, { "code": null, "e": 5170, "s": 5057, "text": "\\documentclass{article} \\usepackage{lastpage}\\begin{document}An Example document.\\[ \\frac{4}{12}\\]\\end{document}" }, { "code": null, "e": 5219, "s": 5170, "text": "And when you save it, it will create a PDF file." }, { "code": null, "e": 5356, "s": 5219, "text": "qmcgaw/latexdevcontainer is a great starting point to create your Dockerfile and install all packages in your image. Here is an example." }, { "code": null, "e": 5403, "s": 5356, "text": "Create a new directory and a Dockerfile in it:" }, { "code": null, "e": 5645, "s": 5403, "text": "FROM qmcgaw/latexdevcontainerARG USERNAME=vscodeUSER rootRUN tlmgr update --self && \\ tlmgr install latexindent latexmk && \\ tlmgr install mathexam setspace adjustbox xkeyval collectbox enumitem lastpage && \\ texhashUSER ${USERNAME}" }, { "code": null, "e": 5756, "s": 5645, "text": "This will update tlmgr and install all packages I need. We can add any LaTeX packages using tlmgr install ...." }, { "code": null, "e": 5796, "s": 5756, "text": "We build an image from this Dockerfile." }, { "code": null, "e": 5836, "s": 5796, "text": "$ docker build -t shinokada/latexexam ." }, { "code": null, "e": 5910, "s": 5836, "text": "I am running this command from the same directory I have the Docker file." }, { "code": null, "e": 5949, "s": 5910, "text": "Let’s check the image we just created." }, { "code": null, "e": 6240, "s": 5949, "text": "$ docker imagesREPOSITORY TAG IMAGE ID CREATED SIZEshinokada/latexexam latest 7035f718823c 32 seconds ago 401MBqmcgaw/latexdevcontainer latest 85b911aaea3e 3 weeks ago 382MB" }, { "code": null, "e": 6289, "s": 6240, "text": "It has 19 MB more than qmcgaw/latexdevcontainer." }, { "code": null, "e": 6379, "s": 6289, "text": "You can push to Docker Hub so that you can use it in the future and share it with others." }, { "code": null, "e": 6433, "s": 6379, "text": "$ docker login...$ docker push shinokada/latexexam..." }, { "code": null, "e": 6528, "s": 6433, "text": "We will update .devcontainer/docker-compose.yml file so that VSCode uses our new Docker image." }, { "code": null, "e": 6890, "s": 6528, "text": "version: \"3.7\"services: vscode: image: shinokada/latexexam volumes: - ../:/workspace - ~/.ssh:/home/vscode/.ssh:ro - ~/.ssh:/root/.ssh:ro - /var/run/docker.sock:/var/run/docker.sock environment: - TZ= cap_add: - SYS_PTRACE security_opt: - seccomp:unconfined entrypoint: zsh -c \"while sleep 1000; do :; done\"" }, { "code": null, "e": 6941, "s": 6890, "text": "The only difference is image: shinokada/latexexam." }, { "code": null, "e": 7084, "s": 6941, "text": "Let’s update .devcontainer/devcontainer.json. We are going to output PDF to the /out directory. We use the same file as before and add a line:" }, { "code": null, "e": 7283, "s": 7084, "text": "...\"settings\": { // General settings \"files.eol\": \"\\n\", // Latex settings \"latex-workshop.chktex.enabled\": true, \"latex-workshop.latex.outDir\": \"./out\", ..." }, { "code": null, "e": 7334, "s": 7283, "text": "Let’s create a sample tex file called percent.tex." }, { "code": null, "e": 7373, "s": 7334, "text": "Your directory structure is like this:" }, { "code": null, "e": 7459, "s": 7373, "text": "Then select “Open Folder in Container” as we did before. It will start Dev Container." }, { "code": null, "e": 7532, "s": 7459, "text": "Save the percent.tex file and see a PDF is created in the out directory." }, { "code": null, "e": 7662, "s": 7532, "text": "When you change files in .devcontainer directory, you need to rebuild a container. Select “Remote-Containers: Rebuild Container”." }, { "code": null, "e": 7820, "s": 7662, "text": "If the above method doesn’t work, you may need to select “Remote-Containers: Reopen Locally” first then select “Remote-Containers: Open Folder in Container”." }, { "code": null, "e": 7989, "s": 7820, "text": "You can view a tex file in the VSCode tab or web browser. Please note you need to do it from a tex file. If you try to open it from another type of file, it won’t work." }, { "code": null, "e": 8222, "s": 7989, "text": "The size of qmcgaw/latexdevcontainer is 382MB and it is much smaller than tianon/latex. You can customize your image by creating your Dockerfile and using the FROM instruction to specify the parent image from which you are building." }, { "code": null, "e": 8388, "s": 8222, "text": "Even though the file size of tianon/latex is big, the advantage of using it is that you don’t need to install packages. It already has most of the standard packages." }, { "code": null, "e": 8451, "s": 8388, "text": "Get full access to every story on Medium by becoming a member." }, { "code": null, "e": 8466, "s": 8451, "text": "latexcontainer" }, { "code": null, "e": 8516, "s": 8466, "text": "Easy Docker LaTeX Setup with vscode and Grammarly" } ]
How to find absolute difference between two numbers in MySQL?
To get the difference between two number in MySQL, let us first create a demo table mysql> create table findDifferenceDemo -> ( -> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY, -> FirstNumber float, -> SecondNumber float -> ); Query OK, 0 rows affected (0.60 sec) Insert some records in the table using insert command. The query is as follows − mysql> insert into findDifferenceDemo(FirstNumber,SecondNumber) values(4.2,2.3); Query OK, 1 row affected (0.20 sec) mysql> insert into findDifferenceDemo(FirstNumber,SecondNumber) values(23.4,5.6); Query OK, 1 row affected (0.14 sec) mysql> insert into findDifferenceDemo(FirstNumber,SecondNumber) values(5.8,34.56); Query OK, 1 row affected (0.16 sec) mysql> insert into findDifferenceDemo(FirstNumber,SecondNumber) values(7.8,7.2); Query OK, 1 row affected (0.16 sec) mysql> insert into findDifferenceDemo(FirstNumber,SecondNumber) values(12.8,10.2); Query OK, 1 row affected (0.13 sec) Display all records from the table using select statement. The query is as follows − mysql> select *from findDifferenceDemo; The following is the output +----+-------------+--------------+ | Id | FirstNumber | SecondNumber | +----+-------------+--------------+ | 1 | 4.2 | 2.3 | | 2 | 23.4 | 5.6 | | 3 | 5.8 | 34.56 | | 4 | 7.8 | 7.2 | | 5 | 12.8 | 10.2 | +----+-------------+--------------+ 5 rows in set (0.00 sec) The following is the query to find absolute difference between two numbers in MySQL mysql> SELECT ABS(FirstNumber - secondNumber) AS diff -> from findDifferenceDemo -> order by diff desc; The following is the output +--------------------+ | diff | +--------------------+ | 28.760001182556152 | | 17.799999713897705 | | 2.6000003814697266 | | 1.8999998569488525 | | 0.6000003814697266 | +--------------------+ 5 rows in set (0.00 sec)
[ { "code": null, "e": 1146, "s": 1062, "text": "To get the difference between two number in MySQL, let us first create a demo table" }, { "code": null, "e": 1339, "s": 1146, "text": "mysql> create table findDifferenceDemo\n -> (\n -> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,\n -> FirstNumber float,\n -> SecondNumber float\n -> );\nQuery OK, 0 rows affected (0.60 sec)" }, { "code": null, "e": 1420, "s": 1339, "text": "Insert some records in the table using insert command. The query is as follows −" }, { "code": null, "e": 2010, "s": 1420, "text": "mysql> insert into findDifferenceDemo(FirstNumber,SecondNumber) values(4.2,2.3);\nQuery OK, 1 row affected (0.20 sec)\nmysql> insert into findDifferenceDemo(FirstNumber,SecondNumber) values(23.4,5.6);\nQuery OK, 1 row affected (0.14 sec)\nmysql> insert into findDifferenceDemo(FirstNumber,SecondNumber) values(5.8,34.56);\nQuery OK, 1 row affected (0.16 sec)\nmysql> insert into findDifferenceDemo(FirstNumber,SecondNumber) values(7.8,7.2);\nQuery OK, 1 row affected (0.16 sec)\nmysql> insert into findDifferenceDemo(FirstNumber,SecondNumber) values(12.8,10.2);\nQuery OK, 1 row affected (0.13 sec)" }, { "code": null, "e": 2095, "s": 2010, "text": "Display all records from the table using select statement. The query is as follows −" }, { "code": null, "e": 2135, "s": 2095, "text": "mysql> select *from findDifferenceDemo;" }, { "code": null, "e": 2163, "s": 2135, "text": "The following is the output" }, { "code": null, "e": 2512, "s": 2163, "text": "+----+-------------+--------------+\n| Id | FirstNumber | SecondNumber |\n+----+-------------+--------------+\n| 1 | 4.2 | 2.3 |\n| 2 | 23.4 | 5.6 |\n| 3 | 5.8 | 34.56 |\n| 4 | 7.8 | 7.2 |\n| 5 | 12.8 | 10.2 |\n+----+-------------+--------------+\n5 rows in set (0.00 sec)" }, { "code": null, "e": 2596, "s": 2512, "text": "The following is the query to find absolute difference between two numbers in MySQL" }, { "code": null, "e": 2706, "s": 2596, "text": "mysql> SELECT ABS(FirstNumber - secondNumber) AS diff\n -> from findDifferenceDemo\n -> order by diff desc;" }, { "code": null, "e": 2734, "s": 2706, "text": "The following is the output" }, { "code": null, "e": 2966, "s": 2734, "text": "+--------------------+\n| diff |\n+--------------------+\n| 28.760001182556152 |\n| 17.799999713897705 |\n| 2.6000003814697266 |\n| 1.8999998569488525 |\n| 0.6000003814697266 |\n+--------------------+\n5 rows in set (0.00 sec)" } ]
Implementing Optical Character Recognition (OCR) using pytesseract | by Nurali Uzakaliyev | Towards Data Science
Greetings fellow python enthusiasts, I would like to share with you a simple, but very effective OCR service, using pytesseract and with a web interface via Flask. Optical Character Recognition (OCR) can be useful for a variety of purposes, such as credit card scan for payment purposes, or converting .jpeg scan of a document to .pdf Without selling out the idea of usage OCR, or how it can be used, let’s begin the coding process! We’re going to use pytesseract (for OCR) & Flask (for a web interface) pip install pytesseractfrom PIL import Imageimport pytesseract Note: if you’re facing some problems with importing pytesseract, you may need to download & install pytesseract.exe, which can be found here. After the installation, you have to include the path to pytesseract executables, which can be done with a single line of code: pytesseract.pytesseract.tesseract_cmd = r'YOUR-PATH-TO-TESSERACT\tesseract.exe' Since we have installed & imported pytesseract, let’s create the core function and check if it works as intended: def ocr_core(filename): text = pytesseract.image_to_string(Image.open(filename)) return text Quite simple, right? The ocr_core function takes a path to your image file and returns its text components. According to documentation, image_to_string function uses English language as default recognition, but we’ll talk about specific languages later. Here are the results: Once we made sure everything is working, time to create a web interface for our OCR service Now we’re going to create a simple html form, allowing user to upload an image file, and retrieve the text from it. from flask import Flask, render_template, requestapp = Flask(__name__)# from ocr_core import ocr_core# uncomment the line above, if your Flask fails to get access to your function, or your OCR & Flask are on different scripts Keeping it simple, lets create some back-end tests for uploaded files, such as allowed extensions: ALLOWED_EXTENSIONS = ['png', 'jpg', 'jpeg']def allowed_file(filename): return '.' in filename and \ filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS Keeping it beautiful and simple, as ‘The Zen of Python’ suggests, right? Now, lets create a path where our user uploaded images will be held: import ospath = os.getcwd()UPLOAD_FOLDER = os.path.join(path, 'uploads\\')if not os.path.isdir(UPLOAD_FOLDER): os.mkdir(UPLOAD_FOLDER)app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER In case you’re wondering why would we import os: we’re gonna need it to get the path for the uploaded images to be held (for back-end), and also to create a source for our <img> tag, once the user successfully uploads the file. If you want to specifically indicate a folder, just change the os.getcwd() to any path you would like to use. If you never created the ‘uploads’ folder, the code above also creates it for you (with love). Now, lets build a simple form, and name the file upload.html <!DOCTYPE html><html><head> <title>OCR</title></head><body> {% if msg %} <h1 style="color: green"> {{ msg }} </h1> {% endif %}<h1> Upload your file </h1><form method=post enctype=multipart/form-data> <input type="file" name=file> <input type="submit" name=Upload value="Upload"> </form>{% if extracted %} <h1> Results: </h1> {% endif %}{% if img_src %} <img src="{{ img_src }}"> {% endif %}{% if extracted %} <p> {{ extracted }} </p> {% endif %}</body></html> Hold up, why are there curly brackets? Well, it’s not fully HTML form, I lied. Actually, it’s jinja formatting, which allows us to format our HTML accordingly. Nothing special here, {% if %} stands for if statement, so if there is any message, it will be wrapped in <h1> tag, etc. The form is pretty simple, but don’t forget enctype=multipart/form-data to allow the form to accept file uploads. All the variables inside the curly brackets appear once the back-end gets into the action, so just before uploading anything, your upload.html should look like this: Critical note: don’t forget to save your ‘upload.html’ file to the same path as your main python script is, regardless you’re working on the hub or local computer. If you have no idea where your working directory is, refer to os.getcwd() above. Once we have completed all the preparations above, time to create a web interface via Flask: @app.route('/', methods = ['GET', 'POST'])def upload_page(): if request.method == 'POST': if 'file' not in request.files: return render_template('upload.html', msg = 'No file selected') file = request.files['file']if file.filename == '': return render_template('upload.html', msg = 'No file')if file and allowed_file(file.filename): file.save(os.path.join(app.config['UPLOAD_FOLDER'], file.filename)) extracted = ocr_core(file) return render_template('upload.html', msg = 'OCR completed', extracted = extracted, img_src = UPLOAD_FOLDER + file.filename) else: return render_template('upload.html')if __name__ == '__main__': app.run() To begin with, we check the request method to be POST, mostly for security measures. Then, we have to check whether files are selected and uploaded (in other words, did the files reach the back-end). Once the entry-level tests are done, we check if the file exists and if its format is allowed. Once all these conditions are met, we save the uploaded file to our upload folder and assign it to a variable called extracted Once you run the code, you should see the address where the app is running: So before uploading, your interface should look like this: And once you select your file, it should slightly change like this: Voila! You just have created an OCR web service! As was promised, we have created a simple, but very effective OCR web service, which allows recognizing text from an image. But there are many ways how to improve it. For instance, you could add options to select which language the OCR should use. both in back-end and front-end like this: def ocr_core(filename): text = pytesseract.image_to_string(Image.open(filename), lang=selected_language) return text All you have to do is specify the lang property in ocr_core function. And add a <select> tag in your upload.html file. Just don’t forget to fetch the data from the front-end and pass it to your ocr_core function Hopefully, this article proved to be useful for you and made some things more clear. Thank you for your time, if you have any feedback or any questions, please be free to leave a comment below.
[ { "code": null, "e": 211, "s": 47, "text": "Greetings fellow python enthusiasts, I would like to share with you a simple, but very effective OCR service, using pytesseract and with a web interface via Flask." }, { "code": null, "e": 382, "s": 211, "text": "Optical Character Recognition (OCR) can be useful for a variety of purposes, such as credit card scan for payment purposes, or converting .jpeg scan of a document to .pdf" }, { "code": null, "e": 480, "s": 382, "text": "Without selling out the idea of usage OCR, or how it can be used, let’s begin the coding process!" }, { "code": null, "e": 551, "s": 480, "text": "We’re going to use pytesseract (for OCR) & Flask (for a web interface)" }, { "code": null, "e": 614, "s": 551, "text": "pip install pytesseractfrom PIL import Imageimport pytesseract" }, { "code": null, "e": 756, "s": 614, "text": "Note: if you’re facing some problems with importing pytesseract, you may need to download & install pytesseract.exe, which can be found here." }, { "code": null, "e": 883, "s": 756, "text": "After the installation, you have to include the path to pytesseract executables, which can be done with a single line of code:" }, { "code": null, "e": 963, "s": 883, "text": "pytesseract.pytesseract.tesseract_cmd = r'YOUR-PATH-TO-TESSERACT\\tesseract.exe'" }, { "code": null, "e": 1077, "s": 963, "text": "Since we have installed & imported pytesseract, let’s create the core function and check if it works as intended:" }, { "code": null, "e": 1176, "s": 1077, "text": "def ocr_core(filename): text = pytesseract.image_to_string(Image.open(filename)) return text" }, { "code": null, "e": 1430, "s": 1176, "text": "Quite simple, right? The ocr_core function takes a path to your image file and returns its text components. According to documentation, image_to_string function uses English language as default recognition, but we’ll talk about specific languages later." }, { "code": null, "e": 1452, "s": 1430, "text": "Here are the results:" }, { "code": null, "e": 1544, "s": 1452, "text": "Once we made sure everything is working, time to create a web interface for our OCR service" }, { "code": null, "e": 1660, "s": 1544, "text": "Now we’re going to create a simple html form, allowing user to upload an image file, and retrieve the text from it." }, { "code": null, "e": 1886, "s": 1660, "text": "from flask import Flask, render_template, requestapp = Flask(__name__)# from ocr_core import ocr_core# uncomment the line above, if your Flask fails to get access to your function, or your OCR & Flask are on different scripts" }, { "code": null, "e": 1985, "s": 1886, "text": "Keeping it simple, lets create some back-end tests for uploaded files, such as allowed extensions:" }, { "code": null, "e": 2155, "s": 1985, "text": "ALLOWED_EXTENSIONS = ['png', 'jpg', 'jpeg']def allowed_file(filename): return '.' in filename and \\ filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS" }, { "code": null, "e": 2228, "s": 2155, "text": "Keeping it beautiful and simple, as ‘The Zen of Python’ suggests, right?" }, { "code": null, "e": 2297, "s": 2228, "text": "Now, lets create a path where our user uploaded images will be held:" }, { "code": null, "e": 2478, "s": 2297, "text": "import ospath = os.getcwd()UPLOAD_FOLDER = os.path.join(path, 'uploads\\\\')if not os.path.isdir(UPLOAD_FOLDER): os.mkdir(UPLOAD_FOLDER)app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER" }, { "code": null, "e": 2816, "s": 2478, "text": "In case you’re wondering why would we import os: we’re gonna need it to get the path for the uploaded images to be held (for back-end), and also to create a source for our <img> tag, once the user successfully uploads the file. If you want to specifically indicate a folder, just change the os.getcwd() to any path you would like to use." }, { "code": null, "e": 2911, "s": 2816, "text": "If you never created the ‘uploads’ folder, the code above also creates it for you (with love)." }, { "code": null, "e": 2972, "s": 2911, "text": "Now, lets build a simple form, and name the file upload.html" }, { "code": null, "e": 3435, "s": 2972, "text": "<!DOCTYPE html><html><head> <title>OCR</title></head><body> {% if msg %} <h1 style=\"color: green\"> {{ msg }} </h1> {% endif %}<h1> Upload your file </h1><form method=post enctype=multipart/form-data> <input type=\"file\" name=file> <input type=\"submit\" name=Upload value=\"Upload\"> </form>{% if extracted %} <h1> Results: </h1> {% endif %}{% if img_src %} <img src=\"{{ img_src }}\"> {% endif %}{% if extracted %} <p> {{ extracted }} </p> {% endif %}</body></html>" }, { "code": null, "e": 3716, "s": 3435, "text": "Hold up, why are there curly brackets? Well, it’s not fully HTML form, I lied. Actually, it’s jinja formatting, which allows us to format our HTML accordingly. Nothing special here, {% if %} stands for if statement, so if there is any message, it will be wrapped in <h1> tag, etc." }, { "code": null, "e": 3830, "s": 3716, "text": "The form is pretty simple, but don’t forget enctype=multipart/form-data to allow the form to accept file uploads." }, { "code": null, "e": 3996, "s": 3830, "text": "All the variables inside the curly brackets appear once the back-end gets into the action, so just before uploading anything, your upload.html should look like this:" }, { "code": null, "e": 4241, "s": 3996, "text": "Critical note: don’t forget to save your ‘upload.html’ file to the same path as your main python script is, regardless you’re working on the hub or local computer. If you have no idea where your working directory is, refer to os.getcwd() above." }, { "code": null, "e": 4334, "s": 4241, "text": "Once we have completed all the preparations above, time to create a web interface via Flask:" }, { "code": null, "e": 5159, "s": 4334, "text": "@app.route('/', methods = ['GET', 'POST'])def upload_page(): if request.method == 'POST': if 'file' not in request.files: return render_template('upload.html', msg = 'No file selected') file = request.files['file']if file.filename == '': return render_template('upload.html', msg = 'No file')if file and allowed_file(file.filename): file.save(os.path.join(app.config['UPLOAD_FOLDER'], file.filename)) extracted = ocr_core(file) return render_template('upload.html', msg = 'OCR completed', extracted = extracted, img_src = UPLOAD_FOLDER + file.filename) else: return render_template('upload.html')if __name__ == '__main__': app.run()" }, { "code": null, "e": 5454, "s": 5159, "text": "To begin with, we check the request method to be POST, mostly for security measures. Then, we have to check whether files are selected and uploaded (in other words, did the files reach the back-end). Once the entry-level tests are done, we check if the file exists and if its format is allowed." }, { "code": null, "e": 5581, "s": 5454, "text": "Once all these conditions are met, we save the uploaded file to our upload folder and assign it to a variable called extracted" }, { "code": null, "e": 5657, "s": 5581, "text": "Once you run the code, you should see the address where the app is running:" }, { "code": null, "e": 5716, "s": 5657, "text": "So before uploading, your interface should look like this:" }, { "code": null, "e": 5784, "s": 5716, "text": "And once you select your file, it should slightly change like this:" }, { "code": null, "e": 5833, "s": 5784, "text": "Voila! You just have created an OCR web service!" }, { "code": null, "e": 6123, "s": 5833, "text": "As was promised, we have created a simple, but very effective OCR web service, which allows recognizing text from an image. But there are many ways how to improve it. For instance, you could add options to select which language the OCR should use. both in back-end and front-end like this:" }, { "code": null, "e": 6247, "s": 6123, "text": "def ocr_core(filename): text = pytesseract.image_to_string(Image.open(filename), lang=selected_language) return text" }, { "code": null, "e": 6459, "s": 6247, "text": "All you have to do is specify the lang property in ocr_core function. And add a <select> tag in your upload.html file. Just don’t forget to fetch the data from the front-end and pass it to your ocr_core function" } ]
How to install the MSI package using PowerShell DSC?
To install the MSI package using DSC, we need to use the DSC resource “Package”. Let see which properties are available for this resource. PS C:\> Get-DscResource -Name Package | Select -ExpandProperty Properties Name PropertyType IsMandatory Values ---- ------------ ----------- ------ Name [string] True {} Path [string] True {} ProductId [string] True {} Arguments [string] False {} Credential [PSCredential] False {} DependsOn [string[]] False {} Ensure [string] False {Absent, Present} LogPath [string] False {} PsDscRunAsCredential [PSCredential] False {} ReturnCode [UInt32[]] False {} Name, Path, and ProductID parameters are mandatory for this DSC resource. The best way to retrieve the above details is to install the sample package on the test machine and then get the details. We will use here the 7Zip MSI package installed on one computer. Get-Package 7-zip* | fl * From the above output, we can grab here the name of the Package after installation, ProductID (i.e. ProductCode). Configuration Install7zip{ Node @("LabMachine2k16","AD"){ Package 7zip{ Name = '7-Zip 19.00 (x64 edition)' ProductId = '23170F69-40C1-2702-1900-000001000000' Path = '\\ad\shared\7z1900-x64.msi' Ensure = 'Present' } } } In the above example, the source package is located at the source location and we want to install 7zip on the two nodes. To generate the MOF file at the specific location so we can use them later to start the configuration, Install7zip -OutputPath C:\Temp\7zipInstall -Verbose Once the MOF file is generated, we can start the configuration to apply DSC, Start-DscConfiguration -Path C:\Temp\7zipInstall -Wait -Force -Verbose Once the above command runs successfully, check if the configuration is applied or not using, Test-DscConfiguration -Path C:\Temp\7zipInstall You should get output like below, which shows that both the servers are in the desired state, which means the MSI package is installed. If the InDesiredState property is false, it means the server has missed the configuration.
[ { "code": null, "e": 1201, "s": 1062, "text": "To install the MSI package using DSC, we need to use the DSC resource “Package”. Let see which properties are available for this resource." }, { "code": null, "e": 1656, "s": 1201, "text": "PS C:\\> Get-DscResource -Name Package | Select -ExpandProperty Properties\n\nName PropertyType IsMandatory Values\n---- ------------ ----------- ------\nName [string] True {}\nPath [string] True {}\nProductId [string] True {}\nArguments [string] False {}\nCredential [PSCredential] False {}\nDependsOn [string[]] False {}\nEnsure [string] False {Absent, Present}\nLogPath [string] False {}\nPsDscRunAsCredential [PSCredential] False {}\nReturnCode [UInt32[]] False {}" }, { "code": null, "e": 1730, "s": 1656, "text": "Name, Path, and ProductID parameters are mandatory for this DSC resource." }, { "code": null, "e": 1917, "s": 1730, "text": "The best way to retrieve the above details is to install the sample package on the test machine and then get the details. We will use here the 7Zip MSI package installed on one computer." }, { "code": null, "e": 1943, "s": 1917, "text": "Get-Package 7-zip* | fl *" }, { "code": null, "e": 2057, "s": 1943, "text": "From the above output, we can grab here the name of the Package after installation, ProductID (i.e. ProductCode)." }, { "code": null, "e": 2330, "s": 2057, "text": "Configuration Install7zip{\n Node @(\"LabMachine2k16\",\"AD\"){\n Package 7zip{\n Name = '7-Zip 19.00 (x64 edition)'\n ProductId = '23170F69-40C1-2702-1900-000001000000'\n Path = '\\\\ad\\shared\\7z1900-x64.msi'\n Ensure = 'Present'\n }\n }\n}" }, { "code": null, "e": 2451, "s": 2330, "text": "In the above example, the source package is located at the source location and we want to install 7zip on the two nodes." }, { "code": null, "e": 2554, "s": 2451, "text": "To generate the MOF file at the specific location so we can use them later to start the configuration," }, { "code": null, "e": 2607, "s": 2554, "text": "Install7zip -OutputPath C:\\Temp\\7zipInstall -Verbose" }, { "code": null, "e": 2684, "s": 2607, "text": "Once the MOF file is generated, we can start the configuration to apply DSC," }, { "code": null, "e": 2755, "s": 2684, "text": "Start-DscConfiguration -Path C:\\Temp\\7zipInstall -Wait -Force -Verbose" }, { "code": null, "e": 2849, "s": 2755, "text": "Once the above command runs successfully, check if the configuration is applied or not using," }, { "code": null, "e": 2897, "s": 2849, "text": "Test-DscConfiguration -Path C:\\Temp\\7zipInstall" }, { "code": null, "e": 3033, "s": 2897, "text": "You should get output like below, which shows that both the servers are in the desired state, which means the MSI package is installed." }, { "code": null, "e": 3124, "s": 3033, "text": "If the InDesiredState property is false, it means the server has missed the configuration." } ]
Beautiful correlation plots in R — a new approach | by Stefan Haring | Towards Data Science
Everyone working with data knows that beautiful and explanatory visualization is key. After all, it's much easier to tell a story with a chart than it is with a plain table. This is especially important when you’re creating reports and dashboards whose aim it is to give your users and clients a quick overview over sometimes very complex and big datasets. One type of data that is not trivial to visualize in an explanatory way is a correlation matrix. In this post, we are going to take a look at transforming a correlation matrix into a beautiful, interactive and very descriptive chart using R and the plotly library. Update (2020–10–04): I had to replace some of the plotly linked charts with static images because they were not displayed properly on mobile. In our example, we are going to use the mtcars dataset to calculate the correlation between 6 variables. data <- mtcars[, c(1, 3:7)]corrdata <- cor(data) This gives us the correlation matrix that we are going to work with. Now while all the information is there, it is not particularly easy to digest all the information in one go. Enter charts, specifically heatmaps. As a starting point, base R provides us with the heatmap() function that lets us visualize the data at least a little bit better. While this is a first step in the right direction, this chart is still not very descriptive and, on top of that, it is not interactive! Ideally, we want to include our final product in a nice Shiny dashboard and enable our users and clients to interact with it. Plotly.js is a JavaScript Graphing Library that is built on top of d3.js and stack.gl that allows users to easily create interactive charts. It is free and open source, and luckily for us, an R implementation exists! This is again an improvement. Our correlation matrix is now displayed as an interactive chart and we have a colorbar indicating the strength of the correlation. However, when taking just a quick glance at the chart, what jumps out? Are you able to identify the strongest and weakest correlations immediately? Probably not! And there is also lots of unnecessary data displayed. By definition, a correlation matrix is symmetric and therefore contains each correlation twice. Additionally, the correlation of a variable with itself is always 1 so there is no need to have that in our chart. Now take a look at the following chart and try to answer the same questions. Much better! The chart is clean, we can immediately spot the strongest and weakest correlations, all the unnecessary data has been removed and it is still interactive and ready to be displayed as part of a beautiful dashboard! To achieve this we’ve used a scatter plot and made the size of the squares dependant on the absolute value of the correlations. How can you create such a chart (with a little effort) yourself? Let’s take a look! The first thing we need to do is to transform our data. In order to create a scatter plot suitable for our needs, all we need is a grid. For the correlation matrix, the x and y values would correspond to the variable names, but all we really need are equally spaced numeric values to create the grid. Our transformation converts our correlation matrix into a data frame with 3 columns: the x and y coordinates of the grid as well as the relevant correlations. #Store our variable names for later usex_labels <- colnames(corrdata)y_labels <- rownames(corrdata)#Change the variable names to numeric for the gridcolnames(corrdata) <- 1:ncol(corrdata)rownames(corrdata) <- nrow(corrdata):1#Melt the data into the desired formatplotdata <- melt(corrdata) You might wonder why the numeric values for the rownames are reversed in the code above. This is to ensure that the resulting plot has the main diagonal of the correlation plot going from the top left to the bottom right corner (unlike in our base R and base plotly examples above). As a result, we get a data frame looking like this: We can plot it with the following code: fig <- plot_ly(data = plotdata, width = 500, height = 500)fig <- fig %>% add_trace(x = ~Var2, y = ~Var1, type = “scatter”, mode = “markers”, color = ~value, symbol = I(“square”)) This is a good start, we have our grid set up correctly and our markers are coloured according to the correlations of our data. Admittedly, we can’t really see them properly and they all have the same size. We will tackle this next. #Adding the size variable & scaling itplotdata$size <-(abs(plotdata$value))scaling <- 500 / ncol(corrdata) / 2plotdata$size <- plotdata$size * scaling First, we define a size variable to be the absolute value of the correlations. To properly size the squares we need to scale them up otherwise we would just have little dots that won’t tell us much. Afterwards, we can add the size to the markers. fig <- plot_ly(data = plotdata, width = 500, height = 500)fig <- fig %>% add_trace(x = ~Var2, y = ~Var1, type = "scatter", mode = "markers", color = ~value, marker = list(size = ~size, opacity = 1), symbol = I("square")) One step closer! The base functionality is now there, our squares are scaled correctly with the correlation and together with the colouring enable us to identify high/low correlation pairs at a glimpse. We will perform some cleanup next. We will correctly name our variables, remove all gridlines and remove the axis titles. To achieve this, we will set up custom axis lists. We will also center the colorbar. xAx1 <- list(showgrid = FALSE, showline = FALSE, zeroline = FALSE, tickvals = colnames(corrdata), ticktext = x_labels, title = FALSE)yAx1 <- list(autoaxis = FALSE, showgrid = FALSE, showline = FALSE, zeroline = FALSE, tickvals = rownames(corrdata), ticktext = y_labels, title = FALSE)fig <- plot_ly(data = plotdata, width = 500, height = 500)fig <- fig %>% add_trace(x = ~Var2, y = ~Var1, type = “scatter”, mode = “markers”, color = ~value, marker = list(size = ~size, opacity = 1), symbol = I(“square”))fig <- fig %>% layout(xaxis = xAx1, yaxis = yAx1)fig <- fig %>% colorbar(title = “”, limits = c(-1,1), x = 1.1, y = 0.75) We’ve already mentioned before that there is a lot of duplicated and unnecessary data displayed in a correlation matrix, due to it being symmetric. We can therefore remove all entries above and including the main diagonal (since all entries in the main diagonal are 1 by definition) in our plot. The easiest way to do this is to just set these values to NA in the original correlation matrix before we apply the transformation. Since this will lead to the first row and last column of our chart being empty, we can remove those as well. #do this before the transformation!corrdata[upper.tri(corrdata, diag = TRUE)] <- NAcorrdata <- corrdata[-1, -ncol(corrdata)] Plotting our chart again yields the following: Almost there! The last step is to add the gridlines back in, give our plot a nice background and fix info that is displayed when hovering over the squares. To add the grid, we will add a second trace to our plot so that we are able to have a second set of x and y axes. We will make this trace invisible so that nothing interferes with our correlation squares. Since we used unit values for placing our initial grid, we need to shift those by 0.5 to create the gridlines. We also need to make sure that our axes are plotted on the same range, otherwise everything gets shifted and messy. It sounds complicated but it is really straightforward. Since we have covered quite a lot to get this far, below is the full code to produce our final plot. After this quite lengthy description on how to create prettier charts displaying correlations we have finally arrived at our desired output. Hopefully, this post will allow you to create amazing, interactive plots that deliver insights into correlations quickly. Please make sure to let me know if you have any feedback or suggestions for improving what I have described in this post! For those interested, I have made the full code including more features available as an R package called correally. Added functionality includes: automatic rescaling depending on plot size coloring options including Hex colors, RColorBrewer and viridis auto formatting of the background, fonts and grids to fit different shiny themes animations of correlation changes over time (in development) Also, make sure to check out my post about 3 easy tricks to improve your plotly charts to further enhance what we’ve covered here!
[ { "code": null, "e": 528, "s": 171, "text": "Everyone working with data knows that beautiful and explanatory visualization is key. After all, it's much easier to tell a story with a chart than it is with a plain table. This is especially important when you’re creating reports and dashboards whose aim it is to give your users and clients a quick overview over sometimes very complex and big datasets." }, { "code": null, "e": 793, "s": 528, "text": "One type of data that is not trivial to visualize in an explanatory way is a correlation matrix. In this post, we are going to take a look at transforming a correlation matrix into a beautiful, interactive and very descriptive chart using R and the plotly library." }, { "code": null, "e": 935, "s": 793, "text": "Update (2020–10–04): I had to replace some of the plotly linked charts with static images because they were not displayed properly on mobile." }, { "code": null, "e": 1040, "s": 935, "text": "In our example, we are going to use the mtcars dataset to calculate the correlation between 6 variables." }, { "code": null, "e": 1089, "s": 1040, "text": "data <- mtcars[, c(1, 3:7)]corrdata <- cor(data)" }, { "code": null, "e": 1158, "s": 1089, "text": "This gives us the correlation matrix that we are going to work with." }, { "code": null, "e": 1304, "s": 1158, "text": "Now while all the information is there, it is not particularly easy to digest all the information in one go. Enter charts, specifically heatmaps." }, { "code": null, "e": 1434, "s": 1304, "text": "As a starting point, base R provides us with the heatmap() function that lets us visualize the data at least a little bit better." }, { "code": null, "e": 1696, "s": 1434, "text": "While this is a first step in the right direction, this chart is still not very descriptive and, on top of that, it is not interactive! Ideally, we want to include our final product in a nice Shiny dashboard and enable our users and clients to interact with it." }, { "code": null, "e": 1913, "s": 1696, "text": "Plotly.js is a JavaScript Graphing Library that is built on top of d3.js and stack.gl that allows users to easily create interactive charts. It is free and open source, and luckily for us, an R implementation exists!" }, { "code": null, "e": 2074, "s": 1913, "text": "This is again an improvement. Our correlation matrix is now displayed as an interactive chart and we have a colorbar indicating the strength of the correlation." }, { "code": null, "e": 2501, "s": 2074, "text": "However, when taking just a quick glance at the chart, what jumps out? Are you able to identify the strongest and weakest correlations immediately? Probably not! And there is also lots of unnecessary data displayed. By definition, a correlation matrix is symmetric and therefore contains each correlation twice. Additionally, the correlation of a variable with itself is always 1 so there is no need to have that in our chart." }, { "code": null, "e": 2578, "s": 2501, "text": "Now take a look at the following chart and try to answer the same questions." }, { "code": null, "e": 2805, "s": 2578, "text": "Much better! The chart is clean, we can immediately spot the strongest and weakest correlations, all the unnecessary data has been removed and it is still interactive and ready to be displayed as part of a beautiful dashboard!" }, { "code": null, "e": 2933, "s": 2805, "text": "To achieve this we’ve used a scatter plot and made the size of the squares dependant on the absolute value of the correlations." }, { "code": null, "e": 3017, "s": 2933, "text": "How can you create such a chart (with a little effort) yourself? Let’s take a look!" }, { "code": null, "e": 3477, "s": 3017, "text": "The first thing we need to do is to transform our data. In order to create a scatter plot suitable for our needs, all we need is a grid. For the correlation matrix, the x and y values would correspond to the variable names, but all we really need are equally spaced numeric values to create the grid. Our transformation converts our correlation matrix into a data frame with 3 columns: the x and y coordinates of the grid as well as the relevant correlations." }, { "code": null, "e": 3767, "s": 3477, "text": "#Store our variable names for later usex_labels <- colnames(corrdata)y_labels <- rownames(corrdata)#Change the variable names to numeric for the gridcolnames(corrdata) <- 1:ncol(corrdata)rownames(corrdata) <- nrow(corrdata):1#Melt the data into the desired formatplotdata <- melt(corrdata)" }, { "code": null, "e": 4050, "s": 3767, "text": "You might wonder why the numeric values for the rownames are reversed in the code above. This is to ensure that the resulting plot has the main diagonal of the correlation plot going from the top left to the bottom right corner (unlike in our base R and base plotly examples above)." }, { "code": null, "e": 4102, "s": 4050, "text": "As a result, we get a data frame looking like this:" }, { "code": null, "e": 4142, "s": 4102, "text": "We can plot it with the following code:" }, { "code": null, "e": 4323, "s": 4142, "text": "fig <- plot_ly(data = plotdata, width = 500, height = 500)fig <- fig %>% add_trace(x = ~Var2, y = ~Var1, type = “scatter”, mode = “markers”, color = ~value, symbol = I(“square”))" }, { "code": null, "e": 4556, "s": 4323, "text": "This is a good start, we have our grid set up correctly and our markers are coloured according to the correlations of our data. Admittedly, we can’t really see them properly and they all have the same size. We will tackle this next." }, { "code": null, "e": 4707, "s": 4556, "text": "#Adding the size variable & scaling itplotdata$size <-(abs(plotdata$value))scaling <- 500 / ncol(corrdata) / 2plotdata$size <- plotdata$size * scaling" }, { "code": null, "e": 4954, "s": 4707, "text": "First, we define a size variable to be the absolute value of the correlations. To properly size the squares we need to scale them up otherwise we would just have little dots that won’t tell us much. Afterwards, we can add the size to the markers." }, { "code": null, "e": 5175, "s": 4954, "text": "fig <- plot_ly(data = plotdata, width = 500, height = 500)fig <- fig %>% add_trace(x = ~Var2, y = ~Var1, type = \"scatter\", mode = \"markers\", color = ~value, marker = list(size = ~size, opacity = 1), symbol = I(\"square\"))" }, { "code": null, "e": 5378, "s": 5175, "text": "One step closer! The base functionality is now there, our squares are scaled correctly with the correlation and together with the colouring enable us to identify high/low correlation pairs at a glimpse." }, { "code": null, "e": 5585, "s": 5378, "text": "We will perform some cleanup next. We will correctly name our variables, remove all gridlines and remove the axis titles. To achieve this, we will set up custom axis lists. We will also center the colorbar." }, { "code": null, "e": 6211, "s": 5585, "text": "xAx1 <- list(showgrid = FALSE, showline = FALSE, zeroline = FALSE, tickvals = colnames(corrdata), ticktext = x_labels, title = FALSE)yAx1 <- list(autoaxis = FALSE, showgrid = FALSE, showline = FALSE, zeroline = FALSE, tickvals = rownames(corrdata), ticktext = y_labels, title = FALSE)fig <- plot_ly(data = plotdata, width = 500, height = 500)fig <- fig %>% add_trace(x = ~Var2, y = ~Var1, type = “scatter”, mode = “markers”, color = ~value, marker = list(size = ~size, opacity = 1), symbol = I(“square”))fig <- fig %>% layout(xaxis = xAx1, yaxis = yAx1)fig <- fig %>% colorbar(title = “”, limits = c(-1,1), x = 1.1, y = 0.75)" }, { "code": null, "e": 6748, "s": 6211, "text": "We’ve already mentioned before that there is a lot of duplicated and unnecessary data displayed in a correlation matrix, due to it being symmetric. We can therefore remove all entries above and including the main diagonal (since all entries in the main diagonal are 1 by definition) in our plot. The easiest way to do this is to just set these values to NA in the original correlation matrix before we apply the transformation. Since this will lead to the first row and last column of our chart being empty, we can remove those as well." }, { "code": null, "e": 6873, "s": 6748, "text": "#do this before the transformation!corrdata[upper.tri(corrdata, diag = TRUE)] <- NAcorrdata <- corrdata[-1, -ncol(corrdata)]" }, { "code": null, "e": 6920, "s": 6873, "text": "Plotting our chart again yields the following:" }, { "code": null, "e": 7076, "s": 6920, "text": "Almost there! The last step is to add the gridlines back in, give our plot a nice background and fix info that is displayed when hovering over the squares." }, { "code": null, "e": 7564, "s": 7076, "text": "To add the grid, we will add a second trace to our plot so that we are able to have a second set of x and y axes. We will make this trace invisible so that nothing interferes with our correlation squares. Since we used unit values for placing our initial grid, we need to shift those by 0.5 to create the gridlines. We also need to make sure that our axes are plotted on the same range, otherwise everything gets shifted and messy. It sounds complicated but it is really straightforward." }, { "code": null, "e": 7665, "s": 7564, "text": "Since we have covered quite a lot to get this far, below is the full code to produce our final plot." }, { "code": null, "e": 7928, "s": 7665, "text": "After this quite lengthy description on how to create prettier charts displaying correlations we have finally arrived at our desired output. Hopefully, this post will allow you to create amazing, interactive plots that deliver insights into correlations quickly." }, { "code": null, "e": 8050, "s": 7928, "text": "Please make sure to let me know if you have any feedback or suggestions for improving what I have described in this post!" }, { "code": null, "e": 8166, "s": 8050, "text": "For those interested, I have made the full code including more features available as an R package called correally." }, { "code": null, "e": 8196, "s": 8166, "text": "Added functionality includes:" }, { "code": null, "e": 8239, "s": 8196, "text": "automatic rescaling depending on plot size" }, { "code": null, "e": 8303, "s": 8239, "text": "coloring options including Hex colors, RColorBrewer and viridis" }, { "code": null, "e": 8384, "s": 8303, "text": "auto formatting of the background, fonts and grids to fit different shiny themes" }, { "code": null, "e": 8445, "s": 8384, "text": "animations of correlation changes over time (in development)" } ]
How to find which Python modules are being imported from a package?
To find all the python modules from a particular package that are being used in an application, you can use the sys.modules dict. sys.modules is a dictionary mapping module names to modules. You can examine its keys to see imported modules. For example, >>> from datetime import datetime >>> import sys >>> print sys.modules.keys() ['copy_reg', 'sre_compile', 'locale', '_sre', 'functools', 'encodings', 'site', '__builtin__', 'datetime', 'sysconfig', 'operator', '__main__', 'types', 'encodings.encodings', 'abc', 'encodings.cp437', '_weakrefset', 'errno', 'encodings.codecs', 'backports', 'sre_constants', 're', '_abcoll', 'ntpath', '_codecs', 'zope', 'nt', '_warnings', 'genericpath', 'stat', 'zipimport', 'encodings.__builtin__', 'mpl_toolkits', 'warnings', 'UserDict', 'encodings.cp1252', 'sys', 'codecs', 'os.path', '_functools', '_locale', 'signal', 'traceback', 'linecache', 'encodings.aliases', 'exceptions', 'sre_parse', 'os', '_weakref'] You could also use python -v, which will emit messages about every imported module. For example, if you have the python code in hello.py, then, $ python -v hello.py
[ { "code": null, "e": 1303, "s": 1062, "text": "To find all the python modules from a particular package that are being used in an application, you can use the sys.modules dict. sys.modules is a dictionary mapping module names to modules. You can examine its keys to see imported modules." }, { "code": null, "e": 1316, "s": 1303, "text": "For example," }, { "code": null, "e": 2011, "s": 1316, "text": ">>> from datetime import datetime\n>>> import sys\n>>> print sys.modules.keys()\n['copy_reg', 'sre_compile', 'locale', '_sre', 'functools', 'encodings', 'site', '__builtin__', 'datetime', 'sysconfig', 'operator', '__main__', 'types', 'encodings.encodings', 'abc', 'encodings.cp437', '_weakrefset', 'errno', 'encodings.codecs', 'backports', 'sre_constants', 're', '_abcoll', 'ntpath', '_codecs', 'zope', 'nt', '_warnings', 'genericpath', 'stat', 'zipimport', 'encodings.__builtin__', 'mpl_toolkits', 'warnings', 'UserDict', 'encodings.cp1252', 'sys', 'codecs', 'os.path', '_functools', '_locale', 'signal', 'traceback', 'linecache', 'encodings.aliases', 'exceptions', 'sre_parse', 'os', '_weakref']" }, { "code": null, "e": 2155, "s": 2011, "text": "You could also use python -v, which will emit messages about every imported module. For example, if you have the python code in hello.py, then," }, { "code": null, "e": 2176, "s": 2155, "text": "$ python -v hello.py" } ]
Entity Framework - Explicit Loading
When you disabled the lazy loading, it is still possible to lazily load related entities, but it must be done with an explicit call. Unlike lazy loading, there is no ambiguity or possibility of confusion regarding when a query is run. Unlike lazy loading, there is no ambiguity or possibility of confusion regarding when a query is run. To do so you use the Load method on the related entity’s entry. To do so you use the Load method on the related entity’s entry. For a one-to-many relationship, call the Load method on Collection. For a one-to-many relationship, call the Load method on Collection. And for a one-to-one relationship, call the Load method on Reference. And for a one-to-one relationship, call the Load method on Reference. Let’s take a look at the following example in which lazy loading is disabled and then the student whose first name is Ali is retrieved. Student information is then written on console. If you look at the code, enrollments information is also written but Enrollments entity is not loaded yet so foreach loop will not be executed. After that Enrollments entity is loaded explicitly now student information and enrollments information will be written on the console window. class Program { static void Main(string[] args) { using (var context = new UniContextEntities()) { context.Configuration.LazyLoadingEnabled = false; var student = (from s in context.Students where s.FirstMidName == "Ali" select s).FirstOrDefault<Student>(); string name = student.FirstMidName + " " + student.LastName; Console.WriteLine("ID: {0}, Name: {1}", student.ID, name); foreach (var enrollment in student.Enrollments) { Console.WriteLine("Enrollment ID: {0}, Course ID: {1}", enrollment.EnrollmentID, enrollment.CourseID); } Console.WriteLine(); Console.WriteLine("Explicitly loaded Enrollments"); Console.WriteLine(); context.Entry(student).Collection(s ⇒ s.Enrollments).Load(); Console.WriteLine("ID: {0}, Name: {1}", student.ID, name); foreach (var enrollment in student.Enrollments) { Console.WriteLine("Enrollment ID: {0}, Course ID: {1}", enrollment.EnrollmentID, enrollment.CourseID); } Console.ReadKey(); } } } When the above example is executed, you will receive the following output. First only student information is displayed and after explicitly loading enrollments entity, both student and his related enrollments information is displayed. ID: 1, Name: Ali Alexander Explicitly loaded Enrollments ID: 1, Name: Ali Alexander Enrollment ID: 1, Course ID: 1050 Enrollment ID: 2, Course ID: 4022 Enrollment ID: 3, Course ID: 4041 We recommend that you execute the above example in a step-by-step manner for better understanding. 19 Lectures 5 hours Trevoir Williams 33 Lectures 3.5 hours Nilay Mehta 21 Lectures 2.5 hours TELCOMA Global 89 Lectures 7.5 hours Mustafa Radaideh Print Add Notes Bookmark this page
[ { "code": null, "e": 3165, "s": 3032, "text": "When you disabled the lazy loading, it is still possible to lazily load related entities, but it must be done with an explicit call." }, { "code": null, "e": 3267, "s": 3165, "text": "Unlike lazy loading, there is no ambiguity or possibility of confusion regarding when a query is run." }, { "code": null, "e": 3369, "s": 3267, "text": "Unlike lazy loading, there is no ambiguity or possibility of confusion regarding when a query is run." }, { "code": null, "e": 3433, "s": 3369, "text": "To do so you use the Load method on the related entity’s entry." }, { "code": null, "e": 3497, "s": 3433, "text": "To do so you use the Load method on the related entity’s entry." }, { "code": null, "e": 3565, "s": 3497, "text": "For a one-to-many relationship, call the Load method on Collection." }, { "code": null, "e": 3633, "s": 3565, "text": "For a one-to-many relationship, call the Load method on Collection." }, { "code": null, "e": 3703, "s": 3633, "text": "And for a one-to-one relationship, call the Load method on Reference." }, { "code": null, "e": 3773, "s": 3703, "text": "And for a one-to-one relationship, call the Load method on Reference." }, { "code": null, "e": 3909, "s": 3773, "text": "Let’s take a look at the following example in which lazy loading is disabled and then the student whose first name is Ali is retrieved." }, { "code": null, "e": 4101, "s": 3909, "text": "Student information is then written on console. If you look at the code, enrollments information is also written but Enrollments entity is not loaded yet so foreach loop will not be executed." }, { "code": null, "e": 4243, "s": 4101, "text": "After that Enrollments entity is loaded explicitly now student information and enrollments information will be written on the console window." }, { "code": null, "e": 5393, "s": 4243, "text": "class Program {\n\n static void Main(string[] args) {\n\n using (var context = new UniContextEntities()) {\n\n context.Configuration.LazyLoadingEnabled = false;\n\n var student = (from s in context.Students where s.FirstMidName == \n \"Ali\" select s).FirstOrDefault<Student>();\n\n string name = student.FirstMidName + \" \" + student.LastName;\n Console.WriteLine(\"ID: {0}, Name: {1}\", student.ID, name);\n\n foreach (var enrollment in student.Enrollments) {\n Console.WriteLine(\"Enrollment ID: {0}, Course ID: {1}\", \n enrollment.EnrollmentID, enrollment.CourseID);\n }\n\n Console.WriteLine();\n Console.WriteLine(\"Explicitly loaded Enrollments\");\n Console.WriteLine();\n\n context.Entry(student).Collection(s ⇒ s.Enrollments).Load();\n Console.WriteLine(\"ID: {0}, Name: {1}\", student.ID, name);\n\n foreach (var enrollment in student.Enrollments) {\n Console.WriteLine(\"Enrollment ID: {0}, Course ID: {1}\", \n enrollment.EnrollmentID, enrollment.CourseID);\n }\n\n Console.ReadKey();\n }\n }\n}" }, { "code": null, "e": 5628, "s": 5393, "text": "When the above example is executed, you will receive the following output. First only student information is displayed and after explicitly loading enrollments entity, both student and his related enrollments information is displayed." }, { "code": null, "e": 5836, "s": 5628, "text": "ID: 1, Name: Ali Alexander\nExplicitly loaded Enrollments\nID: 1, Name: Ali Alexander\n Enrollment ID: 1, Course ID: 1050\n Enrollment ID: 2, Course ID: 4022\n Enrollment ID: 3, Course ID: 4041\n" }, { "code": null, "e": 5935, "s": 5836, "text": "We recommend that you execute the above example in a step-by-step manner for better understanding." }, { "code": null, "e": 5968, "s": 5935, "text": "\n 19 Lectures \n 5 hours \n" }, { "code": null, "e": 5986, "s": 5968, "text": " Trevoir Williams" }, { "code": null, "e": 6021, "s": 5986, "text": "\n 33 Lectures \n 3.5 hours \n" }, { "code": null, "e": 6034, "s": 6021, "text": " Nilay Mehta" }, { "code": null, "e": 6069, "s": 6034, "text": "\n 21 Lectures \n 2.5 hours \n" }, { "code": null, "e": 6085, "s": 6069, "text": " TELCOMA Global" }, { "code": null, "e": 6120, "s": 6085, "text": "\n 89 Lectures \n 7.5 hours \n" }, { "code": null, "e": 6138, "s": 6120, "text": " Mustafa Radaideh" }, { "code": null, "e": 6145, "s": 6138, "text": " Print" }, { "code": null, "e": 6156, "s": 6145, "text": " Add Notes" } ]
How to Get the IP Address of a Docker Container? - GeeksforGeeks
28 Oct, 2020 If you want multiple Docker Containers to talk to each other, they can form a Bridge Network. Each Container Network has its own Subnet mask to distribute IP addresses. The default subnet for a Docker Network is 172.17.0.0/16 In this article, we are going to discuss the different ways you can use to know the IP address of a Docker Container. Start the Bash of the Container. sudo docker exec -it 6cb599fe30ea bash Running the bash Install iproute2 to use the ip command. apt-get install iproute2 Use this command to get the IP address. ip add | grep global Method 1: Using the Bash You can get the IP address of the Docker Container directly using this command. You need to have the Container ID to use this method. sudo docker exec -it 6cb599fe30ea ip addr | grep global Method 2: Direct Command You can also use the Docker Inspect command to return the IP address of the Docker Container. sudo docker inspect --format '{{ .NetworkSettings.IPAddress }}' 6cb599fe30ea Method 3: Using Docker Inspect To conclude, in this article we discussed three different ways to find out the IP address of a Docker Container. Methods 2 and 3 require less effort and using a single line command, you can easily find out the IP address of the container if you have it’s Container ID. Docker Container linux Advanced Computer Subject Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Copying Files to and from Docker Containers ML | Stochastic Gradient Descent (SGD) Principal Component Analysis with Python Fuzzy Logic | Introduction How to create a REST API using Java Spring Boot Classifying data using Support Vector Machines(SVMs) in Python ML | Data Preprocessing in Python Q-Learning in Python Basics of API Testing Using Postman Monolithic vs Microservices architecture
[ { "code": null, "e": 24148, "s": 24120, "text": "\n28 Oct, 2020" }, { "code": null, "e": 24374, "s": 24148, "text": "If you want multiple Docker Containers to talk to each other, they can form a Bridge Network. Each Container Network has its own Subnet mask to distribute IP addresses. The default subnet for a Docker Network is 172.17.0.0/16" }, { "code": null, "e": 24492, "s": 24374, "text": "In this article, we are going to discuss the different ways you can use to know the IP address of a Docker Container." }, { "code": null, "e": 24525, "s": 24492, "text": "Start the Bash of the Container." }, { "code": null, "e": 24565, "s": 24525, "text": "sudo docker exec -it 6cb599fe30ea bash\n" }, { "code": null, "e": 24582, "s": 24565, "text": "Running the bash" }, { "code": null, "e": 24622, "s": 24582, "text": "Install iproute2 to use the ip command." }, { "code": null, "e": 24648, "s": 24622, "text": "apt-get install iproute2\n" }, { "code": null, "e": 24688, "s": 24648, "text": "Use this command to get the IP address." }, { "code": null, "e": 24710, "s": 24688, "text": "ip add | grep global\n" }, { "code": null, "e": 24735, "s": 24710, "text": "Method 1: Using the Bash" }, { "code": null, "e": 24869, "s": 24735, "text": "You can get the IP address of the Docker Container directly using this command. You need to have the Container ID to use this method." }, { "code": null, "e": 24926, "s": 24869, "text": "sudo docker exec -it 6cb599fe30ea ip addr | grep global\n" }, { "code": null, "e": 24952, "s": 24926, "text": "Method 2: Direct Command" }, { "code": null, "e": 25047, "s": 24952, "text": "You can also use the Docker Inspect command to return the IP address of the Docker Container. " }, { "code": null, "e": 25125, "s": 25047, "text": "sudo docker inspect --format '{{ .NetworkSettings.IPAddress }}' 6cb599fe30ea\n" }, { "code": null, "e": 25157, "s": 25125, "text": "Method 3: Using Docker Inspect" }, { "code": null, "e": 25426, "s": 25157, "text": "To conclude, in this article we discussed three different ways to find out the IP address of a Docker Container. Methods 2 and 3 require less effort and using a single line command, you can easily find out the IP address of the container if you have it’s Container ID." }, { "code": null, "e": 25443, "s": 25426, "text": "Docker Container" }, { "code": null, "e": 25449, "s": 25443, "text": "linux" }, { "code": null, "e": 25475, "s": 25449, "text": "Advanced Computer Subject" }, { "code": null, "e": 25573, "s": 25475, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25582, "s": 25573, "text": "Comments" }, { "code": null, "e": 25595, "s": 25582, "text": "Old Comments" }, { "code": null, "e": 25639, "s": 25595, "text": "Copying Files to and from Docker Containers" }, { "code": null, "e": 25678, "s": 25639, "text": "ML | Stochastic Gradient Descent (SGD)" }, { "code": null, "e": 25719, "s": 25678, "text": "Principal Component Analysis with Python" }, { "code": null, "e": 25746, "s": 25719, "text": "Fuzzy Logic | Introduction" }, { "code": null, "e": 25794, "s": 25746, "text": "How to create a REST API using Java Spring Boot" }, { "code": null, "e": 25857, "s": 25794, "text": "Classifying data using Support Vector Machines(SVMs) in Python" }, { "code": null, "e": 25891, "s": 25857, "text": "ML | Data Preprocessing in Python" }, { "code": null, "e": 25912, "s": 25891, "text": "Q-Learning in Python" }, { "code": null, "e": 25948, "s": 25912, "text": "Basics of API Testing Using Postman" } ]