title
stringlengths 3
221
| text
stringlengths 17
477k
| parsed
listlengths 0
3.17k
|
---|---|---|
How to convert Lower case to Upper Case using C#? | To convert Lower case to Upper case, use the ToUpper() method in C#.
Letβs say your string is β
str = "david";
To convert the above lowercase string in uppercase, use the ToUpper() method β
Console.WriteLine("Converted to UpperCase : {0}", str.ToUpper());
The following is the code in C# to convert character case β
using System;
using System.Collections.Generic;
using System.Text;
namespace Demo {
class MyApplication {
static void Main(string[] args) {
string str;
str = "david";
Console.WriteLine("LowerCase : {0}", str);
// convert to uppercase
Console.WriteLine("Converted to UpperCase : {0}", str.ToUpper());
Console.ReadLine();
}
}
} | [
{
"code": null,
"e": 1131,
"s": 1062,
"text": "To convert Lower case to Upper case, use the ToUpper() method in C#."
},
{
"code": null,
"e": 1158,
"s": 1131,
"text": "Letβs say your string is β"
},
{
"code": null,
"e": 1173,
"s": 1158,
"text": "str = \"david\";"
},
{
"code": null,
"e": 1252,
"s": 1173,
"text": "To convert the above lowercase string in uppercase, use the ToUpper() method β"
},
{
"code": null,
"e": 1318,
"s": 1252,
"text": "Console.WriteLine(\"Converted to UpperCase : {0}\", str.ToUpper());"
},
{
"code": null,
"e": 1378,
"s": 1318,
"text": "The following is the code in C# to convert character case β"
},
{
"code": null,
"e": 1779,
"s": 1378,
"text": "using System;\nusing System.Collections.Generic;\nusing System.Text;\n\nnamespace Demo {\n class MyApplication {\n static void Main(string[] args) {\n\n string str;\n str = \"david\";\n Console.WriteLine(\"LowerCase : {0}\", str);\n\n // convert to uppercase\n Console.WriteLine(\"Converted to UpperCase : {0}\", str.ToUpper());\n Console.ReadLine();\n }\n }\n}"
}
] |
Super keyword in JavaScript? | The super keyword is used to access and call functions on an object's parent. The super.prop and super[expr] expressions are legible in any method definition in both classes and object literals. It is used in the "extended" class, which uses "extends" keyword.
super(arguments);
In the following example, the characteristics of a class called "Person" have been extended to another class called "Student". In both classes, we have used unique properties. Here "super" keyword is used to access a property from parent class(Person) to the extended class(Student), whereas "this" keyword is used to access extended class's own property.
<html>
<body>
<script>
class Person {
constructor(name, grade) {
this.name = name;
this.grade = grade;
}
goal() {
return `${this.name} wants to become a crickter!`;
}
interest() {
return `${this.name} interested in cricket !`;
}
}
class Student extends Person {
constructor(name, grade) {
super(name, grade);
}
need() {
return `${this.name} needs a cricket kit`;
}
career() {
return `${super.interest()}
${super.goal()}
${this.need()}`;
}
}
const student = new Student('Rishab pant', '7');
document.write(student.career());
</script>
</body>
</html>
Rishab pant interested in cricket !
Rishab pant wants to become a crickter!
Rishab pant needs a cricket kit | [
{
"code": null,
"e": 1323,
"s": 1062,
"text": "The super keyword is used to access and call functions on an object's parent. The super.prop and super[expr] expressions are legible in any method definition in both classes and object literals. It is used in the \"extended\" class, which uses \"extends\" keyword."
},
{
"code": null,
"e": 1341,
"s": 1323,
"text": "super(arguments);"
},
{
"code": null,
"e": 1697,
"s": 1341,
"text": "In the following example, the characteristics of a class called \"Person\" have been extended to another class called \"Student\". In both classes, we have used unique properties. Here \"super\" keyword is used to access a property from parent class(Person) to the extended class(Student), whereas \"this\" keyword is used to access extended class's own property."
},
{
"code": null,
"e": 2418,
"s": 1697,
"text": "<html>\n<body>\n<script>\n class Person {\n constructor(name, grade) {\n this.name = name;\n this.grade = grade;\n }\n goal() {\n return `${this.name} wants to become a crickter!`;\n }\n interest() {\n return `${this.name} interested in cricket !`;\n }\n }\n class Student extends Person {\n constructor(name, grade) {\n super(name, grade);\n }\n need() {\n return `${this.name} needs a cricket kit`;\n }\n career() {\n return `${super.interest()}\n ${super.goal()}\n ${this.need()}`;\n }\n }\n const student = new Student('Rishab pant', '7');\n document.write(student.career());\n</script>\n</body>\n</html>"
},
{
"code": null,
"e": 2526,
"s": 2418,
"text": "Rishab pant interested in cricket !\nRishab pant wants to become a crickter!\nRishab pant needs a cricket kit"
}
] |
Decimal to binary conversion without using arithmetic operators - GeeksforGeeks | 06 Apr, 2021
Find the binary equivalent of the given non-negative number n without using arithmetic operators.Examples:
Input : n = 10
Output : 1010
Input : n = 38
Output : 100110
Note that + in below algorithm/program is used for concatenation purpose. Algorithm:
decToBin(n)
if n == 0
return "0"
Declare bin = ""
Declare ch
while n > 0
if (n & 1) == 0
ch = '0'
else
ch = '1'
bin = ch + bin
n = n >> 1
return bin
C++
Java
Python3
C#
PHP
Javascript
// C++ implementation of decimal to binary conversion// without using arithmetic operators#include <bits/stdc++.h> using namespace std; // function for decimal to binary conversion// without using arithmetic operatorsstring decToBin(int n){ if (n == 0) return "0"; // to store the binary equivalent of decimal string bin = ""; while (n > 0) { // to get the last binary digit of the number 'n' // and accumulate it at the beginning of 'bin' bin = ((n & 1) == 0 ? '0' : '1') + bin; // right shift 'n' by 1 n >>= 1; } // required binary number return bin;} // Driver program to test aboveint main(){ int n = 38; cout << decToBin(n); return 0;}
// Java implementation of decimal// to binary conversion without// using arithmetic operatorsimport java.io.*; class GFG { // function for decimal to // binary conversion without // using arithmetic operators static String decToBin(int n) { if (n == 0) return "0"; // to store the binary // equivalent of decimal String bin = ""; while (n > 0) { // to get the last binary digit // of the number 'n' and accumulate // it at the beginning of 'bin' bin = ((n & 1) == 0 ? '0' : '1') + bin; // right shift 'n' by 1 n >>= 1; } // required binary number return bin; } // Driver program to test above public static void main (String[] args) { int n = 38; System.out.println(decToBin(n)); }} // This code is contributed by vt_m
# Python3 implementation of# decimal to binary conversion# without using arithmetic operators # function for decimal to# binary conversion without# using arithmetic operatorsdef decToBin(n): if(n == 0): return "0"; # to store the binary # equivalent of decimal bin = ""; while (n > 0): # to get the last binary # digit of the number 'n' # and accumulate it at # the beginning of 'bin' if (n & 1 == 0): bin = '0' + bin; else: bin = '1' + bin; # right shift 'n' by 1 n = n >> 1; # required binary number return bin; # Driver Coden = 38;print(decToBin(n)); # This code is contributed# by mits
// C# implementation of decimal// to binary conversion without// using arithmetic operatorsusing System; class GFG { // function for decimal to // binary conversion without // using arithmetic operators static String decToBin(int n) { if (n == 0) return "0"; // to store the binary // equivalent of decimal String bin = ""; while (n > 0) { // to get the last binary digit // of the number 'n' and accumulate // it at the beginning of 'bin' bin = ((n & 1) == 0 ? '0' : '1') + bin; // right shift 'n' by 1 n >>= 1; } // required binary number return bin; } // Driver program to test above public static void Main() { int n = 38; Console.WriteLine(decToBin(n)); }} // This code is contributed by Sam007
<?php// PHP implementation of decimal// to binary conversion without// using arithmetic operators // function for decimal to// binary conversion without// using arithmetic operatorsfunction decToBin($n){ if ($n == 0) return "0"; // to store the binary // equivalent of decimal $bin = ""; while ($n > 0) { // to get the last binary // digit of the number 'n' // and accumulate it at // the beginning of 'bin' $bin = (($n & 1) == 0 ? '0' : '1') . $bin; // right shift 'n' by 1 $n >>= 1; } // required binary number return $bin;} // Driver Code$n = 38;echo decToBin($n); // This code is contributed// by mits?>
<script>// javascript implementation of decimal// to binary conversion without// using arithmetic operators // function for decimal to// binary conversion without// using arithmetic operatorsfunction decToBin(n){ if (n == 0) return "0"; // to store the binary // equivalent of decimal var bin = ""; while (n > 0) { // to get the last binary digit // of the number 'n' and accumulate // it at the beginning of 'bin' bin = ((n & 1) == 0 ? '0' : '1') + bin; // right shift 'n' by 1 n >>= 1; } // required binary number return bin;} // Driver program to test abovevar n = 38;document.write(decToBin(n)); // This code is contributed by shikhasingrajput</script>
Output:
100110
Time complexity: O(num), where num is the number of bits in the binary representation of n.This article is contributed by Ayush Jauhari. 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.
Mithun Kumar
shikhasingrajput
base-conversion
Mathematical
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Find all factors of a natural number | Set 1
Check if a number is Palindrome
Program to print prime numbers from 1 to N.
Fizz Buzz Implementation
Program to multiply two matrices
Count ways to reach the n'th stair
Add two numbers without using arithmetic operators
Program to add two binary strings
Program to convert a given number to words
Modular multiplicative inverse | [
{
"code": null,
"e": 24327,
"s": 24299,
"text": "\n06 Apr, 2021"
},
{
"code": null,
"e": 24436,
"s": 24327,
"text": "Find the binary equivalent of the given non-negative number n without using arithmetic operators.Examples: "
},
{
"code": null,
"e": 24497,
"s": 24436,
"text": "Input : n = 10\nOutput : 1010\n\nInput : n = 38\nOutput : 100110"
},
{
"code": null,
"e": 24586,
"s": 24499,
"text": "Note that + in below algorithm/program is used for concatenation purpose. Algorithm: "
},
{
"code": null,
"e": 24819,
"s": 24586,
"text": "decToBin(n)\n if n == 0\n return \"0\"\n Declare bin = \"\"\n Declare ch\n while n > 0\n if (n & 1) == 0\n ch = '0'\n else\n ch = '1'\n bin = ch + bin\n n = n >> 1\n return bin"
},
{
"code": null,
"e": 24825,
"s": 24821,
"text": "C++"
},
{
"code": null,
"e": 24830,
"s": 24825,
"text": "Java"
},
{
"code": null,
"e": 24838,
"s": 24830,
"text": "Python3"
},
{
"code": null,
"e": 24841,
"s": 24838,
"text": "C#"
},
{
"code": null,
"e": 24845,
"s": 24841,
"text": "PHP"
},
{
"code": null,
"e": 24856,
"s": 24845,
"text": "Javascript"
},
{
"code": "// C++ implementation of decimal to binary conversion// without using arithmetic operators#include <bits/stdc++.h> using namespace std; // function for decimal to binary conversion// without using arithmetic operatorsstring decToBin(int n){ if (n == 0) return \"0\"; // to store the binary equivalent of decimal string bin = \"\"; while (n > 0) { // to get the last binary digit of the number 'n' // and accumulate it at the beginning of 'bin' bin = ((n & 1) == 0 ? '0' : '1') + bin; // right shift 'n' by 1 n >>= 1; } // required binary number return bin;} // Driver program to test aboveint main(){ int n = 38; cout << decToBin(n); return 0;}",
"e": 25597,
"s": 24856,
"text": null
},
{
"code": "// Java implementation of decimal// to binary conversion without// using arithmetic operatorsimport java.io.*; class GFG { // function for decimal to // binary conversion without // using arithmetic operators static String decToBin(int n) { if (n == 0) return \"0\"; // to store the binary // equivalent of decimal String bin = \"\"; while (n > 0) { // to get the last binary digit // of the number 'n' and accumulate // it at the beginning of 'bin' bin = ((n & 1) == 0 ? '0' : '1') + bin; // right shift 'n' by 1 n >>= 1; } // required binary number return bin; } // Driver program to test above public static void main (String[] args) { int n = 38; System.out.println(decToBin(n)); }} // This code is contributed by vt_m",
"e": 26532,
"s": 25597,
"text": null
},
{
"code": "# Python3 implementation of# decimal to binary conversion# without using arithmetic operators # function for decimal to# binary conversion without# using arithmetic operatorsdef decToBin(n): if(n == 0): return \"0\"; # to store the binary # equivalent of decimal bin = \"\"; while (n > 0): # to get the last binary # digit of the number 'n' # and accumulate it at # the beginning of 'bin' if (n & 1 == 0): bin = '0' + bin; else: bin = '1' + bin; # right shift 'n' by 1 n = n >> 1; # required binary number return bin; # Driver Coden = 38;print(decToBin(n)); # This code is contributed# by mits",
"e": 27265,
"s": 26532,
"text": null
},
{
"code": "// C# implementation of decimal// to binary conversion without// using arithmetic operatorsusing System; class GFG { // function for decimal to // binary conversion without // using arithmetic operators static String decToBin(int n) { if (n == 0) return \"0\"; // to store the binary // equivalent of decimal String bin = \"\"; while (n > 0) { // to get the last binary digit // of the number 'n' and accumulate // it at the beginning of 'bin' bin = ((n & 1) == 0 ? '0' : '1') + bin; // right shift 'n' by 1 n >>= 1; } // required binary number return bin; } // Driver program to test above public static void Main() { int n = 38; Console.WriteLine(decToBin(n)); }} // This code is contributed by Sam007",
"e": 28166,
"s": 27265,
"text": null
},
{
"code": "<?php// PHP implementation of decimal// to binary conversion without// using arithmetic operators // function for decimal to// binary conversion without// using arithmetic operatorsfunction decToBin($n){ if ($n == 0) return \"0\"; // to store the binary // equivalent of decimal $bin = \"\"; while ($n > 0) { // to get the last binary // digit of the number 'n' // and accumulate it at // the beginning of 'bin' $bin = (($n & 1) == 0 ? '0' : '1') . $bin; // right shift 'n' by 1 $n >>= 1; } // required binary number return $bin;} // Driver Code$n = 38;echo decToBin($n); // This code is contributed// by mits?>",
"e": 28901,
"s": 28166,
"text": null
},
{
"code": "<script>// javascript implementation of decimal// to binary conversion without// using arithmetic operators // function for decimal to// binary conversion without// using arithmetic operatorsfunction decToBin(n){ if (n == 0) return \"0\"; // to store the binary // equivalent of decimal var bin = \"\"; while (n > 0) { // to get the last binary digit // of the number 'n' and accumulate // it at the beginning of 'bin' bin = ((n & 1) == 0 ? '0' : '1') + bin; // right shift 'n' by 1 n >>= 1; } // required binary number return bin;} // Driver program to test abovevar n = 38;document.write(decToBin(n)); // This code is contributed by shikhasingrajput</script>",
"e": 29657,
"s": 28901,
"text": null
},
{
"code": null,
"e": 29667,
"s": 29657,
"text": "Output: "
},
{
"code": null,
"e": 29674,
"s": 29667,
"text": "100110"
},
{
"code": null,
"e": 30191,
"s": 29674,
"text": "Time complexity: O(num), where num is the number of bits in the binary representation of n.This article is contributed by Ayush Jauhari. 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. "
},
{
"code": null,
"e": 30204,
"s": 30191,
"text": "Mithun Kumar"
},
{
"code": null,
"e": 30221,
"s": 30204,
"text": "shikhasingrajput"
},
{
"code": null,
"e": 30237,
"s": 30221,
"text": "base-conversion"
},
{
"code": null,
"e": 30250,
"s": 30237,
"text": "Mathematical"
},
{
"code": null,
"e": 30263,
"s": 30250,
"text": "Mathematical"
},
{
"code": null,
"e": 30361,
"s": 30263,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30370,
"s": 30361,
"text": "Comments"
},
{
"code": null,
"e": 30383,
"s": 30370,
"text": "Old Comments"
},
{
"code": null,
"e": 30428,
"s": 30383,
"text": "Find all factors of a natural number | Set 1"
},
{
"code": null,
"e": 30460,
"s": 30428,
"text": "Check if a number is Palindrome"
},
{
"code": null,
"e": 30504,
"s": 30460,
"text": "Program to print prime numbers from 1 to N."
},
{
"code": null,
"e": 30529,
"s": 30504,
"text": "Fizz Buzz Implementation"
},
{
"code": null,
"e": 30562,
"s": 30529,
"text": "Program to multiply two matrices"
},
{
"code": null,
"e": 30597,
"s": 30562,
"text": "Count ways to reach the n'th stair"
},
{
"code": null,
"e": 30648,
"s": 30597,
"text": "Add two numbers without using arithmetic operators"
},
{
"code": null,
"e": 30682,
"s": 30648,
"text": "Program to add two binary strings"
},
{
"code": null,
"e": 30725,
"s": 30682,
"text": "Program to convert a given number to words"
}
] |
MySQL - ALTER VIEW Statement | A MySQL view is a composition of a table in the form of a predefined SQL query. It is stored in the database with an associated name.
You can change the definition of an existing view using the ALTER VIEW Statement
Following is the syntax of the ALTER VIEW Statement β
ALTER
[ALGORITHM = {UNDEFINED | MERGE | TEMPTABLE}]
VIEW view_name [(column_list)]
AS select_statement
[WITH [CASCADED | LOCAL] CHECK OPTION]
Suppose we have created a table named dispatches_data with 5 records in it using the following queries β
mysql> CREATE TABLE dispatches_data(
ProductName VARCHAR(255),
CustomerName VARCHAR(255),
DispatchTimeStamp timestamp,
Price INT,
Location VARCHAR(255)
);
insert into dispatches_data values('Key-Board', 'Raja', TIMESTAMP('2019-05-04', '15:02:45'), 7000, 'Hyderabad');
insert into dispatches_data values('Earphones', 'Roja', TIMESTAMP('2019-06-26', '14:13:12'), 2000, 'Vishakhapatnam');
insert into dispatches_data values('Mouse', 'Puja', TIMESTAMP('2019-12-07', '07:50:37'), 3000, 'Vijayawada');
insert into dispatches_data values('Mobile', 'Vanaja' , TIMESTAMP ('2018-03-21', '16:00:45'), 9000, 'Chennai');
insert into dispatches_data values('Headset', 'Jalaja' , TIMESTAMP('2018-12-30', '10:49:27'), 6000, 'Goa');
Let us create a view using the CREATE VIEW statement as shown below β
mysql> CREATE VIEW testView AS SELECT * FROM dispatches_data;
You can retrieve the definition of the above created view using the SHOW CREATE VIEW statement as shown below β
mysql> SHOW CREATE VIEW testView;
+----------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+----------------------+----------------------+
| View | Create View | character_set_client | collation_connection |
+----------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+----------------------+----------------------+
| testview | CREATE ALGORITHM=UNDEFINED DEFINER=`root`@`localhost` SQL SECURITY DEFINER VIEW `testview` AS select `dispatches_data`.`ProductName` AS `ProductName`,`dispatches_data`.`CustomerName` AS `CustomerName`,`dispatches_data`.`DispatchTimeStamp` AS `DispatchTimeStamp`,`dispatches_data`.`Price` AS `Price`,`dispatches_data`.`Location` AS `Location` from `dispatches_data` | cp850 | cp850_general_ci |
+----------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+----------------------+----------------------+
1 row in set (0.07 sec)
Following query alters the ALGORITHM of the table β
mysql> ALTER ALGORITHM=MERGE VIEW testView AS SELECT * FROM dispatches_data;
Query OK, 0 rows affected (0.73 sec)
If you retrieve the definition of the above created view after altering the table you can observe the name of the algorithm β
mysql> SHOW CREATE VIEW testView;
+----------+--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+----------------------+----------------------+
| View | Create View | character_set_client | collation_connection |
+----------+--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+----------------------+----------------------+
| testview | CREATE ALGORITHM=MERGE DEFINER=`root`@`localhost` SQL SECURITY DEFINER VIEW `testview` AS select `dispatches_data`.`ProductName` AS `ProductName`,`dispatches_data`.`CustomerName` AS `CustomerName`,`dispatches_data`.`DispatchTimeStamp` AS `DispatchTimeStamp`,`dispatches_data`.`Price` AS `Price`,`dispatches_data`.`Location` AS `Location` from `dispatches_data` | cp850 | cp850_general_ci |
+----------+--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+----------------------+----------------------+
1 row in set (0.10 sec)
If a view is created such that it includes all (or certain) columns of a table you can change the columns used in the view using the ALTER VIEW statement.
ALTER
VIEW view_name column_list
AS select_statement
If you retrieve the contents of the above created view using SELECT statement as shown below β
mysql> SELECT * FROM testView;
+-------------+--------------+---------------------+-------+----------------+
| ProductName | CustomerName | DispatchTimeStamp | Price | Location |
+-------------+--------------+---------------------+-------+----------------+
| Key-Board | Raja | 2019-05-04 15:02:45 | 7000 | Hyderabad |
| Earphones | Roja | 2019-06-26 14:13:12 | 2000 | Vishakhapatnam |
| Mouse | Puja | 2019-12-07 07:50:37 | 3000 | Vijayawada |
| Mobile | Vanaja | 2018-03-21 16:00:45 | 9000 | Chennai |
| Headset | Jalaja | 2018-12-30 10:49:27 | 6000 | Goa |
+-------------+--------------+---------------------+-------+----------------+
5 rows in set (0.02 sec)5 rows in set (0.15 sec)
Following query alters the columns of an existing views β
mysql> ALTER VIEW testView (ProductName, Price, Location) AS SELECT ProductName, Price, Location FROM dispatches_data;
Query OK, 0 rows affected (0.34 sec)
You can verify the contents of altered view as shown below β
mysql> SELECT * FROM testView;
+-------------+-------+----------------+
| ProductName | Price | Location |
+-------------+-------+----------------+
| Key-Board | 7000 | Hyderabad |
| Earphones | 2000 | Vishakhapatnam |
| Mouse | 3000 | Vijayawada |
| Mobile | 9000 | Chennai |
| Headset | 6000 | Goa |
+-------------+-------+----------------+
5 rows in set (0.15 sec)
31 Lectures
6 hours
Eduonix Learning Solutions
84 Lectures
5.5 hours
Frahaan Hussain
6 Lectures
3.5 hours
DATAhill Solutions Srinivas Reddy
60 Lectures
10 hours
Vijay Kumar Parvatha Reddy
10 Lectures
1 hours
Harshit Srivastava
25 Lectures
4 hours
Trevoir Williams
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2467,
"s": 2333,
"text": "A MySQL view is a composition of a table in the form of a predefined SQL query. It is stored in the database with an associated name."
},
{
"code": null,
"e": 2548,
"s": 2467,
"text": "You can change the definition of an existing view using the ALTER VIEW Statement"
},
{
"code": null,
"e": 2602,
"s": 2548,
"text": "Following is the syntax of the ALTER VIEW Statement β"
},
{
"code": null,
"e": 2757,
"s": 2602,
"text": "ALTER\n [ALGORITHM = {UNDEFINED | MERGE | TEMPTABLE}]\n VIEW view_name [(column_list)]\n AS select_statement\n [WITH [CASCADED | LOCAL] CHECK OPTION]\n"
},
{
"code": null,
"e": 2862,
"s": 2757,
"text": "Suppose we have created a table named dispatches_data with 5 records in it using the following queries β"
},
{
"code": null,
"e": 3593,
"s": 2862,
"text": "mysql> CREATE TABLE dispatches_data(\n ProductName VARCHAR(255),\n CustomerName VARCHAR(255),\n DispatchTimeStamp timestamp,\n Price INT,\n Location VARCHAR(255)\n);\ninsert into dispatches_data values('Key-Board', 'Raja', TIMESTAMP('2019-05-04', '15:02:45'), 7000, 'Hyderabad');\ninsert into dispatches_data values('Earphones', 'Roja', TIMESTAMP('2019-06-26', '14:13:12'), 2000, 'Vishakhapatnam');\ninsert into dispatches_data values('Mouse', 'Puja', TIMESTAMP('2019-12-07', '07:50:37'), 3000, 'Vijayawada');\ninsert into dispatches_data values('Mobile', 'Vanaja' , TIMESTAMP ('2018-03-21', '16:00:45'), 9000, 'Chennai');\ninsert into dispatches_data values('Headset', 'Jalaja' , TIMESTAMP('2018-12-30', '10:49:27'), 6000, 'Goa');"
},
{
"code": null,
"e": 3663,
"s": 3593,
"text": "Let us create a view using the CREATE VIEW statement as shown below β"
},
{
"code": null,
"e": 3726,
"s": 3663,
"text": "mysql> CREATE VIEW testView AS SELECT * FROM dispatches_data;\n"
},
{
"code": null,
"e": 3838,
"s": 3726,
"text": "You can retrieve the definition of the above created view using the SHOW CREATE VIEW statement as shown below β"
},
{
"code": null,
"e": 6026,
"s": 3838,
"text": "mysql> SHOW CREATE VIEW testView;\n+----------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+----------------------+----------------------+\n| View | Create View | character_set_client | collation_connection |\n+----------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+----------------------+----------------------+\n| testview | CREATE ALGORITHM=UNDEFINED DEFINER=`root`@`localhost` SQL SECURITY DEFINER VIEW `testview` AS select `dispatches_data`.`ProductName` AS `ProductName`,`dispatches_data`.`CustomerName` AS `CustomerName`,`dispatches_data`.`DispatchTimeStamp` AS `DispatchTimeStamp`,`dispatches_data`.`Price` AS `Price`,`dispatches_data`.`Location` AS `Location` from `dispatches_data` | cp850 | cp850_general_ci |\n+----------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+----------------------+----------------------+\n1 row in set (0.07 sec)"
},
{
"code": null,
"e": 6078,
"s": 6026,
"text": "Following query alters the ALGORITHM of the table β"
},
{
"code": null,
"e": 6193,
"s": 6078,
"text": "mysql> ALTER ALGORITHM=MERGE VIEW testView AS SELECT * FROM dispatches_data;\nQuery OK, 0 rows affected (0.73 sec)\n"
},
{
"code": null,
"e": 6319,
"s": 6193,
"text": "If you retrieve the definition of the above created view after altering the table you can observe the name of the algorithm β"
},
{
"code": null,
"e": 8487,
"s": 6319,
"text": "mysql> SHOW CREATE VIEW testView;\n+----------+--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+----------------------+----------------------+\n| View | Create View | character_set_client | collation_connection |\n+----------+--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+----------------------+----------------------+\n| testview | CREATE ALGORITHM=MERGE DEFINER=`root`@`localhost` SQL SECURITY DEFINER VIEW `testview` AS select `dispatches_data`.`ProductName` AS `ProductName`,`dispatches_data`.`CustomerName` AS `CustomerName`,`dispatches_data`.`DispatchTimeStamp` AS `DispatchTimeStamp`,`dispatches_data`.`Price` AS `Price`,`dispatches_data`.`Location` AS `Location` from `dispatches_data` | cp850 | cp850_general_ci |\n+----------+--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+----------------------+----------------------+\n1 row in set (0.10 sec)"
},
{
"code": null,
"e": 8642,
"s": 8487,
"text": "If a view is created such that it includes all (or certain) columns of a table you can change the columns used in the view using the ALTER VIEW statement."
},
{
"code": null,
"e": 8702,
"s": 8642,
"text": "ALTER\n VIEW view_name column_list\n AS select_statement\n"
},
{
"code": null,
"e": 8797,
"s": 8702,
"text": "If you retrieve the contents of the above created view using SELECT statement as shown below β"
},
{
"code": null,
"e": 9579,
"s": 8797,
"text": "mysql> SELECT * FROM testView;\n+-------------+--------------+---------------------+-------+----------------+\n| ProductName | CustomerName | DispatchTimeStamp | Price | Location |\n+-------------+--------------+---------------------+-------+----------------+\n| Key-Board | Raja | 2019-05-04 15:02:45 | 7000 | Hyderabad |\n| Earphones | Roja | 2019-06-26 14:13:12 | 2000 | Vishakhapatnam |\n| Mouse | Puja | 2019-12-07 07:50:37 | 3000 | Vijayawada |\n| Mobile | Vanaja | 2018-03-21 16:00:45 | 9000 | Chennai |\n| Headset | Jalaja | 2018-12-30 10:49:27 | 6000 | Goa |\n+-------------+--------------+---------------------+-------+----------------+\n5 rows in set (0.02 sec)5 rows in set (0.15 sec)"
},
{
"code": null,
"e": 9637,
"s": 9579,
"text": "Following query alters the columns of an existing views β"
},
{
"code": null,
"e": 9794,
"s": 9637,
"text": "mysql> ALTER VIEW testView (ProductName, Price, Location) AS SELECT ProductName, Price, Location FROM dispatches_data;\nQuery OK, 0 rows affected (0.34 sec)\n"
},
{
"code": null,
"e": 9855,
"s": 9794,
"text": "You can verify the contents of altered view as shown below β"
},
{
"code": null,
"e": 10280,
"s": 9855,
"text": "mysql> SELECT * FROM testView;\n+-------------+-------+----------------+\n| ProductName | Price | Location |\n+-------------+-------+----------------+\n| Key-Board | 7000 | Hyderabad |\n| Earphones | 2000 | Vishakhapatnam |\n| Mouse | 3000 | Vijayawada |\n| Mobile | 9000 | Chennai |\n| Headset | 6000 | Goa |\n+-------------+-------+----------------+\n5 rows in set (0.15 sec)"
},
{
"code": null,
"e": 10313,
"s": 10280,
"text": "\n 31 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 10341,
"s": 10313,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 10376,
"s": 10341,
"text": "\n 84 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 10393,
"s": 10376,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 10427,
"s": 10393,
"text": "\n 6 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 10462,
"s": 10427,
"text": " DATAhill Solutions Srinivas Reddy"
},
{
"code": null,
"e": 10496,
"s": 10462,
"text": "\n 60 Lectures \n 10 hours \n"
},
{
"code": null,
"e": 10524,
"s": 10496,
"text": " Vijay Kumar Parvatha Reddy"
},
{
"code": null,
"e": 10557,
"s": 10524,
"text": "\n 10 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 10577,
"s": 10557,
"text": " Harshit Srivastava"
},
{
"code": null,
"e": 10610,
"s": 10577,
"text": "\n 25 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 10628,
"s": 10610,
"text": " Trevoir Williams"
},
{
"code": null,
"e": 10635,
"s": 10628,
"text": " Print"
},
{
"code": null,
"e": 10646,
"s": 10635,
"text": " Add Notes"
}
] |
SIC/XE Architecture - GeeksforGeeks | 20 May, 2019
SIC/XE stands for Simplified Instructional Computer Extra Equipment or Extra Expensive. This computer is an advance version of SIC. Both SIC and SIC/XE are closely related to each other thatβs why they are Upward Compatible.
SIC/XE machine architecture:
1. Memory:
Memory consists of 8 bit-bytes and the memory size is 1 megabytes (220 bytes). Standard SIC memory size is very small. This change in the memory size leads to change in the instruction formats as well as addressing modes. 3 consecutive bytes form a word (24 bits) in SIC/XE architecture.
All address are byte addresses and words are addressed by the location of their lowest numbered byte.
2. Registers:It contain 9 registers (5 SIC registers + 4 additional registers). Four additional registers are:
Mnemonics Use of Register
B Base register
S General working register
T General working register
F Floating-point accumulator
3. Data Formats:
Integers are represented by Binary numbers.
Characters are represented using ASCII codes.
Floating points are represented using 48-bits.
4. Instruction formats:
In SIC/XE architecture there are 4 types of formats available
The Bit(e) is used to distinguish between Formats 3 and Formats 4,e=0 means Format 3 and e=1 means Format 4
e=0 means Format 3 and e=1 means Format 4
Format 1(1 byte):
Format 2(2 bytes):
Format 3(3 bytes):
Format 4(4 bytes):
n=Indirect mode, i=Immediate addressing, x=Index addressing, b=Base addressing, p= Program counter, e=Exponential addressing
5. Addressing Modes:To use Format 3 use of Base register and Program counter is there.
Mode Indication Target Address (TA)
Base relative b=1, p=0 TA=(B) + displacement
Program-counter b=0, p=1 TA=(PC) + displacement
relative
Target address is the effective address of the instruction.
6. Instruction Set:
IN SIC/XE all the instructions are same as that of SIC architecture but because of Floating point data format it provide Floating point Arithmetic functions too.
To perform floating-point arithmetic operations,ADDF = Add floating points,
SUBF = Subtract floating points,
MULF = Multiply floating points,
DIVF = Divide floating points
ADDF = Add floating points,
SUBF = Subtract floating points,
MULF = Multiply floating points,
DIVF = Divide floating points
SVC (Supervisor call) is also provided in the SIC/XE architecture to handle Interrupts.
7. Input and Output:SIC/XE architecture include I/O channels that allow to perform I/O operations while CPU is executing other tasks. It will allow overlapping of computing and I/O, which make this architecture more efficient. Instructions such as SIO, TIO, HIO are used to start, test, and halt the operation I/O channels.
Computer Organization & Architecture
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Direct Access Media (DMA) Controller in Computer Architecture
Architecture of 8085 microprocessor
Computer Organization and Architecture | Pipelining | Set 2 (Dependencies and Data Hazard)
Pin diagram of 8086 microprocessor
Difference between Hardwired and Micro-programmed Control Unit | Set 2
I2C Communication Protocol
Memory mapped I/O and Isolated I/O
Computer Architecture | Flynn's taxonomy
Computer Organization | Different Instruction Cycles
Introduction of Control Unit and its Design | [
{
"code": null,
"e": 26159,
"s": 26131,
"text": "\n20 May, 2019"
},
{
"code": null,
"e": 26384,
"s": 26159,
"text": "SIC/XE stands for Simplified Instructional Computer Extra Equipment or Extra Expensive. This computer is an advance version of SIC. Both SIC and SIC/XE are closely related to each other thatβs why they are Upward Compatible."
},
{
"code": null,
"e": 26413,
"s": 26384,
"text": "SIC/XE machine architecture:"
},
{
"code": null,
"e": 26424,
"s": 26413,
"text": "1. Memory:"
},
{
"code": null,
"e": 26712,
"s": 26424,
"text": "Memory consists of 8 bit-bytes and the memory size is 1 megabytes (220 bytes). Standard SIC memory size is very small. This change in the memory size leads to change in the instruction formats as well as addressing modes. 3 consecutive bytes form a word (24 bits) in SIC/XE architecture."
},
{
"code": null,
"e": 26814,
"s": 26712,
"text": "All address are byte addresses and words are addressed by the location of their lowest numbered byte."
},
{
"code": null,
"e": 26925,
"s": 26814,
"text": "2. Registers:It contain 9 registers (5 SIC registers + 4 additional registers). Four additional registers are:"
},
{
"code": null,
"e": 27184,
"s": 26925,
"text": "\n Mnemonics Use of Register\n B Base register\n S General working register\n T General working register\n F Floating-point accumulator\n"
},
{
"code": null,
"e": 27201,
"s": 27184,
"text": "3. Data Formats:"
},
{
"code": null,
"e": 27245,
"s": 27201,
"text": "Integers are represented by Binary numbers."
},
{
"code": null,
"e": 27291,
"s": 27245,
"text": "Characters are represented using ASCII codes."
},
{
"code": null,
"e": 27338,
"s": 27291,
"text": "Floating points are represented using 48-bits."
},
{
"code": null,
"e": 27362,
"s": 27338,
"text": "4. Instruction formats:"
},
{
"code": null,
"e": 27424,
"s": 27362,
"text": "In SIC/XE architecture there are 4 types of formats available"
},
{
"code": null,
"e": 27532,
"s": 27424,
"text": "The Bit(e) is used to distinguish between Formats 3 and Formats 4,e=0 means Format 3 and e=1 means Format 4"
},
{
"code": null,
"e": 27574,
"s": 27532,
"text": "e=0 means Format 3 and e=1 means Format 4"
},
{
"code": null,
"e": 27592,
"s": 27574,
"text": "Format 1(1 byte):"
},
{
"code": null,
"e": 27611,
"s": 27592,
"text": "Format 2(2 bytes):"
},
{
"code": null,
"e": 27630,
"s": 27611,
"text": "Format 3(3 bytes):"
},
{
"code": null,
"e": 27649,
"s": 27630,
"text": "Format 4(4 bytes):"
},
{
"code": null,
"e": 27774,
"s": 27649,
"text": "n=Indirect mode, i=Immediate addressing, x=Index addressing, b=Base addressing, p= Program counter, e=Exponential addressing"
},
{
"code": null,
"e": 27861,
"s": 27774,
"text": "5. Addressing Modes:To use Format 3 use of Base register and Program counter is there."
},
{
"code": null,
"e": 28110,
"s": 27861,
"text": " \n Mode Indication Target Address (TA) \n Base relative b=1, p=0 TA=(B) + displacement \n Program-counter b=0, p=1 TA=(PC) + displacement \n relative \n"
},
{
"code": null,
"e": 28170,
"s": 28110,
"text": "Target address is the effective address of the instruction."
},
{
"code": null,
"e": 28190,
"s": 28170,
"text": "6. Instruction Set:"
},
{
"code": null,
"e": 28352,
"s": 28190,
"text": "IN SIC/XE all the instructions are same as that of SIC architecture but because of Floating point data format it provide Floating point Arithmetic functions too."
},
{
"code": null,
"e": 28528,
"s": 28352,
"text": "To perform floating-point arithmetic operations,ADDF = Add floating points, \nSUBF = Subtract floating points, \nMULF = Multiply floating points, \nDIVF = Divide floating points "
},
{
"code": null,
"e": 28656,
"s": 28528,
"text": "ADDF = Add floating points, \nSUBF = Subtract floating points, \nMULF = Multiply floating points, \nDIVF = Divide floating points "
},
{
"code": null,
"e": 28744,
"s": 28656,
"text": "SVC (Supervisor call) is also provided in the SIC/XE architecture to handle Interrupts."
},
{
"code": null,
"e": 29068,
"s": 28744,
"text": "7. Input and Output:SIC/XE architecture include I/O channels that allow to perform I/O operations while CPU is executing other tasks. It will allow overlapping of computing and I/O, which make this architecture more efficient. Instructions such as SIO, TIO, HIO are used to start, test, and halt the operation I/O channels."
},
{
"code": null,
"e": 29105,
"s": 29068,
"text": "Computer Organization & Architecture"
},
{
"code": null,
"e": 29203,
"s": 29105,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29265,
"s": 29203,
"text": "Direct Access Media (DMA) Controller in Computer Architecture"
},
{
"code": null,
"e": 29301,
"s": 29265,
"text": "Architecture of 8085 microprocessor"
},
{
"code": null,
"e": 29392,
"s": 29301,
"text": "Computer Organization and Architecture | Pipelining | Set 2 (Dependencies and Data Hazard)"
},
{
"code": null,
"e": 29427,
"s": 29392,
"text": "Pin diagram of 8086 microprocessor"
},
{
"code": null,
"e": 29498,
"s": 29427,
"text": "Difference between Hardwired and Micro-programmed Control Unit | Set 2"
},
{
"code": null,
"e": 29525,
"s": 29498,
"text": "I2C Communication Protocol"
},
{
"code": null,
"e": 29560,
"s": 29525,
"text": "Memory mapped I/O and Isolated I/O"
},
{
"code": null,
"e": 29601,
"s": 29560,
"text": "Computer Architecture | Flynn's taxonomy"
},
{
"code": null,
"e": 29654,
"s": 29601,
"text": "Computer Organization | Different Instruction Cycles"
}
] |
PostgreSQL - Identity Column - GeeksforGeeks | 28 Aug, 2020
In PostgreSQL, the GENERATED AS IDENTITY constraint is used to create a PostgreSQL identity column. It allows users to automatically assign a unique value to a column. The GENERATED AS IDENTITY constraint is the SQL standard-conforming variant of the PostgreSQLβs SERIAL column.
Syntax:
column_name type GENERATED { ALWAYS | BY DEFAULT } AS IDENTITY[ ( sequence_option ) ]
Letβs analyze the above syntax.
The type can be SMALLINT, INT, or BIGINT.
The GENERATED ALWAYS instructs PostgreSQL to always generate a value for the identity column. If you attempt to insert (or update) a value into the GENERATED ALWAYS AS IDENTITY column, PostgreSQL will issue an error.
The GENERATED BY DEFAULT also instructs PostgreSQL to generate a value for the identity column. However, if you provide a value for insert or update, PostgreSQL will use that value to insert into the identity column instead of using the system-generated value.
Now letβs look into some examples.
Example 1:First, create a table named color with the color_id as the identity column:
CREATE TABLE color (
color_id INT GENERATED ALWAYS AS IDENTITY,
color_name VARCHAR NOT NULL
);
Second, insert a new row into the color table:
INSERT INTO color (color_name)
VALUES
('Red');
Because color_id column has the GENERATED AS IDENTITY constraint, PostgreSQL generates a value for it as shown in the query below:
SELECT * FROM color;
This will result in the below:Third, insert a new row by providing values for both color_id and color_name columns:
INSERT INTO color (color_id, color_name)
VALUES
(2, 'Green');
PostgreSQL issued the following error:
[Err] ERROR: cannot insert into column "color_id"
DETAIL: Column "color_id" is an identity column defined as GENERATED ALWAYS.
HINT: Use OVERRIDING SYSTEM VALUE to override.
To fix the error, in this case, you can use the OVERRIDING SYSTEM VALUE clause as follows:
INSERT INTO color (color_id, color_name)
OVERRIDING SYSTEM VALUE
VALUES
(2, 'Green');
Now if we use the below statement to verify the entry:
SELECT * FROM color;
Output:
Example 2:In this example, we will use the GENERATED BY DEFAULT AS IDENTITY to create the same table we created above. To do so, drop the color table as below:
DROP TABLE color;
Now recreate the table as below:
CREATE TABLE color (
color_id INT GENERATED BY DEFAULT AS IDENTITY,
color_name VARCHAR NOT NULL
);
Now, insert a row into the color table:
INSERT INTO color (color_name)
VALUES
('White');
Now, insert another row with a value for the color_id column:
INSERT INTO color (color_id, color_name)
VALUES
(2, 'Yellow');
Here unlike the previous example that uses the GENERATED ALWAYS AS IDENTITY constraint, this statement also works.To verify the inserted data use the below statement:
SELECT * FROM color;
Output:
postgreSQL-managing-table
PostgreSQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
PostgreSQL - GROUP BY clause
PostgreSQL - DROP INDEX
PostgreSQL - LEFT JOIN
PostgreSQL - Record type variable
PostgreSQL - Cursor
PostgreSQL - LIMIT with OFFSET clause
PostgreSQL - Select Into
PostgreSQL - Copy Table
PostgreSQL - ROW_NUMBER Function
Install PostgreSQL on Windows | [
{
"code": null,
"e": 24000,
"s": 23972,
"text": "\n28 Aug, 2020"
},
{
"code": null,
"e": 24279,
"s": 24000,
"text": "In PostgreSQL, the GENERATED AS IDENTITY constraint is used to create a PostgreSQL identity column. It allows users to automatically assign a unique value to a column. The GENERATED AS IDENTITY constraint is the SQL standard-conforming variant of the PostgreSQLβs SERIAL column."
},
{
"code": null,
"e": 24373,
"s": 24279,
"text": "Syntax:\ncolumn_name type GENERATED { ALWAYS | BY DEFAULT } AS IDENTITY[ ( sequence_option ) ]"
},
{
"code": null,
"e": 24405,
"s": 24373,
"text": "Letβs analyze the above syntax."
},
{
"code": null,
"e": 24447,
"s": 24405,
"text": "The type can be SMALLINT, INT, or BIGINT."
},
{
"code": null,
"e": 24664,
"s": 24447,
"text": "The GENERATED ALWAYS instructs PostgreSQL to always generate a value for the identity column. If you attempt to insert (or update) a value into the GENERATED ALWAYS AS IDENTITY column, PostgreSQL will issue an error."
},
{
"code": null,
"e": 24925,
"s": 24664,
"text": "The GENERATED BY DEFAULT also instructs PostgreSQL to generate a value for the identity column. However, if you provide a value for insert or update, PostgreSQL will use that value to insert into the identity column instead of using the system-generated value."
},
{
"code": null,
"e": 24960,
"s": 24925,
"text": "Now letβs look into some examples."
},
{
"code": null,
"e": 25046,
"s": 24960,
"text": "Example 1:First, create a table named color with the color_id as the identity column:"
},
{
"code": null,
"e": 25149,
"s": 25046,
"text": "CREATE TABLE color (\n color_id INT GENERATED ALWAYS AS IDENTITY,\n color_name VARCHAR NOT NULL\n);"
},
{
"code": null,
"e": 25196,
"s": 25149,
"text": "Second, insert a new row into the color table:"
},
{
"code": null,
"e": 25247,
"s": 25196,
"text": "INSERT INTO color (color_name)\nVALUES\n ('Red');"
},
{
"code": null,
"e": 25378,
"s": 25247,
"text": "Because color_id column has the GENERATED AS IDENTITY constraint, PostgreSQL generates a value for it as shown in the query below:"
},
{
"code": null,
"e": 25399,
"s": 25378,
"text": "SELECT * FROM color;"
},
{
"code": null,
"e": 25515,
"s": 25399,
"text": "This will result in the below:Third, insert a new row by providing values for both color_id and color_name columns:"
},
{
"code": null,
"e": 25581,
"s": 25515,
"text": "INSERT INTO color (color_id, color_name)\nVALUES\n (2, 'Green');"
},
{
"code": null,
"e": 25620,
"s": 25581,
"text": "PostgreSQL issued the following error:"
},
{
"code": null,
"e": 25797,
"s": 25620,
"text": "[Err] ERROR: cannot insert into column \"color_id\"\nDETAIL: Column \"color_id\" is an identity column defined as GENERATED ALWAYS.\nHINT: Use OVERRIDING SYSTEM VALUE to override."
},
{
"code": null,
"e": 25888,
"s": 25797,
"text": "To fix the error, in this case, you can use the OVERRIDING SYSTEM VALUE clause as follows:"
},
{
"code": null,
"e": 25979,
"s": 25888,
"text": "INSERT INTO color (color_id, color_name)\nOVERRIDING SYSTEM VALUE \nVALUES\n (2, 'Green');"
},
{
"code": null,
"e": 26034,
"s": 25979,
"text": "Now if we use the below statement to verify the entry:"
},
{
"code": null,
"e": 26055,
"s": 26034,
"text": "SELECT * FROM color;"
},
{
"code": null,
"e": 26063,
"s": 26055,
"text": "Output:"
},
{
"code": null,
"e": 26223,
"s": 26063,
"text": "Example 2:In this example, we will use the GENERATED BY DEFAULT AS IDENTITY to create the same table we created above. To do so, drop the color table as below:"
},
{
"code": null,
"e": 26241,
"s": 26223,
"text": "DROP TABLE color;"
},
{
"code": null,
"e": 26274,
"s": 26241,
"text": "Now recreate the table as below:"
},
{
"code": null,
"e": 26381,
"s": 26274,
"text": "CREATE TABLE color (\n color_id INT GENERATED BY DEFAULT AS IDENTITY,\n color_name VARCHAR NOT NULL\n);"
},
{
"code": null,
"e": 26421,
"s": 26381,
"text": "Now, insert a row into the color table:"
},
{
"code": null,
"e": 26474,
"s": 26421,
"text": "INSERT INTO color (color_name)\nVALUES\n ('White');"
},
{
"code": null,
"e": 26536,
"s": 26474,
"text": "Now, insert another row with a value for the color_id column:"
},
{
"code": null,
"e": 26603,
"s": 26536,
"text": "INSERT INTO color (color_id, color_name)\nVALUES\n (2, 'Yellow');"
},
{
"code": null,
"e": 26770,
"s": 26603,
"text": "Here unlike the previous example that uses the GENERATED ALWAYS AS IDENTITY constraint, this statement also works.To verify the inserted data use the below statement:"
},
{
"code": null,
"e": 26791,
"s": 26770,
"text": "SELECT * FROM color;"
},
{
"code": null,
"e": 26799,
"s": 26791,
"text": "Output:"
},
{
"code": null,
"e": 26825,
"s": 26799,
"text": "postgreSQL-managing-table"
},
{
"code": null,
"e": 26836,
"s": 26825,
"text": "PostgreSQL"
},
{
"code": null,
"e": 26934,
"s": 26836,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26943,
"s": 26934,
"text": "Comments"
},
{
"code": null,
"e": 26956,
"s": 26943,
"text": "Old Comments"
},
{
"code": null,
"e": 26985,
"s": 26956,
"text": "PostgreSQL - GROUP BY clause"
},
{
"code": null,
"e": 27009,
"s": 26985,
"text": "PostgreSQL - DROP INDEX"
},
{
"code": null,
"e": 27032,
"s": 27009,
"text": "PostgreSQL - LEFT JOIN"
},
{
"code": null,
"e": 27066,
"s": 27032,
"text": "PostgreSQL - Record type variable"
},
{
"code": null,
"e": 27086,
"s": 27066,
"text": "PostgreSQL - Cursor"
},
{
"code": null,
"e": 27124,
"s": 27086,
"text": "PostgreSQL - LIMIT with OFFSET clause"
},
{
"code": null,
"e": 27149,
"s": 27124,
"text": "PostgreSQL - Select Into"
},
{
"code": null,
"e": 27173,
"s": 27149,
"text": "PostgreSQL - Copy Table"
},
{
"code": null,
"e": 27206,
"s": 27173,
"text": "PostgreSQL - ROW_NUMBER Function"
}
] |
Sorting array of strings (or words) using Trie - GeeksforGeeks | 17 Sep, 2021
Given an array of strings, print them in alphabetical (dictionary) order. If there are duplicates in input array, we need to print them only once.Examples:
Input : "abc", "xy", "bcd"
Output : abc bcd xy
Input : "geeks", "for", "geeks", "a", "portal",
"to", "learn", "can", "be", "computer",
"science", "zoom", "yup", "fire", "in", "data"
Output : a be can computer data fire for geeks
in learn portal science to yup zoom
Trie is an efficient data structure used for storing data like strings. To print the string in alphabetical order we have to first insert in the trie and then perform preorder traversal to print in alphabetical order.
CPP
Java
// C++ program to sort an array of strings// using Trie#include <bits/stdc++.h>using namespace std; const int MAX_CHAR = 26; struct Trie { // index is set when node is a leaf // node, otherwise -1; int index; Trie* child[MAX_CHAR]; /*to make new trie*/ Trie() { for (int i = 0; i < MAX_CHAR; i++) child[i] = NULL; index = -1; }}; /* function to insert in trie */void insert(Trie* root, string str, int index){ Trie* node = root; for (int i = 0; i < str.size(); i++) { /* taking ascii value to find index of child node */ char ind = str[i] - 'a'; /* making new path if not already */ if (!node->child[ind]) node->child[ind] = new Trie(); // go to next node node = node->child[ind]; } // Mark leaf (end of word) and store // index of word in arr[] node->index = index;} /* function for preorder traversal */bool preorder(Trie* node, string arr[]){ if (node == NULL) return false; for (int i = 0; i < MAX_CHAR; i++) { if (node->child[i] != NULL) { /* if leaf node then print key*/ if (node->child[i]->index != -1) cout << arr[node->child[i]->index] << endl; preorder(node->child[i], arr); } }} void printSorted(string arr[], int n){ Trie* root = new Trie(); // insert all keys of dictionary into trie for (int i = 0; i < n; i++) insert(root, arr[i], i); // print keys in lexicographic order preorder(root, arr);} // Driver codeint main(){ string arr[] = { "abc", "xy", "bcd" }; int n = sizeof(arr) / sizeof(arr[0]); printSorted(arr, n); return 0;}
// Java program to sort an array of strings using Trie // Author : Rohit Jain// GFG user_id : @rj03012002 import java.util.*; class GFG { // Alphabet size static final int MAX_CHAR = 26; // trie node static class Trie { // index is set when node is a leaf // node, otherwise -1; int index; Trie child[] = new Trie[MAX_CHAR]; /*to make new trie*/ Trie() { for (int i = 0; i < MAX_CHAR; i++) child[i] = null; index = -1; } } /* function to insert in trie */ static void insert(Trie root, String str, int index) { Trie node = root; for (int i = 0; i < str.length(); i++) { /* taking ascii value to find index of child node */ int ind = str.charAt(i) - 'a'; /* making new path if not already */ if (node.child[ind] == null) node.child[ind] = new Trie(); // go to next node node = node.child[ind]; } // Mark leaf (end of word) and store // index of word in arr[] node.index = index; } /* function for preorder traversal */ static boolean preorder(Trie node, String arr[]) { if (node == null) { return false; } for (int i = 0; i < MAX_CHAR; i++) { if (node.child[i] != null) { /* if leaf node then print key*/ if (node.child[i].index != -1) { System.out.print( arr[node.child[i].index] + " "); } preorder(node.child[i], arr); } } return false; } static void printSorted(String arr[], int n) { Trie root = new Trie(); // insert all keys of dictionary into trie for (int i = 0; i < n; ++i) { insert(root, arr[i], i); } // print keys in lexicographic order preorder(root, arr); } public static void main(String[] args) { String arr[] = { "abc", "xy", "bcd" }; int n = arr.length; printSorted(arr, n); }}
Output:
abc bcd xy
This article is contributed by Pranav. 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.
rj03012002
Trie
Sorting
Strings
Strings
Sorting
Trie
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Time Complexities of all Sorting Algorithms
Radix Sort
Merge two sorted arrays
Chocolate Distribution Problem
Count Inversions in an array | Set 1 (Using Merge Sort)
Write a program to reverse an array or string
Reverse a string in Java
Longest Common Subsequence | DP-4
C++ Data Types
Write a program to print all permutations of a given string | [
{
"code": null,
"e": 24506,
"s": 24478,
"text": "\n17 Sep, 2021"
},
{
"code": null,
"e": 24664,
"s": 24506,
"text": "Given an array of strings, print them in alphabetical (dictionary) order. If there are duplicates in input array, we need to print them only once.Examples: "
},
{
"code": null,
"e": 24966,
"s": 24664,
"text": "Input : \"abc\", \"xy\", \"bcd\"\nOutput : abc bcd xy \n\nInput : \"geeks\", \"for\", \"geeks\", \"a\", \"portal\", \n \"to\", \"learn\", \"can\", \"be\", \"computer\", \n \"science\", \"zoom\", \"yup\", \"fire\", \"in\", \"data\"\nOutput : a be can computer data fire for geeks\n in learn portal science to yup zoom"
},
{
"code": null,
"e": 25187,
"s": 24968,
"text": "Trie is an efficient data structure used for storing data like strings. To print the string in alphabetical order we have to first insert in the trie and then perform preorder traversal to print in alphabetical order. "
},
{
"code": null,
"e": 25191,
"s": 25187,
"text": "CPP"
},
{
"code": null,
"e": 25196,
"s": 25191,
"text": "Java"
},
{
"code": "// C++ program to sort an array of strings// using Trie#include <bits/stdc++.h>using namespace std; const int MAX_CHAR = 26; struct Trie { // index is set when node is a leaf // node, otherwise -1; int index; Trie* child[MAX_CHAR]; /*to make new trie*/ Trie() { for (int i = 0; i < MAX_CHAR; i++) child[i] = NULL; index = -1; }}; /* function to insert in trie */void insert(Trie* root, string str, int index){ Trie* node = root; for (int i = 0; i < str.size(); i++) { /* taking ascii value to find index of child node */ char ind = str[i] - 'a'; /* making new path if not already */ if (!node->child[ind]) node->child[ind] = new Trie(); // go to next node node = node->child[ind]; } // Mark leaf (end of word) and store // index of word in arr[] node->index = index;} /* function for preorder traversal */bool preorder(Trie* node, string arr[]){ if (node == NULL) return false; for (int i = 0; i < MAX_CHAR; i++) { if (node->child[i] != NULL) { /* if leaf node then print key*/ if (node->child[i]->index != -1) cout << arr[node->child[i]->index] << endl; preorder(node->child[i], arr); } }} void printSorted(string arr[], int n){ Trie* root = new Trie(); // insert all keys of dictionary into trie for (int i = 0; i < n; i++) insert(root, arr[i], i); // print keys in lexicographic order preorder(root, arr);} // Driver codeint main(){ string arr[] = { \"abc\", \"xy\", \"bcd\" }; int n = sizeof(arr) / sizeof(arr[0]); printSorted(arr, n); return 0;}",
"e": 26895,
"s": 25196,
"text": null
},
{
"code": "// Java program to sort an array of strings using Trie // Author : Rohit Jain// GFG user_id : @rj03012002 import java.util.*; class GFG { // Alphabet size static final int MAX_CHAR = 26; // trie node static class Trie { // index is set when node is a leaf // node, otherwise -1; int index; Trie child[] = new Trie[MAX_CHAR]; /*to make new trie*/ Trie() { for (int i = 0; i < MAX_CHAR; i++) child[i] = null; index = -1; } } /* function to insert in trie */ static void insert(Trie root, String str, int index) { Trie node = root; for (int i = 0; i < str.length(); i++) { /* taking ascii value to find index of child node */ int ind = str.charAt(i) - 'a'; /* making new path if not already */ if (node.child[ind] == null) node.child[ind] = new Trie(); // go to next node node = node.child[ind]; } // Mark leaf (end of word) and store // index of word in arr[] node.index = index; } /* function for preorder traversal */ static boolean preorder(Trie node, String arr[]) { if (node == null) { return false; } for (int i = 0; i < MAX_CHAR; i++) { if (node.child[i] != null) { /* if leaf node then print key*/ if (node.child[i].index != -1) { System.out.print( arr[node.child[i].index] + \" \"); } preorder(node.child[i], arr); } } return false; } static void printSorted(String arr[], int n) { Trie root = new Trie(); // insert all keys of dictionary into trie for (int i = 0; i < n; ++i) { insert(root, arr[i], i); } // print keys in lexicographic order preorder(root, arr); } public static void main(String[] args) { String arr[] = { \"abc\", \"xy\", \"bcd\" }; int n = arr.length; printSorted(arr, n); }}",
"e": 29045,
"s": 26895,
"text": null
},
{
"code": null,
"e": 29055,
"s": 29045,
"text": "Output: "
},
{
"code": null,
"e": 29069,
"s": 29055,
"text": "abc bcd xy "
},
{
"code": null,
"e": 29484,
"s": 29069,
"text": "This article is contributed by Pranav. 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": 29495,
"s": 29484,
"text": "rj03012002"
},
{
"code": null,
"e": 29500,
"s": 29495,
"text": "Trie"
},
{
"code": null,
"e": 29508,
"s": 29500,
"text": "Sorting"
},
{
"code": null,
"e": 29516,
"s": 29508,
"text": "Strings"
},
{
"code": null,
"e": 29524,
"s": 29516,
"text": "Strings"
},
{
"code": null,
"e": 29532,
"s": 29524,
"text": "Sorting"
},
{
"code": null,
"e": 29537,
"s": 29532,
"text": "Trie"
},
{
"code": null,
"e": 29635,
"s": 29537,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29679,
"s": 29635,
"text": "Time Complexities of all Sorting Algorithms"
},
{
"code": null,
"e": 29690,
"s": 29679,
"text": "Radix Sort"
},
{
"code": null,
"e": 29714,
"s": 29690,
"text": "Merge two sorted arrays"
},
{
"code": null,
"e": 29745,
"s": 29714,
"text": "Chocolate Distribution Problem"
},
{
"code": null,
"e": 29801,
"s": 29745,
"text": "Count Inversions in an array | Set 1 (Using Merge Sort)"
},
{
"code": null,
"e": 29847,
"s": 29801,
"text": "Write a program to reverse an array or string"
},
{
"code": null,
"e": 29872,
"s": 29847,
"text": "Reverse a string in Java"
},
{
"code": null,
"e": 29906,
"s": 29872,
"text": "Longest Common Subsequence | DP-4"
},
{
"code": null,
"e": 29921,
"s": 29906,
"text": "C++ Data Types"
}
] |
D3.js zoomIdentity() Function - GeeksforGeeks | 06 Sep, 2020
The d3.zoomIdentity() function in D3.js is used to get the identity transform, where k = 1, tx = ty = 0.
Syntax:
d3.zoomIdentity;
Parameters: This function does not accept any parameter.
Return Value: This function returns the identity transform.
Below programs illustrate the d3.zoomIdentity() function in D3.js.
Example 1:
HTML
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <script src= "https://d3js.org/d3.v4.min.js"> </script> <style> svg text { fill: green; font: 20px sans-serif; text-anchor: center; } rect { pointer-events: all; } </style></head> <body> <center> <h1 style="color: green;"> Geeksforgeeks </h1> <h3>D3.js | d3.zoomIdentity() Function</h3> <button id="reset">Reset</button><br/> <svg></svg> <script> var width = 400; var height = 200; var svg = d3.select("svg") .attr("width",width) .attr("height",height); // The scale used to display the axis. var scale = d3.scaleLinear() .range([10,width-20]) .domain([0,100]); var shadowScale = scale.copy(); var axis = d3.axisBottom() .scale(scale); var g = svg.append("g") .attr("transform","translate(0,50)") .call(axis); // Standard zoom behavior var zoom = d3.zoom() .scaleExtent([1,10]) .translateExtent([[0, 0], [width, height]]) .on("zoom", zoomed); // Calling the Zoom var rect = svg.append("rect") .attr("width",width) .attr("height",height) .attr("fill","none") .call(zoom); d3.select("#reset") .on("click", function() { // Creating an identity transform var transform = d3.zoomIdentity; // Applying the transform: rect.call(zoom.transform, transform); }) function zoomed() { var t = d3.event.transform; scale.domain(t.rescaleX(shadowScale).domain()); g.call(axis); } </script> </center></body> </html>
Output:
Example 2:
HTML
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <script src= "https://d3js.org/d3.v4.min.js"> </script> </head> <body> <center> <h1 style="color: green;"> Geeksforgeeks </h1> <h3>D3.js | d3.zoomIdentity() Function</h3> <script> var svg = d3.select("body").append("svg") .attr("width", 400) .attr("height", 300); var g1 = svg.append("g"); var zoom1 = d3.zoom().on("zoom", function() { g1.attr("transform", d3.event.transform); }); g1.call(zoom1.transform, d3.zoomIdentity .translate(150, 100) .scale(2)); g1.append("rect") .attr("x", 20) .attr("y", 20) .attr("width", 60) .attr("height", 60) .attr("fill","green"); d3.selectAll("rect").on("click", function() { g1.transition() .duration(3000) .attr("transform", d3.zoomIdentity) .on("end", function() { d3.select(this) .call(zoom1.transform, d3.zoomIdentity); }) }); </script> </center></body> </html>
Output:
D3.js
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Difference between var, let and const keywords in JavaScript
Difference Between PUT and PATCH Request
How to get character array from string in JavaScript?
How to remove duplicate elements from JavaScript Array ?
How to get selected value in dropdown list using JavaScript ?
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS? | [
{
"code": null,
"e": 25220,
"s": 25192,
"text": "\n06 Sep, 2020"
},
{
"code": null,
"e": 25325,
"s": 25220,
"text": "The d3.zoomIdentity() function in D3.js is used to get the identity transform, where k = 1, tx = ty = 0."
},
{
"code": null,
"e": 25333,
"s": 25325,
"text": "Syntax:"
},
{
"code": null,
"e": 25351,
"s": 25333,
"text": "d3.zoomIdentity;\n"
},
{
"code": null,
"e": 25408,
"s": 25351,
"text": "Parameters: This function does not accept any parameter."
},
{
"code": null,
"e": 25468,
"s": 25408,
"text": "Return Value: This function returns the identity transform."
},
{
"code": null,
"e": 25535,
"s": 25468,
"text": "Below programs illustrate the d3.zoomIdentity() function in D3.js."
},
{
"code": null,
"e": 25546,
"s": 25535,
"text": "Example 1:"
},
{
"code": null,
"e": 25551,
"s": 25546,
"text": "HTML"
},
{
"code": "<!DOCTYPE html> <html> <head> <meta charset=\"utf-8\"> <script src= \"https://d3js.org/d3.v4.min.js\"> </script> <style> svg text { fill: green; font: 20px sans-serif; text-anchor: center; } rect { pointer-events: all; } </style></head> <body> <center> <h1 style=\"color: green;\"> Geeksforgeeks </h1> <h3>D3.js | d3.zoomIdentity() Function</h3> <button id=\"reset\">Reset</button><br/> <svg></svg> <script> var width = 400; var height = 200; var svg = d3.select(\"svg\") .attr(\"width\",width) .attr(\"height\",height); // The scale used to display the axis. var scale = d3.scaleLinear() .range([10,width-20]) .domain([0,100]); var shadowScale = scale.copy(); var axis = d3.axisBottom() .scale(scale); var g = svg.append(\"g\") .attr(\"transform\",\"translate(0,50)\") .call(axis); // Standard zoom behavior var zoom = d3.zoom() .scaleExtent([1,10]) .translateExtent([[0, 0], [width, height]]) .on(\"zoom\", zoomed); // Calling the Zoom var rect = svg.append(\"rect\") .attr(\"width\",width) .attr(\"height\",height) .attr(\"fill\",\"none\") .call(zoom); d3.select(\"#reset\") .on(\"click\", function() { // Creating an identity transform var transform = d3.zoomIdentity; // Applying the transform: rect.call(zoom.transform, transform); }) function zoomed() { var t = d3.event.transform; scale.domain(t.rescaleX(shadowScale).domain()); g.call(axis); } </script> </center></body> </html>",
"e": 27789,
"s": 25551,
"text": null
},
{
"code": null,
"e": 27797,
"s": 27789,
"text": "Output:"
},
{
"code": null,
"e": 27808,
"s": 27797,
"text": "Example 2:"
},
{
"code": null,
"e": 27813,
"s": 27808,
"text": "HTML"
},
{
"code": "<!DOCTYPE html> <html> <head> <meta charset=\"utf-8\"> <script src= \"https://d3js.org/d3.v4.min.js\"> </script> </head> <body> <center> <h1 style=\"color: green;\"> Geeksforgeeks </h1> <h3>D3.js | d3.zoomIdentity() Function</h3> <script> var svg = d3.select(\"body\").append(\"svg\") .attr(\"width\", 400) .attr(\"height\", 300); var g1 = svg.append(\"g\"); var zoom1 = d3.zoom().on(\"zoom\", function() { g1.attr(\"transform\", d3.event.transform); }); g1.call(zoom1.transform, d3.zoomIdentity .translate(150, 100) .scale(2)); g1.append(\"rect\") .attr(\"x\", 20) .attr(\"y\", 20) .attr(\"width\", 60) .attr(\"height\", 60) .attr(\"fill\",\"green\"); d3.selectAll(\"rect\").on(\"click\", function() { g1.transition() .duration(3000) .attr(\"transform\", d3.zoomIdentity) .on(\"end\", function() { d3.select(this) .call(zoom1.transform, d3.zoomIdentity); }) }); </script> </center></body> </html>",
"e": 29235,
"s": 27813,
"text": null
},
{
"code": null,
"e": 29243,
"s": 29235,
"text": "Output:"
},
{
"code": null,
"e": 29249,
"s": 29243,
"text": "D3.js"
},
{
"code": null,
"e": 29260,
"s": 29249,
"text": "JavaScript"
},
{
"code": null,
"e": 29277,
"s": 29260,
"text": "Web Technologies"
},
{
"code": null,
"e": 29375,
"s": 29277,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29384,
"s": 29375,
"text": "Comments"
},
{
"code": null,
"e": 29397,
"s": 29384,
"text": "Old Comments"
},
{
"code": null,
"e": 29458,
"s": 29397,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 29499,
"s": 29458,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 29553,
"s": 29499,
"text": "How to get character array from string in JavaScript?"
},
{
"code": null,
"e": 29610,
"s": 29553,
"text": "How to remove duplicate elements from JavaScript Array ?"
},
{
"code": null,
"e": 29672,
"s": 29610,
"text": "How to get selected value in dropdown list using JavaScript ?"
},
{
"code": null,
"e": 29714,
"s": 29672,
"text": "Roadmap to Become a Web Developer in 2022"
},
{
"code": null,
"e": 29747,
"s": 29714,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 29809,
"s": 29747,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 29852,
"s": 29809,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
JavaFX | Building a Media Player - GeeksforGeeks | 23 Jun, 2020
This JavaFX library is used to make feature-rich internet apps (they offer similar experience and features as that of desktop apps). Like other Java libraries, the products built upon this library are platform independent, they can run on devices such as mobile phones, TVs, computers etc.
Other JVM based technologies like Groovy, JRuby etc can be used alongside JavaFX, however, the need seldom arises as JavaFX is offering most of the features itself. It is highly compatible with Java Swing, and its content can be embedded seamlessly in JavaFX apps.
Building a Media Player in JavaFX
For the media player application we would have three different classes the first one is our Main class which starts this application, then we have Player class to run our videos and audios and MediaBar class to control our media.Implementation:
// Java program to Build a Media // Player in JavaFXimport java.io.File;import java.net.MalformedURLException; import javafx.application.Application;import javafx.event.ActionEvent;import javafx.event.EventHandler;import javafx.stage.FileChooser;import javafx.stage.Stage;import javafx.scene.Scene;import javafx.scene.control.Menu;import javafx.scene.control.MenuBar;import javafx.scene.control.MenuItem;import javafx.scene.layout.BorderPane;import javafx.scene.paint.Color; // launches the applicationpublic class Main extends Application { Player player; FileChooser fileChooser; public void start(final Stage primaryStage) { // setting up the stages MenuItem open = new MenuItem("Open"); Menu file = new Menu("File"); MenuBar menu = new MenuBar(); // Connecting the above three file.getItems().add(open); // it would connect open with file menu.getMenus().add(file); // Adding functionality to switch to different videos fileChooser = new FileChooser(); open.setOnAction(new EventHandler<ActionEvent>(){ public void handle(ActionEvent e) { // Pausing the video while switching player.player.pause(); File file = fileChooser.showOpenDialog(primaryStage); // Choosing the file to play if (file != null) { try { player = new Player(file.toURI().toURL().toExternalForm()); Scene scene = new Scene(player, 720, 535, Color.BLACK); primaryStage.setScene(scene); } catch (MalformedURLException e1) { e1.printStackTrace(); } } } // here you can choose any video player = new Player("file:/// F:/songs/srk.mp4"); // Setting the menu at the top player.setTop(menu); // Adding player to the Scene Scene scene = new Scene(player, 720, 535, Color.BLACK); // height and width of the video player // background color set to Black primaryStage.setScene(scene); // Setting the scene to stage primaryStage.show(); // Showing the stage } // Main function to launch the application public static void main(String[] args){ launch(args); }} import javafx.scene.layout.BorderPane; import javafx.scene.layout.Pane; import javafx.scene.media.Media; import javafx.scene.media.MediaPlayer; import javafx.scene.media.MediaView; public class Player extends BorderPane // Player class extend BorderPane // in order to divide the media // player into regions { Media media; MediaPlayer player; MediaView view; Pane mpane; MediaBar bar; public Player(String file) { // Default constructor media = new Media(file); player = new MediaPlayer(media); view = new MediaView(player); mpane = new Pane(); mpane.getChildren().add(view); // Calling the function getChildren // inorder to add the view setCenter(mpane); bar = new MediaBar(player); // Passing the player to MediaBar setBottom(bar); // Setting the MediaBar at bottom setStyle("-fx-background-color:#bfc2c7"); // Adding color to the mediabar player.play(); // Making the video play } } import javafx.application.Platform; import javafx.beans.InvalidationListener; import javafx.beans.Observable; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.geometry.Insets; import javafx.geometry.Pos; import javafx.scene.control.Button; import javafx.scene.control.Label; import javafx.scene.control.Slider; import javafx.scene.layout.HBox; import javafx.scene.layout.Priority; import javafx.scene.media.MediaPlayer; import javafx.scene.media.MediaPlayer.Status; public class MediaBar extends HBox { // MediaBar extends Horizontal Box // introducing Sliders Slider time = new Slider(); // Slider for time Slider vol = new Slider(); // Slider for volume Button PlayButton = new Button("||"); // For pausing the player Label volume = new Label("Volume: "); MediaPlayer player; public MediaBar(MediaPlayer play) { // Default constructor taking // the MediaPlayer object player = play; setAlignment(Pos.CENTER); // setting the HBox to center setPadding(new Insets(5, 10, 5, 10)); // Settih the preference for volume bar vol.setPrefWidth(70); vol.setMinWidth(30); vol.setValue(100); HBox.setHgrow(time, Priority.ALWAYS); PlayButton.setPrefWidth(30); // Adding the components to the bottom getChildren().add(PlayButton); // Playbutton getChildren().add(time); // time slider getChildren().add(volume); // volume slider getChildren().add(vol); // Adding Functionality // to play the media player PlayButton.setOnAction(new EventHandler<ActionEvent>() { public void handle(ActionEvent e) { Status status = player.getStatus(); // To get the status of Player if (status == status.PLAYING) { // If the status is Video playing if (player.getCurrentTime().greaterThanOrEqualTo(player.getTotalDuration())) { // If the player is at the end of video player.seek(player.getStartTime()); // Restart the video player.play(); } else { // Pausing the player player.pause(); PlayButton.setText(">"); } } // If the video is stopped, halted or paused if (status == Status.HALTED || status == Status.STOPPED || status == Status.PAUSED) { player.play(); // Start the video PlayButton.setText("||"); } } }); // Providing functionality to time slider player.currentTimeProperty().addListener(new InvalidationListener() { public void invalidated(Observable ov) { updatesValues(); } }); // Inorder to jump to the certain part of video time.valueProperty().addListener(new InvalidationListener() { public void invalidated(Observable ov) { if (time.isPressed()) { // It would set the time // as specified by user by pressing player.seek(player.getMedia().getDuration().multiply(time.getValue() / 100)); } } }); // providing functionality to volume slider vol.valueProperty().addListener(new InvalidationListener() { public void invalidated(Observable ov) { if (vol.isPressed()) { player.setVolume(vol.getValue() / 100); // It would set the volume // as specified by user by pressing } } }); } // Outside the constructor protected void updatesValues() { Platform.runLater(new Runnable() { public void run() { // Updating to the new time value // This will move the slider while running your video time.setValue(player.getCurrentTime().toMillis() player.getTotalDuration() .toMillis() * 100); } }); } }
On running the above program on an offline IDE, the Media Player would look something like:
ExplanationWe have three classes over here-1. Main class to launch our program2. Player class to play our Media player3. MediaBar class to add control to our control panel of media bar.
In our Main.java class which extends over the application class we have two methods one main method to launch the program and start method where we can set the stage and media control border. Then we have added the slider at the bottom for controlling the time of video and to control volume. In order to add functionality like to jump to a particular section of video we have used the-
player.seek(player.getMedia().
getDuration().multiply(time.getValue()/100));
And for changing the media
fileChooser.showOpenDialog(primaryStage)
has been used in the above program. For styling purpose we have come up with the CSS which is depicted in
-fx-background-color:#bfc2c7
Among the best features of JavaFX is that one can control formatting with Cascading Style Sheets (CSS). We have used the .getStatus() function to check the status of player that whether it is halted, playing, stopped or paused and to take action accordingly.
Note:While importing select always the JavaFX files.
References:Referred video
Akanksha_Rai
JavaFX
Java
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
Stream In Java
HashMap in Java with Examples
Interfaces in Java
How to iterate any Map in Java
Top 10 algorithms in Interview Questions
vector::push_back() and vector::pop_back() in C++ STL
Overview of Data Structures | Set 1 (Linear Data Structures)
How to write Regular Expressions? | [
{
"code": null,
"e": 25439,
"s": 25411,
"text": "\n23 Jun, 2020"
},
{
"code": null,
"e": 25729,
"s": 25439,
"text": "This JavaFX library is used to make feature-rich internet apps (they offer similar experience and features as that of desktop apps). Like other Java libraries, the products built upon this library are platform independent, they can run on devices such as mobile phones, TVs, computers etc."
},
{
"code": null,
"e": 25994,
"s": 25729,
"text": "Other JVM based technologies like Groovy, JRuby etc can be used alongside JavaFX, however, the need seldom arises as JavaFX is offering most of the features itself. It is highly compatible with Java Swing, and its content can be embedded seamlessly in JavaFX apps."
},
{
"code": null,
"e": 26028,
"s": 25994,
"text": "Building a Media Player in JavaFX"
},
{
"code": null,
"e": 26273,
"s": 26028,
"text": "For the media player application we would have three different classes the first one is our Main class which starts this application, then we have Player class to run our videos and audios and MediaBar class to control our media.Implementation:"
},
{
"code": "// Java program to Build a Media // Player in JavaFXimport java.io.File;import java.net.MalformedURLException; import javafx.application.Application;import javafx.event.ActionEvent;import javafx.event.EventHandler;import javafx.stage.FileChooser;import javafx.stage.Stage;import javafx.scene.Scene;import javafx.scene.control.Menu;import javafx.scene.control.MenuBar;import javafx.scene.control.MenuItem;import javafx.scene.layout.BorderPane;import javafx.scene.paint.Color; // launches the applicationpublic class Main extends Application { Player player; FileChooser fileChooser; public void start(final Stage primaryStage) { // setting up the stages MenuItem open = new MenuItem(\"Open\"); Menu file = new Menu(\"File\"); MenuBar menu = new MenuBar(); // Connecting the above three file.getItems().add(open); // it would connect open with file menu.getMenus().add(file); // Adding functionality to switch to different videos fileChooser = new FileChooser(); open.setOnAction(new EventHandler<ActionEvent>(){ public void handle(ActionEvent e) { // Pausing the video while switching player.player.pause(); File file = fileChooser.showOpenDialog(primaryStage); // Choosing the file to play if (file != null) { try { player = new Player(file.toURI().toURL().toExternalForm()); Scene scene = new Scene(player, 720, 535, Color.BLACK); primaryStage.setScene(scene); } catch (MalformedURLException e1) { e1.printStackTrace(); } } } // here you can choose any video player = new Player(\"file:/// F:/songs/srk.mp4\"); // Setting the menu at the top player.setTop(menu); // Adding player to the Scene Scene scene = new Scene(player, 720, 535, Color.BLACK); // height and width of the video player // background color set to Black primaryStage.setScene(scene); // Setting the scene to stage primaryStage.show(); // Showing the stage } // Main function to launch the application public static void main(String[] args){ launch(args); }} import javafx.scene.layout.BorderPane; import javafx.scene.layout.Pane; import javafx.scene.media.Media; import javafx.scene.media.MediaPlayer; import javafx.scene.media.MediaView; public class Player extends BorderPane // Player class extend BorderPane // in order to divide the media // player into regions { Media media; MediaPlayer player; MediaView view; Pane mpane; MediaBar bar; public Player(String file) { // Default constructor media = new Media(file); player = new MediaPlayer(media); view = new MediaView(player); mpane = new Pane(); mpane.getChildren().add(view); // Calling the function getChildren // inorder to add the view setCenter(mpane); bar = new MediaBar(player); // Passing the player to MediaBar setBottom(bar); // Setting the MediaBar at bottom setStyle(\"-fx-background-color:#bfc2c7\"); // Adding color to the mediabar player.play(); // Making the video play } } import javafx.application.Platform; import javafx.beans.InvalidationListener; import javafx.beans.Observable; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.geometry.Insets; import javafx.geometry.Pos; import javafx.scene.control.Button; import javafx.scene.control.Label; import javafx.scene.control.Slider; import javafx.scene.layout.HBox; import javafx.scene.layout.Priority; import javafx.scene.media.MediaPlayer; import javafx.scene.media.MediaPlayer.Status; public class MediaBar extends HBox { // MediaBar extends Horizontal Box // introducing Sliders Slider time = new Slider(); // Slider for time Slider vol = new Slider(); // Slider for volume Button PlayButton = new Button(\"||\"); // For pausing the player Label volume = new Label(\"Volume: \"); MediaPlayer player; public MediaBar(MediaPlayer play) { // Default constructor taking // the MediaPlayer object player = play; setAlignment(Pos.CENTER); // setting the HBox to center setPadding(new Insets(5, 10, 5, 10)); // Settih the preference for volume bar vol.setPrefWidth(70); vol.setMinWidth(30); vol.setValue(100); HBox.setHgrow(time, Priority.ALWAYS); PlayButton.setPrefWidth(30); // Adding the components to the bottom getChildren().add(PlayButton); // Playbutton getChildren().add(time); // time slider getChildren().add(volume); // volume slider getChildren().add(vol); // Adding Functionality // to play the media player PlayButton.setOnAction(new EventHandler<ActionEvent>() { public void handle(ActionEvent e) { Status status = player.getStatus(); // To get the status of Player if (status == status.PLAYING) { // If the status is Video playing if (player.getCurrentTime().greaterThanOrEqualTo(player.getTotalDuration())) { // If the player is at the end of video player.seek(player.getStartTime()); // Restart the video player.play(); } else { // Pausing the player player.pause(); PlayButton.setText(\">\"); } } // If the video is stopped, halted or paused if (status == Status.HALTED || status == Status.STOPPED || status == Status.PAUSED) { player.play(); // Start the video PlayButton.setText(\"||\"); } } }); // Providing functionality to time slider player.currentTimeProperty().addListener(new InvalidationListener() { public void invalidated(Observable ov) { updatesValues(); } }); // Inorder to jump to the certain part of video time.valueProperty().addListener(new InvalidationListener() { public void invalidated(Observable ov) { if (time.isPressed()) { // It would set the time // as specified by user by pressing player.seek(player.getMedia().getDuration().multiply(time.getValue() / 100)); } } }); // providing functionality to volume slider vol.valueProperty().addListener(new InvalidationListener() { public void invalidated(Observable ov) { if (vol.isPressed()) { player.setVolume(vol.getValue() / 100); // It would set the volume // as specified by user by pressing } } }); } // Outside the constructor protected void updatesValues() { Platform.runLater(new Runnable() { public void run() { // Updating to the new time value // This will move the slider while running your video time.setValue(player.getCurrentTime().toMillis() player.getTotalDuration() .toMillis() * 100); } }); } }",
"e": 34537,
"s": 26273,
"text": null
},
{
"code": null,
"e": 34629,
"s": 34537,
"text": "On running the above program on an offline IDE, the Media Player would look something like:"
},
{
"code": null,
"e": 34815,
"s": 34629,
"text": "ExplanationWe have three classes over here-1. Main class to launch our program2. Player class to play our Media player3. MediaBar class to add control to our control panel of media bar."
},
{
"code": null,
"e": 35202,
"s": 34815,
"text": "In our Main.java class which extends over the application class we have two methods one main method to launch the program and start method where we can set the stage and media control border. Then we have added the slider at the bottom for controlling the time of video and to control volume. In order to add functionality like to jump to a particular section of video we have used the-"
},
{
"code": null,
"e": 35297,
"s": 35202,
"text": "player.seek(player.getMedia().\n getDuration().multiply(time.getValue()/100));"
},
{
"code": null,
"e": 35324,
"s": 35297,
"text": "And for changing the media"
},
{
"code": null,
"e": 35367,
"s": 35324,
"text": " fileChooser.showOpenDialog(primaryStage) "
},
{
"code": null,
"e": 35473,
"s": 35367,
"text": "has been used in the above program. For styling purpose we have come up with the CSS which is depicted in"
},
{
"code": null,
"e": 35502,
"s": 35473,
"text": "-fx-background-color:#bfc2c7"
},
{
"code": null,
"e": 35761,
"s": 35502,
"text": "Among the best features of JavaFX is that one can control formatting with Cascading Style Sheets (CSS). We have used the .getStatus() function to check the status of player that whether it is halted, playing, stopped or paused and to take action accordingly."
},
{
"code": null,
"e": 35814,
"s": 35761,
"text": "Note:While importing select always the JavaFX files."
},
{
"code": null,
"e": 35840,
"s": 35814,
"text": "References:Referred video"
},
{
"code": null,
"e": 35853,
"s": 35840,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 35860,
"s": 35853,
"text": "JavaFX"
},
{
"code": null,
"e": 35865,
"s": 35860,
"text": "Java"
},
{
"code": null,
"e": 35870,
"s": 35865,
"text": "Misc"
},
{
"code": null,
"e": 35875,
"s": 35870,
"text": "Misc"
},
{
"code": null,
"e": 35880,
"s": 35875,
"text": "Misc"
},
{
"code": null,
"e": 35885,
"s": 35880,
"text": "Java"
},
{
"code": null,
"e": 35983,
"s": 35885,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 36034,
"s": 35983,
"text": "Object Oriented Programming (OOPs) Concept in Java"
},
{
"code": null,
"e": 36049,
"s": 36034,
"text": "Stream In Java"
},
{
"code": null,
"e": 36079,
"s": 36049,
"text": "HashMap in Java with Examples"
},
{
"code": null,
"e": 36098,
"s": 36079,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 36129,
"s": 36098,
"text": "How to iterate any Map in Java"
},
{
"code": null,
"e": 36170,
"s": 36129,
"text": "Top 10 algorithms in Interview Questions"
},
{
"code": null,
"e": 36224,
"s": 36170,
"text": "vector::push_back() and vector::pop_back() in C++ STL"
},
{
"code": null,
"e": 36285,
"s": 36224,
"text": "Overview of Data Structures | Set 1 (Linear Data Structures)"
}
] |
Find the largest number | Practice | GeeksforGeeks | Given an integer N the task is to find the largest number which is smaller or equal to it and has its digits in non-decreasing order.
Examples 1:
Input:
N = 200
Output:
199
Explanation:
If the given number
is 200, the largest
number which is smaller
or equal to it having
digits in non decreasing
order is 199.
Example 2:
Input:
N = 139
Output:
139
Explanation:
139 is itself in
non-decresing order.
Your Task:
You don't need to read input or print anything. Your task is to complete the function find() which takes one integer value N, as input parameter and return the largest number which is smaller or equal to it and has its digits in non-decreasing order.
Expected Time Complexity: O(N)
Expected Space Complexity: O(1)
Constraints:
1<=N<=105
0
gupta2411sumit1 month ago
bool isDcreasing( int n ) { string s = to_string(n) ; for( int i = 1 ; i<s.length() ; i++) { if( s[i] < s[i-1] ) { return false ; } } return true ; } int find(int N){ // code here while(N) { if(isDcreasing(N)) { return N ; } N -= 1 ; } return N ; }
0
sgupta95192 months ago
Java soln using a bit recursion
class Solution{ static int find(int N){ // code here StringBuilder sb=new StringBuilder(String.valueOf(N)); StringBuilder s=new StringBuilder(); int i=0; for(i=0;i<sb.length()-1;i++) if(sb.charAt(i)>sb.charAt(i+1)) { s.append(sb.charAt(i)-'1'); break; } else { s.append(sb.charAt(i)); } if(i==sb.length()-1) { s.append(sb.charAt(i)); return Integer.parseInt(s.toString());} for(int j=i+1;j<sb.length();j++) s.append('9'); i=0; while(i<s.length()-1) if(s.charAt(i)<=s.charAt(i+1)) i++; else return find(Integer.parseInt(s.toString())); return Integer.parseInt(s.toString()); }}
0
neeramrutia3 months ago
class Solution{ static int find(int N){ // code here if(N/10==0) { return N; } if(N/100==0) { while(N>0) { int k=N; int a=k%10; k=k/10; int b=k%10; if(a>=b) { return N; } N--; } } if(N/1000==0) { while(N>0) { int k=N; int a=k%10; k=k/10; int b=k%10; k=k/10; int c=k%10; if(a>=b && b>=c) { return N; } N--; } } if(N/10000==0) { while(N>0) { int k=N; int a=k%10; k=k/10; int b=k%10; k=k/10; int c=k%10; k=k/10; int d=k%10; if(a>=b && b>=c && c>=d) { return N; } N--; } } if(N/100000==0) { while(N>0) { int k=N; int a=k%10; k=k/10; int b=k%10; k=k/10; int c=k%10; k=k/10; int d=k%10; k=k/10; int e=k%10; if(a>=b && b>=c && c>=d && d>=e) { return N; } N--; } } if(N==100000) return N; return 0; }}
0
manishkumar04 months ago
public static boolean isValid(String s)
{
for(int i=1;i<s.length();i++)
{
if(s.charAt(i)<s.charAt(i-1))
return false;
}
return true;
}
static int find(int N){
for(int i=N;i>0;i--)
{
if(isValid(String.valueOf(i)))
return i;
}
return 1;
+1
avinav26114 months ago
Easiest C++ Solution
0
vishakhagupta44 months ago
def find (self, N): for y in range(N, -1, -1): if len(str(y))==1 : return N else: numStr= list(str(y)) numStr.sort() digit="".join(numStr) if int(digit) == y: return y
0
gourmehul824 months ago
class Solution{ public static boolean check_order(int y) { Stack<Integer>stack = new Stack<>() ; int check = Integer. MIN_VALUE ; while(y>0) { int temp = y%10 ; stack.add(temp) ; y/=10 ; } while(!stack.isEmpty()) { int s = stack.pop() ; if(s>=check) { check= s ; } else return false ; } return true ; } static int find(int N){ for(int x=N;x>0;--x) { if( check_order(x)) return x ; } return N ; }}
0
mayank20214 months ago
C++ : with recursionint find(int N){
int digit = N%10, N2=N ; while(N>0) { if (digit < N%10) { N2=N2-1; return find(N2); } else { digit =N%10 ; N=N/10; } } return N2;
}
0
luizhsb5 months ago
static int find(int N){
while (N > 0) {
int lastDigit = -1;
int num = N;
boolean isDigitsAscending = true;
while (num > 0 && isDigitsAscending) {
int digit = num % 10;
num = num / 10;
if (lastDigit != -1 && lastDigit < digit) {
isDigitsAscending = false;
break;
}
lastDigit = digit;
}
if (isDigitsAscending) {
break;
} else {
--N;
}
}
return N;
}
0
krushna65 months ago
EASY WAY !!! EASY WAY!!
BY CONVERTING INTO STRING
int chk(int n) { string s = to_string(n); for (int i = 0; i < s.length()-1; i++) if (s[i]>s[i+1])return 0; return 1; }
int find(int n) { int temp = n; while (n--) { if (chk(temp)) return temp; temp--; } }
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": 374,
"s": 238,
"text": "Given an integer N the task is to find the largest number which is smaller or equal to it and has its digits in non-decreasing order.\n "
},
{
"code": null,
"e": 386,
"s": 374,
"text": "Examples 1:"
},
{
"code": null,
"e": 557,
"s": 386,
"text": "Input:\nN = 200\nOutput:\n199\nExplanation:\nIf the given number \nis 200, the largest \nnumber which is smaller \nor equal to it having \ndigits in non decreasing \norder is 199.\n"
},
{
"code": null,
"e": 568,
"s": 557,
"text": "Example 2:"
},
{
"code": null,
"e": 648,
"s": 568,
"text": "Input: \nN = 139\nOutput:\n139\nExplanation:\n139 is itself in \nnon-decresing order."
},
{
"code": null,
"e": 911,
"s": 648,
"text": "\nYour Task:\nYou don't need to read input or print anything. Your task is to complete the function find() which takes one integer value N, as input parameter and return the largest number which is smaller or equal to it and has its digits in non-decreasing order."
},
{
"code": null,
"e": 977,
"s": 911,
"text": "\nExpected Time Complexity: O(N)\nExpected Space Complexity: O(1)\n "
},
{
"code": null,
"e": 1000,
"s": 977,
"text": "Constraints:\n1<=N<=105"
},
{
"code": null,
"e": 1002,
"s": 1000,
"text": "0"
},
{
"code": null,
"e": 1028,
"s": 1002,
"text": "gupta2411sumit1 month ago"
},
{
"code": null,
"e": 1489,
"s": 1028,
"text": "bool isDcreasing( int n ) { string s = to_string(n) ; for( int i = 1 ; i<s.length() ; i++) { if( s[i] < s[i-1] ) { return false ; } } return true ; } int find(int N){ // code here while(N) { if(isDcreasing(N)) { return N ; } N -= 1 ; } return N ; }"
},
{
"code": null,
"e": 1491,
"s": 1489,
"text": "0"
},
{
"code": null,
"e": 1514,
"s": 1491,
"text": "sgupta95192 months ago"
},
{
"code": null,
"e": 1546,
"s": 1514,
"text": "Java soln using a bit recursion"
},
{
"code": null,
"e": 2355,
"s": 1548,
"text": "class Solution{ static int find(int N){ // code here StringBuilder sb=new StringBuilder(String.valueOf(N)); StringBuilder s=new StringBuilder(); int i=0; for(i=0;i<sb.length()-1;i++) if(sb.charAt(i)>sb.charAt(i+1)) { s.append(sb.charAt(i)-'1'); break; } else { s.append(sb.charAt(i)); } if(i==sb.length()-1) { s.append(sb.charAt(i)); return Integer.parseInt(s.toString());} for(int j=i+1;j<sb.length();j++) s.append('9'); i=0; while(i<s.length()-1) if(s.charAt(i)<=s.charAt(i+1)) i++; else return find(Integer.parseInt(s.toString())); return Integer.parseInt(s.toString()); }}"
},
{
"code": null,
"e": 2357,
"s": 2355,
"text": "0"
},
{
"code": null,
"e": 2381,
"s": 2357,
"text": "neeramrutia3 months ago"
},
{
"code": null,
"e": 4015,
"s": 2381,
"text": "class Solution{ static int find(int N){ // code here if(N/10==0) { return N; } if(N/100==0) { while(N>0) { int k=N; int a=k%10; k=k/10; int b=k%10; if(a>=b) { return N; } N--; } } if(N/1000==0) { while(N>0) { int k=N; int a=k%10; k=k/10; int b=k%10; k=k/10; int c=k%10; if(a>=b && b>=c) { return N; } N--; } } if(N/10000==0) { while(N>0) { int k=N; int a=k%10; k=k/10; int b=k%10; k=k/10; int c=k%10; k=k/10; int d=k%10; if(a>=b && b>=c && c>=d) { return N; } N--; } } if(N/100000==0) { while(N>0) { int k=N; int a=k%10; k=k/10; int b=k%10; k=k/10; int c=k%10; k=k/10; int d=k%10; k=k/10; int e=k%10; if(a>=b && b>=c && c>=d && d>=e) { return N; } N--; } } if(N==100000) return N; return 0; }}"
},
{
"code": null,
"e": 4017,
"s": 4015,
"text": "0"
},
{
"code": null,
"e": 4042,
"s": 4017,
"text": "manishkumar04 months ago"
},
{
"code": null,
"e": 4413,
"s": 4042,
"text": "public static boolean isValid(String s)\n {\n for(int i=1;i<s.length();i++)\n {\n if(s.charAt(i)<s.charAt(i-1))\n return false;\n }\n return true;\n }\n \n static int find(int N){\n for(int i=N;i>0;i--)\n {\n if(isValid(String.valueOf(i)))\n return i;\n }\n return 1;"
},
{
"code": null,
"e": 4416,
"s": 4413,
"text": "+1"
},
{
"code": null,
"e": 4439,
"s": 4416,
"text": "avinav26114 months ago"
},
{
"code": null,
"e": 4460,
"s": 4439,
"text": "Easiest C++ Solution"
},
{
"code": null,
"e": 4462,
"s": 4460,
"text": "0"
},
{
"code": null,
"e": 4489,
"s": 4462,
"text": "vishakhagupta44 months ago"
},
{
"code": null,
"e": 4751,
"s": 4489,
"text": " def find (self, N): for y in range(N, -1, -1): if len(str(y))==1 : return N else: numStr= list(str(y)) numStr.sort() digit=\"\".join(numStr) if int(digit) == y: return y"
},
{
"code": null,
"e": 4753,
"s": 4751,
"text": "0"
},
{
"code": null,
"e": 4777,
"s": 4753,
"text": "gourmehul824 months ago"
},
{
"code": null,
"e": 5473,
"s": 4777,
"text": "class Solution{ public static boolean check_order(int y) { Stack<Integer>stack = new Stack<>() ; int check = Integer. MIN_VALUE ; while(y>0) { int temp = y%10 ; stack.add(temp) ; y/=10 ; } while(!stack.isEmpty()) { int s = stack.pop() ; if(s>=check) { check= s ; } else return false ; } return true ; } static int find(int N){ for(int x=N;x>0;--x) { if( check_order(x)) return x ; } return N ; }}"
},
{
"code": null,
"e": 5475,
"s": 5473,
"text": "0"
},
{
"code": null,
"e": 5498,
"s": 5475,
"text": "mayank20214 months ago"
},
{
"code": null,
"e": 5536,
"s": 5498,
"text": "C++ : with recursionint find(int N){"
},
{
"code": null,
"e": 5761,
"s": 5536,
"text": " int digit = N%10, N2=N ; while(N>0) { if (digit < N%10) { N2=N2-1; return find(N2); } else { digit =N%10 ; N=N/10; } } return N2;"
},
{
"code": null,
"e": 5767,
"s": 5761,
"text": " } "
},
{
"code": null,
"e": 5769,
"s": 5767,
"text": "0"
},
{
"code": null,
"e": 5789,
"s": 5769,
"text": "luizhsb5 months ago"
},
{
"code": null,
"e": 6455,
"s": 5789,
"text": " static int find(int N){\n while (N > 0) {\n int lastDigit = -1;\n \n int num = N;\n boolean isDigitsAscending = true;\n while (num > 0 && isDigitsAscending) {\n int digit = num % 10;\n num = num / 10;\n \n if (lastDigit != -1 && lastDigit < digit) {\n isDigitsAscending = false;\n break;\n }\n lastDigit = digit;\n }\n \n if (isDigitsAscending) {\n break;\n } else {\n --N;\n }\n \n }\n \n return N;\n }"
},
{
"code": null,
"e": 6461,
"s": 6459,
"text": "0"
},
{
"code": null,
"e": 6482,
"s": 6461,
"text": "krushna65 months ago"
},
{
"code": null,
"e": 6506,
"s": 6482,
"text": "EASY WAY !!! EASY WAY!!"
},
{
"code": null,
"e": 6532,
"s": 6506,
"text": "BY CONVERTING INTO STRING"
},
{
"code": null,
"e": 6670,
"s": 6532,
"text": "int chk(int n) { string s = to_string(n); for (int i = 0; i < s.length()-1; i++) if (s[i]>s[i+1])return 0; return 1; }"
},
{
"code": null,
"e": 6797,
"s": 6670,
"text": " int find(int n) { int temp = n; while (n--) { if (chk(temp)) return temp; temp--; } } "
},
{
"code": null,
"e": 6943,
"s": 6797,
"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": 6979,
"s": 6943,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 6989,
"s": 6979,
"text": "\nProblem\n"
},
{
"code": null,
"e": 6999,
"s": 6989,
"text": "\nContest\n"
},
{
"code": null,
"e": 7062,
"s": 6999,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 7210,
"s": 7062,
"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": 7418,
"s": 7210,
"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": 7524,
"s": 7418,
"text": "You can access the hints to get an idea about what is expected of you as well as the final solution code."
}
] |
10 Fabulous Python Decorators | by Emmett Boudreau | Towards Data Science | A great thing about the Python programming language is all of the features that it packs into a small package that are incredibly useful. A lot of said features can completely alter the functionality of Python code, which makes the language more versatile. Furthermore, some of these functionalities can serve to shorten the amount of time it takes to write effective software when used properly. A great example of a Python feature that accomplishes these objectives very well is Pythonβs decorators.
Decorators are quick programming macros that can be used to alter the behavior of a Python object. They can be applied to classes and functions, and can actually do a lot of really interesting things! Decorators can serve to shorten code, speed up code, and completely change the way that code acts in Python. Needless to say, this can certainly come in handy! Today I wanted to show off some decorators that I think are worth checking out. There are a lot of decorators, but I picked some of the ones I think have the coolest functionality.
The first decorator on this list comes to us from the functools module. This module is included in the standard library, and is incredibly easy to use. It also contains a lot more cool features than just this decorator, but this decorator is certainly my favorite of the bunch. This decorator can be used to speed up consecutive runs of functions and operations using cache. Of course, this should be used with some notes on swap and caching in mind, but in a general-purpose case of use, most of the time this decorator is worth using. If you would like to learn more about Functools and why I love it, I actually wrote an entire article on just that you can read here:
towardsdatascience.com
Being able to speed up code with a simple decorator is incredibly awesome. A great example of a function that could benefit from a decorator like this is a recursive function, such as this function that calculates a factorial:
def factorial(n): return n * factorial(n-1) if n else 1
Recursion can be pretty hard on calculation times, but adding this decorator can help to speed up consecutive runs of this function dramatically.
@lru_cachedef factorial(n): return n * factorial(n-1) if n else 1
Now whenever we run this function, the first few factorial calculations will be saved into cache. As a result, next time we go to call the function we will only need to calculate the factorials that are after the ones we used prior. Of course, not all factorial calculations will be saved, but it is easy to see why this is a great application of this decorator to speed some code up that is naturally slow.
JIT is short for Just In Time compilation. Normally whenever we run some code in Python, the first thing that happens is compilation. This compilation creates a bit of overhead, as types are allocated memory and stored as unassigned but named aliases. With Just In Time compilation, we do most of this work at execution. In a lot of ways, we can think of this as something akin to parallel computing, where the Python interpreter is working on two things at once in order to save some time.
The Numba JIT compiler is famous for providing that very concept into Python. Similarly to the @lru_cache, this decorator can be called pretty easily with an immediate boost to performance in your code. The Numba package provides the jit decorator, which makes running more intensive software a lot easier without having to drop into C. If you would like to read more on this package, I also have another article all about it you can check out here:
towardsdatascience.com
from numba import jitimport random@jit(nopython=True)def monte_carlo_pi(nsamples): acc = 0 for i in range(nsamples): x = random.random() y = random.random() if (x ** 2 + y ** 2) < 1.0: acc += 1 return 4.0 * acc / nsamples
The do_twice decorator does pretty much what is in its name. This decorator can be used to run a function twice with a single call. There are certainly some uses for this, and I have found it especially helpful with debugging. Another great thing it can be used for is measuring performance for two different iterations. Using Functools as an example, we could make a function run twice in order to check for improvements that come about. This function is provided by the decorators module in Python, which is in the standard library.
from decorators import do_twice@do_twicedef timerfunc(): %timeit factorial(15)
Going along with the simplicity of the do_twice decorator is the count_calls decorator. This decorator can be used to provide information as to how many times a function is used in software. Like do_twice, this certainly can come in handy for debugging. When added to a given function, we will receive an output telling us how many times the function has been ran each time it runs. This decorator is also in the decorators module from the standard library.
from decorators import count_calls@count_callsdef function_example(): print("Hello World!"function_example()function_example()function_example()
One of the best decorators I utilize all the time in order to save time when writing classes is the dataclass decorator. This decorator can be used to quickly write common standard methods that are typically found in the classes that we write. If you would like to learn more about this decorator, I also have an article on it that you can read here:
towardsdatascience.com
This decorator comes from the dataclass module. This module is also in the standard library, so there is no need for PIP to try out this example!
from dataclasses import dataclass@dataclassclass Food: name: str unit_price: float stock: int = 0 def stock_value(self) -> float: return(self.stock * self.unit_price)
This code will automatically create an initialization function, __init__(), with the positional arguments necessary to fill the data in our class. They will also be provided to self automatically, so there is no need to write a long function just to get some data arguments into a class.
In order to understand the purpose of the singleton decorator, we need to first understand what a singleton is. Singletons are in a sense a version of global types. This means that the types are defined to only exist once. Although these are quite common in languages like C++, it is pretty rare to see them in Python. With singletons, we create a class to only be used once and mutate the class rather than an initialized constructed type. In this case, types act less as templates and more as a single controlled object.
Typically, singleton decorators are made by the user, and not in fact imported. This is because the singleton is still a reference to the template provided in our singleton decorator. We can name a singleton function and write a wrapper in order to use this decorator on our class:
def singleton(cls): instances = {} def wrapper(*args, **kwargs): if cls not in instances: instances[cls] = cls(*args, **kwargs) return instances[cls] return wrapper@singletonclass cls: def func(self):
Another way you could approach this problem is by using metaclasses. If you would like to learn more about metaclasses, I wrote an article last year that goes into more details on these and what they are used for you can view here:
towardsdatascience.com
class Singleton(type): _instances = {} def __call__(cls, *args, **kwargs): if cls not in cls._instances: cls._instances[cls] = super(Singleton, cls).__call__(*args, **kwargs) return cls._instances[cls] class Logger(object): __metaclass__ = Singleton
One decorator that might come in handy quite often for scientific computing is the use_unit decorator. This decorator can be used to alter the output of returns to methods. This can be useful for those who donβt want to add units of measurement to their data, but still want people to know what those units are. This decorator is also not really available in any module, but is very commonly written and incredibly useful for scientific applications.
def use_unit(unit): """Have a function return a Quantity with given unit""" use_unit.ureg = pint.UnitRegistry() def decorator_use_unit(func): @functools.wraps(func) def wrapper_use_unit(*args, **kwargs): value = func(*args, **kwargs) return value * use_unit.ureg(unit) return wrapper_use_unit return decorator_use_unit@use_unit("meters per second")def average_speed(distance, duration): return distance / duration
Function wrappers are a design pattern used when dealing with relatively complicated functions in Python. Wrapper functions are typically used to do what might be considered some more low-level, iterative tasks. The benefit of a wrapper function is that it can be used to dramatically improve performance. Like the lru_cache decorator, this decorator is provided by the FuncTools package.
import functools as ft
The wraps decorator itself is simply a convenience decorator for updating the wrapper of a given function. When this decorator is called, the function will update its wrapper each time it is used. This can go a long way in terms of improving performance, as is the case with many tools available in FuncTools.
def my_decorator(f): @wraps(f) def wrapper(*args, **kwds): print('Calling decorated function') return f(*args, **kwds) return wrapper
Wrappers themselves are typically decorators, and the wraps decorator call is typically used on a wrapper function within that decorator call. After writing that code, we can decorate our new function with that wrapper:
@my_decoratordef func(x): print(x)
In some cases, there might be circumstances where one might want to be able to access things that are defined privately as in a more global sense. Sometimes we have functions that are contained within classes that we want to have methodized, and this is exactly what the staticmethod decorator is used for.
Using this decorator, we can make C++ static methods for working with our classes. Normally, methods that are written in the scope of a class will be private to that class, and not accessible unless called as a child. There are circumstances, however, where you might want to take a more functional approach with the way your methods interact with data. Using this decorator, we can create both options without the need for creating more than one function.
class Example: @staticmethod def our_func(stuff): print(stuff)
We also do not need to explicitly provide our class as an argument. The staticmethod decorator takes care of this for us.
FuncTools strikes again in this list with the wonderfully useful singledispatch decorator. Single dispatch is a programming technique that is quite commonplace in many programming languages because of just how great of a way it is to program. While I tend to prefer multiple dispatch, I think that single dispatch can be used to fill the same role in many aspects.
This decorator makes it far easier to work with types in Python. This is even more the case when we are working with multiple types that we want to pass through the same method. I wrote more about this in my FuncTools article, so if you are interested in using the single dispatch methodology, I do recommend it (the link is in #1.)
@singledispatchdef fun(arg, verbose=False): if verbose: print("Let me just say,", end=" ") print(arg)@fun.registerdef _(arg: int, verbose=False): if verbose: print("Strength in numbers, eh?", end=" ") print(arg)@fun.registerdef _(arg: list, verbose=False): if verbose: print("Enumerate this:") for i, elem in enumerate(arg): print(i, elem)
The register function comes from the module atexit. Given that moduleβs name and M.O., you might be able to imagine that this decorator could have something to do with performing some action at termination. The register decorator names a function to be ran at termination. For example, this would work will with some software that needs to save whenever you exit.
from atexit import register@registerdef termin(): print(" Goodbye!")
Needless to say, Pythonβs decorators are incredibly useful. Not only can they be used to slow down the time it takes to write some code, but they can also be incredibly helpful at speeding up code. Not only are decorators incredibly useful when you find them about, but it is also a great idea to write your own. These decorators are only powerful because decorators as a feature are very powerful in Python. Thank you for reading my article, and I hope it brought some of Pythonβs cool abilities to your attention! | [
{
"code": null,
"e": 674,
"s": 172,
"text": "A great thing about the Python programming language is all of the features that it packs into a small package that are incredibly useful. A lot of said features can completely alter the functionality of Python code, which makes the language more versatile. Furthermore, some of these functionalities can serve to shorten the amount of time it takes to write effective software when used properly. A great example of a Python feature that accomplishes these objectives very well is Pythonβs decorators."
},
{
"code": null,
"e": 1216,
"s": 674,
"text": "Decorators are quick programming macros that can be used to alter the behavior of a Python object. They can be applied to classes and functions, and can actually do a lot of really interesting things! Decorators can serve to shorten code, speed up code, and completely change the way that code acts in Python. Needless to say, this can certainly come in handy! Today I wanted to show off some decorators that I think are worth checking out. There are a lot of decorators, but I picked some of the ones I think have the coolest functionality."
},
{
"code": null,
"e": 1887,
"s": 1216,
"text": "The first decorator on this list comes to us from the functools module. This module is included in the standard library, and is incredibly easy to use. It also contains a lot more cool features than just this decorator, but this decorator is certainly my favorite of the bunch. This decorator can be used to speed up consecutive runs of functions and operations using cache. Of course, this should be used with some notes on swap and caching in mind, but in a general-purpose case of use, most of the time this decorator is worth using. If you would like to learn more about Functools and why I love it, I actually wrote an entire article on just that you can read here:"
},
{
"code": null,
"e": 1910,
"s": 1887,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 2137,
"s": 1910,
"text": "Being able to speed up code with a simple decorator is incredibly awesome. A great example of a function that could benefit from a decorator like this is a recursive function, such as this function that calculates a factorial:"
},
{
"code": null,
"e": 2196,
"s": 2137,
"text": "def factorial(n): return n * factorial(n-1) if n else 1"
},
{
"code": null,
"e": 2342,
"s": 2196,
"text": "Recursion can be pretty hard on calculation times, but adding this decorator can help to speed up consecutive runs of this function dramatically."
},
{
"code": null,
"e": 2411,
"s": 2342,
"text": "@lru_cachedef factorial(n): return n * factorial(n-1) if n else 1"
},
{
"code": null,
"e": 2819,
"s": 2411,
"text": "Now whenever we run this function, the first few factorial calculations will be saved into cache. As a result, next time we go to call the function we will only need to calculate the factorials that are after the ones we used prior. Of course, not all factorial calculations will be saved, but it is easy to see why this is a great application of this decorator to speed some code up that is naturally slow."
},
{
"code": null,
"e": 3310,
"s": 2819,
"text": "JIT is short for Just In Time compilation. Normally whenever we run some code in Python, the first thing that happens is compilation. This compilation creates a bit of overhead, as types are allocated memory and stored as unassigned but named aliases. With Just In Time compilation, we do most of this work at execution. In a lot of ways, we can think of this as something akin to parallel computing, where the Python interpreter is working on two things at once in order to save some time."
},
{
"code": null,
"e": 3760,
"s": 3310,
"text": "The Numba JIT compiler is famous for providing that very concept into Python. Similarly to the @lru_cache, this decorator can be called pretty easily with an immediate boost to performance in your code. The Numba package provides the jit decorator, which makes running more intensive software a lot easier without having to drop into C. If you would like to read more on this package, I also have another article all about it you can check out here:"
},
{
"code": null,
"e": 3783,
"s": 3760,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 4046,
"s": 3783,
"text": "from numba import jitimport random@jit(nopython=True)def monte_carlo_pi(nsamples): acc = 0 for i in range(nsamples): x = random.random() y = random.random() if (x ** 2 + y ** 2) < 1.0: acc += 1 return 4.0 * acc / nsamples"
},
{
"code": null,
"e": 4581,
"s": 4046,
"text": "The do_twice decorator does pretty much what is in its name. This decorator can be used to run a function twice with a single call. There are certainly some uses for this, and I have found it especially helpful with debugging. Another great thing it can be used for is measuring performance for two different iterations. Using Functools as an example, we could make a function run twice in order to check for improvements that come about. This function is provided by the decorators module in Python, which is in the standard library."
},
{
"code": null,
"e": 4663,
"s": 4581,
"text": "from decorators import do_twice@do_twicedef timerfunc(): %timeit factorial(15)"
},
{
"code": null,
"e": 5121,
"s": 4663,
"text": "Going along with the simplicity of the do_twice decorator is the count_calls decorator. This decorator can be used to provide information as to how many times a function is used in software. Like do_twice, this certainly can come in handy for debugging. When added to a given function, we will receive an output telling us how many times the function has been ran each time it runs. This decorator is also in the decorators module from the standard library."
},
{
"code": null,
"e": 5269,
"s": 5121,
"text": "from decorators import count_calls@count_callsdef function_example(): print(\"Hello World!\"function_example()function_example()function_example()"
},
{
"code": null,
"e": 5620,
"s": 5269,
"text": "One of the best decorators I utilize all the time in order to save time when writing classes is the dataclass decorator. This decorator can be used to quickly write common standard methods that are typically found in the classes that we write. If you would like to learn more about this decorator, I also have an article on it that you can read here:"
},
{
"code": null,
"e": 5643,
"s": 5620,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 5789,
"s": 5643,
"text": "This decorator comes from the dataclass module. This module is also in the standard library, so there is no need for PIP to try out this example!"
},
{
"code": null,
"e": 5983,
"s": 5789,
"text": "from dataclasses import dataclass@dataclassclass Food: name: str unit_price: float stock: int = 0 def stock_value(self) -> float: return(self.stock * self.unit_price)"
},
{
"code": null,
"e": 6271,
"s": 5983,
"text": "This code will automatically create an initialization function, __init__(), with the positional arguments necessary to fill the data in our class. They will also be provided to self automatically, so there is no need to write a long function just to get some data arguments into a class."
},
{
"code": null,
"e": 6794,
"s": 6271,
"text": "In order to understand the purpose of the singleton decorator, we need to first understand what a singleton is. Singletons are in a sense a version of global types. This means that the types are defined to only exist once. Although these are quite common in languages like C++, it is pretty rare to see them in Python. With singletons, we create a class to only be used once and mutate the class rather than an initialized constructed type. In this case, types act less as templates and more as a single controlled object."
},
{
"code": null,
"e": 7076,
"s": 6794,
"text": "Typically, singleton decorators are made by the user, and not in fact imported. This is because the singleton is still a reference to the template provided in our singleton decorator. We can name a singleton function and write a wrapper in order to use this decorator on our class:"
},
{
"code": null,
"e": 7312,
"s": 7076,
"text": "def singleton(cls): instances = {} def wrapper(*args, **kwargs): if cls not in instances: instances[cls] = cls(*args, **kwargs) return instances[cls] return wrapper@singletonclass cls: def func(self):"
},
{
"code": null,
"e": 7544,
"s": 7312,
"text": "Another way you could approach this problem is by using metaclasses. If you would like to learn more about metaclasses, I wrote an article last year that goes into more details on these and what they are used for you can view here:"
},
{
"code": null,
"e": 7567,
"s": 7544,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 7858,
"s": 7567,
"text": "class Singleton(type): _instances = {} def __call__(cls, *args, **kwargs): if cls not in cls._instances: cls._instances[cls] = super(Singleton, cls).__call__(*args, **kwargs) return cls._instances[cls] class Logger(object): __metaclass__ = Singleton"
},
{
"code": null,
"e": 8309,
"s": 7858,
"text": "One decorator that might come in handy quite often for scientific computing is the use_unit decorator. This decorator can be used to alter the output of returns to methods. This can be useful for those who donβt want to add units of measurement to their data, but still want people to know what those units are. This decorator is also not really available in any module, but is very commonly written and incredibly useful for scientific applications."
},
{
"code": null,
"e": 8781,
"s": 8309,
"text": "def use_unit(unit): \"\"\"Have a function return a Quantity with given unit\"\"\" use_unit.ureg = pint.UnitRegistry() def decorator_use_unit(func): @functools.wraps(func) def wrapper_use_unit(*args, **kwargs): value = func(*args, **kwargs) return value * use_unit.ureg(unit) return wrapper_use_unit return decorator_use_unit@use_unit(\"meters per second\")def average_speed(distance, duration): return distance / duration"
},
{
"code": null,
"e": 9170,
"s": 8781,
"text": "Function wrappers are a design pattern used when dealing with relatively complicated functions in Python. Wrapper functions are typically used to do what might be considered some more low-level, iterative tasks. The benefit of a wrapper function is that it can be used to dramatically improve performance. Like the lru_cache decorator, this decorator is provided by the FuncTools package."
},
{
"code": null,
"e": 9193,
"s": 9170,
"text": "import functools as ft"
},
{
"code": null,
"e": 9503,
"s": 9193,
"text": "The wraps decorator itself is simply a convenience decorator for updating the wrapper of a given function. When this decorator is called, the function will update its wrapper each time it is used. This can go a long way in terms of improving performance, as is the case with many tools available in FuncTools."
},
{
"code": null,
"e": 9660,
"s": 9503,
"text": "def my_decorator(f): @wraps(f) def wrapper(*args, **kwds): print('Calling decorated function') return f(*args, **kwds) return wrapper"
},
{
"code": null,
"e": 9880,
"s": 9660,
"text": "Wrappers themselves are typically decorators, and the wraps decorator call is typically used on a wrapper function within that decorator call. After writing that code, we can decorate our new function with that wrapper:"
},
{
"code": null,
"e": 9918,
"s": 9880,
"text": "@my_decoratordef func(x): print(x)"
},
{
"code": null,
"e": 10225,
"s": 9918,
"text": "In some cases, there might be circumstances where one might want to be able to access things that are defined privately as in a more global sense. Sometimes we have functions that are contained within classes that we want to have methodized, and this is exactly what the staticmethod decorator is used for."
},
{
"code": null,
"e": 10682,
"s": 10225,
"text": "Using this decorator, we can make C++ static methods for working with our classes. Normally, methods that are written in the scope of a class will be private to that class, and not accessible unless called as a child. There are circumstances, however, where you might want to take a more functional approach with the way your methods interact with data. Using this decorator, we can create both options without the need for creating more than one function."
},
{
"code": null,
"e": 10758,
"s": 10682,
"text": "class Example: @staticmethod def our_func(stuff): print(stuff)"
},
{
"code": null,
"e": 10880,
"s": 10758,
"text": "We also do not need to explicitly provide our class as an argument. The staticmethod decorator takes care of this for us."
},
{
"code": null,
"e": 11245,
"s": 10880,
"text": "FuncTools strikes again in this list with the wonderfully useful singledispatch decorator. Single dispatch is a programming technique that is quite commonplace in many programming languages because of just how great of a way it is to program. While I tend to prefer multiple dispatch, I think that single dispatch can be used to fill the same role in many aspects."
},
{
"code": null,
"e": 11578,
"s": 11245,
"text": "This decorator makes it far easier to work with types in Python. This is even more the case when we are working with multiple types that we want to pass through the same method. I wrote more about this in my FuncTools article, so if you are interested in using the single dispatch methodology, I do recommend it (the link is in #1.)"
},
{
"code": null,
"e": 11976,
"s": 11578,
"text": "@singledispatchdef fun(arg, verbose=False): if verbose: print(\"Let me just say,\", end=\" \") print(arg)@fun.registerdef _(arg: int, verbose=False): if verbose: print(\"Strength in numbers, eh?\", end=\" \") print(arg)@fun.registerdef _(arg: list, verbose=False): if verbose: print(\"Enumerate this:\") for i, elem in enumerate(arg): print(i, elem)"
},
{
"code": null,
"e": 12340,
"s": 11976,
"text": "The register function comes from the module atexit. Given that moduleβs name and M.O., you might be able to imagine that this decorator could have something to do with performing some action at termination. The register decorator names a function to be ran at termination. For example, this would work will with some software that needs to save whenever you exit."
},
{
"code": null,
"e": 12412,
"s": 12340,
"text": "from atexit import register@registerdef termin(): print(\" Goodbye!\")"
}
] |
How to use autocomplete attribute in HTML? | The autocomplete attribute is used with form element to set the autocomplete feature on or off. If the autocomplete feature is on, the browser will automatically show values, based on what users entered before in the field.
If the autocomplete feature is off, the browser wonβt automatically show values, based on what users entered before in the field.
The following are the attribute values β
You can try to run the following code to learn how to use autocomplete attribute in HTML. To check running the below code, enter some values in the input type text and click Submit. After that fill the field again and run the code again, so that on typing a value in the field, you can see the autocomplete values. This is for autocomplete on value.
For autocomplete off value, web browser wonβt complete values based on what users entered before.
<!DOCTYPE html>
<html>
<head>
<title> HTML autocomplete attribute</title>
</head>
<body>
<form action = "" method = "get" autocomplete="on">
Details:<br><br>
Student Name<br><input type = "name" name = "sname"><br>
Training week<br><input type = "week" name = "week"><br>
<input type = "submit" value = "Submit">
</form>
</body>
</html> | [
{
"code": null,
"e": 1286,
"s": 1062,
"text": "The autocomplete attribute is used with form element to set the autocomplete feature on or off. If the autocomplete feature is on, the browser will automatically show values, based on what users entered before in the field."
},
{
"code": null,
"e": 1416,
"s": 1286,
"text": "If the autocomplete feature is off, the browser wonβt automatically show values, based on what users entered before in the field."
},
{
"code": null,
"e": 1457,
"s": 1416,
"text": "The following are the attribute values β"
},
{
"code": null,
"e": 1807,
"s": 1457,
"text": "You can try to run the following code to learn how to use autocomplete attribute in HTML. To check running the below code, enter some values in the input type text and click Submit. After that fill the field again and run the code again, so that on typing a value in the field, you can see the autocomplete values. This is for autocomplete on value."
},
{
"code": null,
"e": 1905,
"s": 1807,
"text": "For autocomplete off value, web browser wonβt complete values based on what users entered before."
},
{
"code": null,
"e": 2308,
"s": 1905,
"text": "<!DOCTYPE html>\n<html>\n <head>\n <title> HTML autocomplete attribute</title>\n </head>\n <body>\n <form action = \"\" method = \"get\" autocomplete=\"on\">\n Details:<br><br>\n Student Name<br><input type = \"name\" name = \"sname\"><br>\n Training week<br><input type = \"week\" name = \"week\"><br>\n <input type = \"submit\" value = \"Submit\">\n </form>\n </body>\n</html>"
}
] |
How to plot a gradient color line in matplotlib? | To plot a gradient color line in matplotlib, we can take the following steps β
Create x, y and c data points, using numpy.
Create x, y and c data points, using numpy.
Create scatter points over the axes (closely so as to get a line), using the scatter() method with c and marker='_'.
Create scatter points over the axes (closely so as to get a line), using the scatter() method with c and marker='_'.
To display the figure, use the show() method.
To display the figure, use the show() method.
import numpy as np
from matplotlib import pyplot as plt
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True
x = np.linspace(-1, 1, 1000)
y = np.exp(x)
c = np.tan(x)
plt.scatter(x, y, c=c, marker='_')
plt.show() | [
{
"code": null,
"e": 1141,
"s": 1062,
"text": "To plot a gradient color line in matplotlib, we can take the following steps β"
},
{
"code": null,
"e": 1185,
"s": 1141,
"text": "Create x, y and c data points, using numpy."
},
{
"code": null,
"e": 1229,
"s": 1185,
"text": "Create x, y and c data points, using numpy."
},
{
"code": null,
"e": 1346,
"s": 1229,
"text": "Create scatter points over the axes (closely so as to get a line), using the scatter() method with c and marker='_'."
},
{
"code": null,
"e": 1463,
"s": 1346,
"text": "Create scatter points over the axes (closely so as to get a line), using the scatter() method with c and marker='_'."
},
{
"code": null,
"e": 1509,
"s": 1463,
"text": "To display the figure, use the show() method."
},
{
"code": null,
"e": 1555,
"s": 1509,
"text": "To display the figure, use the show() method."
},
{
"code": null,
"e": 1801,
"s": 1555,
"text": "import numpy as np\nfrom matplotlib import pyplot as plt\nplt.rcParams[\"figure.figsize\"] = [7.50, 3.50]\nplt.rcParams[\"figure.autolayout\"] = True\nx = np.linspace(-1, 1, 1000)\ny = np.exp(x)\nc = np.tan(x)\nplt.scatter(x, y, c=c, marker='_')\nplt.show()"
}
] |
C++ Program to Demonstrate the Implementation of 4-Color Problem | This is a C++ Program to Demonstrate the Implementation of 4-Color Problem.
Begin
Develop function issafe() to check if the current color assignment
is safe for vertex v i.e. checks whether the edge exists or not.
If it exists,
then next check whether the color to be filled in the new vertex is already used by its adjacent vertices.
End
Begin
Function graphColoringtil(bool graph[V][V], int m, int col[], int v)
solve 4 coloring problem:
Here,
g[V][V] = It is a 2D array where V is the number of vertices in graph
m = maximum number of colors that can be used.
col[] = an color array that should have numbers from 1 to m.
if v == V
return true
For c = 1 to m
if (isSafe(v, g, col, c))
col[v] = c
if (graphColoringtil (g, k, col, v+1) == true)
return true
col[v] = 0
return false
End
Begin
function graphColor():
It mainly uses graphColoringUtil() to solve the problem.
It returns false if the m colors cannot be assigned,
otherwise return true.
End
#include <iostream>
#include <cstdio>
#define V 5
using namespace std;
bool isSafe (int v, bool graph[V][V], int col[], int C) {
for (int i = 0; i < V; i++)
if (graph[v][i] && C == col[i])
return false;
return true;
}
bool graphColoringtil(bool g[V][V], int k, int col[], int v) {
if (v == V) //If all vertices are assigned a color then
return true;
for (int c = 1; c <= k; c++) { //Consider this vertex v and try different colors
if (isSafe(v, g, col, c)) { //Check if assignment of color c to v is fine
col[v] = c;
if (graphColoringtil (g, k, col, v+1) == true) //recur to assign colors to rest of the vertices
return true;
col[v] = 0; //If assigning color c doesn't lead to a solution then remove it
}
}
return false;
}
void solution(int color[]) {
cout<<"The assigned colors are: \n";
for (int i = 0; i < V; i++)
cout<<color[i];
cout<<"\n";
}
bool graphColor(bool graph[V][V], int k) {
int *color = new int[V];
//initialize all colors value as 0
for (int i = 0; i < V; i++)
color[i] = 0;
if (graphColoringtil(graph, k, color, 0) == false) {
cout<<"Solution does not exist";
return false;
}
solution(color);
return true;
}
int main() {
bool g[V][V] = {
{0, 0, 1, 0,1},
{1, 1, 1, 0,0},
{1, 1, 0, 0,1},
{0, 1, 1, 0,0}
};
int k= 4;
graphColor(g, k);
return 0;
}
The assigned colors are:
1 2 3 1 1 | [
{
"code": null,
"e": 1138,
"s": 1062,
"text": "This is a C++ Program to Demonstrate the Implementation of 4-Color Problem."
},
{
"code": null,
"e": 2137,
"s": 1138,
"text": "Begin\n Develop function issafe() to check if the current color assignment\n is safe for vertex v i.e. checks whether the edge exists or not.\n If it exists,\n then next check whether the color to be filled in the new vertex is already used by its adjacent vertices.\nEnd\nBegin\n Function graphColoringtil(bool graph[V][V], int m, int col[], int v)\n solve 4 coloring problem:\n Here,\n g[V][V] = It is a 2D array where V is the number of vertices in graph\n m = maximum number of colors that can be used.\n col[] = an color array that should have numbers from 1 to m.\n if v == V\n return true\n For c = 1 to m\n if (isSafe(v, g, col, c))\n col[v] = c\n if (graphColoringtil (g, k, col, v+1) == true)\n return true\n col[v] = 0\n return false\nEnd\n\nBegin\n function graphColor():\n It mainly uses graphColoringUtil() to solve the problem.\n It returns false if the m colors cannot be assigned,\n otherwise return true.\nEnd"
},
{
"code": null,
"e": 3567,
"s": 2137,
"text": "#include <iostream>\n#include <cstdio>\n#define V 5\nusing namespace std;\nbool isSafe (int v, bool graph[V][V], int col[], int C) {\n for (int i = 0; i < V; i++)\n if (graph[v][i] && C == col[i])\n return false;\n return true;\n}\nbool graphColoringtil(bool g[V][V], int k, int col[], int v) {\n if (v == V) //If all vertices are assigned a color then\n return true;\n for (int c = 1; c <= k; c++) { //Consider this vertex v and try different colors\n if (isSafe(v, g, col, c)) { //Check if assignment of color c to v is fine\n col[v] = c;\n if (graphColoringtil (g, k, col, v+1) == true) //recur to assign colors to rest of the vertices\n return true;\n col[v] = 0; //If assigning color c doesn't lead to a solution then remove it\n }\n }\n return false;\n}\nvoid solution(int color[]) {\n cout<<\"The assigned colors are: \\n\";\n for (int i = 0; i < V; i++)\n cout<<color[i];\n cout<<\"\\n\";\n}\nbool graphColor(bool graph[V][V], int k) {\n int *color = new int[V];\n //initialize all colors value as 0\n for (int i = 0; i < V; i++)\n color[i] = 0;\n if (graphColoringtil(graph, k, color, 0) == false) {\n cout<<\"Solution does not exist\";\n return false;\n }\n solution(color);\n return true;\n}\nint main() {\n bool g[V][V] = {\n {0, 0, 1, 0,1},\n {1, 1, 1, 0,0},\n {1, 1, 0, 0,1},\n {0, 1, 1, 0,0}\n };\n int k= 4;\n graphColor(g, k);\n return 0;\n}"
},
{
"code": null,
"e": 3602,
"s": 3567,
"text": "The assigned colors are:\n1 2 3 1 1"
}
] |
jQuery - CSS Selectors Methods | The jQuery library supports nearly all of the selectors included in Cascading Style Sheet (CSS) specifications 1 through 3, as outlined on the World Wide Web Consortium's site.
Using JQuery library developers can enhance their websites without worrying about browsers and their versions as long as the browsers have JavaScript enabled.
Most of the JQuery CSS Methods do not modify the content of the jQuery object and they are used to apply CSS properties on DOM elements.
This is very simple to apply any CSS property using JQuery method css( PropertyName, PropertyValue ).
Here is the syntax for the method β
selector.css( PropertyName, PropertyValue );
Here you can pass PropertyName as a javascript string and based on its value, PropertyValue could be string or integer.
Following is an example which adds font color to the second list item.
<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() {
$("li").eq(2).css("color", "red");
});
</script>
</head>
<body>
<div>
<ul>
<li>list item 1</li>
<li>list item 2</li>
<li>list item 3</li>
<li>list item 4</li>
<li>list item 5</li>
<li>list item 6</li>
</ul>
</div>
</body>
</html>
This will produce following result β
list item 1
list item 2
list item 3
list item 4
list item 5
list item 6
You can apply multiple CSS properties using a single JQuery method CSS( {key1:val1, key2:val2....). You can apply as many properties as you like in a single call.
Here is the syntax for the method β
selector.css( {key1:val1, key2:val2....keyN:valN})
Here you can pass key as property and val as its value as described above.
Following is an example which adds font color as well as background color to the second list item.
<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() {
$("li").eq(2).css({"color":"red", "background-color":"green"});
});
</script>
</head>
<body>
<div>
<ul>
<li>list item 1</li>
<li>list item 2</li>
<li>list item 3</li>
<li>list item 4</li>
<li>list item 5</li>
<li>list item 6</li>
</ul>
</div>
</body>
</html>
This will produce following result β
list item 1
list item 2
list item 3
list item 4
list item 5
list item 6
The width( val ) and height( val ) method can be used to set the width and height respectively of any element.
Following is a simple example which sets the width of first division element where as rest of the elements have width set by style sheet
<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() {
$("div:first").width(100);
$("div:first").css("background-color", "blue");
});
</script>
<style>
div {
width:70px; height:50px; float:left;
margin:5px; background:red; cursor:pointer;
}
</style>
</head>
<body>
<div></div>
<div>d</div>
<div>d</div>
<div>d</div>
<div>d</div>
</body>
</html>
This will produce following result β
Following table lists down all the methods which you can use to play with CSS properties β
Return a style property on the first matched element.
Set a single style property to a value on all matched elements.
Set a key/value object as style properties to all matched elements.
Set the CSS height of every matched element.
Get the current computed, pixel, height of the first matched element.
Gets the inner height (excludes the border and includes the padding) for the first matched element.
Gets the inner width (excludes the border and includes the padding) for the first matched element.
Get the current offset of the first matched element, in pixels, relative to the document.
Returns a jQuery collection with the positioned parent of the first matched element.
Gets the outer height (includes the border and padding by default) for the first matched element.
Get the outer width (includes the border and padding by default) for the first matched element.
Gets the top and left position of an element relative to its offset parent.
When a value is passed in, the scroll left offset is set to that value on all matched elements.
Gets the scroll left offset of the first matched element.
When a value is passed in, the scroll top offset is set to that value on all matched elements.
Gets the scroll top offset of the first matched element.
Set the CSS width of every matched element.
Get the current computed, pixel, width of the first matched element.
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": 2499,
"s": 2322,
"text": "The jQuery library supports nearly all of the selectors included in Cascading Style Sheet (CSS) specifications 1 through 3, as outlined on the World Wide Web Consortium's site."
},
{
"code": null,
"e": 2658,
"s": 2499,
"text": "Using JQuery library developers can enhance their websites without worrying about browsers and their versions as long as the browsers have JavaScript enabled."
},
{
"code": null,
"e": 2795,
"s": 2658,
"text": "Most of the JQuery CSS Methods do not modify the content of the jQuery object and they are used to apply CSS properties on DOM elements."
},
{
"code": null,
"e": 2897,
"s": 2795,
"text": "This is very simple to apply any CSS property using JQuery method css( PropertyName, PropertyValue )."
},
{
"code": null,
"e": 2933,
"s": 2897,
"text": "Here is the syntax for the method β"
},
{
"code": null,
"e": 2979,
"s": 2933,
"text": "selector.css( PropertyName, PropertyValue );\n"
},
{
"code": null,
"e": 3099,
"s": 2979,
"text": "Here you can pass PropertyName as a javascript string and based on its value, PropertyValue could be string or integer."
},
{
"code": null,
"e": 3170,
"s": 3099,
"text": "Following is an example which adds font color to the second list item."
},
{
"code": null,
"e": 3843,
"s": 3170,
"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 $(\"li\").eq(2).css(\"color\", \"red\");\n });\n </script>\n </head>\n\t\n <body>\n <div>\n <ul>\n <li>list item 1</li>\n <li>list item 2</li>\n <li>list item 3</li>\n <li>list item 4</li>\n <li>list item 5</li>\n <li>list item 6</li>\n </ul>\n </div>\n </body>\n</html>"
},
{
"code": null,
"e": 3880,
"s": 3843,
"text": "This will produce following result β"
},
{
"code": null,
"e": 3892,
"s": 3880,
"text": "list item 1"
},
{
"code": null,
"e": 3904,
"s": 3892,
"text": "list item 2"
},
{
"code": null,
"e": 3916,
"s": 3904,
"text": "list item 3"
},
{
"code": null,
"e": 3928,
"s": 3916,
"text": "list item 4"
},
{
"code": null,
"e": 3940,
"s": 3928,
"text": "list item 5"
},
{
"code": null,
"e": 3952,
"s": 3940,
"text": "list item 6"
},
{
"code": null,
"e": 4116,
"s": 3952,
"text": "You can apply multiple CSS properties using a single JQuery method CSS( {key1:val1, key2:val2....). You can apply as many properties as you like in a single call."
},
{
"code": null,
"e": 4152,
"s": 4116,
"text": "Here is the syntax for the method β"
},
{
"code": null,
"e": 4204,
"s": 4152,
"text": "selector.css( {key1:val1, key2:val2....keyN:valN})\n"
},
{
"code": null,
"e": 4279,
"s": 4204,
"text": "Here you can pass key as property and val as its value as described above."
},
{
"code": null,
"e": 4378,
"s": 4279,
"text": "Following is an example which adds font color as well as background color to the second list item."
},
{
"code": null,
"e": 5080,
"s": 4378,
"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 $(\"li\").eq(2).css({\"color\":\"red\", \"background-color\":\"green\"});\n });\n </script>\n </head>\n\t\n <body>\n <div>\n <ul>\n <li>list item 1</li>\n <li>list item 2</li>\n <li>list item 3</li>\n <li>list item 4</li>\n <li>list item 5</li>\n <li>list item 6</li>\n </ul>\n </div>\n </body>\n</html>"
},
{
"code": null,
"e": 5117,
"s": 5080,
"text": "This will produce following result β"
},
{
"code": null,
"e": 5129,
"s": 5117,
"text": "list item 1"
},
{
"code": null,
"e": 5141,
"s": 5129,
"text": "list item 2"
},
{
"code": null,
"e": 5153,
"s": 5141,
"text": "list item 3"
},
{
"code": null,
"e": 5165,
"s": 5153,
"text": "list item 4"
},
{
"code": null,
"e": 5177,
"s": 5165,
"text": "list item 5"
},
{
"code": null,
"e": 5189,
"s": 5177,
"text": "list item 6"
},
{
"code": null,
"e": 5300,
"s": 5189,
"text": "The width( val ) and height( val ) method can be used to set the width and height respectively of any element."
},
{
"code": null,
"e": 5438,
"s": 5300,
"text": "Following is a simple example which sets the width of first division element where as rest of the elements have width set by style sheet"
},
{
"code": null,
"e": 6171,
"s": 5438,
"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 $(\"div:first\").width(100);\n $(\"div:first\").css(\"background-color\", \"blue\");\n });\n </script>\n\t\t\n <style>\n div { \n width:70px; height:50px; float:left; \n margin:5px; background:red; cursor:pointer; \n }\n </style>\n </head>\n\t\n <body>\n <div></div>\n <div>d</div>\n <div>d</div>\n <div>d</div>\n <div>d</div>\n </body>\n</html>"
},
{
"code": null,
"e": 6208,
"s": 6171,
"text": "This will produce following result β"
},
{
"code": null,
"e": 6299,
"s": 6208,
"text": "Following table lists down all the methods which you can use to play with CSS properties β"
},
{
"code": null,
"e": 6353,
"s": 6299,
"text": "Return a style property on the first matched element."
},
{
"code": null,
"e": 6417,
"s": 6353,
"text": "Set a single style property to a value on all matched elements."
},
{
"code": null,
"e": 6485,
"s": 6417,
"text": "Set a key/value object as style properties to all matched elements."
},
{
"code": null,
"e": 6530,
"s": 6485,
"text": "Set the CSS height of every matched element."
},
{
"code": null,
"e": 6600,
"s": 6530,
"text": "Get the current computed, pixel, height of the first matched element."
},
{
"code": null,
"e": 6700,
"s": 6600,
"text": "Gets the inner height (excludes the border and includes the padding) for the first matched element."
},
{
"code": null,
"e": 6799,
"s": 6700,
"text": "Gets the inner width (excludes the border and includes the padding) for the first matched element."
},
{
"code": null,
"e": 6889,
"s": 6799,
"text": "Get the current offset of the first matched element, in pixels, relative to the document."
},
{
"code": null,
"e": 6974,
"s": 6889,
"text": "Returns a jQuery collection with the positioned parent of the first matched element."
},
{
"code": null,
"e": 7072,
"s": 6974,
"text": "Gets the outer height (includes the border and padding by default) for the first matched element."
},
{
"code": null,
"e": 7168,
"s": 7072,
"text": "Get the outer width (includes the border and padding by default) for the first matched element."
},
{
"code": null,
"e": 7244,
"s": 7168,
"text": "Gets the top and left position of an element relative to its offset parent."
},
{
"code": null,
"e": 7340,
"s": 7244,
"text": "When a value is passed in, the scroll left offset is set to that value on all matched elements."
},
{
"code": null,
"e": 7398,
"s": 7340,
"text": "Gets the scroll left offset of the first matched element."
},
{
"code": null,
"e": 7493,
"s": 7398,
"text": "When a value is passed in, the scroll top offset is set to that value on all matched elements."
},
{
"code": null,
"e": 7550,
"s": 7493,
"text": "Gets the scroll top offset of the first matched element."
},
{
"code": null,
"e": 7594,
"s": 7550,
"text": "Set the CSS width of every matched element."
},
{
"code": null,
"e": 7663,
"s": 7594,
"text": "Get the current computed, pixel, width of the first matched element."
},
{
"code": null,
"e": 7696,
"s": 7663,
"text": "\n 27 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 7710,
"s": 7696,
"text": " Mahesh Kumar"
},
{
"code": null,
"e": 7745,
"s": 7710,
"text": "\n 27 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 7759,
"s": 7745,
"text": " Pratik Singh"
},
{
"code": null,
"e": 7794,
"s": 7759,
"text": "\n 72 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 7811,
"s": 7794,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 7844,
"s": 7811,
"text": "\n 60 Lectures \n 9 hours \n"
},
{
"code": null,
"e": 7872,
"s": 7844,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 7905,
"s": 7872,
"text": "\n 17 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 7926,
"s": 7905,
"text": " Sandip Bhattacharya"
},
{
"code": null,
"e": 7958,
"s": 7926,
"text": "\n 12 Lectures \n 53 mins\n"
},
{
"code": null,
"e": 7975,
"s": 7958,
"text": " Laurence Svekis"
},
{
"code": null,
"e": 7982,
"s": 7975,
"text": " Print"
},
{
"code": null,
"e": 7993,
"s": 7982,
"text": " Add Notes"
}
] |
Deep Reinforcement Learning and Hyperparameter Tuning | by Christian Hubbs | Towards Data Science | One of the most difficult and time consuming parts of deep reinforcement learning is the optimization of hyperparameters. These values β such as the discount factor [latex]\gamma[/latex], or the learning rate β can make all the difference in the performance of your agent.
Agents need to be trained to see how the hyperparameters affect performance β thereβs no a priori way to know whether a higher or lower value for a given parameter will improve total rewards. This translates into multiple, costly training runs to get a good agent in addition to tracking the experiments, data, and everything associated with training the models.
Ray provides a way to deal with all of this with the Tune library, which automatically handles your various models, saves the data, adjusts your hyperparameters, and summarizes the results for quick and easy reference.
We walk through a brief example of using Tuneβs grid search features to optimize our hyperparameters.
Tune is a part of the Ray project but requires a separate install, so if you havenβt installed it yet, youβll need to run the following to get Tune to work.
pip install ray[tune]
From here, we can import our packages to train our model.
import rayfrom ray import tune
Starting with the basics, letβs use Tune to train an agent to solve CartPole-v0. Tune takes a few dictionaries with various settings and criteria to train. The two that it must have are config and stop arguments.
The config dictionary will provide the Tune with the environment it needs to run as well as any environment specific configurations that you may want to specify. This is also where most of your hyperparameters are going to reside, but we'll get to that in a moment.
The stop dictionary tells Tune when to finish a training run or when to stop training altogether. It can be customized based on reward criteria, elapsed time, number of steps taken, and so forth. When I first started with Tune, I overlooked setting any stopping criteria and wound up letting an algorithm train for hours before realizing it. So, you can run it without this, but you may rack up a decent AWS bill if you're not careful!
Try the code below to run the PPO algorithm on CartPole-v0 for 10,000 time steps.
ray.init(ignore_reinit_error=True)config = { 'env': 'CartPole-v0'}stop = { 'timesteps_total': 10000}results = tune.run( 'PPO', # Specify the algorithm to train config=config, stop=stop)
With these settings, you should see a print-out of the status of your workers, memory, as well as the logdir where all of the data is stored for analysis later.
The console will print these values with each iteration unless the verbose argument in tune.run() is set to 0 (silent).
When training is complete, youβll get an output saying the status has been terminated, the elapsed time, and mean reward for the past 100 episodes among other data.
The power of Tune really comes in when we leverage it to adjust our hyperparameters. For this, weβll turn to the grid_search function which allows the user to specify a set of hyperparameters for the model to test.
To do this, we just need to wrap a list of values in the tune.grid_search() function and place that in our configuration dictionary. Let's go back to our CartPole example above. We might want to see if the learning rate makes any difference and if a two-headed network provides any benefit. We can use grid_search() to implement the different combinations of these as shown below:
config = { "env": 'CartPole-v0', "num_workers": 2, "vf_share_layers": tune.grid_search([True, False]), "lr": tune.grid_search([1e-4, 1e-5, 1e-6]), }results = tune.run( 'PPO', stop={ 'timesteps_total': 100000 }, config=config)
Now we see an expanded status printout which contains the various trials we want to run:
As Ray kicks off each one of these, it will show the combination of hyperparameters we want to explore as well as the rewards, iterations, and elapsed time for each. When it completes, we should see TERMINATED as the status for each to show that it worked properly (otherwise it would read ERROR).
The output of our tune.run() function is an analysis object that we've labeled results. We can use this to access further details about our experiments. The relevant data can be accessed via results.dataframe(), which will return a Pandas data frame containing average rewards, iterations, KL divergence, configuration settings, and on and on. The data frame also contains the specific directory your experiments were saved in (logdir) so you can get into the details of your particular run.
If you look into the logdir directory, you'll find a number of files that contain the saved data from your training runs. The primary file for our purposes will be progress.csv - this contains the training data from each of the iterations, allowing you to dive into the details.
For example, if we want to view the training and loss curves for our different settings, we can loop over the logdir column in our data frame, load each of the progress.csv files and plot the results.
# Plot training resultsimport matplotlib.pyplot as pltimport pandas as pdcolors = plt.rcParams['axes.prop_cycle'].by_key()['color']df = results.dataframe()# Get column for total loss, policy loss, and value losstl_col = [i for i, j in enumerate(df.columns) if 'total_loss' in j][0]pl_col = [i for i, j in enumerate(df.columns) if 'policy_loss' in j][0]vl_col = [i for i, j in enumerate(df.columns) if 'vf_loss' in j][0]labels = []fig, ax = plt.subplots(2, 2, figsize=(15, 15), sharex=True)for i, path in df['logdir'].iteritems(): data = pd.read_csv(path + '/progress.csv') # Get labels for legend lr = data['experiment_tag'][0].split('=')[1].split(',')[0] layers = data['experiment_tag'][0].split('=')[-1] labels.append('LR={}; Shared Layers={}'.format(lr, layers)) ax[0, 0].plot(data['timesteps_total'], data['episode_reward_mean'], c=colors[i], label=labels[-1]) ax[0, 1].plot(data['timesteps_total'], data.iloc[:, tl_col], c=colors[i], label=labels[-1]) ax[1, 0].plot(data['timesteps_total'], data.iloc[:, pl_col], c=colors[i], label=labels[-1]) ax[1, 1].plot(data['timesteps_total'], data.iloc[:, vl_col], c=colors[i], label=labels[-1])ax[0, 0].set_ylabel('Mean Rewards')ax[0, 0].set_title('Training Rewards by Time Step')ax[0, 0].legend(labels=labels, loc='upper center', ncol=3, bbox_to_anchor=[0.75, 1.2])ax[0, 1].set_title('Total Loss by Time Step')ax[0, 1].set_ylabel('Total Loss')ax[0, 1].set_xlabel('Training Episodes')ax[1, 0].set_title('Policy Loss by Time Step')ax[1, 0].set_ylabel('Policy Loss')ax[1, 0].set_xlabel('Time Step')ax[1, 1].set_title('Value Loss by Time Step')ax[1, 1].set_ylabel('Value Loss')ax[1, 1].set_xlabel('Time Step')plt.show()
There are far more tuning options available in Tune. If you want to see what you can tweak, take a look at the documentation for your particular algorithm. Moreover, Tune enables different approaches to hyperparameter optimization. Grid search can be slow, so just by changing a few options, you can use Bayesian optimization, HyperOpt and others. Finally, Tune makes population based training (PBT) easy allowing multiple agents to scale across various machines. All of this will be covered in future posts! | [
{
"code": null,
"e": 445,
"s": 172,
"text": "One of the most difficult and time consuming parts of deep reinforcement learning is the optimization of hyperparameters. These values β such as the discount factor [latex]\\gamma[/latex], or the learning rate β can make all the difference in the performance of your agent."
},
{
"code": null,
"e": 808,
"s": 445,
"text": "Agents need to be trained to see how the hyperparameters affect performance β thereβs no a priori way to know whether a higher or lower value for a given parameter will improve total rewards. This translates into multiple, costly training runs to get a good agent in addition to tracking the experiments, data, and everything associated with training the models."
},
{
"code": null,
"e": 1027,
"s": 808,
"text": "Ray provides a way to deal with all of this with the Tune library, which automatically handles your various models, saves the data, adjusts your hyperparameters, and summarizes the results for quick and easy reference."
},
{
"code": null,
"e": 1129,
"s": 1027,
"text": "We walk through a brief example of using Tuneβs grid search features to optimize our hyperparameters."
},
{
"code": null,
"e": 1286,
"s": 1129,
"text": "Tune is a part of the Ray project but requires a separate install, so if you havenβt installed it yet, youβll need to run the following to get Tune to work."
},
{
"code": null,
"e": 1308,
"s": 1286,
"text": "pip install ray[tune]"
},
{
"code": null,
"e": 1366,
"s": 1308,
"text": "From here, we can import our packages to train our model."
},
{
"code": null,
"e": 1397,
"s": 1366,
"text": "import rayfrom ray import tune"
},
{
"code": null,
"e": 1610,
"s": 1397,
"text": "Starting with the basics, letβs use Tune to train an agent to solve CartPole-v0. Tune takes a few dictionaries with various settings and criteria to train. The two that it must have are config and stop arguments."
},
{
"code": null,
"e": 1876,
"s": 1610,
"text": "The config dictionary will provide the Tune with the environment it needs to run as well as any environment specific configurations that you may want to specify. This is also where most of your hyperparameters are going to reside, but we'll get to that in a moment."
},
{
"code": null,
"e": 2312,
"s": 1876,
"text": "The stop dictionary tells Tune when to finish a training run or when to stop training altogether. It can be customized based on reward criteria, elapsed time, number of steps taken, and so forth. When I first started with Tune, I overlooked setting any stopping criteria and wound up letting an algorithm train for hours before realizing it. So, you can run it without this, but you may rack up a decent AWS bill if you're not careful!"
},
{
"code": null,
"e": 2394,
"s": 2312,
"text": "Try the code below to run the PPO algorithm on CartPole-v0 for 10,000 time steps."
},
{
"code": null,
"e": 2595,
"s": 2394,
"text": "ray.init(ignore_reinit_error=True)config = { 'env': 'CartPole-v0'}stop = { 'timesteps_total': 10000}results = tune.run( 'PPO', # Specify the algorithm to train config=config, stop=stop)"
},
{
"code": null,
"e": 2756,
"s": 2595,
"text": "With these settings, you should see a print-out of the status of your workers, memory, as well as the logdir where all of the data is stored for analysis later."
},
{
"code": null,
"e": 2876,
"s": 2756,
"text": "The console will print these values with each iteration unless the verbose argument in tune.run() is set to 0 (silent)."
},
{
"code": null,
"e": 3041,
"s": 2876,
"text": "When training is complete, youβll get an output saying the status has been terminated, the elapsed time, and mean reward for the past 100 episodes among other data."
},
{
"code": null,
"e": 3256,
"s": 3041,
"text": "The power of Tune really comes in when we leverage it to adjust our hyperparameters. For this, weβll turn to the grid_search function which allows the user to specify a set of hyperparameters for the model to test."
},
{
"code": null,
"e": 3637,
"s": 3256,
"text": "To do this, we just need to wrap a list of values in the tune.grid_search() function and place that in our configuration dictionary. Let's go back to our CartPole example above. We might want to see if the learning rate makes any difference and if a two-headed network provides any benefit. We can use grid_search() to implement the different combinations of these as shown below:"
},
{
"code": null,
"e": 3898,
"s": 3637,
"text": "config = { \"env\": 'CartPole-v0', \"num_workers\": 2, \"vf_share_layers\": tune.grid_search([True, False]), \"lr\": tune.grid_search([1e-4, 1e-5, 1e-6]), }results = tune.run( 'PPO', stop={ 'timesteps_total': 100000 }, config=config)"
},
{
"code": null,
"e": 3987,
"s": 3898,
"text": "Now we see an expanded status printout which contains the various trials we want to run:"
},
{
"code": null,
"e": 4285,
"s": 3987,
"text": "As Ray kicks off each one of these, it will show the combination of hyperparameters we want to explore as well as the rewards, iterations, and elapsed time for each. When it completes, we should see TERMINATED as the status for each to show that it worked properly (otherwise it would read ERROR)."
},
{
"code": null,
"e": 4777,
"s": 4285,
"text": "The output of our tune.run() function is an analysis object that we've labeled results. We can use this to access further details about our experiments. The relevant data can be accessed via results.dataframe(), which will return a Pandas data frame containing average rewards, iterations, KL divergence, configuration settings, and on and on. The data frame also contains the specific directory your experiments were saved in (logdir) so you can get into the details of your particular run."
},
{
"code": null,
"e": 5056,
"s": 4777,
"text": "If you look into the logdir directory, you'll find a number of files that contain the saved data from your training runs. The primary file for our purposes will be progress.csv - this contains the training data from each of the iterations, allowing you to dive into the details."
},
{
"code": null,
"e": 5257,
"s": 5056,
"text": "For example, if we want to view the training and loss curves for our different settings, we can loop over the logdir column in our data frame, load each of the progress.csv files and plot the results."
},
{
"code": null,
"e": 7103,
"s": 5257,
"text": "# Plot training resultsimport matplotlib.pyplot as pltimport pandas as pdcolors = plt.rcParams['axes.prop_cycle'].by_key()['color']df = results.dataframe()# Get column for total loss, policy loss, and value losstl_col = [i for i, j in enumerate(df.columns) if 'total_loss' in j][0]pl_col = [i for i, j in enumerate(df.columns) if 'policy_loss' in j][0]vl_col = [i for i, j in enumerate(df.columns) if 'vf_loss' in j][0]labels = []fig, ax = plt.subplots(2, 2, figsize=(15, 15), sharex=True)for i, path in df['logdir'].iteritems(): data = pd.read_csv(path + '/progress.csv') # Get labels for legend lr = data['experiment_tag'][0].split('=')[1].split(',')[0] layers = data['experiment_tag'][0].split('=')[-1] labels.append('LR={}; Shared Layers={}'.format(lr, layers)) ax[0, 0].plot(data['timesteps_total'], data['episode_reward_mean'], c=colors[i], label=labels[-1]) ax[0, 1].plot(data['timesteps_total'], data.iloc[:, tl_col], c=colors[i], label=labels[-1]) ax[1, 0].plot(data['timesteps_total'], data.iloc[:, pl_col], c=colors[i], label=labels[-1]) ax[1, 1].plot(data['timesteps_total'], data.iloc[:, vl_col], c=colors[i], label=labels[-1])ax[0, 0].set_ylabel('Mean Rewards')ax[0, 0].set_title('Training Rewards by Time Step')ax[0, 0].legend(labels=labels, loc='upper center', ncol=3, bbox_to_anchor=[0.75, 1.2])ax[0, 1].set_title('Total Loss by Time Step')ax[0, 1].set_ylabel('Total Loss')ax[0, 1].set_xlabel('Training Episodes')ax[1, 0].set_title('Policy Loss by Time Step')ax[1, 0].set_ylabel('Policy Loss')ax[1, 0].set_xlabel('Time Step')ax[1, 1].set_title('Value Loss by Time Step')ax[1, 1].set_ylabel('Value Loss')ax[1, 1].set_xlabel('Time Step')plt.show()"
}
] |
Angular 2 - Lifecycle Hooks | Angular 2 application goes through an entire set of processes or has a lifecycle right from its initiation to the end of the application.
The following diagram shows the entire processes in the lifecycle of the Angular 2 application.
Following is a description of each lifecycle hook.
ngOnChanges β When the value of a data bound property changes, then this method is called.
ngOnChanges β When the value of a data bound property changes, then this method is called.
ngOnInit β This is called whenever the initialization of the directive/component after Angular first displays the data-bound properties happens.
ngOnInit β This is called whenever the initialization of the directive/component after Angular first displays the data-bound properties happens.
ngDoCheck β This is for the detection and to act on changes that Angular can't or won't detect on its own.
ngDoCheck β This is for the detection and to act on changes that Angular can't or won't detect on its own.
ngAfterContentInit β This is called in response after Angular projects external content into the component's view.
ngAfterContentInit β This is called in response after Angular projects external content into the component's view.
ngAfterContentChecked β This is called in response after Angular checks the content projected into the component.
ngAfterContentChecked β This is called in response after Angular checks the content projected into the component.
ngAfterViewInit β This is called in response after Angular initializes the component's views and child views.
ngAfterViewInit β This is called in response after Angular initializes the component's views and child views.
ngAfterViewChecked β This is called in response after Angular checks the component's views and child views.
ngAfterViewChecked β This is called in response after Angular checks the component's views and child views.
ngOnDestroy β This is the cleanup phase just before Angular destroys the directive/component.
ngOnDestroy β This is the cleanup phase just before Angular destroys the directive/component.
Following is an example of implementing one lifecycle hook. In the app.component.ts file, place the following code.
import {
Component
} from '@angular/core';
@Component ({
selector: 'my-app',
template: '<div> {{values}} </div> '
})
export class AppComponent {
values = '';
ngOnInit() {
this.values = "Hello";
}
}
In the above program, we are calling the ngOnInit lifecycle hook to specifically mention that the value of the this.values parameter should be set to βHelloβ.
Once you save all the code changes and refresh the browser, you will get the following output.
16 Lectures
1.5 hours
Anadi Sharma
28 Lectures
2.5 hours
Anadi Sharma
11 Lectures
7.5 hours
SHIVPRASAD KOIRALA
16 Lectures
2.5 hours
Frahaan Hussain
69 Lectures
5 hours
Senol Atac
53 Lectures
3.5 hours
Senol Atac
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2435,
"s": 2297,
"text": "Angular 2 application goes through an entire set of processes or has a lifecycle right from its initiation to the end of the application."
},
{
"code": null,
"e": 2531,
"s": 2435,
"text": "The following diagram shows the entire processes in the lifecycle of the Angular 2 application."
},
{
"code": null,
"e": 2582,
"s": 2531,
"text": "Following is a description of each lifecycle hook."
},
{
"code": null,
"e": 2673,
"s": 2582,
"text": "ngOnChanges β When the value of a data bound property changes, then this method is called."
},
{
"code": null,
"e": 2764,
"s": 2673,
"text": "ngOnChanges β When the value of a data bound property changes, then this method is called."
},
{
"code": null,
"e": 2909,
"s": 2764,
"text": "ngOnInit β This is called whenever the initialization of the directive/component after Angular first displays the data-bound properties happens."
},
{
"code": null,
"e": 3054,
"s": 2909,
"text": "ngOnInit β This is called whenever the initialization of the directive/component after Angular first displays the data-bound properties happens."
},
{
"code": null,
"e": 3161,
"s": 3054,
"text": "ngDoCheck β This is for the detection and to act on changes that Angular can't or won't detect on its own."
},
{
"code": null,
"e": 3268,
"s": 3161,
"text": "ngDoCheck β This is for the detection and to act on changes that Angular can't or won't detect on its own."
},
{
"code": null,
"e": 3383,
"s": 3268,
"text": "ngAfterContentInit β This is called in response after Angular projects external content into the component's view."
},
{
"code": null,
"e": 3498,
"s": 3383,
"text": "ngAfterContentInit β This is called in response after Angular projects external content into the component's view."
},
{
"code": null,
"e": 3612,
"s": 3498,
"text": "ngAfterContentChecked β This is called in response after Angular checks the content projected into the component."
},
{
"code": null,
"e": 3726,
"s": 3612,
"text": "ngAfterContentChecked β This is called in response after Angular checks the content projected into the component."
},
{
"code": null,
"e": 3836,
"s": 3726,
"text": "ngAfterViewInit β This is called in response after Angular initializes the component's views and child views."
},
{
"code": null,
"e": 3946,
"s": 3836,
"text": "ngAfterViewInit β This is called in response after Angular initializes the component's views and child views."
},
{
"code": null,
"e": 4054,
"s": 3946,
"text": "ngAfterViewChecked β This is called in response after Angular checks the component's views and child views."
},
{
"code": null,
"e": 4162,
"s": 4054,
"text": "ngAfterViewChecked β This is called in response after Angular checks the component's views and child views."
},
{
"code": null,
"e": 4256,
"s": 4162,
"text": "ngOnDestroy β This is the cleanup phase just before Angular destroys the directive/component."
},
{
"code": null,
"e": 4350,
"s": 4256,
"text": "ngOnDestroy β This is the cleanup phase just before Angular destroys the directive/component."
},
{
"code": null,
"e": 4466,
"s": 4350,
"text": "Following is an example of implementing one lifecycle hook. In the app.component.ts file, place the following code."
},
{
"code": null,
"e": 4703,
"s": 4466,
"text": "import { \n Component \n} from '@angular/core'; \n\n@Component ({ \n selector: 'my-app', \n template: '<div> {{values}} </div> ' \n}) \n\nexport class AppComponent { \n values = ''; \n ngOnInit() { \n this.values = \"Hello\"; \n } \n}"
},
{
"code": null,
"e": 4862,
"s": 4703,
"text": "In the above program, we are calling the ngOnInit lifecycle hook to specifically mention that the value of the this.values parameter should be set to βHelloβ."
},
{
"code": null,
"e": 4957,
"s": 4862,
"text": "Once you save all the code changes and refresh the browser, you will get the following output."
},
{
"code": null,
"e": 4992,
"s": 4957,
"text": "\n 16 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 5006,
"s": 4992,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 5041,
"s": 5006,
"text": "\n 28 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 5055,
"s": 5041,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 5090,
"s": 5055,
"text": "\n 11 Lectures \n 7.5 hours \n"
},
{
"code": null,
"e": 5110,
"s": 5090,
"text": " SHIVPRASAD KOIRALA"
},
{
"code": null,
"e": 5145,
"s": 5110,
"text": "\n 16 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 5162,
"s": 5145,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 5195,
"s": 5162,
"text": "\n 69 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 5207,
"s": 5195,
"text": " Senol Atac"
},
{
"code": null,
"e": 5242,
"s": 5207,
"text": "\n 53 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 5254,
"s": 5242,
"text": " Senol Atac"
},
{
"code": null,
"e": 5261,
"s": 5254,
"text": " Print"
},
{
"code": null,
"e": 5272,
"s": 5261,
"text": " Add Notes"
}
] |
How to convert string into a number using AngularJS ? - GeeksforGeeks | 30 Sep, 2020
In this article, we will see how to convert a string into a number with the help of AngularJS.
Approach:
The parseInt() method is used for converting the string to an integer.
We will check whether the string is an integer or not by the isNumber() method.
Example 1: In the first example, the string β90β is converted to an integer.
HTML
<!DOCTYPE HTML><html> <head> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.13/angular.min.js"> </script> <script> var myApp = angular.module("app", []); myApp.controller("controller", function ($scope) { $scope.a = '90'; $scope.isNumberA = angular.isNumber($scope.a); $scope.convertToInt = function () { $scope.a = parseInt($scope.a); $scope.isNumberA = angular.isNumber($scope.a); }; }); </script></head> <body style="text-align:center;"> <h1 style="color:green;"> GeeksForGeeks </h1> <p> Convert string into a number in AngularJS </p> <div ng-app="app"> <div ng-controller="controller"> Value = {{a}} <br> <br> <button ng-click='convertToInt()'> Click to convert </button> <br> <br> isNumber(value) - {{isNumberA}}<br> </div> </div></body> </html>
Output:
Example 2: The 2 strings are added and then converted to an integer and then added again.
HTML
<!DOCTYPE HTML><html> <head> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.13/angular.min.js"> </script> <script> var myApp = angular.module("app", []); myApp.controller("controller", function ($scope) { $scope.a = "10"; $scope.b = "20"; $scope.strToInt = function () { $scope.a = parseInt($scope.a); $scope.b = parseInt($scope.b); }; }); </script></head> <body style="text-align:center;"> <h1 style="color:green;"> GeeksForGeeks </h1> <p> Convert string into a number in AngularJS </p> <div ng-app="app"> <div ng-controller="controller"> Value-1 = {{a}} <br> Value-2 = {{b}} <br><br> <button ng-click='strToInt()'> Click to convert </button> <br><br> sum - {{a + b}}<br> </div> </div></body> </html>
Output:
Attention reader! Donβt stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course.
AngularJS-Misc
HTML-Misc
AngularJS
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Top 10 Angular Libraries For Web Developers
Angular PrimeNG Dropdown Component
Angular 10 (blur) Event
How to make a Bootstrap Modal Popup in Angular 9/8 ?
How to create module with Routing in Angular 9 ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
How to set the default value for an HTML <select> element ?
How to update Node.js and NPM to next version ?
How to set input type date in dd-mm-yyyy format using HTML ? | [
{
"code": null,
"e": 25109,
"s": 25081,
"text": "\n30 Sep, 2020"
},
{
"code": null,
"e": 25204,
"s": 25109,
"text": "In this article, we will see how to convert a string into a number with the help of AngularJS."
},
{
"code": null,
"e": 25215,
"s": 25204,
"text": "Approach: "
},
{
"code": null,
"e": 25287,
"s": 25215,
"text": "The parseInt() method is used for converting the string to an integer. "
},
{
"code": null,
"e": 25367,
"s": 25287,
"text": "We will check whether the string is an integer or not by the isNumber() method."
},
{
"code": null,
"e": 25444,
"s": 25367,
"text": "Example 1: In the first example, the string β90β is converted to an integer."
},
{
"code": null,
"e": 25449,
"s": 25444,
"text": "HTML"
},
{
"code": "<!DOCTYPE HTML><html> <head> <script src=\"https://ajax.googleapis.com/ajax/libs/angularjs/1.2.13/angular.min.js\"> </script> <script> var myApp = angular.module(\"app\", []); myApp.controller(\"controller\", function ($scope) { $scope.a = '90'; $scope.isNumberA = angular.isNumber($scope.a); $scope.convertToInt = function () { $scope.a = parseInt($scope.a); $scope.isNumberA = angular.isNumber($scope.a); }; }); </script></head> <body style=\"text-align:center;\"> <h1 style=\"color:green;\"> GeeksForGeeks </h1> <p> Convert string into a number in AngularJS </p> <div ng-app=\"app\"> <div ng-controller=\"controller\"> Value = {{a}} <br> <br> <button ng-click='convertToInt()'> Click to convert </button> <br> <br> isNumber(value) - {{isNumberA}}<br> </div> </div></body> </html>",
"e": 26495,
"s": 25449,
"text": null
},
{
"code": null,
"e": 26503,
"s": 26495,
"text": "Output:"
},
{
"code": null,
"e": 26593,
"s": 26503,
"text": "Example 2: The 2 strings are added and then converted to an integer and then added again."
},
{
"code": null,
"e": 26598,
"s": 26593,
"text": "HTML"
},
{
"code": "<!DOCTYPE HTML><html> <head> <script src=\"https://ajax.googleapis.com/ajax/libs/angularjs/1.2.13/angular.min.js\"> </script> <script> var myApp = angular.module(\"app\", []); myApp.controller(\"controller\", function ($scope) { $scope.a = \"10\"; $scope.b = \"20\"; $scope.strToInt = function () { $scope.a = parseInt($scope.a); $scope.b = parseInt($scope.b); }; }); </script></head> <body style=\"text-align:center;\"> <h1 style=\"color:green;\"> GeeksForGeeks </h1> <p> Convert string into a number in AngularJS </p> <div ng-app=\"app\"> <div ng-controller=\"controller\"> Value-1 = {{a}} <br> Value-2 = {{b}} <br><br> <button ng-click='strToInt()'> Click to convert </button> <br><br> sum - {{a + b}}<br> </div> </div></body> </html>",
"e": 27593,
"s": 26598,
"text": null
},
{
"code": null,
"e": 27601,
"s": 27593,
"text": "Output:"
},
{
"code": null,
"e": 27738,
"s": 27601,
"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": 27753,
"s": 27738,
"text": "AngularJS-Misc"
},
{
"code": null,
"e": 27763,
"s": 27753,
"text": "HTML-Misc"
},
{
"code": null,
"e": 27773,
"s": 27763,
"text": "AngularJS"
},
{
"code": null,
"e": 27778,
"s": 27773,
"text": "HTML"
},
{
"code": null,
"e": 27795,
"s": 27778,
"text": "Web Technologies"
},
{
"code": null,
"e": 27800,
"s": 27795,
"text": "HTML"
},
{
"code": null,
"e": 27898,
"s": 27800,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27942,
"s": 27898,
"text": "Top 10 Angular Libraries For Web Developers"
},
{
"code": null,
"e": 27977,
"s": 27942,
"text": "Angular PrimeNG Dropdown Component"
},
{
"code": null,
"e": 28001,
"s": 27977,
"text": "Angular 10 (blur) Event"
},
{
"code": null,
"e": 28054,
"s": 28001,
"text": "How to make a Bootstrap Modal Popup in Angular 9/8 ?"
},
{
"code": null,
"e": 28103,
"s": 28054,
"text": "How to create module with Routing in Angular 9 ?"
},
{
"code": null,
"e": 28165,
"s": 28103,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 28215,
"s": 28165,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
},
{
"code": null,
"e": 28275,
"s": 28215,
"text": "How to set the default value for an HTML <select> element ?"
},
{
"code": null,
"e": 28323,
"s": 28275,
"text": "How to update Node.js and NPM to next version ?"
}
] |
How to plot an array in Python using Matplotlib? | To plot an array in Python, we can take the following steps β
Set the figure size and adjust the padding between and around the subplots.
Create two arrays, x and y, using numpy.
Set the title of the curve using title() method.
Plot x and y data points, with red color.
To display the figure, use show() method.
import numpy as np
import matplotlib.pyplot as plt
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True
x = np.array([5, 4, 1, 4, 5])
y = np.sort(x)
plt.title("Line graph")
plt.plot(x, y, color="red")
plt.show() | [
{
"code": null,
"e": 1124,
"s": 1062,
"text": "To plot an array in Python, we can take the following steps β"
},
{
"code": null,
"e": 1200,
"s": 1124,
"text": "Set the figure size and adjust the padding between and around the subplots."
},
{
"code": null,
"e": 1241,
"s": 1200,
"text": "Create two arrays, x and y, using numpy."
},
{
"code": null,
"e": 1290,
"s": 1241,
"text": "Set the title of the curve using title() method."
},
{
"code": null,
"e": 1332,
"s": 1290,
"text": "Plot x and y data points, with red color."
},
{
"code": null,
"e": 1374,
"s": 1332,
"text": "To display the figure, use show() method."
},
{
"code": null,
"e": 1624,
"s": 1374,
"text": "import numpy as np\nimport matplotlib.pyplot as plt\n\nplt.rcParams[\"figure.figsize\"] = [7.50, 3.50]\nplt.rcParams[\"figure.autolayout\"] = True\n\nx = np.array([5, 4, 1, 4, 5])\ny = np.sort(x)\n\nplt.title(\"Line graph\")\nplt.plot(x, y, color=\"red\")\n\nplt.show()"
}
] |
Aptitude - Number System Online Quiz | Following quiz provides Multiple Choice Questions (MCQs) related to Number System. You will have to read all the given answers and click over the correct answer. If you are not sure about the answer then you can check the answer using Show Answer button. You can use Next Quiz button to check new set of questions in the quiz.
Q 1 - The unit digit in 7153 is?
A - 6
B - 0
C - 7
D - 1
7153 = (74)38 x 7 Now, unit digit of (74)38 = 1 Therefore, unit digit of 7153 = 1 x 7 = 7
Q 2 - (568 x 568 x 568 + 432 x 432 x 432) / (568 x 568 - 568 x 432 + 432 + 432) = ?
A - 568
B - 1000
C - 432
D - 10
This is solved using the following formulae: (a3 + b3) = (a + b)( a2 - ab + b2) The value of (a+b) = (a3 + b3) / ( a2 - ab + b2) = (568 + 432) = 1000
Q 3 - The difference of the squares of two consecutive even integers is divisible by which of the following integers?
A - 1
B - 5
C - 4
D - 2
Let the consecutive integers(even) be 2p and (2p + 2): = (2p + 2)2 - 2p2 = (2p + 2 + 2p)(2p + 2 -2p) = 2(4p + 2) = 4 (2p + 1) Therefore, divisible by 4.
Q 4 - How many natural numbers are there between 17 and 9 which are exactly divisible by 6?
A - 13
B - 15
C - 14
D - 16
Numbers -> 18, 24, 30, ... , 90 A.P: a = 18, d = 6, l = 90 tn = a + (n-1)d 90 = 18 + (n-1)6 90 = 18 + 6n -6 n = 13
Q 5 - 6 + 15 + 24 + 33 + ... + 123 = ?
A - 903
B - 603
C - 752
D - 690
a = 6, d = 9, l = 123 Let number of terms be n 123 = a + (n - 1)d 123 = 6 + (n - 1)9 123 = 9n - 9 n = 14 Sn = nβ2 (a + l) = 14β2 (6 + 123) = 7 x 129 = 903
Q 6 - What is the unit digit in in 7105?
A - 5
B - 7
C - 9
D - 1
Unit digit in (7)105 = unit digit in (74)26 x 71 = unit digit in (1 x 7) = 7 Thus Unit digit in (7)105 is 7.
Q 7 - 916 x y x 3 = 214344. What is y?
A - 78
B - 68
C - 84
D - 66
916 x y x 3 = 214344 => 2748 x y = 214344 => y = 214344 / 2748 => y = 78
Q 8 - 106 x 106 - 94 x 94 = y. What is y?
A - 2400
B - 2000
C - 1904
D - 1906
y = 106 x 106 - 94 x 94 = (106)2 - (94)2 = (100 + 6)2 - (100 - 6)2 Using formulae (a+b)2 = a2 + b2 + 2ab and (a-b)2 = a2 + b2 - 2ab (a+b)2 - (a-b)2 = 4ab β΄ y = 4 x 100 x 6 = 2400
Q 9 - Which of the following is a prime number?
A - 81
B - 33
C - 93
D - 97
97. As all other numbers are divisible by 3.
Q 10 - What is the common factor in (4743 + 4343) and (4747 + 4347)
A - 47-43
B - 47+43
C - 4743 + 4343
D - 4747 + 4347
an + bn is divisible by a + b if n is an odd number. β΄ each number is divisible by (47 + 43).
87 Lectures
22.5 hours
Programming Line
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 4219,
"s": 3892,
"text": "Following quiz provides Multiple Choice Questions (MCQs) related to Number System. You will have to read all the given answers and click over the correct answer. If you are not sure about the answer then you can check the answer using Show Answer button. You can use Next Quiz button to check new set of questions in the quiz."
},
{
"code": null,
"e": 4252,
"s": 4219,
"text": "Q 1 - The unit digit in 7153 is?"
},
{
"code": null,
"e": 4258,
"s": 4252,
"text": "A - 6"
},
{
"code": null,
"e": 4264,
"s": 4258,
"text": "B - 0"
},
{
"code": null,
"e": 4270,
"s": 4264,
"text": "C - 7"
},
{
"code": null,
"e": 4276,
"s": 4270,
"text": "D - 1"
},
{
"code": null,
"e": 4391,
"s": 4276,
"text": "7153 = (74)38 x 7 Now, unit digit of (74)38 = 1 Therefore, unit digit of 7153 = 1 x 7 = 7"
},
{
"code": null,
"e": 4475,
"s": 4391,
"text": "Q 2 - (568 x 568 x 568 + 432 x 432 x 432) / (568 x 568 - 568 x 432 + 432 + 432) = ?"
},
{
"code": null,
"e": 4483,
"s": 4475,
"text": "A - 568"
},
{
"code": null,
"e": 4492,
"s": 4483,
"text": "B - 1000"
},
{
"code": null,
"e": 4500,
"s": 4492,
"text": "C - 432"
},
{
"code": null,
"e": 4507,
"s": 4500,
"text": "D - 10"
},
{
"code": null,
"e": 4657,
"s": 4507,
"text": "This is solved using the following formulae: (a3 + b3) = (a + b)( a2 - ab + b2) The value of (a+b) = (a3 + b3) / ( a2 - ab + b2) = (568 + 432) = 1000"
},
{
"code": null,
"e": 4775,
"s": 4657,
"text": "Q 3 - The difference of the squares of two consecutive even integers is divisible by which of the following integers?"
},
{
"code": null,
"e": 4781,
"s": 4775,
"text": "A - 1"
},
{
"code": null,
"e": 4787,
"s": 4781,
"text": "B - 5"
},
{
"code": null,
"e": 4793,
"s": 4787,
"text": "C - 4"
},
{
"code": null,
"e": 4799,
"s": 4793,
"text": "D - 2"
},
{
"code": null,
"e": 4952,
"s": 4799,
"text": "Let the consecutive integers(even) be 2p and (2p + 2): = (2p + 2)2 - 2p2 = (2p + 2 + 2p)(2p + 2 -2p) = 2(4p + 2) = 4 (2p + 1) Therefore, divisible by 4."
},
{
"code": null,
"e": 5044,
"s": 4952,
"text": "Q 4 - How many natural numbers are there between 17 and 9 which are exactly divisible by 6?"
},
{
"code": null,
"e": 5051,
"s": 5044,
"text": "A - 13"
},
{
"code": null,
"e": 5058,
"s": 5051,
"text": "B - 15"
},
{
"code": null,
"e": 5065,
"s": 5058,
"text": "C - 14"
},
{
"code": null,
"e": 5072,
"s": 5065,
"text": "D - 16"
},
{
"code": null,
"e": 5187,
"s": 5072,
"text": "Numbers -> 18, 24, 30, ... , 90 A.P: a = 18, d = 6, l = 90 tn = a + (n-1)d 90 = 18 + (n-1)6 90 = 18 + 6n -6 n = 13"
},
{
"code": null,
"e": 5226,
"s": 5187,
"text": "Q 5 - 6 + 15 + 24 + 33 + ... + 123 = ?"
},
{
"code": null,
"e": 5234,
"s": 5226,
"text": "A - 903"
},
{
"code": null,
"e": 5242,
"s": 5234,
"text": "B - 603"
},
{
"code": null,
"e": 5250,
"s": 5242,
"text": "C - 752"
},
{
"code": null,
"e": 5258,
"s": 5250,
"text": "D - 690"
},
{
"code": null,
"e": 5422,
"s": 5258,
"text": "a = 6, d = 9, l = 123 Let number of terms be n 123 = a + (n - 1)d 123 = 6 + (n - 1)9 123 = 9n - 9 n = 14 Sn = nβ2 (a + l) = 14β2 (6 + 123) = 7 x 129 = 903"
},
{
"code": null,
"e": 5463,
"s": 5422,
"text": "Q 6 - What is the unit digit in in 7105?"
},
{
"code": null,
"e": 5469,
"s": 5463,
"text": "A - 5"
},
{
"code": null,
"e": 5475,
"s": 5469,
"text": "B - 7"
},
{
"code": null,
"e": 5481,
"s": 5475,
"text": "C - 9"
},
{
"code": null,
"e": 5487,
"s": 5481,
"text": "D - 1"
},
{
"code": null,
"e": 5597,
"s": 5487,
"text": " Unit digit in (7)105 = unit digit in (74)26 x 71 = unit digit in (1 x 7) = 7 Thus Unit digit in (7)105 is 7."
},
{
"code": null,
"e": 5636,
"s": 5597,
"text": "Q 7 - 916 x y x 3 = 214344. What is y?"
},
{
"code": null,
"e": 5643,
"s": 5636,
"text": "A - 78"
},
{
"code": null,
"e": 5650,
"s": 5643,
"text": "B - 68"
},
{
"code": null,
"e": 5657,
"s": 5650,
"text": "C - 84"
},
{
"code": null,
"e": 5664,
"s": 5657,
"text": "D - 66"
},
{
"code": null,
"e": 5740,
"s": 5664,
"text": " 916 x y x 3 = 214344 => 2748 x y = 214344 => y = 214344 / 2748 => y = 78 "
},
{
"code": null,
"e": 5782,
"s": 5740,
"text": "Q 8 - 106 x 106 - 94 x 94 = y. What is y?"
},
{
"code": null,
"e": 5791,
"s": 5782,
"text": "A - 2400"
},
{
"code": null,
"e": 5800,
"s": 5791,
"text": "B - 2000"
},
{
"code": null,
"e": 5809,
"s": 5800,
"text": "C - 1904"
},
{
"code": null,
"e": 5818,
"s": 5809,
"text": "D - 1906"
},
{
"code": null,
"e": 6016,
"s": 5818,
"text": " y = 106 x 106 - 94 x 94 = (106)2 - (94)2 = (100 + 6)2 - (100 - 6)2 Using formulae (a+b)2 = a2 + b2 + 2ab and (a-b)2 = a2 + b2 - 2ab (a+b)2 - (a-b)2 = 4ab β΄ y = 4 x 100 x 6 = 2400 "
},
{
"code": null,
"e": 6064,
"s": 6016,
"text": "Q 9 - Which of the following is a prime number?"
},
{
"code": null,
"e": 6071,
"s": 6064,
"text": "A - 81"
},
{
"code": null,
"e": 6078,
"s": 6071,
"text": "B - 33"
},
{
"code": null,
"e": 6085,
"s": 6078,
"text": "C - 93"
},
{
"code": null,
"e": 6092,
"s": 6085,
"text": "D - 97"
},
{
"code": null,
"e": 6137,
"s": 6092,
"text": "97. As all other numbers are divisible by 3."
},
{
"code": null,
"e": 6205,
"s": 6137,
"text": "Q 10 - What is the common factor in (4743 + 4343) and (4747 + 4347)"
},
{
"code": null,
"e": 6215,
"s": 6205,
"text": "A - 47-43"
},
{
"code": null,
"e": 6225,
"s": 6215,
"text": "B - 47+43"
},
{
"code": null,
"e": 6241,
"s": 6225,
"text": "C - 4743 + 4343"
},
{
"code": null,
"e": 6257,
"s": 6241,
"text": "D - 4747 + 4347"
},
{
"code": null,
"e": 6351,
"s": 6257,
"text": "an + bn is divisible by a + b if n is an odd number. β΄ each number is divisible by (47 + 43)."
},
{
"code": null,
"e": 6387,
"s": 6351,
"text": "\n 87 Lectures \n 22.5 hours \n"
},
{
"code": null,
"e": 6405,
"s": 6387,
"text": " Programming Line"
},
{
"code": null,
"e": 6412,
"s": 6405,
"text": " Print"
},
{
"code": null,
"e": 6423,
"s": 6412,
"text": " Add Notes"
}
] |
Reading a CSV file in Java using OpenCSV - GeeksforGeeks | 29 Jul, 2021
A Comma-Separated Values (CSV) file is just a normal plain-text file, store data in column by column, and split it by a separator (e.g normally it is a comma β, β).
OpenCSV is a CSV parser library for Java. OpenCSV supports all the basic CSV-type operations you are want to do. Java 7 is currently the minimum supported version for OpenCSV. Java language does not provide any native support for effectively handling CSV files so we are using OpenCSV for handling CSV files in Java.
How to Use OpenCSV
1. For maven project, you can include the OpenCSV maven dependency in pom.xml file.
HTML
<dependency> <groupId>com.opencsv</groupId> <artifactId>opencsv</artifactId> <version>4.1</version></dependency>
2. For Gradle Project, you can include the OpenCSV dependency.
compile group: 'com.opencsv', name: 'opencsv', version: '4.1'
3. You can Download OpenCSV Jar and include in your project class path.
Some useful classes of opencsv
CSVReader β This class provides the operations to read the CSV file as a list of String array.CSVWriter β This class allows us to write the data to a CSV file.CsvToBean β This class will be used when you want to populate your java beans from a CSV file content.BeanToCsv β This class helps to export data to CSV file from your java application.
CSVReader β This class provides the operations to read the CSV file as a list of String array.
CSVWriter β This class allows us to write the data to a CSV file.
CsvToBean β This class will be used when you want to populate your java beans from a CSV file content.
BeanToCsv β This class helps to export data to CSV file from your java application.
Reading CSV File
For reading a CSV file you need CSVReader class. Following are sample CSV file that weβll read.
name, rollno, department, result, cgpa
amar, 42, cse, pass, 8.6
rohini, 21, ece, fail, 3.2
aman, 23, cse, pass, 8.9
rahul, 45, ee, fail, 4.6
pratik, 65, cse, pass, 7.2
raunak, 23, me, pass, 9.1
suvam, 68, me, pass, 8.2
We can read csv file by two ways :
1. Read data line by line : Lets see how to read CSV file line by line. For reading data line by line, first we have to construct and initialize CSVReader object by passing the filereader object of CSV file. After that we have to call readNext() method of CSVReader object to read data line by line as shown in below code.
Java
// Java code to illustrate reading a// CSV file line by linepublic static void readDataLineByLine(String file){ try { // Create an object of filereader // class with CSV file as a parameter. FileReader filereader = new FileReader(file); // create csvReader object passing // file reader as a parameter CSVReader csvReader = new CSVReader(filereader); String[] nextRecord; // we are going to read data line by line while ((nextRecord = csvReader.readNext()) != null) { for (String cell : nextRecord) { System.out.print(cell + "\t"); } System.out.println(); } } catch (Exception e) { e.printStackTrace(); }}
2. Read all data at once : We read the CSV records one by one using the readNext() method. CSVReader also provides a method called readAll() to read all the records at once into a List.
List allData = csvReader.readAll();
When we read csv file by default, header will not ignored, as shown in output of above codes. When we need to skip the first element in the list then we can specify start line while creating CSVReader.
CSVReader csvReader =
new CSVReaderBuilder(reader).withSkipLines(1).build();
Code:
Java
// Java code to illustrate reading a// all data at oncepublic static void readAllDataAtOnce(String file){ try { // Create an object of file reader // class with CSV file as a parameter. FileReader filereader = new FileReader(file); // create csvReader object and skip first Line CSVReader csvReader = new CSVReaderBuilder(filereader) .withSkipLines(1) .build(); List<String[]> allData = csvReader.readAll(); // print Data for (String[] row : allData) { for (String cell : row) { System.out.print(cell + "\t"); } System.out.println(); } } catch (Exception e) { e.printStackTrace(); }}
Reading CSV File with different separator
CSV files can be separated with a delimiter other than a comma e.g. semi-colon, pipe etc. The following example shows how to read data of CSV file separated by a semi-colon character.
Semi-colon separated CSV file example :
name;rollno;department;result;cgpa
amar;42;cse;pass;8.6
rohini;21;ece;fail;3.2
aman;23;cse;pass;8.9
rahul;45;ee;fail;4.6
pratik;65;cse;pass;7.2
raunak;23;me;pass;9.1
suvam;68;me;pass;8.2
For Custom separator first CSVParser with specific parser character is created.
CSVParser parser = new CSVParserBuilder().withSeparator(';').build();
Then we will create CSVReader object withCSVParser() method along with constructor and provided the made parser object to parameter of withCSVParser method.At last call build method to build object.
CSVReader csvReader = new CSVReaderBuilder(filereader).withCSVParser(parser).build();
Code:
Java
// Java code to illustrate// Reading CSV File with different separatorpublic static void readDataFromCustomSeparator(String file){ try { // Create an object of file reader class with CSV file as a parameter. FileReader filereader = new FileReader(file); // create csvParser object with // custom separator semi-colon CSVParser parser = new CSVParserBuilder().withSeparator(';').build(); // create csvReader object with parameter // filereader and parser CSVReader csvReader = new CSVReaderBuilder(filereader) .withCSVParser(parser) .build(); // Read all data at once List<String[]> allData = csvReader.readAll(); // Print Data. for (String[] row : allData) { for (String cell : row) { System.out.print(cell + "\t"); } System.out.println(); } } catch (Exception e) { e.printStackTrace(); }}
Example β Reading two csv Files result.csv and results_semicolon_Separator.csv result.csv has default separator β, β but results_semicolon_Separator.csv has a separator β;β in place of β, β.
Codes:
Java
// Java program to illustrate reading// two CSV files// with different separators import java.io.FileReader;import java.util.List;import com.opencsv.*; public class ReadCSVData { private static final String CSV_FILE_PATH = "D:\\EclipseWorkSpace\\CSVOperations\\results.csv"; private static final String CSV_FILE_CUSTOM_SEPARATOR = "D:\\EclipseWorkSpace\\CSVOperations\\results_semicolon_Separator.csv"; public static void main(String[] args) { System.out.println("Read Data Line by Line With Header \n"); readDataLineByLine(CSV_FILE_PATH); System.out.println("_______________________________________________"); System.out.println("Read All Data at Once and Hide the Header also \n"); readAllDataAtOnce(CSV_FILE_PATH); System.out.println("_______________________________________________"); System.out.println("Custom Separator here semi-colon\n"); readDataFromCustomSeparator(CSV_FILE_CUSTOM_SEPARATOR); System.out.println("_______________________________________________"); } public static void readDataLineByLine(String file) { try { // Create an object of filereader class // with CSV file as a parameter. FileReader filereader = new FileReader(file); // create csvReader object passing // filereader as parameter CSVReader csvReader = new CSVReader(filereader); String[] nextRecord; // we are going to read data line by line while ((nextRecord = csvReader.readNext()) != null) { for (String cell : nextRecord) { System.out.print(cell + "\t"); } System.out.println(); } } catch (Exception e) { e.printStackTrace(); } } public static void readAllDataAtOnce(String file) { try { // Create an object of filereader class // with CSV file as a parameter. FileReader filereader = new FileReader(file); // create csvReader object // and skip first Line CSVReader csvReader = new CSVReaderBuilder(filereader) .withSkipLines(1) .build(); List<String[]> allData = csvReader.readAll(); // print Data for (String[] row : allData) { for (String cell : row) { System.out.print(cell + "\t"); } System.out.println(); } } catch (Exception e) { e.printStackTrace(); } } public static void readDataFromCustomSeparator(String file) { try { // Create object of filereader // class with csv file as parameter. FileReader filereader = new FileReader(file); // create csvParser object with // custom separator semi-colon CSVParser parser = new CSVParserBuilder().withSeparator(';').build(); // create csvReader object with // parameter filereader and parser CSVReader csvReader = new CSVReaderBuilder(filereader) .withCSVParser(parser) .build(); // Read all data at once List<String[]> allData = csvReader.readAll(); // print Data for (String[] row : allData) { for (String cell : row) { System.out.print(cell + "\t"); } System.out.println(); } } catch (Exception e) { e.printStackTrace(); } }}
Output:
_______________________________________________
Read Data Line by Line With Header
name rollno department result cgpa
amar 42 cse pass 8.6
rohini 21 ece fail 3.2
aman 23 cse pass 8.9
rahul 45 ee fail 4.6
pratik 65 cse pass 7.2
raunak 23 me pass 9.1
suvam 68 me pass 8.2
_______________________________________________
Read All Data at Once and Hide the Header also
amar 42 cse pass 8.6
rohini 21 ece fail 3.2
aman 23 cse pass 8.9
rahul 45 ee fail 4.6
pratik 65 cse pass 7.2
raunak 23 me pass 9.1
suvam 68 me pass 8.2
_______________________________________________
Custom Separator here semi-colon
name rollno department result cgpa
amar 42 cse pass 8.6
rohini 21 ece fail 3.2
aman 23 cse pass 8.9
rahul 45 ee fail 4.6
pratik 65 cse pass 7.2
raunak 23 me pass 9.1
suvam 68 me pass 8.2
_______________________________________________
In future articles, we will include more Operations on CSV file using OpenCSV. References: CSVReader class Documentation, OpenCSV Documentation
Arijeet Bhakat
anikakapoor
simmytarika5
GBlog
Java
Java
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
GET and POST requests using Python
6 Best IDE's For Python in 2022
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Arrays in Java
Split() String method in Java with examples
For-each loop in Java
Reverse a string in Java
Object Oriented Programming (OOPs) Concept in Java | [
{
"code": null,
"e": 24455,
"s": 24427,
"text": "\n29 Jul, 2021"
},
{
"code": null,
"e": 24620,
"s": 24455,
"text": "A Comma-Separated Values (CSV) file is just a normal plain-text file, store data in column by column, and split it by a separator (e.g normally it is a comma β, β)."
},
{
"code": null,
"e": 24937,
"s": 24620,
"text": "OpenCSV is a CSV parser library for Java. OpenCSV supports all the basic CSV-type operations you are want to do. Java 7 is currently the minimum supported version for OpenCSV. Java language does not provide any native support for effectively handling CSV files so we are using OpenCSV for handling CSV files in Java."
},
{
"code": null,
"e": 24956,
"s": 24937,
"text": "How to Use OpenCSV"
},
{
"code": null,
"e": 25040,
"s": 24956,
"text": "1. For maven project, you can include the OpenCSV maven dependency in pom.xml file."
},
{
"code": null,
"e": 25045,
"s": 25040,
"text": "HTML"
},
{
"code": "<dependency> <groupId>com.opencsv</groupId> <artifactId>opencsv</artifactId> <version>4.1</version></dependency>",
"e": 25167,
"s": 25045,
"text": null
},
{
"code": null,
"e": 25231,
"s": 25167,
"text": "2. For Gradle Project, you can include the OpenCSV dependency. "
},
{
"code": null,
"e": 25293,
"s": 25231,
"text": "compile group: 'com.opencsv', name: 'opencsv', version: '4.1'"
},
{
"code": null,
"e": 25365,
"s": 25293,
"text": "3. You can Download OpenCSV Jar and include in your project class path."
},
{
"code": null,
"e": 25397,
"s": 25365,
"text": "Some useful classes of opencsv "
},
{
"code": null,
"e": 25742,
"s": 25397,
"text": "CSVReader β This class provides the operations to read the CSV file as a list of String array.CSVWriter β This class allows us to write the data to a CSV file.CsvToBean β This class will be used when you want to populate your java beans from a CSV file content.BeanToCsv β This class helps to export data to CSV file from your java application."
},
{
"code": null,
"e": 25837,
"s": 25742,
"text": "CSVReader β This class provides the operations to read the CSV file as a list of String array."
},
{
"code": null,
"e": 25903,
"s": 25837,
"text": "CSVWriter β This class allows us to write the data to a CSV file."
},
{
"code": null,
"e": 26006,
"s": 25903,
"text": "CsvToBean β This class will be used when you want to populate your java beans from a CSV file content."
},
{
"code": null,
"e": 26090,
"s": 26006,
"text": "BeanToCsv β This class helps to export data to CSV file from your java application."
},
{
"code": null,
"e": 26107,
"s": 26090,
"text": "Reading CSV File"
},
{
"code": null,
"e": 26205,
"s": 26107,
"text": "For reading a CSV file you need CSVReader class. Following are sample CSV file that weβll read. "
},
{
"code": null,
"e": 26424,
"s": 26205,
"text": "name, rollno, department, result, cgpa\namar, 42, cse, pass, 8.6\nrohini, 21, ece, fail, 3.2\naman, 23, cse, pass, 8.9\nrahul, 45, ee, fail, 4.6\npratik, 65, cse, pass, 7.2\nraunak, 23, me, pass, 9.1\nsuvam, 68, me, pass, 8.2"
},
{
"code": null,
"e": 26460,
"s": 26424,
"text": "We can read csv file by two ways : "
},
{
"code": null,
"e": 26783,
"s": 26460,
"text": "1. Read data line by line : Lets see how to read CSV file line by line. For reading data line by line, first we have to construct and initialize CSVReader object by passing the filereader object of CSV file. After that we have to call readNext() method of CSVReader object to read data line by line as shown in below code."
},
{
"code": null,
"e": 26788,
"s": 26783,
"text": "Java"
},
{
"code": "// Java code to illustrate reading a// CSV file line by linepublic static void readDataLineByLine(String file){ try { // Create an object of filereader // class with CSV file as a parameter. FileReader filereader = new FileReader(file); // create csvReader object passing // file reader as a parameter CSVReader csvReader = new CSVReader(filereader); String[] nextRecord; // we are going to read data line by line while ((nextRecord = csvReader.readNext()) != null) { for (String cell : nextRecord) { System.out.print(cell + \"\\t\"); } System.out.println(); } } catch (Exception e) { e.printStackTrace(); }}",
"e": 27535,
"s": 26788,
"text": null
},
{
"code": null,
"e": 27721,
"s": 27535,
"text": "2. Read all data at once : We read the CSV records one by one using the readNext() method. CSVReader also provides a method called readAll() to read all the records at once into a List."
},
{
"code": null,
"e": 27759,
"s": 27721,
"text": " List allData = csvReader.readAll(); "
},
{
"code": null,
"e": 27962,
"s": 27759,
"text": "When we read csv file by default, header will not ignored, as shown in output of above codes. When we need to skip the first element in the list then we can specify start line while creating CSVReader. "
},
{
"code": null,
"e": 28040,
"s": 27962,
"text": "CSVReader csvReader = \nnew CSVReaderBuilder(reader).withSkipLines(1).build();"
},
{
"code": null,
"e": 28047,
"s": 28040,
"text": "Code: "
},
{
"code": null,
"e": 28052,
"s": 28047,
"text": "Java"
},
{
"code": "// Java code to illustrate reading a// all data at oncepublic static void readAllDataAtOnce(String file){ try { // Create an object of file reader // class with CSV file as a parameter. FileReader filereader = new FileReader(file); // create csvReader object and skip first Line CSVReader csvReader = new CSVReaderBuilder(filereader) .withSkipLines(1) .build(); List<String[]> allData = csvReader.readAll(); // print Data for (String[] row : allData) { for (String cell : row) { System.out.print(cell + \"\\t\"); } System.out.println(); } } catch (Exception e) { e.printStackTrace(); }}",
"e": 28834,
"s": 28052,
"text": null
},
{
"code": null,
"e": 28876,
"s": 28834,
"text": "Reading CSV File with different separator"
},
{
"code": null,
"e": 29061,
"s": 28876,
"text": "CSV files can be separated with a delimiter other than a comma e.g. semi-colon, pipe etc. The following example shows how to read data of CSV file separated by a semi-colon character. "
},
{
"code": null,
"e": 29103,
"s": 29061,
"text": "Semi-colon separated CSV file example : "
},
{
"code": null,
"e": 29290,
"s": 29103,
"text": "name;rollno;department;result;cgpa\namar;42;cse;pass;8.6\nrohini;21;ece;fail;3.2\naman;23;cse;pass;8.9\nrahul;45;ee;fail;4.6\npratik;65;cse;pass;7.2\nraunak;23;me;pass;9.1\nsuvam;68;me;pass;8.2"
},
{
"code": null,
"e": 29371,
"s": 29290,
"text": "For Custom separator first CSVParser with specific parser character is created. "
},
{
"code": null,
"e": 29441,
"s": 29371,
"text": "CSVParser parser = new CSVParserBuilder().withSeparator(';').build();"
},
{
"code": null,
"e": 29641,
"s": 29441,
"text": "Then we will create CSVReader object withCSVParser() method along with constructor and provided the made parser object to parameter of withCSVParser method.At last call build method to build object. "
},
{
"code": null,
"e": 29727,
"s": 29641,
"text": "CSVReader csvReader = new CSVReaderBuilder(filereader).withCSVParser(parser).build();"
},
{
"code": null,
"e": 29735,
"s": 29727,
"text": "Code: "
},
{
"code": null,
"e": 29740,
"s": 29735,
"text": "Java"
},
{
"code": "// Java code to illustrate// Reading CSV File with different separatorpublic static void readDataFromCustomSeparator(String file){ try { // Create an object of file reader class with CSV file as a parameter. FileReader filereader = new FileReader(file); // create csvParser object with // custom separator semi-colon CSVParser parser = new CSVParserBuilder().withSeparator(';').build(); // create csvReader object with parameter // filereader and parser CSVReader csvReader = new CSVReaderBuilder(filereader) .withCSVParser(parser) .build(); // Read all data at once List<String[]> allData = csvReader.readAll(); // Print Data. for (String[] row : allData) { for (String cell : row) { System.out.print(cell + \"\\t\"); } System.out.println(); } } catch (Exception e) { e.printStackTrace(); }}",
"e": 30758,
"s": 29740,
"text": null
},
{
"code": null,
"e": 30949,
"s": 30758,
"text": "Example β Reading two csv Files result.csv and results_semicolon_Separator.csv result.csv has default separator β, β but results_semicolon_Separator.csv has a separator β;β in place of β, β."
},
{
"code": null,
"e": 30957,
"s": 30949,
"text": " Codes:"
},
{
"code": null,
"e": 30962,
"s": 30957,
"text": "Java"
},
{
"code": "// Java program to illustrate reading// two CSV files// with different separators import java.io.FileReader;import java.util.List;import com.opencsv.*; public class ReadCSVData { private static final String CSV_FILE_PATH = \"D:\\\\EclipseWorkSpace\\\\CSVOperations\\\\results.csv\"; private static final String CSV_FILE_CUSTOM_SEPARATOR = \"D:\\\\EclipseWorkSpace\\\\CSVOperations\\\\results_semicolon_Separator.csv\"; public static void main(String[] args) { System.out.println(\"Read Data Line by Line With Header \\n\"); readDataLineByLine(CSV_FILE_PATH); System.out.println(\"_______________________________________________\"); System.out.println(\"Read All Data at Once and Hide the Header also \\n\"); readAllDataAtOnce(CSV_FILE_PATH); System.out.println(\"_______________________________________________\"); System.out.println(\"Custom Separator here semi-colon\\n\"); readDataFromCustomSeparator(CSV_FILE_CUSTOM_SEPARATOR); System.out.println(\"_______________________________________________\"); } public static void readDataLineByLine(String file) { try { // Create an object of filereader class // with CSV file as a parameter. FileReader filereader = new FileReader(file); // create csvReader object passing // filereader as parameter CSVReader csvReader = new CSVReader(filereader); String[] nextRecord; // we are going to read data line by line while ((nextRecord = csvReader.readNext()) != null) { for (String cell : nextRecord) { System.out.print(cell + \"\\t\"); } System.out.println(); } } catch (Exception e) { e.printStackTrace(); } } public static void readAllDataAtOnce(String file) { try { // Create an object of filereader class // with CSV file as a parameter. FileReader filereader = new FileReader(file); // create csvReader object // and skip first Line CSVReader csvReader = new CSVReaderBuilder(filereader) .withSkipLines(1) .build(); List<String[]> allData = csvReader.readAll(); // print Data for (String[] row : allData) { for (String cell : row) { System.out.print(cell + \"\\t\"); } System.out.println(); } } catch (Exception e) { e.printStackTrace(); } } public static void readDataFromCustomSeparator(String file) { try { // Create object of filereader // class with csv file as parameter. FileReader filereader = new FileReader(file); // create csvParser object with // custom separator semi-colon CSVParser parser = new CSVParserBuilder().withSeparator(';').build(); // create csvReader object with // parameter filereader and parser CSVReader csvReader = new CSVReaderBuilder(filereader) .withCSVParser(parser) .build(); // Read all data at once List<String[]> allData = csvReader.readAll(); // print Data for (String[] row : allData) { for (String cell : row) { System.out.print(cell + \"\\t\"); } System.out.println(); } } catch (Exception e) { e.printStackTrace(); } }}",
"e": 34703,
"s": 30962,
"text": null
},
{
"code": null,
"e": 34712,
"s": 34703,
"text": "Output: "
},
{
"code": null,
"e": 35918,
"s": 34712,
"text": "_______________________________________________\nRead Data Line by Line With Header \n\nname rollno department result cgpa \namar 42 cse pass 8.6 \nrohini 21 ece fail 3.2 \naman 23 cse pass 8.9 \nrahul 45 ee fail 4.6 \npratik 65 cse pass 7.2 \nraunak 23 me pass 9.1 \nsuvam 68 me pass 8.2 \n_______________________________________________\nRead All Data at Once and Hide the Header also \n\namar 42 cse pass 8.6 \nrohini 21 ece fail 3.2 \naman 23 cse pass 8.9 \nrahul 45 ee fail 4.6 \npratik 65 cse pass 7.2 \nraunak 23 me pass 9.1 \nsuvam 68 me pass 8.2 \n_______________________________________________\nCustom Separator here semi-colon\n\nname rollno department result cgpa \namar 42 cse pass 8.6 \nrohini 21 ece fail 3.2 \naman 23 cse pass 8.9 \nrahul 45 ee fail 4.6 \npratik 65 cse pass 7.2 \nraunak 23 me pass 9.1 \nsuvam 68 me pass 8.2 \n_______________________________________________"
},
{
"code": null,
"e": 36063,
"s": 35918,
"text": "In future articles, we will include more Operations on CSV file using OpenCSV. References: CSVReader class Documentation, OpenCSV Documentation "
},
{
"code": null,
"e": 36078,
"s": 36063,
"text": "Arijeet Bhakat"
},
{
"code": null,
"e": 36090,
"s": 36078,
"text": "anikakapoor"
},
{
"code": null,
"e": 36103,
"s": 36090,
"text": "simmytarika5"
},
{
"code": null,
"e": 36109,
"s": 36103,
"text": "GBlog"
},
{
"code": null,
"e": 36114,
"s": 36109,
"text": "Java"
},
{
"code": null,
"e": 36119,
"s": 36114,
"text": "Java"
},
{
"code": null,
"e": 36217,
"s": 36119,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 36226,
"s": 36217,
"text": "Comments"
},
{
"code": null,
"e": 36239,
"s": 36226,
"text": "Old Comments"
},
{
"code": null,
"e": 36295,
"s": 36239,
"text": "Top 10 Front End Developer Skills That You Need in 2022"
},
{
"code": null,
"e": 36320,
"s": 36295,
"text": "DSA Sheet by Love Babbar"
},
{
"code": null,
"e": 36355,
"s": 36320,
"text": "GET and POST requests using Python"
},
{
"code": null,
"e": 36387,
"s": 36355,
"text": "6 Best IDE's For Python in 2022"
},
{
"code": null,
"e": 36449,
"s": 36387,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 36464,
"s": 36449,
"text": "Arrays in Java"
},
{
"code": null,
"e": 36508,
"s": 36464,
"text": "Split() String method in Java with examples"
},
{
"code": null,
"e": 36530,
"s": 36508,
"text": "For-each loop in Java"
},
{
"code": null,
"e": 36555,
"s": 36530,
"text": "Reverse a string in Java"
}
] |
Stop Installing Tensorflow using pip for performance sake! | by Michael Phi | Towards Data Science | Stop installing Tensorflow using pip! Use conda instead. If you donβt know what conda is, itβs an open source package and environment management system that runs cross-platform. So it works on Mac, Windows, and Linux. If you arenβt already using conda, I recommend that you start as it makes managing your data science tools much more enjoyable.
Here are two pretty big reasons why you should install Tensorflow using conda instead of pip.
The conda Tensorflow packages leverage the Intel Math Kernel Library for Deep Neural Networks or the MKL-DNN starting with version 1.9.0. This library gives a huge performance boost. Here is a chart to prove it!
As you can see, the performance of the conda installation can give over 8X the speed boost compared to the pip installation. That is great for people who still frequently use their CPU for training and inferencing. As a Machine Learning Engineer, I use my CPU to run a test train on my code before pushing it to a GPU enabled machine. This increase in speed will help me iterate faster. I also do a lot of inference on a CPU when I can, so this will help my models performance.
Not only does the MKL library speed up your Tensorflow packages, it also speeds up other widely used libraries like NumPy, NumpyExr, SciPy, and Scikit-Learn! See how you can get that set up from links below.
The conda install will automatically install the CUDA and CuDNN libraries needed for GPU support. The pip install will require you to do that manually. Everybody likes a one step process, especially when it comes to downloading libraries.
So I hope those two reasons are good enough for you to switch over to using conda. If youβre convinced here are the steps to get started.
pip uninstall tensorflow
Install Anaconda or Miniconda if you havenβt already. Miniconda is just installing conda and itβs dependencies while Anaconda will pre-install a lot of packages for you. I prefer Miniconda to get started. After conda is installed try this.
conda install tensorflow
Replace tensorflow with tensorflow-gpu if you want the GPU enabled version.
Besides being faster and simpler to use for Tensorflow, conda provides other sets of tools that makes it so much easier to integrate into your workflow. One of my favorites is their virtual environment features. You can read more about conda and tensorflow here. And more on the MKL optimization here. Hope this helps and as always, thanks for reading!
I write many more posts like this! if you enjoy this, check out my other content at micahelphi.com
βπ½ Want more Content? Check out my blog at https://www.michaelphi.com
πΊ Like to watch project-based videos? Check out my Youtube!
π₯ Stay up to date on articles and videos by signing up for my email newsletter! | [
{
"code": null,
"e": 392,
"s": 46,
"text": "Stop installing Tensorflow using pip! Use conda instead. If you donβt know what conda is, itβs an open source package and environment management system that runs cross-platform. So it works on Mac, Windows, and Linux. If you arenβt already using conda, I recommend that you start as it makes managing your data science tools much more enjoyable."
},
{
"code": null,
"e": 486,
"s": 392,
"text": "Here are two pretty big reasons why you should install Tensorflow using conda instead of pip."
},
{
"code": null,
"e": 698,
"s": 486,
"text": "The conda Tensorflow packages leverage the Intel Math Kernel Library for Deep Neural Networks or the MKL-DNN starting with version 1.9.0. This library gives a huge performance boost. Here is a chart to prove it!"
},
{
"code": null,
"e": 1176,
"s": 698,
"text": "As you can see, the performance of the conda installation can give over 8X the speed boost compared to the pip installation. That is great for people who still frequently use their CPU for training and inferencing. As a Machine Learning Engineer, I use my CPU to run a test train on my code before pushing it to a GPU enabled machine. This increase in speed will help me iterate faster. I also do a lot of inference on a CPU when I can, so this will help my models performance."
},
{
"code": null,
"e": 1384,
"s": 1176,
"text": "Not only does the MKL library speed up your Tensorflow packages, it also speeds up other widely used libraries like NumPy, NumpyExr, SciPy, and Scikit-Learn! See how you can get that set up from links below."
},
{
"code": null,
"e": 1623,
"s": 1384,
"text": "The conda install will automatically install the CUDA and CuDNN libraries needed for GPU support. The pip install will require you to do that manually. Everybody likes a one step process, especially when it comes to downloading libraries."
},
{
"code": null,
"e": 1761,
"s": 1623,
"text": "So I hope those two reasons are good enough for you to switch over to using conda. If youβre convinced here are the steps to get started."
},
{
"code": null,
"e": 1786,
"s": 1761,
"text": "pip uninstall tensorflow"
},
{
"code": null,
"e": 2026,
"s": 1786,
"text": "Install Anaconda or Miniconda if you havenβt already. Miniconda is just installing conda and itβs dependencies while Anaconda will pre-install a lot of packages for you. I prefer Miniconda to get started. After conda is installed try this."
},
{
"code": null,
"e": 2051,
"s": 2026,
"text": "conda install tensorflow"
},
{
"code": null,
"e": 2127,
"s": 2051,
"text": "Replace tensorflow with tensorflow-gpu if you want the GPU enabled version."
},
{
"code": null,
"e": 2480,
"s": 2127,
"text": "Besides being faster and simpler to use for Tensorflow, conda provides other sets of tools that makes it so much easier to integrate into your workflow. One of my favorites is their virtual environment features. You can read more about conda and tensorflow here. And more on the MKL optimization here. Hope this helps and as always, thanks for reading!"
},
{
"code": null,
"e": 2579,
"s": 2480,
"text": "I write many more posts like this! if you enjoy this, check out my other content at micahelphi.com"
},
{
"code": null,
"e": 2649,
"s": 2579,
"text": "βπ½ Want more Content? Check out my blog at https://www.michaelphi.com"
},
{
"code": null,
"e": 2709,
"s": 2649,
"text": "πΊ Like to watch project-based videos? Check out my Youtube!"
}
] |
Python - Normal Distribution in Statistics - GeeksforGeeks | 10 Jan, 2020
scipy.stats.norm() is a normal continuous random variable. It is inherited from the of generic methods as an instance of the rv_continuous class. It completes the methods with details specific for this particular distribution.
Parameters :
q : lower and upper tail probabilityx : quantilesloc : [optional]location parameter. Default = 0scale : [optional]scale parameter. Default = 1size : [tuple of ints, optional] shape or random variates.moments : [optional] composed of letters [βmvskβ]; βmβ = mean, βvβ = variance, βsβ = Fisherβs skew and βkβ = Fisherβs kurtosis. (default = βmvβ).
Results : normal continuous random variable
Code #1 : Creating normal continuous random variable
# importing library from scipy.stats import norm numargs = norm.numargs a, b = 4.32, 3.18rv = norm(a, b) print ("RV : \n", rv)
Output :
RV :
scipy.stats._distn_infrastructure.rv_frozen object at 0x000002A9D81635C8
Code #2 : normal continuous variates and probability distribution
import numpy as np quantile = np.arange (0.01, 1, 0.1) # Random Variates R = norm.rvs(a, b) print ("Random Variates : \n", R) # PDF R = norm.pdf(a, b, quantile) print ("\nProbability Distribution : \n", R)
Output :
Random Variates :
8.848528530091645
Probability Distribution :
[0.00000000e+00 1.72515030e-23 7.57695185e-07 1.48928058e-03
2.03862091e-02 6.43213365e-02 1.14069546e-01 1.54822160e-01
1.82936660e-01 2.00024445e-01]
Code #3 : Graphical Representation.
import numpy as np import matplotlib.pyplot as plt distribution = np.linspace(0, np.minimum(rv.dist.b, 3)) print("Distribution : \n", distribution) plot = plt.plot(distribution, rv.pdf(distribution))
Output :
Distribution :
[0. 0.04081633 0.08163265 0.12244898 0.16326531 0.20408163
0.24489796 0.28571429 0.32653061 0.36734694 0.40816327 0.44897959
0.48979592 0.53061224 0.57142857 0.6122449 0.65306122 0.69387755
0.73469388 0.7755102 0.81632653 0.85714286 0.89795918 0.93877551
0.97959184 1.02040816 1.06122449 1.10204082 1.14285714 1.18367347
1.2244898 1.26530612 1.30612245 1.34693878 1.3877551 1.42857143
1.46938776 1.51020408 1.55102041 1.59183673 1.63265306 1.67346939
1.71428571 1.75510204 1.79591837 1.83673469 1.87755102 1.91836735
1.95918367 2. ]
Code #4 : Varying Positional Arguments
import matplotlib.pyplot as plt import numpy as np x = np.linspace(0, 5, 100) # Varying positional arguments y1 = norm .pdf(x, 1, 3, 5) y2 = norm .pdf(x, 1, 4, 4) plt.plot(x, y1, "*", x, y2, "r--")
Output :
Python scipy-stats-functions
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
Enumerate() in Python
Read a file line by line in Python
Defaultdict in Python
Different ways to create Pandas Dataframe
sum() function in Python
Iterate over a list in Python
Deque in Python
How to Install PIP on Windows ?
Python String | replace() | [
{
"code": null,
"e": 23941,
"s": 23913,
"text": "\n10 Jan, 2020"
},
{
"code": null,
"e": 24168,
"s": 23941,
"text": "scipy.stats.norm() is a normal continuous random variable. It is inherited from the of generic methods as an instance of the rv_continuous class. It completes the methods with details specific for this particular distribution."
},
{
"code": null,
"e": 24181,
"s": 24168,
"text": "Parameters :"
},
{
"code": null,
"e": 24527,
"s": 24181,
"text": "q : lower and upper tail probabilityx : quantilesloc : [optional]location parameter. Default = 0scale : [optional]scale parameter. Default = 1size : [tuple of ints, optional] shape or random variates.moments : [optional] composed of letters [βmvskβ]; βmβ = mean, βvβ = variance, βsβ = Fisherβs skew and βkβ = Fisherβs kurtosis. (default = βmvβ)."
},
{
"code": null,
"e": 24571,
"s": 24527,
"text": "Results : normal continuous random variable"
},
{
"code": null,
"e": 24624,
"s": 24571,
"text": "Code #1 : Creating normal continuous random variable"
},
{
"code": "# importing library from scipy.stats import norm numargs = norm.numargs a, b = 4.32, 3.18rv = norm(a, b) print (\"RV : \\n\", rv) ",
"e": 24761,
"s": 24624,
"text": null
},
{
"code": null,
"e": 24770,
"s": 24761,
"text": "Output :"
},
{
"code": null,
"e": 24851,
"s": 24770,
"text": "RV : \n scipy.stats._distn_infrastructure.rv_frozen object at 0x000002A9D81635C8\n"
},
{
"code": null,
"e": 24917,
"s": 24851,
"text": "Code #2 : normal continuous variates and probability distribution"
},
{
"code": "import numpy as np quantile = np.arange (0.01, 1, 0.1) # Random Variates R = norm.rvs(a, b) print (\"Random Variates : \\n\", R) # PDF R = norm.pdf(a, b, quantile) print (\"\\nProbability Distribution : \\n\", R) ",
"e": 25128,
"s": 24917,
"text": null
},
{
"code": null,
"e": 25137,
"s": 25128,
"text": "Output :"
},
{
"code": null,
"e": 25362,
"s": 25137,
"text": "Random Variates : \n 8.848528530091645\n\nProbability Distribution : \n [0.00000000e+00 1.72515030e-23 7.57695185e-07 1.48928058e-03\n 2.03862091e-02 6.43213365e-02 1.14069546e-01 1.54822160e-01\n 1.82936660e-01 2.00024445e-01]\n \n"
},
{
"code": null,
"e": 25398,
"s": 25362,
"text": "Code #3 : Graphical Representation."
},
{
"code": "import numpy as np import matplotlib.pyplot as plt distribution = np.linspace(0, np.minimum(rv.dist.b, 3)) print(\"Distribution : \\n\", distribution) plot = plt.plot(distribution, rv.pdf(distribution)) ",
"e": 25609,
"s": 25398,
"text": null
},
{
"code": null,
"e": 25618,
"s": 25609,
"text": "Output :"
},
{
"code": null,
"e": 26197,
"s": 25618,
"text": "Distribution : \n [0. 0.04081633 0.08163265 0.12244898 0.16326531 0.20408163\n 0.24489796 0.28571429 0.32653061 0.36734694 0.40816327 0.44897959\n 0.48979592 0.53061224 0.57142857 0.6122449 0.65306122 0.69387755\n 0.73469388 0.7755102 0.81632653 0.85714286 0.89795918 0.93877551\n 0.97959184 1.02040816 1.06122449 1.10204082 1.14285714 1.18367347\n 1.2244898 1.26530612 1.30612245 1.34693878 1.3877551 1.42857143\n 1.46938776 1.51020408 1.55102041 1.59183673 1.63265306 1.67346939\n 1.71428571 1.75510204 1.79591837 1.83673469 1.87755102 1.91836735\n 1.95918367 2. ]\n "
},
{
"code": null,
"e": 26236,
"s": 26197,
"text": "Code #4 : Varying Positional Arguments"
},
{
"code": "import matplotlib.pyplot as plt import numpy as np x = np.linspace(0, 5, 100) # Varying positional arguments y1 = norm .pdf(x, 1, 3, 5) y2 = norm .pdf(x, 1, 4, 4) plt.plot(x, y1, \"*\", x, y2, \"r--\") ",
"e": 26445,
"s": 26236,
"text": null
},
{
"code": null,
"e": 26454,
"s": 26445,
"text": "Output :"
},
{
"code": null,
"e": 26483,
"s": 26454,
"text": "Python scipy-stats-functions"
},
{
"code": null,
"e": 26490,
"s": 26483,
"text": "Python"
},
{
"code": null,
"e": 26588,
"s": 26490,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26597,
"s": 26588,
"text": "Comments"
},
{
"code": null,
"e": 26610,
"s": 26597,
"text": "Old Comments"
},
{
"code": null,
"e": 26628,
"s": 26610,
"text": "Python Dictionary"
},
{
"code": null,
"e": 26650,
"s": 26628,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 26685,
"s": 26650,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 26707,
"s": 26685,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 26749,
"s": 26707,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 26774,
"s": 26749,
"text": "sum() function in Python"
},
{
"code": null,
"e": 26804,
"s": 26774,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 26820,
"s": 26804,
"text": "Deque in Python"
},
{
"code": null,
"e": 26852,
"s": 26820,
"text": "How to Install PIP on Windows ?"
}
] |
How to add CSS properties to an element dynamically using jQuery ? - GeeksforGeeks | 24 Mar, 2021
In this article, we will see how to add some CSS properties dynamically using jQuery. To add CSS properties dynamically, we use css() method. The css() method is used to change style property of the selected element.
The css() method can be used in different ways. This method can also be used to check the present value of the property for the selected element:
Syntax:
$(selector).css(property)
Here we have created two elements inside body tag i.e. <h1> and <h3> elements. We apply CSS property on <body> tag and <h1> tag using css() method dynamically.
Example:
HTML
<!DOCTYpe html><html> <head> <title> How to add CSS properties to an element dynamically using jQuery? </title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"> </script> <script> $(document).ready(function () { $("body").css("text-align", "center"); $("h1").css("color", "green"); }); </script></head> <body> <h1>GeeksforGeeks</h1> <h3> How to add CSS properties to an element <br>dynamically using jQuery? </h3></body> </html>
Output:
HTML-Questions
HTML-Tags
jQuery-Methods
jQuery-Questions
JQuery
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to prevent Body from scrolling when a modal is opened using jQuery ?
jQuery | ajax() Method
Difference Between JavaScript and jQuery
How to get the value in an input text box using jQuery ?
jQuery | parent() & parents() with Examples
Top 10 Front End Developer Skills That You Need in 2022
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS? | [
{
"code": null,
"e": 25364,
"s": 25336,
"text": "\n24 Mar, 2021"
},
{
"code": null,
"e": 25582,
"s": 25364,
"text": "In this article, we will see how to add some CSS properties dynamically using jQuery. To add CSS properties dynamically, we use css() method. The css() method is used to change style property of the selected element. "
},
{
"code": null,
"e": 25728,
"s": 25582,
"text": "The css() method can be used in different ways. This method can also be used to check the present value of the property for the selected element:"
},
{
"code": null,
"e": 25736,
"s": 25728,
"text": "Syntax:"
},
{
"code": null,
"e": 25762,
"s": 25736,
"text": "$(selector).css(property)"
},
{
"code": null,
"e": 25922,
"s": 25762,
"text": "Here we have created two elements inside body tag i.e. <h1> and <h3> elements. We apply CSS property on <body> tag and <h1> tag using css() method dynamically."
},
{
"code": null,
"e": 25931,
"s": 25922,
"text": "Example:"
},
{
"code": null,
"e": 25936,
"s": 25931,
"text": "HTML"
},
{
"code": "<!DOCTYpe html><html> <head> <title> How to add CSS properties to an element dynamically using jQuery? </title> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"> </script> <script> $(document).ready(function () { $(\"body\").css(\"text-align\", \"center\"); $(\"h1\").css(\"color\", \"green\"); }); </script></head> <body> <h1>GeeksforGeeks</h1> <h3> How to add CSS properties to an element <br>dynamically using jQuery? </h3></body> </html>",
"e": 26496,
"s": 25936,
"text": null
},
{
"code": null,
"e": 26504,
"s": 26496,
"text": "Output:"
},
{
"code": null,
"e": 26519,
"s": 26504,
"text": "HTML-Questions"
},
{
"code": null,
"e": 26529,
"s": 26519,
"text": "HTML-Tags"
},
{
"code": null,
"e": 26544,
"s": 26529,
"text": "jQuery-Methods"
},
{
"code": null,
"e": 26561,
"s": 26544,
"text": "jQuery-Questions"
},
{
"code": null,
"e": 26568,
"s": 26561,
"text": "JQuery"
},
{
"code": null,
"e": 26585,
"s": 26568,
"text": "Web Technologies"
},
{
"code": null,
"e": 26683,
"s": 26585,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26692,
"s": 26683,
"text": "Comments"
},
{
"code": null,
"e": 26705,
"s": 26692,
"text": "Old Comments"
},
{
"code": null,
"e": 26778,
"s": 26705,
"text": "How to prevent Body from scrolling when a modal is opened using jQuery ?"
},
{
"code": null,
"e": 26801,
"s": 26778,
"text": "jQuery | ajax() Method"
},
{
"code": null,
"e": 26842,
"s": 26801,
"text": "Difference Between JavaScript and jQuery"
},
{
"code": null,
"e": 26899,
"s": 26842,
"text": "How to get the value in an input text box using jQuery ?"
},
{
"code": null,
"e": 26943,
"s": 26899,
"text": "jQuery | parent() & parents() with Examples"
},
{
"code": null,
"e": 26999,
"s": 26943,
"text": "Top 10 Front End Developer Skills That You Need in 2022"
},
{
"code": null,
"e": 27032,
"s": 26999,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 27094,
"s": 27032,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 27137,
"s": 27094,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
What is the difference between break and continue statements in C#? | The break statement terminates the loop and transfers execution to the statement immediately following the loop.
The continue statement causes the loop to skip the remainder of its body and immediately retest its condition prior to reiterating.
When the break statement is encountered inside a loop, the loop is immediately terminated and program control resumes at the next statement following the loop.
The continue statement in C# works somewhat like the break statement. Instead of forcing termination, however, continue forces the next iteration of the loop to take place, skipping any code in between.
The following is the complete code to use continue statement in a while loop β
using System;
namespace Demo {
class Program {
static void Main(string[] args) {
/* local variable definition */
int a = 10;
/* loop execution */
while (a > 20) {
if (a == 15) {
/* skip the iteration */
a = a + 1;
continue;
}
Console.WriteLine("value of a: {0}", a);
a++;
}
Console.ReadLine();
}
}
}
The following is an example of break statement β
using System;
namespace Demo {
class Program {
static void Main(string[] args) {
/* local variable definition */
int a = 10;
/* while loop execution */
while (a < 20) {
Console.WriteLine("value of a: {0}", a);
a++;
if (a > 15) {
/* terminate the loop using break statement */
break;
}
}
Console.ReadLine();
}
}
} | [
{
"code": null,
"e": 1175,
"s": 1062,
"text": "The break statement terminates the loop and transfers execution to the statement immediately following the loop."
},
{
"code": null,
"e": 1307,
"s": 1175,
"text": "The continue statement causes the loop to skip the remainder of its body and immediately retest its condition prior to reiterating."
},
{
"code": null,
"e": 1467,
"s": 1307,
"text": "When the break statement is encountered inside a loop, the loop is immediately terminated and program control resumes at the next statement following the loop."
},
{
"code": null,
"e": 1670,
"s": 1467,
"text": "The continue statement in C# works somewhat like the break statement. Instead of forcing termination, however, continue forces the next iteration of the loop to take place, skipping any code in between."
},
{
"code": null,
"e": 1749,
"s": 1670,
"text": "The following is the complete code to use continue statement in a while loop β"
},
{
"code": null,
"e": 2216,
"s": 1749,
"text": "using System;\nnamespace Demo {\n class Program {\n static void Main(string[] args) {\n\n /* local variable definition */\n int a = 10;\n\n /* loop execution */\n while (a > 20) {\n if (a == 15) {\n /* skip the iteration */\n a = a + 1;\n continue;\n }\n Console.WriteLine(\"value of a: {0}\", a);\n a++;\n }\n Console.ReadLine();\n }\n }\n}"
},
{
"code": null,
"e": 2265,
"s": 2216,
"text": "The following is an example of break statement β"
},
{
"code": null,
"e": 2730,
"s": 2265,
"text": "using System;\nnamespace Demo {\n class Program {\n static void Main(string[] args) {\n /* local variable definition */\n int a = 10;\n\n /* while loop execution */\n while (a < 20) {\n Console.WriteLine(\"value of a: {0}\", a);\n a++;\n\n if (a > 15) {\n /* terminate the loop using break statement */\n break;\n }\n }\n Console.ReadLine();\n }\n }\n}"
}
] |
JavaFX - Pie Chart | A pie-chart is a representation of values as slices of a circle with different colors. These slices are labeled and the values corresponding to each slice is represented in the chart.
Following is a Pie Chart depicting the mobile sales of various companies at an instance.
In JavaFX, a pie chart is represented by a class named PieChart. This class belongs to the package javafx.scene.chart.
By instantiating this class, you can create a PieChart node in JavaFX.
This class has 5 properties which are as follows β
clockwise β This is a Boolean Operator; on setting this operator true, the data slices in the pie charts will be arranged clockwise starting from the start angle of the pie chart.
clockwise β This is a Boolean Operator; on setting this operator true, the data slices in the pie charts will be arranged clockwise starting from the start angle of the pie chart.
data β This represents an ObservableList object, which holds the data of the pie chart.
data β This represents an ObservableList object, which holds the data of the pie chart.
labelLineLength β An integer operator representing the length of the lines connecting the labels and the slices of the pie chart.
labelLineLength β An integer operator representing the length of the lines connecting the labels and the slices of the pie chart.
labelsVisible β This is a Boolean Operator; on setting this operator true, the labels for the pie charts will be drawn. By default, this operator is set to be true.
labelsVisible β This is a Boolean Operator; on setting this operator true, the labels for the pie charts will be drawn. By default, this operator is set to be true.
startAngle β This is a double type operator, which represents the angle to start the first pie slice at.
startAngle β This is a double type operator, which represents the angle to start the first pie slice at.
To generate a pie chart, Prepare an ObservableList object as shown in the following code block β
//Preparing ObservbleList object
ObservableList<PieChart.Data> pieChartData = FXCollections.observableArrayList(
new PieChart.Data("Iphone 5S", 13),
new PieChart.Data("Samsung Grand", 25),
new PieChart.Data("MOTO G", 10),
new PieChart.Data("Nokia Lumia", 22));
After preparing the ObservableList object, pass it as an argument to the constructor of the class PieChart as follows β
//Creating a Pie chart
PieChart pieChart = new PieChart(pieChartData);
Or, by using the method named setData() of the class named PieChart of the package named javafx.scene.chart.
pieChart.setData(pieChartData);
To generate a PieChart in JavaFX, follow the steps given below.
Create a Java class and inherit the Application class of the package javafx.application and implement the start() method of this class as follows.
public class ClassName extends Application {
@Override
public void start(Stage primaryStage) throws Exception {
}
}
Prepare an object of the interface ObservableList object by passing the data of the pie chart as shown below β
ObservableList<PieChart.Data> pieChartData = FXCollections.observableArrayList(
new PieChart.Data("Iphone 5S", 13),
new PieChart.Data("Samsung Grand", 25),
new PieChart.Data("MOTO G", 10),
new PieChart.Data("Nokia Lumia", 22));
Create a PieChart by passing the ObservableList object as shown below.
//Creating a Pie chart
PieChart pieChart = new PieChart(pieChartData);
Set the title of the Pie Chart using the setTitle() method of the class PieChart. This belongs to the package javafx.scene.chart β
//Setting the title of the Pie chart
pieChart.setTitle("Mobile Sales");
Set the slices of the Pie Charts clockwise. This is done by passing Boolean value true to the setClockwise() method of the class PieChart. This belongs to the package javafx.scene.chart β
//setting the direction to arrange the data
pieChart.setClockwise(true);
Set the length of the label line using the setLabelLineLength() method of the class PieChart which belongs to the package javafx.scene.chart, as follows β
//Setting the length of the label line
pieChart.setLabelLineLength(50);
Set the labels of the pie chart to visible by passing the Boolean value true to the method setLabelsVisible() of the class PieChart. This belongs to the package javafx.scene.chart β
//Setting the labels of the pie chart visible
pieChart.setLabelsVisible(true);
Set the Start angle of the pie chart using the setStartAngle() method of the class PieChart. This belongs to the package javafx.scene.chart β
//Setting the start angle of the pie chart
pieChart.setStartAngle(180);
In the start() method, create a group object by instantiating the class named Group. This belongs to the package javafx.scene.
Pass the PieChart (node) object, created in the previous step as a parameter to the constructor of the Group class. This should be done in order to add it to the group as follows β
Group root = new Group(piechart);
Create a Scene by instantiating the class named Scene, which belongs to the package javafx.scene. To this class, pass the Group object (root) created in the previous step.
In addition to the root object, you can also pass two double parameters representing height and width of the screen, along with the object of the Group class as shown below.
Scene scene = new Scene(group ,600, 300);
You can set the title to the stage using the setTitle() method of the Stage class. The primaryStage is a Stage Object, which is passed to the start method of the scene class as a parameter.
Using the primaryStage object, set the title of the scene as Sample Application as follows.
primaryStage.setTitle("Sample Application");
You can add a Scene object to the stage using the method setScene() of the class named Stage. Add the Scene object prepared in the previous steps using this method as shown below.
primaryStage.setScene(scene);
Display the contents of the scene using the method named show() of the Stage class as follows.
primaryStage.show();
Launch the JavaFX application by calling the static method launch() of the Application class from the main method as follows.
public static void main(String args[]){
launch(args);
}
The table given below depicts mobile sale with the help of a pie chart. The following table has a list of different mobile brands and their sale (units per day).
Following is a Java program which generates a pie chart, depicting the above data using JavaFX. Save this code in a file with the name PieChartExample.java.
import javafx.application.Application;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.stage.Stage;
import javafx.scene.chart.PieChart;
public class PieChartExample extends Application {
@Override
public void start(Stage stage) {
//Preparing ObservbleList object
ObservableList<PieChart.Data> pieChartData = FXCollections.observableArrayList(
new PieChart.Data("Iphone 5S", 13),
new PieChart.Data("Samsung Grand", 25),
new PieChart.Data("MOTO G", 10),
new PieChart.Data("Nokia Lumia", 22));
//Creating a Pie chart
PieChart pieChart = new PieChart(pieChartData);
//Setting the title of the Pie chart
pieChart.setTitle("Mobile Sales");
//setting the direction to arrange the data
pieChart.setClockwise(true);
//Setting the length of the label line
pieChart.setLabelLineLength(50);
//Setting the labels of the pie chart visible
pieChart.setLabelsVisible(true);
//Setting the start angle of the pie chart
pieChart.setStartAngle(180);
//Creating a Group object
Group root = new Group(pieChart);
//Creating a scene object
Scene scene = new Scene(root, 600, 400);
//Setting title to the Stage
stage.setTitle("Pie chart");
//Adding scene to the stage
stage.setScene(scene);
//Displaying the contents of the stage
stage.show();
}
public static void main(String args[]){
launch(args);
}
}
Compile and execute the saved java file from the command prompt using the following commands.
javac PieChartExample.java
java PieChartExample
On executing, the above program generates a JavaFX window displaying a pie chart as shown below.
33 Lectures
7.5 hours
Syed Raza
64 Lectures
12.5 hours
Emenwa Global, Ejike IfeanyiChukwu
20 Lectures
4 hours
Emenwa Global, Ejike IfeanyiChukwu
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2084,
"s": 1900,
"text": "A pie-chart is a representation of values as slices of a circle with different colors. These slices are labeled and the values corresponding to each slice is represented in the chart."
},
{
"code": null,
"e": 2173,
"s": 2084,
"text": "Following is a Pie Chart depicting the mobile sales of various companies at an instance."
},
{
"code": null,
"e": 2292,
"s": 2173,
"text": "In JavaFX, a pie chart is represented by a class named PieChart. This class belongs to the package javafx.scene.chart."
},
{
"code": null,
"e": 2363,
"s": 2292,
"text": "By instantiating this class, you can create a PieChart node in JavaFX."
},
{
"code": null,
"e": 2414,
"s": 2363,
"text": "This class has 5 properties which are as follows β"
},
{
"code": null,
"e": 2594,
"s": 2414,
"text": "clockwise β This is a Boolean Operator; on setting this operator true, the data slices in the pie charts will be arranged clockwise starting from the start angle of the pie chart."
},
{
"code": null,
"e": 2774,
"s": 2594,
"text": "clockwise β This is a Boolean Operator; on setting this operator true, the data slices in the pie charts will be arranged clockwise starting from the start angle of the pie chart."
},
{
"code": null,
"e": 2862,
"s": 2774,
"text": "data β This represents an ObservableList object, which holds the data of the pie chart."
},
{
"code": null,
"e": 2950,
"s": 2862,
"text": "data β This represents an ObservableList object, which holds the data of the pie chart."
},
{
"code": null,
"e": 3080,
"s": 2950,
"text": "labelLineLength β An integer operator representing the length of the lines connecting the labels and the slices of the pie chart."
},
{
"code": null,
"e": 3210,
"s": 3080,
"text": "labelLineLength β An integer operator representing the length of the lines connecting the labels and the slices of the pie chart."
},
{
"code": null,
"e": 3375,
"s": 3210,
"text": "labelsVisible β This is a Boolean Operator; on setting this operator true, the labels for the pie charts will be drawn. By default, this operator is set to be true."
},
{
"code": null,
"e": 3540,
"s": 3375,
"text": "labelsVisible β This is a Boolean Operator; on setting this operator true, the labels for the pie charts will be drawn. By default, this operator is set to be true."
},
{
"code": null,
"e": 3645,
"s": 3540,
"text": "startAngle β This is a double type operator, which represents the angle to start the first pie slice at."
},
{
"code": null,
"e": 3750,
"s": 3645,
"text": "startAngle β This is a double type operator, which represents the angle to start the first pie slice at."
},
{
"code": null,
"e": 3847,
"s": 3750,
"text": "To generate a pie chart, Prepare an ObservableList object as shown in the following code block β"
},
{
"code": null,
"e": 4135,
"s": 3847,
"text": "//Preparing ObservbleList object \nObservableList<PieChart.Data> pieChartData = FXCollections.observableArrayList( \n new PieChart.Data(\"Iphone 5S\", 13), \n new PieChart.Data(\"Samsung Grand\", 25), \n new PieChart.Data(\"MOTO G\", 10), \n new PieChart.Data(\"Nokia Lumia\", 22)); \n"
},
{
"code": null,
"e": 4255,
"s": 4135,
"text": "After preparing the ObservableList object, pass it as an argument to the constructor of the class PieChart as follows β"
},
{
"code": null,
"e": 4328,
"s": 4255,
"text": "//Creating a Pie chart \nPieChart pieChart = new PieChart(pieChartData);\n"
},
{
"code": null,
"e": 4437,
"s": 4328,
"text": "Or, by using the method named setData() of the class named PieChart of the package named javafx.scene.chart."
},
{
"code": null,
"e": 4470,
"s": 4437,
"text": "pieChart.setData(pieChartData);\n"
},
{
"code": null,
"e": 4534,
"s": 4470,
"text": "To generate a PieChart in JavaFX, follow the steps given below."
},
{
"code": null,
"e": 4681,
"s": 4534,
"text": "Create a Java class and inherit the Application class of the package javafx.application and implement the start() method of this class as follows."
},
{
"code": null,
"e": 4822,
"s": 4681,
"text": "public class ClassName extends Application { \n @Override \n public void start(Stage primaryStage) throws Exception { \n } \n}"
},
{
"code": null,
"e": 4933,
"s": 4822,
"text": "Prepare an object of the interface ObservableList object by passing the data of the pie chart as shown below β"
},
{
"code": null,
"e": 5178,
"s": 4933,
"text": "ObservableList<PieChart.Data> pieChartData = FXCollections.observableArrayList( \n new PieChart.Data(\"Iphone 5S\", 13), \n new PieChart.Data(\"Samsung Grand\", 25), \n new PieChart.Data(\"MOTO G\", 10), \n new PieChart.Data(\"Nokia Lumia\", 22));\n"
},
{
"code": null,
"e": 5249,
"s": 5178,
"text": "Create a PieChart by passing the ObservableList object as shown below."
},
{
"code": null,
"e": 5322,
"s": 5249,
"text": "//Creating a Pie chart \nPieChart pieChart = new PieChart(pieChartData);\n"
},
{
"code": null,
"e": 5453,
"s": 5322,
"text": "Set the title of the Pie Chart using the setTitle() method of the class PieChart. This belongs to the package javafx.scene.chart β"
},
{
"code": null,
"e": 5527,
"s": 5453,
"text": "//Setting the title of the Pie chart \npieChart.setTitle(\"Mobile Sales\");\n"
},
{
"code": null,
"e": 5715,
"s": 5527,
"text": "Set the slices of the Pie Charts clockwise. This is done by passing Boolean value true to the setClockwise() method of the class PieChart. This belongs to the package javafx.scene.chart β"
},
{
"code": null,
"e": 5790,
"s": 5715,
"text": "//setting the direction to arrange the data \npieChart.setClockwise(true);\n"
},
{
"code": null,
"e": 5945,
"s": 5790,
"text": "Set the length of the label line using the setLabelLineLength() method of the class PieChart which belongs to the package javafx.scene.chart, as follows β"
},
{
"code": null,
"e": 6019,
"s": 5945,
"text": "//Setting the length of the label line \npieChart.setLabelLineLength(50);\n"
},
{
"code": null,
"e": 6201,
"s": 6019,
"text": "Set the labels of the pie chart to visible by passing the Boolean value true to the method setLabelsVisible() of the class PieChart. This belongs to the package javafx.scene.chart β"
},
{
"code": null,
"e": 6283,
"s": 6201,
"text": "//Setting the labels of the pie chart visible \npieChart.setLabelsVisible(true);\n"
},
{
"code": null,
"e": 6425,
"s": 6283,
"text": "Set the Start angle of the pie chart using the setStartAngle() method of the class PieChart. This belongs to the package javafx.scene.chart β"
},
{
"code": null,
"e": 6500,
"s": 6425,
"text": "//Setting the start angle of the pie chart \npieChart.setStartAngle(180); \n"
},
{
"code": null,
"e": 6627,
"s": 6500,
"text": "In the start() method, create a group object by instantiating the class named Group. This belongs to the package javafx.scene."
},
{
"code": null,
"e": 6808,
"s": 6627,
"text": "Pass the PieChart (node) object, created in the previous step as a parameter to the constructor of the Group class. This should be done in order to add it to the group as follows β"
},
{
"code": null,
"e": 6843,
"s": 6808,
"text": "Group root = new Group(piechart);\n"
},
{
"code": null,
"e": 7015,
"s": 6843,
"text": "Create a Scene by instantiating the class named Scene, which belongs to the package javafx.scene. To this class, pass the Group object (root) created in the previous step."
},
{
"code": null,
"e": 7189,
"s": 7015,
"text": "In addition to the root object, you can also pass two double parameters representing height and width of the screen, along with the object of the Group class as shown below."
},
{
"code": null,
"e": 7232,
"s": 7189,
"text": "Scene scene = new Scene(group ,600, 300);\n"
},
{
"code": null,
"e": 7422,
"s": 7232,
"text": "You can set the title to the stage using the setTitle() method of the Stage class. The primaryStage is a Stage Object, which is passed to the start method of the scene class as a parameter."
},
{
"code": null,
"e": 7514,
"s": 7422,
"text": "Using the primaryStage object, set the title of the scene as Sample Application as follows."
},
{
"code": null,
"e": 7560,
"s": 7514,
"text": "primaryStage.setTitle(\"Sample Application\");\n"
},
{
"code": null,
"e": 7740,
"s": 7560,
"text": "You can add a Scene object to the stage using the method setScene() of the class named Stage. Add the Scene object prepared in the previous steps using this method as shown below."
},
{
"code": null,
"e": 7771,
"s": 7740,
"text": "primaryStage.setScene(scene);\n"
},
{
"code": null,
"e": 7866,
"s": 7771,
"text": "Display the contents of the scene using the method named show() of the Stage class as follows."
},
{
"code": null,
"e": 7888,
"s": 7866,
"text": "primaryStage.show();\n"
},
{
"code": null,
"e": 8014,
"s": 7888,
"text": "Launch the JavaFX application by calling the static method launch() of the Application class from the main method as follows."
},
{
"code": null,
"e": 8085,
"s": 8014,
"text": "public static void main(String args[]){ \n launch(args); \n} "
},
{
"code": null,
"e": 8247,
"s": 8085,
"text": "The table given below depicts mobile sale with the help of a pie chart. The following table has a list of different mobile brands and their sale (units per day)."
},
{
"code": null,
"e": 8404,
"s": 8247,
"text": "Following is a Java program which generates a pie chart, depicting the above data using JavaFX. Save this code in a file with the name PieChartExample.java."
},
{
"code": null,
"e": 10164,
"s": 8404,
"text": "import javafx.application.Application; \nimport javafx.collections.FXCollections; \nimport javafx.collections.ObservableList; \nimport javafx.scene.Group; \nimport javafx.scene.Scene; \nimport javafx.stage.Stage; \nimport javafx.scene.chart.PieChart; \n \npublic class PieChartExample extends Application { \n @Override \n public void start(Stage stage) { \n //Preparing ObservbleList object \n ObservableList<PieChart.Data> pieChartData = FXCollections.observableArrayList(\n new PieChart.Data(\"Iphone 5S\", 13), \n new PieChart.Data(\"Samsung Grand\", 25), \n new PieChart.Data(\"MOTO G\", 10), \n new PieChart.Data(\"Nokia Lumia\", 22)); \n \n //Creating a Pie chart \n PieChart pieChart = new PieChart(pieChartData); \n \n //Setting the title of the Pie chart \n pieChart.setTitle(\"Mobile Sales\"); \n \n //setting the direction to arrange the data \n pieChart.setClockwise(true); \n \n //Setting the length of the label line \n pieChart.setLabelLineLength(50); \n\n //Setting the labels of the pie chart visible \n pieChart.setLabelsVisible(true); \n \n //Setting the start angle of the pie chart \n pieChart.setStartAngle(180); \n \n //Creating a Group object \n Group root = new Group(pieChart); \n \n //Creating a scene object \n Scene scene = new Scene(root, 600, 400); \n \n //Setting title to the Stage \n stage.setTitle(\"Pie chart\"); \n \n //Adding scene to the stage \n stage.setScene(scene); \n \n //Displaying the contents of the stage \n stage.show(); \n } \n public static void main(String args[]){ \n launch(args); \n } \n} "
},
{
"code": null,
"e": 10258,
"s": 10164,
"text": "Compile and execute the saved java file from the command prompt using the following commands."
},
{
"code": null,
"e": 10308,
"s": 10258,
"text": "javac PieChartExample.java \njava PieChartExample\n"
},
{
"code": null,
"e": 10405,
"s": 10308,
"text": "On executing, the above program generates a JavaFX window displaying a pie chart as shown below."
},
{
"code": null,
"e": 10440,
"s": 10405,
"text": "\n 33 Lectures \n 7.5 hours \n"
},
{
"code": null,
"e": 10451,
"s": 10440,
"text": " Syed Raza"
},
{
"code": null,
"e": 10487,
"s": 10451,
"text": "\n 64 Lectures \n 12.5 hours \n"
},
{
"code": null,
"e": 10523,
"s": 10487,
"text": " Emenwa Global, Ejike IfeanyiChukwu"
},
{
"code": null,
"e": 10556,
"s": 10523,
"text": "\n 20 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 10592,
"s": 10556,
"text": " Emenwa Global, Ejike IfeanyiChukwu"
},
{
"code": null,
"e": 10599,
"s": 10592,
"text": " Print"
},
{
"code": null,
"e": 10610,
"s": 10599,
"text": " Add Notes"
}
] |
Building Calculator using PyQt5 in Python - GeeksforGeeks | 28 May, 2020
In this article we will see how we can create a calculator using PyQt5,A calculator is something used for making mathematical calculations, in particular a small electronic device with a keyboard and a visual display. below is the how the calculator will looks like
Create a label to show the numbers and the output and set its geometry
Align the label text fro right side and increase the font size of it
Create push buttons for the numbers from 0 to 9 and set their geometry in the proper order
Create operator push button example for addition, subtraction etc
Add a color effect to the equals button to highlight it
Add action to each button
Inside the actions of each button except the equals to action, append the text of the label with the respective number or the operator
Inside the equals to action get the text of the label and start the try except block
Inside the try block use eval method on the label text to get the ans and set the answer to the label
Inside the except block set βWrong Inputβ as text
For delete action make the last character removed from the label and for the clear action set the whole text to blank.
Below is the implementation
# importing librariesfrom PyQt5.QtWidgets import *from PyQt5 import QtCore, QtGuifrom PyQt5.QtGui import *from PyQt5.QtCore import * import sys class Window(QMainWindow): def __init__(self): super().__init__() # setting title self.setWindowTitle("Python ") # setting geometry self.setGeometry(100, 100, 360, 350) # calling method self.UiComponents() # showing all the widgets self.show() # method for widgets def UiComponents(self): # creating a label self.label = QLabel(self) # setting geometry to the label self.label.setGeometry(5, 5, 350, 70) # creating label multi line self.label.setWordWrap(True) # setting style sheet to the label self.label.setStyleSheet("QLabel" "{" "border : 4px solid black;" "background : white;" "}") # setting alignment to the label self.label.setAlignment(Qt.AlignRight) # setting font self.label.setFont(QFont('Arial', 15)) # adding number button to the screen # creating a push button push1 = QPushButton("1", self) # setting geometry push1.setGeometry(5, 150, 80, 40) # creating a push button push2 = QPushButton("2", self) # setting geometry push2.setGeometry(95, 150, 80, 40) # creating a push button push3 = QPushButton("3", self) # setting geometry push3.setGeometry(185, 150, 80, 40) # creating a push button push4 = QPushButton("4", self) # setting geometry push4.setGeometry(5, 200, 80, 40) # creating a push button push5 = QPushButton("5", self) # setting geometry push5.setGeometry(95, 200, 80, 40) # creating a push button push6 = QPushButton("5", self) # setting geometry push6.setGeometry(185, 200, 80, 40) # creating a push button push7 = QPushButton("7", self) # setting geometry push7.setGeometry(5, 250, 80, 40) # creating a push button push8 = QPushButton("8", self) # setting geometry push8.setGeometry(95, 250, 80, 40) # creating a push button push9 = QPushButton("9", self) # setting geometry push9.setGeometry(185, 250, 80, 40) # creating a push button push0 = QPushButton("0", self) # setting geometry push0.setGeometry(5, 300, 80, 40) # adding operator push button # creating push button push_equal = QPushButton("=", self) # setting geometry push_equal.setGeometry(275, 300, 80, 40) # adding equal button a color effect c_effect = QGraphicsColorizeEffect() c_effect.setColor(Qt.blue) push_equal.setGraphicsEffect(c_effect) # creating push button push_plus = QPushButton("+", self) # setting geometry push_plus.setGeometry(275, 250, 80, 40) # creating push button push_minus = QPushButton("-", self) # setting geometry push_minus.setGeometry(275, 200, 80, 40) # creating push button push_mul = QPushButton("*", self) # setting geometry push_mul.setGeometry(275, 150, 80, 40) # creating push button push_div = QPushButton("/", self) # setting geometry push_div.setGeometry(185, 300, 80, 40) # creating push button push_point = QPushButton(".", self) # setting geometry push_point.setGeometry(95, 300, 80, 40) # clear button push_clear = QPushButton("Clear", self) push_clear.setGeometry(5, 100, 200, 40) # del one character button push_del = QPushButton("Del", self) push_del.setGeometry(210, 100, 145, 40) # adding action to each of the button push_minus.clicked.connect(self.action_minus) push_equal.clicked.connect(self.action_equal) push0.clicked.connect(self.action0) push1.clicked.connect(self.action1) push2.clicked.connect(self.action2) push3.clicked.connect(self.action3) push4.clicked.connect(self.action4) push5.clicked.connect(self.action5) push6.clicked.connect(self.action6) push7.clicked.connect(self.action7) push8.clicked.connect(self.action8) push9.clicked.connect(self.action9) push_div.clicked.connect(self.action_div) push_mul.clicked.connect(self.action_mul) push_plus.clicked.connect(self.action_plus) push_point.clicked.connect(self.action_point) push_clear.clicked.connect(self.action_clear) push_del.clicked.connect(self.action_del) def action_equal(self): # get the label text equation = self.label.text() try: # getting the ans ans = eval(equation) # setting text to the label self.label.setText(str(ans)) except: # setting text to the label self.label.setText("Wrong Input") def action_plus(self): # appending label text text = self.label.text() self.label.setText(text + " + ") def action_minus(self): # appending label text text = self.label.text() self.label.setText(text + " - ") def action_div(self): # appending label text text = self.label.text() self.label.setText(text + " / ") def action_mul(self): # appending label text text = self.label.text() self.label.setText(text + " * ") def action_point(self): # appending label text text = self.label.text() self.label.setText(text + ".") def action0(self): # appending label text text = self.label.text() self.label.setText(text + "0") def action1(self): # appending label text text = self.label.text() self.label.setText(text + "1") def action2(self): # appending label text text = self.label.text() self.label.setText(text + "2") def action3(self): # appending label text text = self.label.text() self.label.setText(text + "3") def action4(self): # appending label text text = self.label.text() self.label.setText(text + "4") def action5(self): # appending label text text = self.label.text() self.label.setText(text + "5") def action6(self): # appending label text text = self.label.text() self.label.setText(text + "6") def action7(self): # appending label text text = self.label.text() self.label.setText(text + "7") def action8(self): # appending label text text = self.label.text() self.label.setText(text + "8") def action9(self): # appending label text text = self.label.text() self.label.setText(text + "9") def action_clear(self): # clearing the label text self.label.setText("") def action_del(self): # clearing a single digit text = self.label.text() print(text[:len(text)-1]) self.label.setText(text[:len(text)-1]) # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec())
Output :
Python-PyQt
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Box Plot in Python using Matplotlib
Python | Get dictionary keys as a list
Bar Plot in Matplotlib
Multithreading in Python | Set 2 (Synchronization)
Python Dictionary keys() method
loops in python
Python - Call function from another file
Ways to filter Pandas DataFrame by column values
Python | Convert set into a list
Python program to find number of days between two given dates | [
{
"code": null,
"e": 23927,
"s": 23899,
"text": "\n28 May, 2020"
},
{
"code": null,
"e": 24194,
"s": 23927,
"text": "In this article we will see how we can create a calculator using PyQt5,A calculator is something used for making mathematical calculations, in particular a small electronic device with a keyboard and a visual display. below is the how the calculator will looks like "
},
{
"code": null,
"e": 24266,
"s": 24194,
"text": "Create a label to show the numbers and the output and set its geometry "
},
{
"code": null,
"e": 24336,
"s": 24266,
"text": "Align the label text fro right side and increase the font size of it "
},
{
"code": null,
"e": 24428,
"s": 24336,
"text": "Create push buttons for the numbers from 0 to 9 and set their geometry in the proper order "
},
{
"code": null,
"e": 24495,
"s": 24428,
"text": "Create operator push button example for addition, subtraction etc "
},
{
"code": null,
"e": 24551,
"s": 24495,
"text": "Add a color effect to the equals button to highlight it"
},
{
"code": null,
"e": 24578,
"s": 24551,
"text": "Add action to each button "
},
{
"code": null,
"e": 24714,
"s": 24578,
"text": "Inside the actions of each button except the equals to action, append the text of the label with the respective number or the operator "
},
{
"code": null,
"e": 24800,
"s": 24714,
"text": "Inside the equals to action get the text of the label and start the try except block "
},
{
"code": null,
"e": 24903,
"s": 24800,
"text": "Inside the try block use eval method on the label text to get the ans and set the answer to the label "
},
{
"code": null,
"e": 24954,
"s": 24903,
"text": "Inside the except block set βWrong Inputβ as text "
},
{
"code": null,
"e": 25073,
"s": 24954,
"text": "For delete action make the last character removed from the label and for the clear action set the whole text to blank."
},
{
"code": null,
"e": 25103,
"s": 25073,
"text": "Below is the implementation "
},
{
"code": "# importing librariesfrom PyQt5.QtWidgets import *from PyQt5 import QtCore, QtGuifrom PyQt5.QtGui import *from PyQt5.QtCore import * import sys class Window(QMainWindow): def __init__(self): super().__init__() # setting title self.setWindowTitle(\"Python \") # setting geometry self.setGeometry(100, 100, 360, 350) # calling method self.UiComponents() # showing all the widgets self.show() # method for widgets def UiComponents(self): # creating a label self.label = QLabel(self) # setting geometry to the label self.label.setGeometry(5, 5, 350, 70) # creating label multi line self.label.setWordWrap(True) # setting style sheet to the label self.label.setStyleSheet(\"QLabel\" \"{\" \"border : 4px solid black;\" \"background : white;\" \"}\") # setting alignment to the label self.label.setAlignment(Qt.AlignRight) # setting font self.label.setFont(QFont('Arial', 15)) # adding number button to the screen # creating a push button push1 = QPushButton(\"1\", self) # setting geometry push1.setGeometry(5, 150, 80, 40) # creating a push button push2 = QPushButton(\"2\", self) # setting geometry push2.setGeometry(95, 150, 80, 40) # creating a push button push3 = QPushButton(\"3\", self) # setting geometry push3.setGeometry(185, 150, 80, 40) # creating a push button push4 = QPushButton(\"4\", self) # setting geometry push4.setGeometry(5, 200, 80, 40) # creating a push button push5 = QPushButton(\"5\", self) # setting geometry push5.setGeometry(95, 200, 80, 40) # creating a push button push6 = QPushButton(\"5\", self) # setting geometry push6.setGeometry(185, 200, 80, 40) # creating a push button push7 = QPushButton(\"7\", self) # setting geometry push7.setGeometry(5, 250, 80, 40) # creating a push button push8 = QPushButton(\"8\", self) # setting geometry push8.setGeometry(95, 250, 80, 40) # creating a push button push9 = QPushButton(\"9\", self) # setting geometry push9.setGeometry(185, 250, 80, 40) # creating a push button push0 = QPushButton(\"0\", self) # setting geometry push0.setGeometry(5, 300, 80, 40) # adding operator push button # creating push button push_equal = QPushButton(\"=\", self) # setting geometry push_equal.setGeometry(275, 300, 80, 40) # adding equal button a color effect c_effect = QGraphicsColorizeEffect() c_effect.setColor(Qt.blue) push_equal.setGraphicsEffect(c_effect) # creating push button push_plus = QPushButton(\"+\", self) # setting geometry push_plus.setGeometry(275, 250, 80, 40) # creating push button push_minus = QPushButton(\"-\", self) # setting geometry push_minus.setGeometry(275, 200, 80, 40) # creating push button push_mul = QPushButton(\"*\", self) # setting geometry push_mul.setGeometry(275, 150, 80, 40) # creating push button push_div = QPushButton(\"/\", self) # setting geometry push_div.setGeometry(185, 300, 80, 40) # creating push button push_point = QPushButton(\".\", self) # setting geometry push_point.setGeometry(95, 300, 80, 40) # clear button push_clear = QPushButton(\"Clear\", self) push_clear.setGeometry(5, 100, 200, 40) # del one character button push_del = QPushButton(\"Del\", self) push_del.setGeometry(210, 100, 145, 40) # adding action to each of the button push_minus.clicked.connect(self.action_minus) push_equal.clicked.connect(self.action_equal) push0.clicked.connect(self.action0) push1.clicked.connect(self.action1) push2.clicked.connect(self.action2) push3.clicked.connect(self.action3) push4.clicked.connect(self.action4) push5.clicked.connect(self.action5) push6.clicked.connect(self.action6) push7.clicked.connect(self.action7) push8.clicked.connect(self.action8) push9.clicked.connect(self.action9) push_div.clicked.connect(self.action_div) push_mul.clicked.connect(self.action_mul) push_plus.clicked.connect(self.action_plus) push_point.clicked.connect(self.action_point) push_clear.clicked.connect(self.action_clear) push_del.clicked.connect(self.action_del) def action_equal(self): # get the label text equation = self.label.text() try: # getting the ans ans = eval(equation) # setting text to the label self.label.setText(str(ans)) except: # setting text to the label self.label.setText(\"Wrong Input\") def action_plus(self): # appending label text text = self.label.text() self.label.setText(text + \" + \") def action_minus(self): # appending label text text = self.label.text() self.label.setText(text + \" - \") def action_div(self): # appending label text text = self.label.text() self.label.setText(text + \" / \") def action_mul(self): # appending label text text = self.label.text() self.label.setText(text + \" * \") def action_point(self): # appending label text text = self.label.text() self.label.setText(text + \".\") def action0(self): # appending label text text = self.label.text() self.label.setText(text + \"0\") def action1(self): # appending label text text = self.label.text() self.label.setText(text + \"1\") def action2(self): # appending label text text = self.label.text() self.label.setText(text + \"2\") def action3(self): # appending label text text = self.label.text() self.label.setText(text + \"3\") def action4(self): # appending label text text = self.label.text() self.label.setText(text + \"4\") def action5(self): # appending label text text = self.label.text() self.label.setText(text + \"5\") def action6(self): # appending label text text = self.label.text() self.label.setText(text + \"6\") def action7(self): # appending label text text = self.label.text() self.label.setText(text + \"7\") def action8(self): # appending label text text = self.label.text() self.label.setText(text + \"8\") def action9(self): # appending label text text = self.label.text() self.label.setText(text + \"9\") def action_clear(self): # clearing the label text self.label.setText(\"\") def action_del(self): # clearing a single digit text = self.label.text() print(text[:len(text)-1]) self.label.setText(text[:len(text)-1]) # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec())",
"e": 32624,
"s": 25103,
"text": null
},
{
"code": null,
"e": 32635,
"s": 32624,
"text": "Output : "
},
{
"code": null,
"e": 32647,
"s": 32635,
"text": "Python-PyQt"
},
{
"code": null,
"e": 32654,
"s": 32647,
"text": "Python"
},
{
"code": null,
"e": 32752,
"s": 32654,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 32761,
"s": 32752,
"text": "Comments"
},
{
"code": null,
"e": 32774,
"s": 32761,
"text": "Old Comments"
},
{
"code": null,
"e": 32810,
"s": 32774,
"text": "Box Plot in Python using Matplotlib"
},
{
"code": null,
"e": 32849,
"s": 32810,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 32872,
"s": 32849,
"text": "Bar Plot in Matplotlib"
},
{
"code": null,
"e": 32923,
"s": 32872,
"text": "Multithreading in Python | Set 2 (Synchronization)"
},
{
"code": null,
"e": 32955,
"s": 32923,
"text": "Python Dictionary keys() method"
},
{
"code": null,
"e": 32971,
"s": 32955,
"text": "loops in python"
},
{
"code": null,
"e": 33012,
"s": 32971,
"text": "Python - Call function from another file"
},
{
"code": null,
"e": 33061,
"s": 33012,
"text": "Ways to filter Pandas DataFrame by column values"
},
{
"code": null,
"e": 33094,
"s": 33061,
"text": "Python | Convert set into a list"
}
] |
How to multiply two vectors in R as in mathematics? | In mathematics, when two vectors are multiplied the output is a scalar quantity which is the sum of the product of the values. For example, if we have two vectors x and y each containing 1 and 2 then the multiplication of the two vectors will be 5. In R, we can do it by using t(x)%*%y.
Live Demo
x1<-1:2
y1<-1:2
t(x1)%*%y1
[,1]
[1,] 5
Live Demo
x2<-1:100
y2<-1:100
t(x2)%*%y2
[,1]
[1,] 338350
Live Demo
x3<-sample(0:5,120,replace=TRUE)
x3
[1] 2 4 1 4 5 0 2 2 0 4 4 5 5 1 4 2 4 2 0 0 0 2 0 1 5 2 5 4 3 5 1 2 1 1 3 3 2
[38] 1 0 3 5 3 0 0 5 5 5 3 3 5 4 3 4 5 4 3 5 1 0 5 4 0 5 1 3 5 0 3 2 2 3 3 0 0
[75] 0 4 4 1 5 3 4 3 5 2 2 4 0 3 2 4 0 4 5 3 1 2 0 0 0 2 2 2 3 3 1 2 4 2 3 2 0
[112] 5 2 1 5 3 4 1 5 1
y3<-sample(0:5,120,replace=TRUE)
y3
[1] 2 0 3 0 2 4 5 3 0 4 5 2 4 3 3 3 4 2 3 2 1 5 0 5 2 4 4 1 3 2 2 1 5 3 0 2 0
[38] 2 2 1 1 3 1 3 3 2 3 3 0 1 4 5 1 2 3 3 5 2 5 2 1 0 0 5 0 3 1 5 2 4 3 4 2 2
[75] 4 4 1 4 2 4 2 2 4 5 0 3 5 3 4 1 1 4 0 1 1 4 1 3 5 3 5 5 5 2 5 1 5 0 0 2 0
[112] 0 3 2 0 4 2 4 4 3
t(x3)%*%y3
[,1]
[1,] 766
Live Demo
x4<-sample(1:10,120,replace=TRUE)
x4
[1] 4 2 3 4 4 7 4 10 7 5 8 5 6 7 6 10 10 9 6 10 3 3 10 10 4
[26] 10 2 5 7 2 2 4 2 10 2 9 9 1 5 2 8 2 8 1 5 10 4 6 3 9
[51] 10 7 6 2 7 10 9 7 9 3 1 10 9 1 9 3 6 10 1 8 5 2 6 3 8
[76] 6 3 6 5 9 8 2 5 7 8 6 4 4 6 10 3 5 2 10 7 6 8 4 7 8
[101] 4 9 3 5 5 2 7 5 2 5 6 3 10 9 3 1 2 10 10 4
y4<-sample(1:10,120,replace=TRUE)
y4
[1] 10 10 7 6 9 7 1 7 7 1 2 9 6 8 2 7 8 5 8 6 1 3 1 5 8
[26] 1 9 2 7 4 4 9 6 3 5 1 1 4 5 9 1 8 6 9 7 4 6 4 9 1
[51] 4 10 7 10 8 7 5 2 1 3 8 10 10 3 1 6 8 5 9 1 9 5 1 3 9
[76] 2 2 3 7 8 5 5 3 5 4 7 7 2 4 9 3 8 3 7 6 3 7 2 7 4
[101] 1 6 3 4 6 1 1 10 3 4 8 2 5 1 3 3 7 7 5 7
t(x4)%*%y4
[,1]
[1,] 3532
Live Demo
x5<-sample(101:110,120,replace=TRUE)
x5
[1] 103 109 110 109 107 107 105 107 101 105 101 105 106 102 108 109 103 107
[19] 105 105 108 105 104 103 105 103 106 108 103 110 104 109 105 103 107 109
[37] 105 102 103 106 105 110 105 110 104 110 107 105 105 101 106 109 103 106
[55] 103 107 104 102 101 108 103 101 104 110 104 104 103 107 102 110 101 107
[73] 110 103 103 101 107 108 107 106 105 101 103 102 106 110 108 103 101 102
[91] 107 106 108 109 108 108 109 107 109 105 107 105 106 110 103 104 103 103
[109] 103 101 107 102 107 106 107 109 102 101 102 102
y5<-sample(101:110,120,replace=TRUE)
y5
[1] 107 106 107 108 104 110 107 110 104 105 107 107 101 103 109 110 110 108
[19] 107 110 103 110 103 106 108 103 106 103 101 108 104 103 103 106 103 110
[37] 102 102 104 103 101 109 104 106 109 108 105 110 110 101 103 110 102 101
[55] 102 102 108 110 105 104 109 105 109 101 109 106 107 104 105 107 104 110
[73] 107 106 108 103 104 102 106 101 103 106 104 101 107 101 104 109 107 110
[91] 110 107 109 107 105 103 107 103 104 107 102 103 103 102 109 104 104 101
[109] 104 106 109 108 106 106 104 104 101 101 110 103
t(x5)%*%y5
[,1]
[1,] 1333499
Live Demo
x6<-sample(51:60,120,replace=TRUE)
x6
[1] 51 53 55 60 58 53 53 58 51 59 59 51 58 58 52 55 51 60 56 59 56 56 58 56 56
[26] 58 52 54 60 54 55 51 56 55 53 59 58 59 60 58 56 58 56 54 56 51 60 58 58 53
[51] 53 52 53 51 55 53 57 59 55 53 53 56 54 52 57 58 51 55 58 52 54 53 52 54 59
[76] 54 56 58 52 51 59 59 56 51 56 53 59 51 53 53 59 57 53 53 55 52 52 51 52 58
[101] 56 52 57 60 52 53 59 54 55 53 60 55 52 58 51 58 52 52 53 57
y6<-sample(0:1,120,replace=TRUE)
y6
[1] 1 0 0 0 0 0 1 0 0 0 0 1 1 0 1 1 1 0 1 0 1 0 1 1 1 0 1 1 1 0 1 1 1 0 0 0 1
[38] 1 1 0 0 0 1 0 0 0 0 0 0 0 1 0 0 1 0 1 1 0 0 1 0 0 1 0 0 0 0 0 0 1 1 0 0 0
[75] 1 0 0 0 0 0 1 1 0 0 1 0 0 0 0 0 0 0 1 0 0 1 1 0 0 1 1 0 0 0 1 1 1 1 1 1 1
[112] 0 0 0 1 1 0 1 0 0
t(x6)%*%y6
[,1]
[1,] 2692
Live Demo
x7<-sample(c(5,15,25,35,45,55,65,75,85,95),120,replace=TRUE)
x7
[1] 15 75 45 15 35 25 45 45 85 25 75 45 15 5 45 15 45 35 55 45 15 85 45 95 85
[26] 35 75 45 25 55 45 25 95 95 65 75 5 85 25 55 95 65 65 65 45 45 25 15 5 45
[51] 25 25 5 95 55 55 95 95 35 45 25 5 15 95 75 25 65 65 25 35 75 25 75 25 65
[76] 95 75 55 25 5 15 65 65 5 35 55 75 15 95 35 15 95 95 5 55 35 95 5 45 25
[101] 75 75 35 35 45 55 25 65 35 45 35 35 95 85 35 35 5 55 5 85
y7<-sample(c(1,11,21,31,41,51,61,71,81,91),120,replace=TRUE)
y7
[1] 41 31 31 41 71 11 51 31 11 41 41 31 91 71 11 21 91 11 11 11 41 1 31 31 61
[26] 21 51 41 31 11 81 31 71 91 21 1 21 11 31 11 41 71 71 21 51 41 31 81 81 41
[51] 71 31 11 51 71 61 41 81 61 61 21 71 41 91 1 61 91 21 21 61 41 11 91 81 31
[76] 1 31 31 71 41 41 61 71 11 51 71 41 81 91 81 31 31 41 61 21 91 91 61 1 31
[101] 81 51 91 51 81 71 41 31 21 41 71 61 41 71 91 21 71 21 51 1
t(x7)%*%y7
[,1]
[1,] 264460
Live Demo
x8<-rnorm(25,5,0.04)
x8
[1] 5.044193 4.965799 5.016561 4.936845 5.091920 4.978903 4.975891 4.981731
[9] 5.002986 5.003291 5.049467 4.940315 5.022184 5.029431 5.025540 5.066160
[17] 5.002058 4.969025 4.995391 5.006298 5.044991 4.993655 5.017182 5.020555
[25] 4.939784
y8<-rnorm(25,5,0.08)
y8
[1] 5.103655 4.963152 5.184913 5.150147 4.977731 5.040406 5.104955 5.062985
[9] 5.036312 5.082053 5.019926 5.009339 5.031032 4.851256 4.876433 4.908972
[17] 4.957003 5.039052 5.048009 5.030555 5.095683 4.898264 4.943438 4.901391
[25] 5.007738
t(x8)%*%y8
[,1]
[1,] 627.2037 | [
{
"code": null,
"e": 1349,
"s": 1062,
"text": "In mathematics, when two vectors are multiplied the output is a scalar quantity which is the sum of the product of the values. For example, if we have two vectors x and y each containing 1 and 2 then the multiplication of the two vectors will be 5. In R, we can do it by using t(x)%*%y."
},
{
"code": null,
"e": 1360,
"s": 1349,
"text": " Live Demo"
},
{
"code": null,
"e": 1387,
"s": 1360,
"text": "x1<-1:2\ny1<-1:2\nt(x1)%*%y1"
},
{
"code": null,
"e": 1399,
"s": 1387,
"text": "[,1]\n[1,] 5"
},
{
"code": null,
"e": 1410,
"s": 1399,
"text": " Live Demo"
},
{
"code": null,
"e": 1441,
"s": 1410,
"text": "x2<-1:100\ny2<-1:100\nt(x2)%*%y2"
},
{
"code": null,
"e": 1458,
"s": 1441,
"text": "[,1]\n[1,] 338350"
},
{
"code": null,
"e": 1469,
"s": 1458,
"text": " Live Demo"
},
{
"code": null,
"e": 2072,
"s": 1469,
"text": "x3<-sample(0:5,120,replace=TRUE)\nx3\n[1] 2 4 1 4 5 0 2 2 0 4 4 5 5 1 4 2 4 2 0 0 0 2 0 1 5 2 5 4 3 5 1 2 1 1 3 3 2\n[38] 1 0 3 5 3 0 0 5 5 5 3 3 5 4 3 4 5 4 3 5 1 0 5 4 0 5 1 3 5 0 3 2 2 3 3 0 0\n[75] 0 4 4 1 5 3 4 3 5 2 2 4 0 3 2 4 0 4 5 3 1 2 0 0 0 2 2 2 3 3 1 2 4 2 3 2 0\n[112] 5 2 1 5 3 4 1 5 1\ny3<-sample(0:5,120,replace=TRUE)\ny3\n[1] 2 0 3 0 2 4 5 3 0 4 5 2 4 3 3 3 4 2 3 2 1 5 0 5 2 4 4 1 3 2 2 1 5 3 0 2 0\n[38] 2 2 1 1 3 1 3 3 2 3 3 0 1 4 5 1 2 3 3 5 2 5 2 1 0 0 5 0 3 1 5 2 4 3 4 2 2\n[75] 4 4 1 4 2 4 2 2 4 5 0 3 5 3 4 1 1 4 0 1 1 4 1 3 5 3 5 5 5 2 5 1 5 0 0 2 0\n[112] 0 3 2 0 4 2 4 4 3\nt(x3)%*%y3"
},
{
"code": null,
"e": 2086,
"s": 2072,
"text": "[,1]\n[1,] 766"
},
{
"code": null,
"e": 2097,
"s": 2086,
"text": " Live Demo"
},
{
"code": null,
"e": 2737,
"s": 2097,
"text": "x4<-sample(1:10,120,replace=TRUE)\nx4\n[1] 4 2 3 4 4 7 4 10 7 5 8 5 6 7 6 10 10 9 6 10 3 3 10 10 4\n[26] 10 2 5 7 2 2 4 2 10 2 9 9 1 5 2 8 2 8 1 5 10 4 6 3 9\n[51] 10 7 6 2 7 10 9 7 9 3 1 10 9 1 9 3 6 10 1 8 5 2 6 3 8\n[76] 6 3 6 5 9 8 2 5 7 8 6 4 4 6 10 3 5 2 10 7 6 8 4 7 8\n[101] 4 9 3 5 5 2 7 5 2 5 6 3 10 9 3 1 2 10 10 4\ny4<-sample(1:10,120,replace=TRUE)\ny4\n[1] 10 10 7 6 9 7 1 7 7 1 2 9 6 8 2 7 8 5 8 6 1 3 1 5 8\n[26] 1 9 2 7 4 4 9 6 3 5 1 1 4 5 9 1 8 6 9 7 4 6 4 9 1\n[51] 4 10 7 10 8 7 5 2 1 3 8 10 10 3 1 6 8 5 9 1 9 5 1 3 9\n[76] 2 2 3 7 8 5 5 3 5 4 7 7 2 4 9 3 8 3 7 6 3 7 2 7 4\n[101] 1 6 3 4 6 1 1 10 3 4 8 2 5 1 3 3 7 7 5 7\nt(x4)%*%y4"
},
{
"code": null,
"e": 2752,
"s": 2737,
"text": "[,1]\n[1,] 3532"
},
{
"code": null,
"e": 2763,
"s": 2752,
"text": " Live Demo"
},
{
"code": null,
"e": 3884,
"s": 2763,
"text": "x5<-sample(101:110,120,replace=TRUE)\nx5\n[1] 103 109 110 109 107 107 105 107 101 105 101 105 106 102 108 109 103 107\n[19] 105 105 108 105 104 103 105 103 106 108 103 110 104 109 105 103 107 109\n[37] 105 102 103 106 105 110 105 110 104 110 107 105 105 101 106 109 103 106\n[55] 103 107 104 102 101 108 103 101 104 110 104 104 103 107 102 110 101 107\n[73] 110 103 103 101 107 108 107 106 105 101 103 102 106 110 108 103 101 102\n[91] 107 106 108 109 108 108 109 107 109 105 107 105 106 110 103 104 103 103\n[109] 103 101 107 102 107 106 107 109 102 101 102 102\ny5<-sample(101:110,120,replace=TRUE)\ny5\n[1] 107 106 107 108 104 110 107 110 104 105 107 107 101 103 109 110 110 108\n[19] 107 110 103 110 103 106 108 103 106 103 101 108 104 103 103 106 103 110\n[37] 102 102 104 103 101 109 104 106 109 108 105 110 110 101 103 110 102 101\n[55] 102 102 108 110 105 104 109 105 109 101 109 106 107 104 105 107 104 110\n[73] 107 106 108 103 104 102 106 101 103 106 104 101 107 101 104 109 107 110\n[91] 110 107 109 107 105 103 107 103 104 107 102 103 103 102 109 104 104 101\n[109] 104 106 109 108 106 106 104 104 101 101 110 103\nt(x5)%*%y5"
},
{
"code": null,
"e": 3902,
"s": 3884,
"text": "[,1]\n[1,] 1333499"
},
{
"code": null,
"e": 3913,
"s": 3902,
"text": " Live Demo"
},
{
"code": null,
"e": 4644,
"s": 3913,
"text": "x6<-sample(51:60,120,replace=TRUE)\nx6\n[1] 51 53 55 60 58 53 53 58 51 59 59 51 58 58 52 55 51 60 56 59 56 56 58 56 56\n[26] 58 52 54 60 54 55 51 56 55 53 59 58 59 60 58 56 58 56 54 56 51 60 58 58 53\n[51] 53 52 53 51 55 53 57 59 55 53 53 56 54 52 57 58 51 55 58 52 54 53 52 54 59\n[76] 54 56 58 52 51 59 59 56 51 56 53 59 51 53 53 59 57 53 53 55 52 52 51 52 58\n[101] 56 52 57 60 52 53 59 54 55 53 60 55 52 58 51 58 52 52 53 57\ny6<-sample(0:1,120,replace=TRUE)\ny6\n[1] 1 0 0 0 0 0 1 0 0 0 0 1 1 0 1 1 1 0 1 0 1 0 1 1 1 0 1 1 1 0 1 1 1 0 0 0 1\n[38] 1 1 0 0 0 1 0 0 0 0 0 0 0 1 0 0 1 0 1 1 0 0 1 0 0 1 0 0 0 0 0 0 1 1 0 0 0\n[75] 1 0 0 0 0 0 1 1 0 0 1 0 0 0 0 0 0 0 1 0 0 1 1 0 0 1 1 0 0 0 1 1 1 1 1 1 1\n[112] 0 0 0 1 1 0 1 0 0\nt(x6)%*%y6"
},
{
"code": null,
"e": 4659,
"s": 4644,
"text": "[,1]\n[1,] 2692"
},
{
"code": null,
"e": 4670,
"s": 4659,
"text": " Live Demo"
},
{
"code": null,
"e": 5563,
"s": 4670,
"text": "x7<-sample(c(5,15,25,35,45,55,65,75,85,95),120,replace=TRUE)\nx7\n[1] 15 75 45 15 35 25 45 45 85 25 75 45 15 5 45 15 45 35 55 45 15 85 45 95 85\n[26] 35 75 45 25 55 45 25 95 95 65 75 5 85 25 55 95 65 65 65 45 45 25 15 5 45\n[51] 25 25 5 95 55 55 95 95 35 45 25 5 15 95 75 25 65 65 25 35 75 25 75 25 65\n[76] 95 75 55 25 5 15 65 65 5 35 55 75 15 95 35 15 95 95 5 55 35 95 5 45 25\n[101] 75 75 35 35 45 55 25 65 35 45 35 35 95 85 35 35 5 55 5 85\ny7<-sample(c(1,11,21,31,41,51,61,71,81,91),120,replace=TRUE)\ny7\n[1] 41 31 31 41 71 11 51 31 11 41 41 31 91 71 11 21 91 11 11 11 41 1 31 31 61\n[26] 21 51 41 31 11 81 31 71 91 21 1 21 11 31 11 41 71 71 21 51 41 31 81 81 41\n[51] 71 31 11 51 71 61 41 81 61 61 21 71 41 91 1 61 91 21 21 61 41 11 91 81 31\n[76] 1 31 31 71 41 41 61 71 11 51 71 41 81 91 81 31 31 41 61 21 91 91 61 1 31\n[101] 81 51 91 51 81 71 41 31 21 41 71 61 41 71 91 21 71 21 51 1\nt(x7)%*%y7"
},
{
"code": null,
"e": 5580,
"s": 5563,
"text": "[,1]\n[1,] 264460"
},
{
"code": null,
"e": 5591,
"s": 5580,
"text": " Live Demo"
},
{
"code": null,
"e": 6136,
"s": 5591,
"text": "x8<-rnorm(25,5,0.04)\nx8\n[1] 5.044193 4.965799 5.016561 4.936845 5.091920 4.978903 4.975891 4.981731\n[9] 5.002986 5.003291 5.049467 4.940315 5.022184 5.029431 5.025540 5.066160\n[17] 5.002058 4.969025 4.995391 5.006298 5.044991 4.993655 5.017182 5.020555\n[25] 4.939784\ny8<-rnorm(25,5,0.08)\ny8\n[1] 5.103655 4.963152 5.184913 5.150147 4.977731 5.040406 5.104955 5.062985\n[9] 5.036312 5.082053 5.019926 5.009339 5.031032 4.851256 4.876433 4.908972\n[17] 4.957003 5.039052 5.048009 5.030555 5.095683 4.898264 4.943438 4.901391\n[25] 5.007738\nt(x8)%*%y8"
},
{
"code": null,
"e": 6155,
"s": 6136,
"text": "[,1]\n[1,] 627.2037"
}
] |
Java Graphics2D Class Example - onlinetutorialspoint | PROGRAMMINGJava ExamplesC Examples
Java Examples
C Examples
C Tutorials
aws
JAVAEXCEPTIONSCOLLECTIONSSWINGJDBC
EXCEPTIONS
COLLECTIONS
SWING
JDBC
JAVA 8
SPRING
SPRING BOOT
HIBERNATE
PYTHON
PHP
JQUERY
PROGRAMMINGJava ExamplesC Examples
Java Examples
C Examples
C Tutorials
aws
In this tutorials, we are going to see how to use the Java Graphics2D class.
Java Graphics class is a abstract base class, it allows the application to draw something on different AWT or Swing components.
The Graphics2D Class is extended class of Graphics class, it provides more sophisticated controls over text layout, color management and coordinate transformations.
Since this example on Java Graphics2D, I am going to present an interesting output here.
package com.onlinetutorialspoint.swing;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.geom.GeneralPath;
import java.util.Random;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Graphics2D_Demo extends JPanel{
public void paintComponent(Graphics g){
super.paintComponent(g);
int[] xValues = {55,67,109,73,83,55,27,37,1,43};
int[] yValues = {0,36,36,54,96,72,96,54,36,36};
Graphics2D graphics2D = (Graphics2D) g;
GeneralPath path = new GeneralPath();
path.moveTo(xValues[0], yValues[0]);
for (int i= 1;i<xValues.length;i++){
path.lineTo(xValues[i], yValues[i]);
}
path.closePath();
graphics2D.translate(150, 150);
Random rNumbers = new Random();
for (int i= 1;i<=20;i++){
graphics2D.rotate(Math.PI/10.0);
graphics2D.setColor(new Color(rNumbers.nextInt(256),rNumbers.nextInt(256),rNumbers.nextInt(256)));
graphics2D.fill(path);
}
}
public static void main(String[] args) {
JFrame frame = new JFrame("Graphics2D Demo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Graphics2D_Demo demo = new Graphics2D_Demo();
frame.add(demo);
frame.setBackground(Color.WHITE);
frame.setSize(315, 330);
frame.setVisible(true);
}
}
Output :
Happy Learning π
How to draw shapes using Graphics
How to create Java Smiley Swing
How to create Java Rainbow using Swing
How to use Java JSlider Example
Java Swing JList Example
Java Swing JTabbedPane Example
Java Swing JLabel Example
Java Swing Login Example
Java JList Multiple Selection Example
Java LinkedList class Example
Java WeakHashMap class Example
Properties class Example in Java
Java Class Example Tutorials
Java Static Variable Method Block Class Example
Java Reflection Get Class Hierarchy
How to draw shapes using Graphics
How to create Java Smiley Swing
How to create Java Rainbow using Swing
How to use Java JSlider Example
Java Swing JList Example
Java Swing JTabbedPane Example
Java Swing JLabel Example
Java Swing Login Example
Java JList Multiple Selection Example
Java LinkedList class Example
Java WeakHashMap class Example
Properties class Example in Java
Java Class Example Tutorials
Java Static Variable Method Block Class Example
Java Reflection Get Class Hierarchy
Ξ
Install Java on Mac OS
Install AWS CLI on Windows
Install Minikube on Windows
Install Docker Toolbox on Windows
Install SOAPUI on Windows
Install Gradle on Windows
Install RabbitMQ on Windows
Install PuTTY on windows
Install Mysql on Windows
Install Hibernate Tools in Eclipse
Install Elasticsearch on Windows
Install Maven on Windows
Install Maven on Ubuntu
Install Maven on Windows Command
Add OJDBC jar to Maven Repository
Install Ant on Windows
Install RabbitMQ on Windows
Install Apache Kafka on Ubuntu
Install Apache Kafka on Windows
Java8 β Install Windows
Java8 β foreach
Java8 β forEach with index
Java8 β Stream Filter Objects
Java8 β Comparator Userdefined
Java8 β GroupingBy
Java8 β SummingInt
Java8 β walk ReadFiles
Java8 β JAVA_HOME on Windows
Howto β Install Java on Mac OS
Howto β Convert Iterable to Stream
Howto β Get common elements from two Lists
Howto β Convert List to String
Howto β Concatenate Arrays using Stream
Howto β Remove duplicates from List
Howto β Filter null values from Stream
Howto β Convert List to Map
Howto β Convert Stream to List
Howto β Sort a Map
Howto β Filter a Map
Howto β Get Current UTC Time
Howto β Verify an Array contains a specific value
Howto β Convert ArrayList to Array
Howto β Read File Line By Line
Howto β Convert Date to LocalDate
Howto β Merge Streams
Howto β Resolve NullPointerException in toMap
Howto -Get Stream count
Howto β Get Min and Max values in a Stream
Howto β Convert InputStream to String | [
{
"code": null,
"e": 158,
"s": 123,
"text": "PROGRAMMINGJava ExamplesC Examples"
},
{
"code": null,
"e": 172,
"s": 158,
"text": "Java Examples"
},
{
"code": null,
"e": 183,
"s": 172,
"text": "C Examples"
},
{
"code": null,
"e": 195,
"s": 183,
"text": "C Tutorials"
},
{
"code": null,
"e": 199,
"s": 195,
"text": "aws"
},
{
"code": null,
"e": 234,
"s": 199,
"text": "JAVAEXCEPTIONSCOLLECTIONSSWINGJDBC"
},
{
"code": null,
"e": 245,
"s": 234,
"text": "EXCEPTIONS"
},
{
"code": null,
"e": 257,
"s": 245,
"text": "COLLECTIONS"
},
{
"code": null,
"e": 263,
"s": 257,
"text": "SWING"
},
{
"code": null,
"e": 268,
"s": 263,
"text": "JDBC"
},
{
"code": null,
"e": 275,
"s": 268,
"text": "JAVA 8"
},
{
"code": null,
"e": 282,
"s": 275,
"text": "SPRING"
},
{
"code": null,
"e": 294,
"s": 282,
"text": "SPRING BOOT"
},
{
"code": null,
"e": 304,
"s": 294,
"text": "HIBERNATE"
},
{
"code": null,
"e": 311,
"s": 304,
"text": "PYTHON"
},
{
"code": null,
"e": 315,
"s": 311,
"text": "PHP"
},
{
"code": null,
"e": 322,
"s": 315,
"text": "JQUERY"
},
{
"code": null,
"e": 357,
"s": 322,
"text": "PROGRAMMINGJava ExamplesC Examples"
},
{
"code": null,
"e": 371,
"s": 357,
"text": "Java Examples"
},
{
"code": null,
"e": 382,
"s": 371,
"text": "C Examples"
},
{
"code": null,
"e": 394,
"s": 382,
"text": "C Tutorials"
},
{
"code": null,
"e": 398,
"s": 394,
"text": "aws"
},
{
"code": null,
"e": 475,
"s": 398,
"text": "In this tutorials, we are going to see how to use the Java Graphics2D class."
},
{
"code": null,
"e": 603,
"s": 475,
"text": "Java Graphics class is a abstract base class, it allows the application to draw something on different AWT or Swing components."
},
{
"code": null,
"e": 768,
"s": 603,
"text": "The Graphics2D Class is extended class of Graphics class, it provides more sophisticated controls over text layout, color management and coordinate transformations."
},
{
"code": null,
"e": 857,
"s": 768,
"text": "Since this example on Java Graphics2D, I am going to present an interesting output here."
},
{
"code": null,
"e": 2336,
"s": 857,
"text": "package com.onlinetutorialspoint.swing;\n\nimport java.awt.Color;\nimport java.awt.Graphics;\nimport java.awt.Graphics2D;\nimport java.awt.geom.GeneralPath;\nimport java.util.Random;\n\nimport javax.swing.JFrame;\nimport javax.swing.JPanel;\n\npublic class Graphics2D_Demo extends JPanel{\n\n public void paintComponent(Graphics g){\n super.paintComponent(g);\n \n int[] xValues = {55,67,109,73,83,55,27,37,1,43};\n int[] yValues = {0,36,36,54,96,72,96,54,36,36};\n \n Graphics2D graphics2D = (Graphics2D) g;\n GeneralPath path = new GeneralPath();\n \n path.moveTo(xValues[0], yValues[0]);\n \n for (int i= 1;i<xValues.length;i++){\n path.lineTo(xValues[i], yValues[i]);\n }\n \n path.closePath();\n graphics2D.translate(150, 150);\n Random rNumbers = new Random();\n for (int i= 1;i<=20;i++){\n graphics2D.rotate(Math.PI/10.0);\n graphics2D.setColor(new Color(rNumbers.nextInt(256),rNumbers.nextInt(256),rNumbers.nextInt(256)));\n graphics2D.fill(path);\n }\n \n }\n public static void main(String[] args) {\n JFrame frame = new JFrame(\"Graphics2D Demo\");\n frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n \n Graphics2D_Demo demo = new Graphics2D_Demo();\n frame.add(demo);\n frame.setBackground(Color.WHITE);\n frame.setSize(315, 330);\n frame.setVisible(true);\n }\n\n}"
},
{
"code": null,
"e": 2345,
"s": 2336,
"text": "Output :"
},
{
"code": null,
"e": 2362,
"s": 2345,
"text": "Happy Learning π"
},
{
"code": null,
"e": 2853,
"s": 2362,
"text": "\nHow to draw shapes using Graphics\nHow to create Java Smiley Swing\nHow to create Java Rainbow using Swing\nHow to use Java JSlider Example\nJava Swing JList Example\nJava Swing JTabbedPane Example\nJava Swing JLabel Example\nJava Swing Login Example\nJava JList Multiple Selection Example\nJava LinkedList class Example\nJava WeakHashMap class Example\nProperties class Example in Java\nJava Class Example Tutorials\nJava Static Variable Method Block Class Example\nJava Reflection Get Class Hierarchy\n"
},
{
"code": null,
"e": 2887,
"s": 2853,
"text": "How to draw shapes using Graphics"
},
{
"code": null,
"e": 2919,
"s": 2887,
"text": "How to create Java Smiley Swing"
},
{
"code": null,
"e": 2958,
"s": 2919,
"text": "How to create Java Rainbow using Swing"
},
{
"code": null,
"e": 2990,
"s": 2958,
"text": "How to use Java JSlider Example"
},
{
"code": null,
"e": 3015,
"s": 2990,
"text": "Java Swing JList Example"
},
{
"code": null,
"e": 3046,
"s": 3015,
"text": "Java Swing JTabbedPane Example"
},
{
"code": null,
"e": 3072,
"s": 3046,
"text": "Java Swing JLabel Example"
},
{
"code": null,
"e": 3097,
"s": 3072,
"text": "Java Swing Login Example"
},
{
"code": null,
"e": 3135,
"s": 3097,
"text": "Java JList Multiple Selection Example"
},
{
"code": null,
"e": 3165,
"s": 3135,
"text": "Java LinkedList class Example"
},
{
"code": null,
"e": 3196,
"s": 3165,
"text": "Java WeakHashMap class Example"
},
{
"code": null,
"e": 3229,
"s": 3196,
"text": "Properties class Example in Java"
},
{
"code": null,
"e": 3258,
"s": 3229,
"text": "Java Class Example Tutorials"
},
{
"code": null,
"e": 3306,
"s": 3258,
"text": "Java Static Variable Method Block Class Example"
},
{
"code": null,
"e": 3342,
"s": 3306,
"text": "Java Reflection Get Class Hierarchy"
},
{
"code": null,
"e": 3348,
"s": 3346,
"text": "Ξ"
},
{
"code": null,
"e": 3372,
"s": 3348,
"text": " Install Java on Mac OS"
},
{
"code": null,
"e": 3400,
"s": 3372,
"text": " Install AWS CLI on Windows"
},
{
"code": null,
"e": 3429,
"s": 3400,
"text": " Install Minikube on Windows"
},
{
"code": null,
"e": 3464,
"s": 3429,
"text": " Install Docker Toolbox on Windows"
},
{
"code": null,
"e": 3491,
"s": 3464,
"text": " Install SOAPUI on Windows"
},
{
"code": null,
"e": 3518,
"s": 3491,
"text": " Install Gradle on Windows"
},
{
"code": null,
"e": 3547,
"s": 3518,
"text": " Install RabbitMQ on Windows"
},
{
"code": null,
"e": 3573,
"s": 3547,
"text": " Install PuTTY on windows"
},
{
"code": null,
"e": 3599,
"s": 3573,
"text": " Install Mysql on Windows"
},
{
"code": null,
"e": 3635,
"s": 3599,
"text": " Install Hibernate Tools in Eclipse"
},
{
"code": null,
"e": 3669,
"s": 3635,
"text": " Install Elasticsearch on Windows"
},
{
"code": null,
"e": 3695,
"s": 3669,
"text": " Install Maven on Windows"
},
{
"code": null,
"e": 3720,
"s": 3695,
"text": " Install Maven on Ubuntu"
},
{
"code": null,
"e": 3754,
"s": 3720,
"text": " Install Maven on Windows Command"
},
{
"code": null,
"e": 3789,
"s": 3754,
"text": " Add OJDBC jar to Maven Repository"
},
{
"code": null,
"e": 3813,
"s": 3789,
"text": " Install Ant on Windows"
},
{
"code": null,
"e": 3842,
"s": 3813,
"text": " Install RabbitMQ on Windows"
},
{
"code": null,
"e": 3874,
"s": 3842,
"text": " Install Apache Kafka on Ubuntu"
},
{
"code": null,
"e": 3907,
"s": 3874,
"text": " Install Apache Kafka on Windows"
},
{
"code": null,
"e": 3932,
"s": 3907,
"text": " Java8 β Install Windows"
},
{
"code": null,
"e": 3949,
"s": 3932,
"text": " Java8 β foreach"
},
{
"code": null,
"e": 3977,
"s": 3949,
"text": " Java8 β forEach with index"
},
{
"code": null,
"e": 4008,
"s": 3977,
"text": " Java8 β Stream Filter Objects"
},
{
"code": null,
"e": 4040,
"s": 4008,
"text": " Java8 β Comparator Userdefined"
},
{
"code": null,
"e": 4060,
"s": 4040,
"text": " Java8 β GroupingBy"
},
{
"code": null,
"e": 4080,
"s": 4060,
"text": " Java8 β SummingInt"
},
{
"code": null,
"e": 4104,
"s": 4080,
"text": " Java8 β walk ReadFiles"
},
{
"code": null,
"e": 4134,
"s": 4104,
"text": " Java8 β JAVA_HOME on Windows"
},
{
"code": null,
"e": 4166,
"s": 4134,
"text": " Howto β Install Java on Mac OS"
},
{
"code": null,
"e": 4202,
"s": 4166,
"text": " Howto β Convert Iterable to Stream"
},
{
"code": null,
"e": 4246,
"s": 4202,
"text": " Howto β Get common elements from two Lists"
},
{
"code": null,
"e": 4278,
"s": 4246,
"text": " Howto β Convert List to String"
},
{
"code": null,
"e": 4319,
"s": 4278,
"text": " Howto β Concatenate Arrays using Stream"
},
{
"code": null,
"e": 4356,
"s": 4319,
"text": " Howto β Remove duplicates from List"
},
{
"code": null,
"e": 4396,
"s": 4356,
"text": " Howto β Filter null values from Stream"
},
{
"code": null,
"e": 4425,
"s": 4396,
"text": " Howto β Convert List to Map"
},
{
"code": null,
"e": 4457,
"s": 4425,
"text": " Howto β Convert Stream to List"
},
{
"code": null,
"e": 4477,
"s": 4457,
"text": " Howto β Sort a Map"
},
{
"code": null,
"e": 4499,
"s": 4477,
"text": " Howto β Filter a Map"
},
{
"code": null,
"e": 4529,
"s": 4499,
"text": " Howto β Get Current UTC Time"
},
{
"code": null,
"e": 4580,
"s": 4529,
"text": " Howto β Verify an Array contains a specific value"
},
{
"code": null,
"e": 4616,
"s": 4580,
"text": " Howto β Convert ArrayList to Array"
},
{
"code": null,
"e": 4648,
"s": 4616,
"text": " Howto β Read File Line By Line"
},
{
"code": null,
"e": 4683,
"s": 4648,
"text": " Howto β Convert Date to LocalDate"
},
{
"code": null,
"e": 4706,
"s": 4683,
"text": " Howto β Merge Streams"
},
{
"code": null,
"e": 4753,
"s": 4706,
"text": " Howto β Resolve NullPointerException in toMap"
},
{
"code": null,
"e": 4778,
"s": 4753,
"text": " Howto -Get Stream count"
},
{
"code": null,
"e": 4822,
"s": 4778,
"text": " Howto β Get Min and Max values in a Stream"
}
] |
GWT - RPC Communication | A GWT based application is generally consists of a client side module and server side module. Client side code runs in browser and server side code runs in web server. Client side code has to make an HTTP request accross the network to access server side data.
RPC, Remote Procedure Call is the mechansim used by GWT in which client code can directly executes the server side methods.
GWT RPC is servlet based.
GWT RPC is servlet based.
GWT RPC is asynchronous and client is never blocked during communication.
GWT RPC is asynchronous and client is never blocked during communication.
Using GWT RPC Java objects can be sent directly between the client and the server (which are automatically serialized by the GWT framework).
Using GWT RPC Java objects can be sent directly between the client and the server (which are automatically serialized by the GWT framework).
Server-side servlet is termed as service.
Server-side servlet is termed as service.
Remote procedure call that is calling methods of server side servlets from client side code is referred to as invoking a service.
Remote procedure call that is calling methods of server side servlets from client side code is referred to as invoking a service.
Following are the three components used in GWT RPC communication mechanism
A remote service (server-side servlet) that runs on the server.
Client code to invoke that service.
Java data objects which will be passed between client and server.
GWT client and server both serialize and deserialize data automatically so developers are not required to serialize/deserialize objects and data objects can travel over HTTP.
Following diagram is showing the RPC Architecture.
To start using RPC, we're required to follow the GWT conventions.
Define a java model object at client side which should be serializable.
public class Message implements Serializable {
...
private String message;
public Message(){};
public void setMessage(String message) {
this.message = message;
}
...
}
Define an interface for service on client side that extends RemoteService listing all service methods.
Use annotation @RemoteServiceRelativePath to map the service with a default path of remote servlet relative to the module base URL.
@RemoteServiceRelativePath("message")
public interface MessageService extends RemoteService {
Message getMessage(String input);
}
Define an asynchronous interface to service on client side (at same location as service mentioned above) which will be used in the GWT client code.
public interface MessageServiceAsync {
void getMessage(String input, AsyncCallback<Message> callback);
}
Implement the interface at server side and that class should extends RemoteServiceServlet class.
public class MessageServiceImpl extends RemoteServiceServlet
implements MessageService{
...
public Message getMessage(String input) {
String messageString = "Hello " + input + "!";
Message message = new Message();
message.setMessage(messageString);
return message;
}
}
Edit the web application deployment descriptor (web.xml) to include MessageServiceImpl Servlet declaration.
<web-app>
...
<servlet>
<servlet-name>messageServiceImpl</servlet-name>
<servlet-class>com.tutorialspoint.server.MessageServiceImpl
</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>messageServiceImpl</servlet-name>
<url-pattern>/helloworld/message</url-pattern>
</servlet-mapping>
</web-app>
Create the service proxy class.
MessageServiceAsync messageService = GWT.create(MessageService.class);
Create the AsyncCallback Handler to handle RPC callback in which server returns the Message back to client
class MessageCallBack implements AsyncCallback<Message> {
@Override
public void onFailure(Throwable caught) {
Window.alert("Unable to obtain server response: "
+ caught.getMessage());
}
@Override
public void onSuccess(Message result) {
Window.alert(result.getMessage());
}
}
Call Remote service when user interacts with UI
public class HelloWorld implements EntryPoint {
...
public void onModuleLoad() {
...
buttonMessage.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
messageService.getMessage(txtName.getValue(),
new MessageCallBack());
}
});
...
}
}
This example will take you through simple steps to show example of a RPC Communication in GWT. Follow the following steps to update the GWT application we created in GWT - Create Application chapter β
Following is the content of the modified module descriptor src/com.tutorialspoint/HelloWorld.gwt.xml.
<?xml version = "1.0" encoding = "UTF-8"?>
<module rename-to = 'helloworld'>
<!-- Inherit the core Web Toolkit stuff. -->
<inherits name = 'com.google.gwt.user.User'/>
<!-- Inherit the default GWT style sheet. -->
<inherits name = 'com.google.gwt.user.theme.clean.Clean'/>
<!-- Inherit the UiBinder module. -->
<inherits name = "com.google.gwt.uibinder.UiBinder"/>
<!-- Specify the app entry point class. -->
<entry-point class = 'com.tutorialspoint.client.HelloWorld'/>
<!-- Specify the paths for translatable code -->
<source path = 'client'/>
<source path = 'shared'/>
</module>
Following is the content of the modified Style Sheet file war/HelloWorld.css.
body {
text-align: center;
font-family: verdana, sans-serif;
}
h1 {
font-size: 2em;
font-weight: bold;
color: #777777;
margin: 40px 0px 70px;
text-align: center;
}
Following is the content of the modified HTML host file war/HelloWorld.html.
<html>
<head>
<title>Hello World</title>
<link rel = "stylesheet" href = "HelloWorld.css"/>
<script language = "javascript" src = "helloworld/helloworld.nocache.js">
</script>
</head>
<body>
<h1>RPC Communication Demonstration</h1>
<div id = "gwtContainer"></div>
</body>
</html>
Now create Message.java file in the src/com.tutorialspoint/client package and place the following contents in it
package com.tutorialspoint.client;
import java.io.Serializable;
public class Message implements Serializable {
private static final long serialVersionUID = 1L;
private String message;
public Message(){};
public void setMessage(String message) {
this.message = message;
}
public String getMessage() {
return message;
}
}
Now create MessageService.java file in the src/com.tutorialspoint/client package and place the following contents in it
package com.tutorialspoint.client;
import com.google.gwt.user.client.rpc.RemoteService;
import com.google.gwt.user.client.rpc.RemoteServiceRelativePath;
@RemoteServiceRelativePath("message")
public interface MessageService extends RemoteService {
Message getMessage(String input);
}
Now create MessageServiceAsync.java file in the src/com.tutorialspoint/client package and place the following contents in it
package com.tutorialspoint.client;
import com.google.gwt.user.client.rpc.AsyncCallback;
public interface MessageServiceAsync {
void getMessage(String input, AsyncCallback<Message> callback);
}
Now create MessageServiceImpl.java file in the src/com.tutorialspoint/server package and place the following contents in it
package com.tutorialspoint.server;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;
import com.tutorialspoint.client.Message;
import com.tutorialspoint.client.MessageService;
public class MessageServiceImpl extends RemoteServiceServlet
implements MessageService{
private static final long serialVersionUID = 1L;
public Message getMessage(String input) {
String messageString = "Hello " + input + "!";
Message message = new Message();
message.setMessage(messageString);
return message;
}
}
Update the content of the modified web application deployment descriptor war/WEB-INF/web.xml to include MessageServiceImpl Servlet declaration.
<?xml version = "1.0" encoding = "UTF-8"?>
<!DOCTYPE web-app
PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd">
<web-app>
<!-- Default page to serve -->
<welcome-file-list>
<welcome-file>HelloWorld.html</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>messageServiceImpl</servlet-name>
<servlet-class>com.tutorialspoint.server.MessageServiceImpl
</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>messageServiceImpl</servlet-name>
<url-pattern>/helloworld/message</url-pattern>
</servlet-mapping>
</web-app>
Replace the contents of HelloWorld.java in src/com.tutorialspoint/client package with the following
package com.tutorialspoint.client;
import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.KeyCodes;
import com.google.gwt.event.dom.client.KeyUpEvent;
import com.google.gwt.event.dom.client.KeyUpHandler;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.DecoratorPanel;
import com.google.gwt.user.client.ui.HasHorizontalAlignment;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.VerticalPanel;
public class HelloWorld implements EntryPoint {
private MessageServiceAsync messageService =
GWT.create(MessageService.class);
private class MessageCallBack implements AsyncCallback<Message> {
@Override
public void onFailure(Throwable caught) {
/* server side error occured */
Window.alert("Unable to obtain server response: " + caught.getMessage());
}
@Override
public void onSuccess(Message result) {
/* server returned result, show user the message */
Window.alert(result.getMessage());
}
}
public void onModuleLoad() {
/*create UI */
final TextBox txtName = new TextBox();
txtName.setWidth("200");
txtName.addKeyUpHandler(new KeyUpHandler() {
@Override
public void onKeyUp(KeyUpEvent event) {
if(event.getNativeKeyCode() == KeyCodes.KEY_ENTER){
/* make remote call to server to get the message */
messageService.getMessage(txtName.getValue(),
new MessageCallBack());
}
}
});
Label lblName = new Label("Enter your name: ");
Button buttonMessage = new Button("Click Me!");
buttonMessage.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
/* make remote call to server to get the message */
messageService.getMessage(txtName.getValue(),
new MessageCallBack());
}
});
HorizontalPanel hPanel = new HorizontalPanel();
hPanel.add(lblName);
hPanel.add(txtName);
hPanel.setCellWidth(lblName, "130");
VerticalPanel vPanel = new VerticalPanel();
vPanel.setSpacing(10);
vPanel.add(hPanel);
vPanel.add(buttonMessage);
vPanel.setCellHorizontalAlignment(buttonMessage,
HasHorizontalAlignment.ALIGN_RIGHT);
DecoratorPanel panel = new DecoratorPanel();
panel.add(vPanel);
// Add widgets to the root panel.
RootPanel.get("gwtContainer").add(panel);
}
}
Once you are ready with all the changes done, let us compile and run the application in development mode as we did in GWT - Create Application chapter. If everything is fine with your application, this will produce following result β
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2284,
"s": 2023,
"text": "A GWT based application is generally consists of a client side module and server side module. Client side code runs in browser and server side code runs in web server. Client side code has to make an HTTP request accross the network to access server side data."
},
{
"code": null,
"e": 2408,
"s": 2284,
"text": "RPC, Remote Procedure Call is the mechansim used by GWT in which client code can directly executes the server side methods."
},
{
"code": null,
"e": 2434,
"s": 2408,
"text": "GWT RPC is servlet based."
},
{
"code": null,
"e": 2460,
"s": 2434,
"text": "GWT RPC is servlet based."
},
{
"code": null,
"e": 2534,
"s": 2460,
"text": "GWT RPC is asynchronous and client is never blocked during communication."
},
{
"code": null,
"e": 2608,
"s": 2534,
"text": "GWT RPC is asynchronous and client is never blocked during communication."
},
{
"code": null,
"e": 2749,
"s": 2608,
"text": "Using GWT RPC Java objects can be sent directly between the client and the server (which are automatically serialized by the GWT framework)."
},
{
"code": null,
"e": 2890,
"s": 2749,
"text": "Using GWT RPC Java objects can be sent directly between the client and the server (which are automatically serialized by the GWT framework)."
},
{
"code": null,
"e": 2932,
"s": 2890,
"text": "Server-side servlet is termed as service."
},
{
"code": null,
"e": 2974,
"s": 2932,
"text": "Server-side servlet is termed as service."
},
{
"code": null,
"e": 3104,
"s": 2974,
"text": "Remote procedure call that is calling methods of server side servlets from client side code is referred to as invoking a service."
},
{
"code": null,
"e": 3234,
"s": 3104,
"text": "Remote procedure call that is calling methods of server side servlets from client side code is referred to as invoking a service."
},
{
"code": null,
"e": 3309,
"s": 3234,
"text": "Following are the three components used in GWT RPC communication mechanism"
},
{
"code": null,
"e": 3373,
"s": 3309,
"text": "A remote service (server-side servlet) that runs on the server."
},
{
"code": null,
"e": 3409,
"s": 3373,
"text": "Client code to invoke that service."
},
{
"code": null,
"e": 3475,
"s": 3409,
"text": "Java data objects which will be passed between client and server."
},
{
"code": null,
"e": 3650,
"s": 3475,
"text": "GWT client and server both serialize and deserialize data automatically so developers are not required to serialize/deserialize objects and data objects can travel over HTTP."
},
{
"code": null,
"e": 3701,
"s": 3650,
"text": "Following diagram is showing the RPC Architecture."
},
{
"code": null,
"e": 3767,
"s": 3701,
"text": "To start using RPC, we're required to follow the GWT conventions."
},
{
"code": null,
"e": 3839,
"s": 3767,
"text": "Define a java model object at client side which should be serializable."
},
{
"code": null,
"e": 4032,
"s": 3839,
"text": "public class Message implements Serializable {\n ...\n private String message;\n public Message(){};\n\n public void setMessage(String message) {\n this.message = message;\n }\n ...\n}"
},
{
"code": null,
"e": 4135,
"s": 4032,
"text": "Define an interface for service on client side that extends RemoteService listing all service methods."
},
{
"code": null,
"e": 4267,
"s": 4135,
"text": "Use annotation @RemoteServiceRelativePath to map the service with a default path of remote servlet relative to the module base URL."
},
{
"code": null,
"e": 4400,
"s": 4267,
"text": "@RemoteServiceRelativePath(\"message\")\npublic interface MessageService extends RemoteService {\n Message getMessage(String input);\n}"
},
{
"code": null,
"e": 4548,
"s": 4400,
"text": "Define an asynchronous interface to service on client side (at same location as service mentioned above) which will be used in the GWT client code."
},
{
"code": null,
"e": 4656,
"s": 4548,
"text": "public interface MessageServiceAsync {\n void getMessage(String input, AsyncCallback<Message> callback);\n}"
},
{
"code": null,
"e": 4753,
"s": 4656,
"text": "Implement the interface at server side and that class should extends RemoteServiceServlet class."
},
{
"code": null,
"e": 5058,
"s": 4753,
"text": "public class MessageServiceImpl extends RemoteServiceServlet\n implements MessageService{\n ...\n public Message getMessage(String input) {\n String messageString = \"Hello \" + input + \"!\";\n Message message = new Message();\n message.setMessage(messageString);\n return message;\n }\n}"
},
{
"code": null,
"e": 5166,
"s": 5058,
"text": "Edit the web application deployment descriptor (web.xml) to include MessageServiceImpl Servlet declaration."
},
{
"code": null,
"e": 5518,
"s": 5166,
"text": "<web-app>\n ...\n <servlet>\n <servlet-name>messageServiceImpl</servlet-name>\n <servlet-class>com.tutorialspoint.server.MessageServiceImpl\n </servlet-class>\n </servlet>\n \n <servlet-mapping>\n <servlet-name>messageServiceImpl</servlet-name>\n <url-pattern>/helloworld/message</url-pattern>\n </servlet-mapping>\n</web-app>"
},
{
"code": null,
"e": 5550,
"s": 5518,
"text": "Create the service proxy class."
},
{
"code": null,
"e": 5621,
"s": 5550,
"text": "MessageServiceAsync messageService = GWT.create(MessageService.class);"
},
{
"code": null,
"e": 5728,
"s": 5621,
"text": "Create the AsyncCallback Handler to handle RPC callback in which server returns the Message back to client"
},
{
"code": null,
"e": 6047,
"s": 5728,
"text": "class MessageCallBack implements AsyncCallback<Message> {\n\n @Override\n public void onFailure(Throwable caught) {\n Window.alert(\"Unable to obtain server response: \"\n + caught.getMessage());\t\n }\n\n @Override\n public void onSuccess(Message result) {\n Window.alert(result.getMessage()); \n }\t \n}"
},
{
"code": null,
"e": 6095,
"s": 6047,
"text": "Call Remote service when user interacts with UI"
},
{
"code": null,
"e": 6448,
"s": 6095,
"text": "public class HelloWorld implements EntryPoint {\n ... \n public void onModuleLoad() {\n ...\n buttonMessage.addClickHandler(new ClickHandler() {\t\t\t\n @Override\n public void onClick(ClickEvent event) {\n messageService.getMessage(txtName.getValue(), \n new MessageCallBack());\n }\n });\n ...\n }\n}"
},
{
"code": null,
"e": 6649,
"s": 6448,
"text": "This example will take you through simple steps to show example of a RPC Communication in GWT. Follow the following steps to update the GWT application we created in GWT - Create Application chapter β"
},
{
"code": null,
"e": 6751,
"s": 6649,
"text": "Following is the content of the modified module descriptor src/com.tutorialspoint/HelloWorld.gwt.xml."
},
{
"code": null,
"e": 7489,
"s": 6751,
"text": "<?xml version = \"1.0\" encoding = \"UTF-8\"?>\n<module rename-to = 'helloworld'>\n <!-- Inherit the core Web Toolkit stuff. -->\n <inherits name = 'com.google.gwt.user.User'/>\n\n <!-- Inherit the default GWT style sheet. -->\n <inherits name = 'com.google.gwt.user.theme.clean.Clean'/>\n <!-- Inherit the UiBinder module. -->\n <inherits name = \"com.google.gwt.uibinder.UiBinder\"/>\n <!-- Specify the app entry point class. -->\n <entry-point class = 'com.tutorialspoint.client.HelloWorld'/>\n \n <!-- Specify the paths for translatable code -->\n <source path = 'client'/>\n <source path = 'shared'/>\n\n</module>"
},
{
"code": null,
"e": 7567,
"s": 7489,
"text": "Following is the content of the modified Style Sheet file war/HelloWorld.css."
},
{
"code": null,
"e": 7753,
"s": 7567,
"text": "body {\n text-align: center;\n font-family: verdana, sans-serif;\n}\n\nh1 {\n font-size: 2em;\n font-weight: bold;\n color: #777777;\n margin: 40px 0px 70px;\n text-align: center;\n}"
},
{
"code": null,
"e": 7830,
"s": 7753,
"text": "Following is the content of the modified HTML host file war/HelloWorld.html."
},
{
"code": null,
"e": 8159,
"s": 7830,
"text": "<html>\n <head>\n <title>Hello World</title>\n <link rel = \"stylesheet\" href = \"HelloWorld.css\"/>\n <script language = \"javascript\" src = \"helloworld/helloworld.nocache.js\">\n </script>\n </head>\n\n <body>\n <h1>RPC Communication Demonstration</h1>\n <div id = \"gwtContainer\"></div>\n </body>\n</html>"
},
{
"code": null,
"e": 8272,
"s": 8159,
"text": "Now create Message.java file in the src/com.tutorialspoint/client package and place the following contents in it"
},
{
"code": null,
"e": 8631,
"s": 8272,
"text": "package com.tutorialspoint.client;\n\nimport java.io.Serializable;\n\npublic class Message implements Serializable {\n \n private static final long serialVersionUID = 1L;\n private String message;\n public Message(){};\n\n public void setMessage(String message) {\n this.message = message;\n }\n\n public String getMessage() {\n return message;\n }\n}"
},
{
"code": null,
"e": 8751,
"s": 8631,
"text": "Now create MessageService.java file in the src/com.tutorialspoint/client package and place the following contents in it"
},
{
"code": null,
"e": 9039,
"s": 8751,
"text": "package com.tutorialspoint.client;\n\nimport com.google.gwt.user.client.rpc.RemoteService;\nimport com.google.gwt.user.client.rpc.RemoteServiceRelativePath;\n\n@RemoteServiceRelativePath(\"message\")\npublic interface MessageService extends RemoteService {\n Message getMessage(String input);\n}"
},
{
"code": null,
"e": 9164,
"s": 9039,
"text": "Now create MessageServiceAsync.java file in the src/com.tutorialspoint/client package and place the following contents in it"
},
{
"code": null,
"e": 9362,
"s": 9164,
"text": "package com.tutorialspoint.client;\n\nimport com.google.gwt.user.client.rpc.AsyncCallback;\n\npublic interface MessageServiceAsync {\n void getMessage(String input, AsyncCallback<Message> callback);\n}"
},
{
"code": null,
"e": 9486,
"s": 9362,
"text": "Now create MessageServiceImpl.java file in the src/com.tutorialspoint/server package and place the following contents in it"
},
{
"code": null,
"e": 10030,
"s": 9486,
"text": "package com.tutorialspoint.server;\n\nimport com.google.gwt.user.server.rpc.RemoteServiceServlet;\nimport com.tutorialspoint.client.Message;\nimport com.tutorialspoint.client.MessageService;\n\npublic class MessageServiceImpl extends RemoteServiceServlet \n implements MessageService{\n\n private static final long serialVersionUID = 1L;\n\n public Message getMessage(String input) {\n String messageString = \"Hello \" + input + \"!\";\n Message message = new Message();\n message.setMessage(messageString);\n return message;\n } \n}"
},
{
"code": null,
"e": 10174,
"s": 10030,
"text": "Update the content of the modified web application deployment descriptor war/WEB-INF/web.xml to include MessageServiceImpl Servlet declaration."
},
{
"code": null,
"e": 10827,
"s": 10174,
"text": "<?xml version = \"1.0\" encoding = \"UTF-8\"?>\n<!DOCTYPE web-app\n PUBLIC \"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN\"\n \"http://java.sun.com/dtd/web-app_2_3.dtd\">\n\n<web-app>\n <!-- Default page to serve -->\n <welcome-file-list>\n <welcome-file>HelloWorld.html</welcome-file>\n </welcome-file-list>\n \n <servlet>\n <servlet-name>messageServiceImpl</servlet-name>\n <servlet-class>com.tutorialspoint.server.MessageServiceImpl\n </servlet-class>\n </servlet>\n\n <servlet-mapping>\n <servlet-name>messageServiceImpl</servlet-name>\n <url-pattern>/helloworld/message</url-pattern>\n </servlet-mapping>\n</web-app>"
},
{
"code": null,
"e": 10927,
"s": 10827,
"text": "Replace the contents of HelloWorld.java in src/com.tutorialspoint/client package with the following"
},
{
"code": null,
"e": 13900,
"s": 10927,
"text": "package com.tutorialspoint.client;\n\nimport com.google.gwt.core.client.EntryPoint;\nimport com.google.gwt.core.client.GWT;\nimport com.google.gwt.event.dom.client.ClickEvent;\nimport com.google.gwt.event.dom.client.ClickHandler;\nimport com.google.gwt.event.dom.client.KeyCodes;\nimport com.google.gwt.event.dom.client.KeyUpEvent;\nimport com.google.gwt.event.dom.client.KeyUpHandler;\nimport com.google.gwt.user.client.Window;\nimport com.google.gwt.user.client.rpc.AsyncCallback;\nimport com.google.gwt.user.client.ui.Button;\nimport com.google.gwt.user.client.ui.DecoratorPanel;\nimport com.google.gwt.user.client.ui.HasHorizontalAlignment;\nimport com.google.gwt.user.client.ui.HorizontalPanel;\nimport com.google.gwt.user.client.ui.Label;\nimport com.google.gwt.user.client.ui.RootPanel;\nimport com.google.gwt.user.client.ui.TextBox;\nimport com.google.gwt.user.client.ui.VerticalPanel;\n\npublic class HelloWorld implements EntryPoint {\n\t\n private MessageServiceAsync messageService = \n GWT.create(MessageService.class);\n\n private class MessageCallBack implements AsyncCallback<Message> {\n @Override\n public void onFailure(Throwable caught) {\n /* server side error occured */\n Window.alert(\"Unable to obtain server response: \" + caught.getMessage());\t\n }\n @Override\n public void onSuccess(Message result) {\n /* server returned result, show user the message */\n Window.alert(result.getMessage());\n }\t \n }\n\n public void onModuleLoad() {\n /*create UI */\n final TextBox txtName = new TextBox(); \n txtName.setWidth(\"200\");\n txtName.addKeyUpHandler(new KeyUpHandler() {\n @Override\n public void onKeyUp(KeyUpEvent event) {\n if(event.getNativeKeyCode() == KeyCodes.KEY_ENTER){\n /* make remote call to server to get the message */\n messageService.getMessage(txtName.getValue(), \n new MessageCallBack());\n }\t\t\t\t\n }\n });\n Label lblName = new Label(\"Enter your name: \");\n\n Button buttonMessage = new Button(\"Click Me!\");\n\n buttonMessage.addClickHandler(new ClickHandler() {\t\t\t\n @Override\n public void onClick(ClickEvent event) {\n /* make remote call to server to get the message */\n messageService.getMessage(txtName.getValue(), \n new MessageCallBack());\n }\n });\n\n HorizontalPanel hPanel = new HorizontalPanel();\t\n hPanel.add(lblName);\n hPanel.add(txtName);\n hPanel.setCellWidth(lblName, \"130\");\n\n VerticalPanel vPanel = new VerticalPanel();\n vPanel.setSpacing(10);\n vPanel.add(hPanel);\n vPanel.add(buttonMessage);\n vPanel.setCellHorizontalAlignment(buttonMessage, \n HasHorizontalAlignment.ALIGN_RIGHT);\n\n DecoratorPanel panel = new DecoratorPanel();\n panel.add(vPanel);\n\n // Add widgets to the root panel.\n RootPanel.get(\"gwtContainer\").add(panel);\n } \n} "
},
{
"code": null,
"e": 14134,
"s": 13900,
"text": "Once you are ready with all the changes done, let us compile and run the application in development mode as we did in GWT - Create Application chapter. If everything is fine with your application, this will produce following result β"
},
{
"code": null,
"e": 14141,
"s": 14134,
"text": " Print"
},
{
"code": null,
"e": 14152,
"s": 14141,
"text": " Add Notes"
}
] |
R is Slow - And It's Your Fault! | Drew Seewald | Towards Data Science | Anyone who works in the data science space is familiar with R. Youβve surely come across someone making the argument that R is a slow language and canβt handle larger data. That simply isnβt always the case. A lot of R code Iβve seen in the wild shows that there is a lack of fundamental understanding of how the language works. Letβs look at one example of how to optimize your code to work with you instead of against you.
realdrewdata.medium.com
Letβs start with how the R programming language works. It is what is referred to as an interpreted language. This means you donβt have to compile anything before running code, the computer just interprets and runs it, giving you results. This helps speed up how quickly you can write and test your code, but has the drawback of generally being slower to execute. There is a lot of overhead in the processing because R needs to check the type of a variable nearly every time it looks at it. This makes it easy to change types and reuse variable names, but slows down computation for very repetitive tasks, like performing an action in a loop.
Letβs take an example of a simple programming problem: find all of the factors of a given number. To do this, we can look at every number starting with 1 all the way up to, and including, the given number. If our number is 2048, this would be every number from 1 to 2048. We would divide 2048 by each of those possible factors. If the remainder is 0, the number is a factor.
For the beginner programmer, you could tackle this pretty easily with a for loop. We assign 2048 to a variable, x. Then we can create a blank vector to store the factors in as we find them.
x <- 2048factors <- c()
Now the for loop. Weβll go from 1 to x. Inside the for loop, weβll create an if statement. The condition for the if statement will be x modulo (%%) i being equal to 0. The modulo will give us the remainder of dividing x by each number. When this is 0 weβll execute the next line that adds the value of i to our vector of factors.
for (i in 1:x) { if (x %% i == 0) { factors <- c(factors, i) }}
There isnβt anything wrong with this approach. Running it shouldnβt take any time at all on a pretty standard computer. Youβll get the correct values in the factors vector as well. So whatβs wrong with this approach?
When R uses loops, it essentially has to check the value of x and i each and every time the loop runs. To our minds it seems obvious that these will always be numeric, but R still needs to check every time. This starts to become a problem when you want to find the factors for a larger number, such as 2,048,000. On my computer, the same loop took about 26(!) seconds to find all the factors of 2,048,000.
If you want to run it on your machine, use the rbenchmark package. Use the benchmark function and give your code to benchmark a name, like Loop. Set that name equal to our loop and youβll get back your execution time in the elapsed section of the output. Note that the code is run multiple times and the elapsed time is the cumulative time for all runs.
library(rbenchmark)benchmark( "Loop" = { loop_factors <- c(1) for (i in 2:x) { if (x %% i == 0) { loop_factors <- c(loop_factors, i) } } })# Output# test replications elapsed relative user.self sys.self user.child# Loop 100 27.5 1 27.44 0 NA# Sys.child# NA
Now I know what youβre saying, use python (or another faster language)! But there is no reason R canβt handle this task much faster, if you know how it works. All we need to do is eliminate that overhead of R checking every variableβs type every single time it loops. Something like this maybe:
factors <- (1:x)[(x %% 1:x) == 0]
There you go problem solved! That runs about 7 to 8 times faster and gives the same correct answer. But this is all about understanding why and I like code to be readable, so letβs dive a bit deeper in as we rewrite this optimized statement.
First off, we already established that part of why R was taking a long time to run the loop was because it was checking the types of the variables every time it loops. Lucky for us, R was designed to leverage vectors to avoid this. Vectors are required to have the same type for every element, so R doesnβt need to check each and every element while it is computing. So to optimize things weβll use vectorized operations.
towardsdatascience.com
First, weβll take our number, x, and use the modulo operator (%%) to get every remainder when dividing it by every number from 1 to x. We can use 1:x to create the vector of all the numbers 1 through x. When we use the modulo of the single element x by a vector of numbers, R divides x by each element of the vector, returning a vector of the remainders.
remainders <- x %% 1:x
Next, we want to test which remainders are 0. Similarly to how the remainders operation worked, we can compare the entire remainders vector to 0. This will return a vector of TRUE/FALSE, where TRUE represents remainders that are 0.
true_false <- remainders == 0
Now, we can use the true_false vector to filter our possible numbers, 1 to x, giving us the final answer.
(1:x)[true_false]
Letβs check the speed of our calculations again, comparing all three versions: the for loop version, the single line vector optimized version, and the readable vector optimized version. Iβll use the benchmark function again, this time adding a Vector and Vector Readable. x is once again set to 2,048,000.
benchmark( "Loop" = { loop_factors <- c(1) for (i in 2:x) { if (x %% i == 0) { loop_factors <- c(loop_factors, i) } } }, "Vector" = { loop_factors <- (1:x)[(x %% 1:x) == 0] }, "Vector Readable" = { remainders <- x %% 1:x true_false <- remainders == 0 loop_factors <- (1:x)[true_false] })# Output# test replications elapsed relative user.self sys.self# 1 Loop 100 27.52 7.519 27.38 0.00# 2 Vector 100 3.66 1.000 2.99 0.66# 3 Vector Readable 100 3.77 1.030 3.24 0.50## user.child sys.child# 1 NA NA# 2 NA NA# 3 NA NA
In the output, the fastest running code will have a relative value of 1. Every other snippet will show how many times longer it took relative to that fastest snippet. In my case, the single line version was slightly faster than the readable version. This is most likely due to us storing the outputs between steps to make it more readable. You can also see that the for loop was 7.5 times slower than the vector versions. Vectors really do help optimize your code!
Thatβs awesome! R can do anything much faster using vectors, right? Well, R still has some limitations. While using vectors can greatly speed up calculations, R still does the majority of calculations in memory. So once we reach sufficiently large numbers, R wonβt be able to allocate vectors of the size required to do the calculation, like 2,048,000,000. Hereβs what happens:
So in the end, it is important to know your tools. R is a very approachable language that is pretty easy to pick up. Learning a few tricks, such as leveraging vectors, can speed up your calculations and help keep R relevant in your toolkit. You also need to know the limitations of your tool. Learning to optimize your code with vectors is useful, but once you hit a certain size of data and calculations, you may want to start looking to a new language. | [
{
"code": null,
"e": 597,
"s": 172,
"text": "Anyone who works in the data science space is familiar with R. Youβve surely come across someone making the argument that R is a slow language and canβt handle larger data. That simply isnβt always the case. A lot of R code Iβve seen in the wild shows that there is a lack of fundamental understanding of how the language works. Letβs look at one example of how to optimize your code to work with you instead of against you."
},
{
"code": null,
"e": 621,
"s": 597,
"text": "realdrewdata.medium.com"
},
{
"code": null,
"e": 1263,
"s": 621,
"text": "Letβs start with how the R programming language works. It is what is referred to as an interpreted language. This means you donβt have to compile anything before running code, the computer just interprets and runs it, giving you results. This helps speed up how quickly you can write and test your code, but has the drawback of generally being slower to execute. There is a lot of overhead in the processing because R needs to check the type of a variable nearly every time it looks at it. This makes it easy to change types and reuse variable names, but slows down computation for very repetitive tasks, like performing an action in a loop."
},
{
"code": null,
"e": 1638,
"s": 1263,
"text": "Letβs take an example of a simple programming problem: find all of the factors of a given number. To do this, we can look at every number starting with 1 all the way up to, and including, the given number. If our number is 2048, this would be every number from 1 to 2048. We would divide 2048 by each of those possible factors. If the remainder is 0, the number is a factor."
},
{
"code": null,
"e": 1828,
"s": 1638,
"text": "For the beginner programmer, you could tackle this pretty easily with a for loop. We assign 2048 to a variable, x. Then we can create a blank vector to store the factors in as we find them."
},
{
"code": null,
"e": 1852,
"s": 1828,
"text": "x <- 2048factors <- c()"
},
{
"code": null,
"e": 2182,
"s": 1852,
"text": "Now the for loop. Weβll go from 1 to x. Inside the for loop, weβll create an if statement. The condition for the if statement will be x modulo (%%) i being equal to 0. The modulo will give us the remainder of dividing x by each number. When this is 0 weβll execute the next line that adds the value of i to our vector of factors."
},
{
"code": null,
"e": 2259,
"s": 2182,
"text": "for (i in 1:x) { if (x %% i == 0) { factors <- c(factors, i) }}"
},
{
"code": null,
"e": 2476,
"s": 2259,
"text": "There isnβt anything wrong with this approach. Running it shouldnβt take any time at all on a pretty standard computer. Youβll get the correct values in the factors vector as well. So whatβs wrong with this approach?"
},
{
"code": null,
"e": 2882,
"s": 2476,
"text": "When R uses loops, it essentially has to check the value of x and i each and every time the loop runs. To our minds it seems obvious that these will always be numeric, but R still needs to check every time. This starts to become a problem when you want to find the factors for a larger number, such as 2,048,000. On my computer, the same loop took about 26(!) seconds to find all the factors of 2,048,000."
},
{
"code": null,
"e": 3236,
"s": 2882,
"text": "If you want to run it on your machine, use the rbenchmark package. Use the benchmark function and give your code to benchmark a name, like Loop. Set that name equal to our loop and youβll get back your execution time in the elapsed section of the output. Note that the code is run multiple times and the elapsed time is the cumulative time for all runs."
},
{
"code": null,
"e": 3602,
"s": 3236,
"text": "library(rbenchmark)benchmark( \"Loop\" = { loop_factors <- c(1) for (i in 2:x) { if (x %% i == 0) { loop_factors <- c(loop_factors, i) } } })# Output# test replications elapsed relative user.self sys.self user.child# Loop 100 27.5 1 27.44 0 NA# Sys.child# NA"
},
{
"code": null,
"e": 3897,
"s": 3602,
"text": "Now I know what youβre saying, use python (or another faster language)! But there is no reason R canβt handle this task much faster, if you know how it works. All we need to do is eliminate that overhead of R checking every variableβs type every single time it loops. Something like this maybe:"
},
{
"code": null,
"e": 3931,
"s": 3897,
"text": "factors <- (1:x)[(x %% 1:x) == 0]"
},
{
"code": null,
"e": 4173,
"s": 3931,
"text": "There you go problem solved! That runs about 7 to 8 times faster and gives the same correct answer. But this is all about understanding why and I like code to be readable, so letβs dive a bit deeper in as we rewrite this optimized statement."
},
{
"code": null,
"e": 4595,
"s": 4173,
"text": "First off, we already established that part of why R was taking a long time to run the loop was because it was checking the types of the variables every time it loops. Lucky for us, R was designed to leverage vectors to avoid this. Vectors are required to have the same type for every element, so R doesnβt need to check each and every element while it is computing. So to optimize things weβll use vectorized operations."
},
{
"code": null,
"e": 4618,
"s": 4595,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 4973,
"s": 4618,
"text": "First, weβll take our number, x, and use the modulo operator (%%) to get every remainder when dividing it by every number from 1 to x. We can use 1:x to create the vector of all the numbers 1 through x. When we use the modulo of the single element x by a vector of numbers, R divides x by each element of the vector, returning a vector of the remainders."
},
{
"code": null,
"e": 4996,
"s": 4973,
"text": "remainders <- x %% 1:x"
},
{
"code": null,
"e": 5228,
"s": 4996,
"text": "Next, we want to test which remainders are 0. Similarly to how the remainders operation worked, we can compare the entire remainders vector to 0. This will return a vector of TRUE/FALSE, where TRUE represents remainders that are 0."
},
{
"code": null,
"e": 5258,
"s": 5228,
"text": "true_false <- remainders == 0"
},
{
"code": null,
"e": 5364,
"s": 5258,
"text": "Now, we can use the true_false vector to filter our possible numbers, 1 to x, giving us the final answer."
},
{
"code": null,
"e": 5382,
"s": 5364,
"text": "(1:x)[true_false]"
},
{
"code": null,
"e": 5688,
"s": 5382,
"text": "Letβs check the speed of our calculations again, comparing all three versions: the for loop version, the single line vector optimized version, and the readable vector optimized version. Iβll use the benchmark function again, this time adding a Vector and Vector Readable. x is once again set to 2,048,000."
},
{
"code": null,
"e": 6455,
"s": 5688,
"text": "benchmark( \"Loop\" = { loop_factors <- c(1) for (i in 2:x) { if (x %% i == 0) { loop_factors <- c(loop_factors, i) } } }, \"Vector\" = { loop_factors <- (1:x)[(x %% 1:x) == 0] }, \"Vector Readable\" = { remainders <- x %% 1:x true_false <- remainders == 0 loop_factors <- (1:x)[true_false] })# Output# test replications elapsed relative user.self sys.self# 1 Loop 100 27.52 7.519 27.38 0.00# 2 Vector 100 3.66 1.000 2.99 0.66# 3 Vector Readable 100 3.77 1.030 3.24 0.50## user.child sys.child# 1 NA NA# 2 NA NA# 3 NA NA"
},
{
"code": null,
"e": 6920,
"s": 6455,
"text": "In the output, the fastest running code will have a relative value of 1. Every other snippet will show how many times longer it took relative to that fastest snippet. In my case, the single line version was slightly faster than the readable version. This is most likely due to us storing the outputs between steps to make it more readable. You can also see that the for loop was 7.5 times slower than the vector versions. Vectors really do help optimize your code!"
},
{
"code": null,
"e": 7298,
"s": 6920,
"text": "Thatβs awesome! R can do anything much faster using vectors, right? Well, R still has some limitations. While using vectors can greatly speed up calculations, R still does the majority of calculations in memory. So once we reach sufficiently large numbers, R wonβt be able to allocate vectors of the size required to do the calculation, like 2,048,000,000. Hereβs what happens:"
}
] |
Interactive Data Visualization with Vega | by DeΜborah Mesquita | Towards Data Science | Iβm always learning new visualization tools because this helps me identify the right one for the task at hand. When it comes to Data Visualization, d3 is usually the go-to choice, but recently I've been playing with Vega and I'm loving it.
Vega introduces a visualization grammar. A grammar is basically a set of rules that dictate how to use a language, so we can think of Vega as a tool that defines a set of rules of how to build and manipulate visual elements.
As my experience with data visualization grows, Iβm finding more and more that constraints are a good thing. By introducing a visualization grammar, Vega gives us some constraints to work with. The best thing about it is that these constraints can make us feel very productive while building data visualizations.
There is also Vega-Lite, a high-level grammar that focuses on rapid creation of common statistical graphics, but today we'll stick with Vega which is a more general purpose tool.
Ok, enough of introductions, letβs get an overview about how Vega works.
We can deploy Vega on the web, but in this tutorial weβll simply use the Vega Editor (which is another great thing about Vega).
While working with Vega we define the visualization in a JSON object. Letβs start building a Bar Chart.
If we break down this chart we have:
π The data (the categories and amount for each data point)
π The x-axis, where each category is accommodated (weβll need a scale to say were each category should be placed)
π The y-axis, where the amount for each data point is displayed (weβll need a scale to say were each amount should be placed)
βπΎ The rectangles
And this is how we define the above using Vega:
{ "$schema": "https://vega.github.io/schema/vega/v5.json", "width": 400, "height": 200, "padding": 5, "data": [ { "name": "our_data", "values": [ { "category": "A", "amount": 28 }, { "category": "B", "amount": 55 }, { "category": "C", "amount": 43 } ] } ], "scales": [ { "name": "xscale", "type": "band", "domain": { "data": "our_data", "field": "category" }, "range": "width", "padding": 0.05 }, { "name": "yscale", "domain": { "data": "our_data", "field": "amount" }, "range": "height" } ], "axes": [ { "orient": "bottom", "scale": "xscale" }, { "orient": "left", "scale": "yscale" } ], "marks": [ { "type": "rect", "from": { "data": "our_data" }, "encode": { "enter": { "x": { "scale": "xscale", "field": "category" }, "width": { "scale": "xscale", "band": 1 }, "y": { "scale": "yscale", "field": "amount" }, "y2": { "scale": "yscale", "value": 0 }, "fill": { "value": "steelblue" } } } } ]}
You can try it live here.
Letβs go through each of these definitions. Iβll explain them briefly here but there are a lot more properties we can use to customize things (itβs a good idea to check the Docs when using each of them).
We can define data directly in a specification (like we are doing using the "values" property) or load data from an external file (json or csv for example) using the "url" property.
Vega scales are provided by the d3-scale library. We specify the type of scale with the "type" keyword (default is linear). Scale domains can be specified in multiple ways:
A data reference object that specifies field values in one or more data sets, like we are doing with {"data": "our_data", "field": "amount"}. Vega computes the [min,max] array of the amount key from the dataset
As a literal array of domain values
A signal reference that resolves to a domain value array. For example, {"signal": "myDomain"} (donβt worry, Iβll talk about Signals later on)
Here we need to specify the orientation and the scale that should be used to create the axis. There are a lot of properties we can use to customize them.
We use marks to encode data using geometric primitives (rectangles, circles, lines and so on). In this bar chart we are using the Rect mark. They need a given position, width, and height. We also need to specify what data should be used to build the marks (the "from" property).
"from": {"data":"our_data"}
All the definitions for things like "x", "y" and "width" will come from this dataset. Vega Types might look a little confusing at first, so letβs go through the ones we are using here:
"x": {"scale": "xscale", "field": "category"}
The "x" property for the rects will be set by the passing the values from "category" field to the "xscale".
"y": {"scale": "xscale", "band": 1}
The "y" property for each rect will be the range band width of the band scale xscale.
"fill": {"value": "steelblue"}
The "fill" color of the rects will be steelblue. To define constant values we use the "value" property.
Vega uses the same enter, update, exit pattern that d3 uses:
βThe enter properties are evaluated when data is processed for the first time and a mark instance is newly added to a scene. The update properties are evaluated for all existing (non-exiting) mark instances. The exit properties are evaluated when the data backing a mark is removed, and so the mark is leaving the visual scene.β β Vega docs
We use the pattern inside the "encode" property. In this bar chart we are placing the elements when the data is processed:
"encode": { "enter": { "x": {"scale": "xscale", "field": "category"}, "width": {"scale": "xscale", "band": 1}, "y": {"scale": "yscale", "field": "amount"}, "y2": {"scale": "yscale", "value": 0}, "fill": {"value": "steelblue"} }}
And this was the Vega 101 tour! To get a better sense of what Vega is capable of letβs build a timeline chart.
Besides loading the data we can also filter, calculate new fields or derive new data streams using Vega Transforms. We can sort the items by name using the collect transform:
"data": [ { "name": "libraries", "format": { "type": "json", "parse": { "release": "date:'%Y'" } }, "values": [ { "name": "vega", "release": "2013", "license": "BSD 3-Clause", "description": "Vega is a visualization grammar, a declarative language for creating, saving, and sharing interactive visualization designs" }, { "name": "d3", "release": "2011", "license": "BSD 3-Clause", "description": "D3 (Data-Driven Documents or D3.js) is a JavaScript library for visualizing data using web standards" }, { "name": "plotly", "release": "2012", "license": "MIT", "description": "Plotly.js is an open source JavaScript library for creating graphs and dashboards" } ], "transform": [ { "type": "collect", "sort": { "field": "name" } } ] } ]
Another great thing about Vega is that it's possible the inspect the contents of all the data we use to build the visualizations:
We'll need a time scale for the x-axis and an ordinal scale to color the rectangles:
"scales": [ { "name": "xScale", "type": "time", "domain": { "data": "libraries", "field": "release" }, "range": "width", "nice": "year" }, { "name": "colorScale", "type": "ordinal", "domain": { "data": "libraries", "field": "license" }, "range": { "scheme": "dark2" } } ]
Let's place an axis in the bottom and show the year in the labels:
"axes": [ { "scale": "xScale", "orient": "bottom", "format": "%Y" } ]
There are three marks: the rectangles, the text inside the rectangles and the line from each rectangle to the axis. We'll use "rect", "text" and "rule" marks to define each of them.
But first let's introduce an important Vega property: Signals.
Signals are dynamic variables. As the documentation says, the signal values are reactive: they can update in response to input event streams, external API calls, or changes to upstream signals. Here we'll use them with initial values, but their power comes from being able to update them (we'll see how to do that another time).
"signals": [ { "name": "rectWidth", "value": 50 }, { "name": "rectHeight", "value": 40 }, { "name": "rectY", "value": 85 }, { "name": "rectCenter", "init": "[rectWidth/2,rectY+rectHeight/2]" } ]
Now that we have the signals we can use them to place the marks. Signals can also hold Vega expressions. A very used one is the scale:
scale(name, value[, group])Applies the named scale transform (or projection) to the specified value. The optional group argument takes a scenegraph group mark item to indicate the specific scope in which to look up the scale or projection.
In this example we'll use an expression to place the rectangles in the middle of each year with this expression:
"signal": "scale('xScale',datum.release)-rectWidth/2" //scale(name, value[,group]
As we saw earlier, we need to specify what data should be used to build the marks with the "from" property. Vega is so great that we can specify the data from another mark itself! In this case, we'll use the data from the rect marks so we can get the center for each rectangle and place the text in the middle. To access the data points we use "datum" inside the expression.
"marks": [ { "type": "rect", "name": "rectangles", "from": { "data": "libraries" }, "encode": { "enter": { "width": { "signal": "rectWidth" }, "height": { "signal": "rectHeight" }, "x": { "signal": "scale('xScale',datum.release)-rectWidth/2" }, "y": { "signal": "rectY" }, "fill": { "signal": "scale('colorScale', datum.license)" }, "tooltip": { "signal": "{'Description': datum.description}" } }, "update": { "fillOpacity": { "value": 1 } }, "hover": { "fillOpacity": { "value": 0.5 } } } }, { "type": "text", "name": "labels", "from": { "data": "rectangles" // β¬
οΈcool }, "encode": { "enter": { "text": { "signal": "datum.datum.name" }, "x": { "signal": "datum.x+rectCenter[0]" //datum.x is from rect }, "y": { "signal": "rectCenter[1]" }, "align": { "value": "center" }, "baseline": { "value": "middle" }, "fontWeight": { "value": "bold" }, "fill": { "value": "black" } } }, "interactive": false }, { "type": "rule", "from": { "data": "labels" // β¬
οΈcool }, "encode": { "enter": { "x": { "signal": "datum.x" }, "x2": { "signal": "datum.x" }, "y": { "signal": "datum.y+rectCenter[0]-5" }, "y2": { "signal": "height" }, "strokeWidth": { "value": 2 } } } } ]
Legends definitions are similar to mark definitions. To customize is the addressable elements are:
legend for the legend group mark,
title for the title text mark,
labels for label text marks,
symbols for legend symbol marks,
entries for symbol legend group marks containing a symbol / label pair, and
gradient for a gradient rect marks: one rect with gradient fill for continuous gradient legends, multiple rect marks with solid fill for discrete gradient legends.
Here we'll only set the "x" position for the legend (the whole group) and set the fontSize for the title and the labels.
"legends": [ { "title": "License", "fill": "colorScale", "orient": "none", "encode": { "title": { "update": { "fontSize": { "value": 15 } } }, "labels": { "update": { "fontSize": { "value": 12 } } }, "legend": { "update": { "x": { "value": 500 } } } } } ]
The config object defines default visual values to set a visualizationβs theme. Here we are setting the typefaces for the text of the graph. The title directive adds a descriptive title to a chart.
"config": { "text": { "font": "Ideal Sans, Avenir Next, Helvetica" }, "title": { "font": "Ideal Sans, Avenir Next, Helvetica", "fontWeight": 500, "fontSize": 17, "limit": -1 }, "axis": { "labelFont": "Ideal Sans, Avenir Next, Helvetica", "labelFontSize": 12 } },"title": { "text": "Data visualization tools release dates", "orient": "top", "anchor": "start", "frame": "group", "encode": { "update": { "dx": { "value": -1 } } } }
And we are done! You can see the code here.
There are some other cool Vega features that we didn't see in this tutorial:
Triggers: Modify data sets or mark properties in response to signal values
Projections: Cartographic projections to map (longitude, latitude) data
Event Streams: Define input event streams to specify interactions
Layout: Perform grid layout for a collection of group marks
Today I use Vega in my workflow to prototype and test assumptions about the choices of my data visualizations. If after that I identify that I need something more customized Iβll then change gears and use d3 for that.
You can check more Vega examples here: https://vega.github.io/vega/examples/. We can view all the examples in the Online Vega Editor, which is awesome.
And that's it! Thanks for reading! π | [
{
"code": null,
"e": 412,
"s": 172,
"text": "Iβm always learning new visualization tools because this helps me identify the right one for the task at hand. When it comes to Data Visualization, d3 is usually the go-to choice, but recently I've been playing with Vega and I'm loving it."
},
{
"code": null,
"e": 637,
"s": 412,
"text": "Vega introduces a visualization grammar. A grammar is basically a set of rules that dictate how to use a language, so we can think of Vega as a tool that defines a set of rules of how to build and manipulate visual elements."
},
{
"code": null,
"e": 950,
"s": 637,
"text": "As my experience with data visualization grows, Iβm finding more and more that constraints are a good thing. By introducing a visualization grammar, Vega gives us some constraints to work with. The best thing about it is that these constraints can make us feel very productive while building data visualizations."
},
{
"code": null,
"e": 1129,
"s": 950,
"text": "There is also Vega-Lite, a high-level grammar that focuses on rapid creation of common statistical graphics, but today we'll stick with Vega which is a more general purpose tool."
},
{
"code": null,
"e": 1202,
"s": 1129,
"text": "Ok, enough of introductions, letβs get an overview about how Vega works."
},
{
"code": null,
"e": 1330,
"s": 1202,
"text": "We can deploy Vega on the web, but in this tutorial weβll simply use the Vega Editor (which is another great thing about Vega)."
},
{
"code": null,
"e": 1434,
"s": 1330,
"text": "While working with Vega we define the visualization in a JSON object. Letβs start building a Bar Chart."
},
{
"code": null,
"e": 1471,
"s": 1434,
"text": "If we break down this chart we have:"
},
{
"code": null,
"e": 1530,
"s": 1471,
"text": "π The data (the categories and amount for each data point)"
},
{
"code": null,
"e": 1644,
"s": 1530,
"text": "π The x-axis, where each category is accommodated (weβll need a scale to say were each category should be placed)"
},
{
"code": null,
"e": 1770,
"s": 1644,
"text": "π The y-axis, where the amount for each data point is displayed (weβll need a scale to say were each amount should be placed)"
},
{
"code": null,
"e": 1788,
"s": 1770,
"text": "βπΎ The rectangles"
},
{
"code": null,
"e": 1836,
"s": 1788,
"text": "And this is how we define the above using Vega:"
},
{
"code": null,
"e": 3223,
"s": 1836,
"text": "{ \"$schema\": \"https://vega.github.io/schema/vega/v5.json\", \"width\": 400, \"height\": 200, \"padding\": 5, \"data\": [ { \"name\": \"our_data\", \"values\": [ { \"category\": \"A\", \"amount\": 28 }, { \"category\": \"B\", \"amount\": 55 }, { \"category\": \"C\", \"amount\": 43 } ] } ], \"scales\": [ { \"name\": \"xscale\", \"type\": \"band\", \"domain\": { \"data\": \"our_data\", \"field\": \"category\" }, \"range\": \"width\", \"padding\": 0.05 }, { \"name\": \"yscale\", \"domain\": { \"data\": \"our_data\", \"field\": \"amount\" }, \"range\": \"height\" } ], \"axes\": [ { \"orient\": \"bottom\", \"scale\": \"xscale\" }, { \"orient\": \"left\", \"scale\": \"yscale\" } ], \"marks\": [ { \"type\": \"rect\", \"from\": { \"data\": \"our_data\" }, \"encode\": { \"enter\": { \"x\": { \"scale\": \"xscale\", \"field\": \"category\" }, \"width\": { \"scale\": \"xscale\", \"band\": 1 }, \"y\": { \"scale\": \"yscale\", \"field\": \"amount\" }, \"y2\": { \"scale\": \"yscale\", \"value\": 0 }, \"fill\": { \"value\": \"steelblue\" } } } } ]}"
},
{
"code": null,
"e": 3249,
"s": 3223,
"text": "You can try it live here."
},
{
"code": null,
"e": 3453,
"s": 3249,
"text": "Letβs go through each of these definitions. Iβll explain them briefly here but there are a lot more properties we can use to customize things (itβs a good idea to check the Docs when using each of them)."
},
{
"code": null,
"e": 3635,
"s": 3453,
"text": "We can define data directly in a specification (like we are doing using the \"values\" property) or load data from an external file (json or csv for example) using the \"url\" property."
},
{
"code": null,
"e": 3808,
"s": 3635,
"text": "Vega scales are provided by the d3-scale library. We specify the type of scale with the \"type\" keyword (default is linear). Scale domains can be specified in multiple ways:"
},
{
"code": null,
"e": 4019,
"s": 3808,
"text": "A data reference object that specifies field values in one or more data sets, like we are doing with {\"data\": \"our_data\", \"field\": \"amount\"}. Vega computes the [min,max] array of the amount key from the dataset"
},
{
"code": null,
"e": 4055,
"s": 4019,
"text": "As a literal array of domain values"
},
{
"code": null,
"e": 4197,
"s": 4055,
"text": "A signal reference that resolves to a domain value array. For example, {\"signal\": \"myDomain\"} (donβt worry, Iβll talk about Signals later on)"
},
{
"code": null,
"e": 4351,
"s": 4197,
"text": "Here we need to specify the orientation and the scale that should be used to create the axis. There are a lot of properties we can use to customize them."
},
{
"code": null,
"e": 4630,
"s": 4351,
"text": "We use marks to encode data using geometric primitives (rectangles, circles, lines and so on). In this bar chart we are using the Rect mark. They need a given position, width, and height. We also need to specify what data should be used to build the marks (the \"from\" property)."
},
{
"code": null,
"e": 4658,
"s": 4630,
"text": "\"from\": {\"data\":\"our_data\"}"
},
{
"code": null,
"e": 4843,
"s": 4658,
"text": "All the definitions for things like \"x\", \"y\" and \"width\" will come from this dataset. Vega Types might look a little confusing at first, so letβs go through the ones we are using here:"
},
{
"code": null,
"e": 4889,
"s": 4843,
"text": "\"x\": {\"scale\": \"xscale\", \"field\": \"category\"}"
},
{
"code": null,
"e": 4997,
"s": 4889,
"text": "The \"x\" property for the rects will be set by the passing the values from \"category\" field to the \"xscale\"."
},
{
"code": null,
"e": 5033,
"s": 4997,
"text": "\"y\": {\"scale\": \"xscale\", \"band\": 1}"
},
{
"code": null,
"e": 5119,
"s": 5033,
"text": "The \"y\" property for each rect will be the range band width of the band scale xscale."
},
{
"code": null,
"e": 5150,
"s": 5119,
"text": "\"fill\": {\"value\": \"steelblue\"}"
},
{
"code": null,
"e": 5254,
"s": 5150,
"text": "The \"fill\" color of the rects will be steelblue. To define constant values we use the \"value\" property."
},
{
"code": null,
"e": 5315,
"s": 5254,
"text": "Vega uses the same enter, update, exit pattern that d3 uses:"
},
{
"code": null,
"e": 5656,
"s": 5315,
"text": "βThe enter properties are evaluated when data is processed for the first time and a mark instance is newly added to a scene. The update properties are evaluated for all existing (non-exiting) mark instances. The exit properties are evaluated when the data backing a mark is removed, and so the mark is leaving the visual scene.β β Vega docs"
},
{
"code": null,
"e": 5779,
"s": 5656,
"text": "We use the pattern inside the \"encode\" property. In this bar chart we are placing the elements when the data is processed:"
},
{
"code": null,
"e": 6050,
"s": 5779,
"text": "\"encode\": { \"enter\": { \"x\": {\"scale\": \"xscale\", \"field\": \"category\"}, \"width\": {\"scale\": \"xscale\", \"band\": 1}, \"y\": {\"scale\": \"yscale\", \"field\": \"amount\"}, \"y2\": {\"scale\": \"yscale\", \"value\": 0}, \"fill\": {\"value\": \"steelblue\"} }}"
},
{
"code": null,
"e": 6161,
"s": 6050,
"text": "And this was the Vega 101 tour! To get a better sense of what Vega is capable of letβs build a timeline chart."
},
{
"code": null,
"e": 6336,
"s": 6161,
"text": "Besides loading the data we can also filter, calculate new fields or derive new data streams using Vega Transforms. We can sort the items by name using the collect transform:"
},
{
"code": null,
"e": 7346,
"s": 6336,
"text": "\"data\": [ { \"name\": \"libraries\", \"format\": { \"type\": \"json\", \"parse\": { \"release\": \"date:'%Y'\" } }, \"values\": [ { \"name\": \"vega\", \"release\": \"2013\", \"license\": \"BSD 3-Clause\", \"description\": \"Vega is a visualization grammar, a declarative language for creating, saving, and sharing interactive visualization designs\" }, { \"name\": \"d3\", \"release\": \"2011\", \"license\": \"BSD 3-Clause\", \"description\": \"D3 (Data-Driven Documents or D3.js) is a JavaScript library for visualizing data using web standards\" }, { \"name\": \"plotly\", \"release\": \"2012\", \"license\": \"MIT\", \"description\": \"Plotly.js is an open source JavaScript library for creating graphs and dashboards\" } ], \"transform\": [ { \"type\": \"collect\", \"sort\": { \"field\": \"name\" } } ] } ]"
},
{
"code": null,
"e": 7476,
"s": 7346,
"text": "Another great thing about Vega is that it's possible the inspect the contents of all the data we use to build the visualizations:"
},
{
"code": null,
"e": 7561,
"s": 7476,
"text": "We'll need a time scale for the x-axis and an ordinal scale to color the rectangles:"
},
{
"code": null,
"e": 7941,
"s": 7561,
"text": "\"scales\": [ { \"name\": \"xScale\", \"type\": \"time\", \"domain\": { \"data\": \"libraries\", \"field\": \"release\" }, \"range\": \"width\", \"nice\": \"year\" }, { \"name\": \"colorScale\", \"type\": \"ordinal\", \"domain\": { \"data\": \"libraries\", \"field\": \"license\" }, \"range\": { \"scheme\": \"dark2\" } } ]"
},
{
"code": null,
"e": 8008,
"s": 7941,
"text": "Let's place an axis in the bottom and show the year in the labels:"
},
{
"code": null,
"e": 8100,
"s": 8008,
"text": "\"axes\": [ { \"scale\": \"xScale\", \"orient\": \"bottom\", \"format\": \"%Y\" } ]"
},
{
"code": null,
"e": 8282,
"s": 8100,
"text": "There are three marks: the rectangles, the text inside the rectangles and the line from each rectangle to the axis. We'll use \"rect\", \"text\" and \"rule\" marks to define each of them."
},
{
"code": null,
"e": 8345,
"s": 8282,
"text": "But first let's introduce an important Vega property: Signals."
},
{
"code": null,
"e": 8674,
"s": 8345,
"text": "Signals are dynamic variables. As the documentation says, the signal values are reactive: they can update in response to input event streams, external API calls, or changes to upstream signals. Here we'll use them with initial values, but their power comes from being able to update them (we'll see how to do that another time)."
},
{
"code": null,
"e": 8934,
"s": 8674,
"text": "\"signals\": [ { \"name\": \"rectWidth\", \"value\": 50 }, { \"name\": \"rectHeight\", \"value\": 40 }, { \"name\": \"rectY\", \"value\": 85 }, { \"name\": \"rectCenter\", \"init\": \"[rectWidth/2,rectY+rectHeight/2]\" } ]"
},
{
"code": null,
"e": 9069,
"s": 8934,
"text": "Now that we have the signals we can use them to place the marks. Signals can also hold Vega expressions. A very used one is the scale:"
},
{
"code": null,
"e": 9309,
"s": 9069,
"text": "scale(name, value[, group])Applies the named scale transform (or projection) to the specified value. The optional group argument takes a scenegraph group mark item to indicate the specific scope in which to look up the scale or projection."
},
{
"code": null,
"e": 9422,
"s": 9309,
"text": "In this example we'll use an expression to place the rectangles in the middle of each year with this expression:"
},
{
"code": null,
"e": 9512,
"s": 9422,
"text": "\"signal\": \"scale('xScale',datum.release)-rectWidth/2\" //scale(name, value[,group]"
},
{
"code": null,
"e": 9887,
"s": 9512,
"text": "As we saw earlier, we need to specify what data should be used to build the marks with the \"from\" property. Vega is so great that we can specify the data from another mark itself! In this case, we'll use the data from the rect marks so we can get the center for each rectangle and place the text in the middle. To access the data points we use \"datum\" inside the expression."
},
{
"code": null,
"e": 11824,
"s": 9887,
"text": "\"marks\": [ { \"type\": \"rect\", \"name\": \"rectangles\", \"from\": { \"data\": \"libraries\" }, \"encode\": { \"enter\": { \"width\": { \"signal\": \"rectWidth\" }, \"height\": { \"signal\": \"rectHeight\" }, \"x\": { \"signal\": \"scale('xScale',datum.release)-rectWidth/2\" }, \"y\": { \"signal\": \"rectY\" }, \"fill\": { \"signal\": \"scale('colorScale', datum.license)\" }, \"tooltip\": { \"signal\": \"{'Description': datum.description}\" } }, \"update\": { \"fillOpacity\": { \"value\": 1 } }, \"hover\": { \"fillOpacity\": { \"value\": 0.5 } } } }, { \"type\": \"text\", \"name\": \"labels\", \"from\": { \"data\": \"rectangles\" // β¬
οΈcool }, \"encode\": { \"enter\": { \"text\": { \"signal\": \"datum.datum.name\" }, \"x\": { \"signal\": \"datum.x+rectCenter[0]\" //datum.x is from rect }, \"y\": { \"signal\": \"rectCenter[1]\" }, \"align\": { \"value\": \"center\" }, \"baseline\": { \"value\": \"middle\" }, \"fontWeight\": { \"value\": \"bold\" }, \"fill\": { \"value\": \"black\" } } }, \"interactive\": false }, { \"type\": \"rule\", \"from\": { \"data\": \"labels\" // β¬
οΈcool }, \"encode\": { \"enter\": { \"x\": { \"signal\": \"datum.x\" }, \"x2\": { \"signal\": \"datum.x\" }, \"y\": { \"signal\": \"datum.y+rectCenter[0]-5\" }, \"y2\": { \"signal\": \"height\" }, \"strokeWidth\": { \"value\": 2 } } } } ]"
},
{
"code": null,
"e": 11923,
"s": 11824,
"text": "Legends definitions are similar to mark definitions. To customize is the addressable elements are:"
},
{
"code": null,
"e": 11957,
"s": 11923,
"text": "legend for the legend group mark,"
},
{
"code": null,
"e": 11988,
"s": 11957,
"text": "title for the title text mark,"
},
{
"code": null,
"e": 12017,
"s": 11988,
"text": "labels for label text marks,"
},
{
"code": null,
"e": 12050,
"s": 12017,
"text": "symbols for legend symbol marks,"
},
{
"code": null,
"e": 12126,
"s": 12050,
"text": "entries for symbol legend group marks containing a symbol / label pair, and"
},
{
"code": null,
"e": 12290,
"s": 12126,
"text": "gradient for a gradient rect marks: one rect with gradient fill for continuous gradient legends, multiple rect marks with solid fill for discrete gradient legends."
},
{
"code": null,
"e": 12411,
"s": 12290,
"text": "Here we'll only set the \"x\" position for the legend (the whole group) and set the fontSize for the title and the labels."
},
{
"code": null,
"e": 12900,
"s": 12411,
"text": "\"legends\": [ { \"title\": \"License\", \"fill\": \"colorScale\", \"orient\": \"none\", \"encode\": { \"title\": { \"update\": { \"fontSize\": { \"value\": 15 } } }, \"labels\": { \"update\": { \"fontSize\": { \"value\": 12 } } }, \"legend\": { \"update\": { \"x\": { \"value\": 500 } } } } } ]"
},
{
"code": null,
"e": 13098,
"s": 12900,
"text": "The config object defines default visual values to set a visualizationβs theme. Here we are setting the typefaces for the text of the graph. The title directive adds a descriptive title to a chart."
},
{
"code": null,
"e": 13633,
"s": 13098,
"text": "\"config\": { \"text\": { \"font\": \"Ideal Sans, Avenir Next, Helvetica\" }, \"title\": { \"font\": \"Ideal Sans, Avenir Next, Helvetica\", \"fontWeight\": 500, \"fontSize\": 17, \"limit\": -1 }, \"axis\": { \"labelFont\": \"Ideal Sans, Avenir Next, Helvetica\", \"labelFontSize\": 12 } },\"title\": { \"text\": \"Data visualization tools release dates\", \"orient\": \"top\", \"anchor\": \"start\", \"frame\": \"group\", \"encode\": { \"update\": { \"dx\": { \"value\": -1 } } } }"
},
{
"code": null,
"e": 13677,
"s": 13633,
"text": "And we are done! You can see the code here."
},
{
"code": null,
"e": 13754,
"s": 13677,
"text": "There are some other cool Vega features that we didn't see in this tutorial:"
},
{
"code": null,
"e": 13829,
"s": 13754,
"text": "Triggers: Modify data sets or mark properties in response to signal values"
},
{
"code": null,
"e": 13901,
"s": 13829,
"text": "Projections: Cartographic projections to map (longitude, latitude) data"
},
{
"code": null,
"e": 13967,
"s": 13901,
"text": "Event Streams: Define input event streams to specify interactions"
},
{
"code": null,
"e": 14027,
"s": 13967,
"text": "Layout: Perform grid layout for a collection of group marks"
},
{
"code": null,
"e": 14245,
"s": 14027,
"text": "Today I use Vega in my workflow to prototype and test assumptions about the choices of my data visualizations. If after that I identify that I need something more customized Iβll then change gears and use d3 for that."
},
{
"code": null,
"e": 14397,
"s": 14245,
"text": "You can check more Vega examples here: https://vega.github.io/vega/examples/. We can view all the examples in the Online Vega Editor, which is awesome."
}
] |
Why to use fgets() over scanf() in C? - GeeksforGeeks | 14 Mar, 2019
Any time you use an *f function, whether it be printf, scanf, or their derivatives (fprintf, fscanf, etc...), you are doing more things than you might realize. Not only are you reading (or writing) something, but-and hereβs the problem- you are interpreting it. The format string can be thought of as kind of an βevalβ function like you would see if you program in Lisp. So the problem with simply reading input from the user and echoing it back out is that a malevolent actor can simply insert a function pointer or executable code and voila, you are no longer in control.
Advantage of using scanf():The user doesnβt need to know the size of the stack, which is the starter code is one-hundred bytes. Thatβs kind of good, although anyone can just sit there trying longer and longer input strings until BufferOverflow error occur. Ideally, you would just write a script that automatically tries increasing string sizes and reads the exit code of the program. Once it detects an error, you simply work your way back to a close estimate of the stack. Any modern operating system using memory address randomization to make the whole process of hijacking an application harder, but itβs by no means impossible.
fgets() over scanf():
fgets function is short for file-get-string. Remember that files can be pretty much anything on *nix systems (sockets, streams, or actual files), so we can use it to read from standard input, which again, is also technically a file. This also makes our program more robust, because as mentioned in the source, simply adjust the code to read from the command line, a file, or stdin, without much trouble.
Crucially, the fgets function also allows us to specify a specific buffer length, thereby disallowing any buffer overflow attacks. If you look at the full code below, youβll notice that a default buffer size has been defined as a macro. Remember that C canβt use βconst intβ variables to initialize an array properly. You can hack it using variable-length arrays (VLAβs), but itβs not ideal, and I strongly recommend against it. So while in C++ we would normally use literally anything else, here we do use preprocessor macros, but keep in mind that C and C++ have vastly different capabilities when it comes to their static type checking, namely that C++ is good over C. Hence fgets() method can actually Handle Errors during I/O.
So the code to actually read the user input is as follows:
char* inputBuffer = malloc(sizeof(char) * DEFAULT_BUFFER_SIZE);memset(inputBuffer, NUL, DEFAULT_BUFFER_SIZE); char* result = NULL; while (result == NULL) { result = fgets(inputBuffer, DEFAULT_BUFFER_SIZE, stdin); if (inputBuffer[strlen(inputBuffer) - 1] != '\n') { ErrorInputStringTooLong(); // Since 'result' is the canary // we are using to notify of a failure // in execution, set it to NULL, to indicate an error. // This is a useful value because // if for some reason the fgets f/nction were // to fail, the return value would also be NULL. result = NULL; }}
As expected, we dynamically allocate a buffer of predetermined size. Dynamically allocating it as opposed to stack-allocating it gives us another layer of protection against stack smashing.
Note: We are explicitly zeroing out the memory in the inputBuffer. C does nothing for you, and malloc is no exception. The call to malloc returns a pointer to the first memory cell of the requested memory, but the values in every single one of those cells are unchanged from before the call. For all intents and purposes, they are garbage, so we zero them out. Note also that by zeroing out, we are automatically giving ourselves the null terminator, although the fgets function does actually append a null to the end of the input string, provided there is enough room in the buffer.
When the user inputs too long string:
Youβll notice that I check to make sure the last read value was not a new line. If that is true, this means that the user passed in an input string that was too long. To fix this, we need to set our βresultβ variable to NULL so we cycle through the loop again, but we also need to clear out the input buffer. Otherwise, the program will simply read from the old input, which has not yet been used, rather than prompting the user for additional input. To handle this, I supply two additional functions.
static inline void ErrorInputStringTooLong(){ // NOTE: Print to stderr, not to stdout. fprintf(stderr, "[ERROR]: The input was too long, please try again.\n"); // Having notified the user, // clear the input buffer and return. ClearInputBuffer();} static inline void ClearInputBuffer(){ // This variable is merely here to munch the garbage out of the input // buffer. As long as the input buffer's current character is not either // a new line character or the end of input, keep reading characters. This // seems to be the only portable way of clearing the input buffer. char c = NUL; while ((c = getchar()) != '\n' && c != EOF) { // Do nothing until input buffer fully flushed. }}
Note: Usually, to clear the input buffer, one would just call fseek(stdin, 0, SEEK_END); but it doesnβt seem to work on every platform. Hence, the above-described method is used.
Note: if fgets returns an error, you should call ferror() to figure out what went wrong.
c-input-output
C-Library
C Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
TCP Server-Client implementation in C
Exception Handling in C++
Multithreading in C
Arrow operator -> in C/C++ with Examples
'this' pointer in C++
How to split a string in C/C++, Python and Java?
Smart Pointers in C++ and How to Use Them
UDP Server-Client implementation in C
How to dynamically allocate a 2D array in C?
Unordered Sets in C++ Standard Template Library | [
{
"code": null,
"e": 23843,
"s": 23815,
"text": "\n14 Mar, 2019"
},
{
"code": null,
"e": 24417,
"s": 23843,
"text": "Any time you use an *f function, whether it be printf, scanf, or their derivatives (fprintf, fscanf, etc...), you are doing more things than you might realize. Not only are you reading (or writing) something, but-and hereβs the problem- you are interpreting it. The format string can be thought of as kind of an βevalβ function like you would see if you program in Lisp. So the problem with simply reading input from the user and echoing it back out is that a malevolent actor can simply insert a function pointer or executable code and voila, you are no longer in control."
},
{
"code": null,
"e": 25050,
"s": 24417,
"text": "Advantage of using scanf():The user doesnβt need to know the size of the stack, which is the starter code is one-hundred bytes. Thatβs kind of good, although anyone can just sit there trying longer and longer input strings until BufferOverflow error occur. Ideally, you would just write a script that automatically tries increasing string sizes and reads the exit code of the program. Once it detects an error, you simply work your way back to a close estimate of the stack. Any modern operating system using memory address randomization to make the whole process of hijacking an application harder, but itβs by no means impossible."
},
{
"code": null,
"e": 25072,
"s": 25050,
"text": "fgets() over scanf():"
},
{
"code": null,
"e": 25476,
"s": 25072,
"text": "fgets function is short for file-get-string. Remember that files can be pretty much anything on *nix systems (sockets, streams, or actual files), so we can use it to read from standard input, which again, is also technically a file. This also makes our program more robust, because as mentioned in the source, simply adjust the code to read from the command line, a file, or stdin, without much trouble."
},
{
"code": null,
"e": 26208,
"s": 25476,
"text": "Crucially, the fgets function also allows us to specify a specific buffer length, thereby disallowing any buffer overflow attacks. If you look at the full code below, youβll notice that a default buffer size has been defined as a macro. Remember that C canβt use βconst intβ variables to initialize an array properly. You can hack it using variable-length arrays (VLAβs), but itβs not ideal, and I strongly recommend against it. So while in C++ we would normally use literally anything else, here we do use preprocessor macros, but keep in mind that C and C++ have vastly different capabilities when it comes to their static type checking, namely that C++ is good over C. Hence fgets() method can actually Handle Errors during I/O."
},
{
"code": null,
"e": 26267,
"s": 26208,
"text": "So the code to actually read the user input is as follows:"
},
{
"code": "char* inputBuffer = malloc(sizeof(char) * DEFAULT_BUFFER_SIZE);memset(inputBuffer, NUL, DEFAULT_BUFFER_SIZE); char* result = NULL; while (result == NULL) { result = fgets(inputBuffer, DEFAULT_BUFFER_SIZE, stdin); if (inputBuffer[strlen(inputBuffer) - 1] != '\\n') { ErrorInputStringTooLong(); // Since 'result' is the canary // we are using to notify of a failure // in execution, set it to NULL, to indicate an error. // This is a useful value because // if for some reason the fgets f/nction were // to fail, the return value would also be NULL. result = NULL; }}",
"e": 26905,
"s": 26267,
"text": null
},
{
"code": null,
"e": 27095,
"s": 26905,
"text": "As expected, we dynamically allocate a buffer of predetermined size. Dynamically allocating it as opposed to stack-allocating it gives us another layer of protection against stack smashing."
},
{
"code": null,
"e": 27679,
"s": 27095,
"text": "Note: We are explicitly zeroing out the memory in the inputBuffer. C does nothing for you, and malloc is no exception. The call to malloc returns a pointer to the first memory cell of the requested memory, but the values in every single one of those cells are unchanged from before the call. For all intents and purposes, they are garbage, so we zero them out. Note also that by zeroing out, we are automatically giving ourselves the null terminator, although the fgets function does actually append a null to the end of the input string, provided there is enough room in the buffer."
},
{
"code": null,
"e": 27717,
"s": 27679,
"text": "When the user inputs too long string:"
},
{
"code": null,
"e": 28219,
"s": 27717,
"text": "Youβll notice that I check to make sure the last read value was not a new line. If that is true, this means that the user passed in an input string that was too long. To fix this, we need to set our βresultβ variable to NULL so we cycle through the loop again, but we also need to clear out the input buffer. Otherwise, the program will simply read from the old input, which has not yet been used, rather than prompting the user for additional input. To handle this, I supply two additional functions."
},
{
"code": "static inline void ErrorInputStringTooLong(){ // NOTE: Print to stderr, not to stdout. fprintf(stderr, \"[ERROR]: The input was too long, please try again.\\n\"); // Having notified the user, // clear the input buffer and return. ClearInputBuffer();} static inline void ClearInputBuffer(){ // This variable is merely here to munch the garbage out of the input // buffer. As long as the input buffer's current character is not either // a new line character or the end of input, keep reading characters. This // seems to be the only portable way of clearing the input buffer. char c = NUL; while ((c = getchar()) != '\\n' && c != EOF) { // Do nothing until input buffer fully flushed. }}",
"e": 28954,
"s": 28219,
"text": null
},
{
"code": null,
"e": 29133,
"s": 28954,
"text": "Note: Usually, to clear the input buffer, one would just call fseek(stdin, 0, SEEK_END); but it doesnβt seem to work on every platform. Hence, the above-described method is used."
},
{
"code": null,
"e": 29222,
"s": 29133,
"text": "Note: if fgets returns an error, you should call ferror() to figure out what went wrong."
},
{
"code": null,
"e": 29237,
"s": 29222,
"text": "c-input-output"
},
{
"code": null,
"e": 29247,
"s": 29237,
"text": "C-Library"
},
{
"code": null,
"e": 29258,
"s": 29247,
"text": "C Language"
},
{
"code": null,
"e": 29356,
"s": 29258,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29365,
"s": 29356,
"text": "Comments"
},
{
"code": null,
"e": 29378,
"s": 29365,
"text": "Old Comments"
},
{
"code": null,
"e": 29416,
"s": 29378,
"text": "TCP Server-Client implementation in C"
},
{
"code": null,
"e": 29442,
"s": 29416,
"text": "Exception Handling in C++"
},
{
"code": null,
"e": 29462,
"s": 29442,
"text": "Multithreading in C"
},
{
"code": null,
"e": 29503,
"s": 29462,
"text": "Arrow operator -> in C/C++ with Examples"
},
{
"code": null,
"e": 29525,
"s": 29503,
"text": "'this' pointer in C++"
},
{
"code": null,
"e": 29574,
"s": 29525,
"text": "How to split a string in C/C++, Python and Java?"
},
{
"code": null,
"e": 29616,
"s": 29574,
"text": "Smart Pointers in C++ and How to Use Them"
},
{
"code": null,
"e": 29654,
"s": 29616,
"text": "UDP Server-Client implementation in C"
},
{
"code": null,
"e": 29699,
"s": 29654,
"text": "How to dynamically allocate a 2D array in C?"
}
] |
FAB - Speed Dial in Flutter - GeeksforGeeks | 23 Sep, 2020
Floating action button, commonly abbreviated as FAB, is a primary action button that has a fixed position hovering over in an app, without altering the contents of the screen. Speed dial is a transition type of FAB, where it emits multiple entities as an action of a FAB in the same screen.
FAB has three parts. They are containers, icons, and text. Based on these parts, FAB is classified into two types.
1. Regular: Container with only an Icon (Default)
2. Extended:
i. Container with only Text
ii. Container with both Icon and Text
FAB containers have two default sizes. They are default (56 x 56 dp) and mini (40 x 40 dp). FAB containerβs shape or width are of two types.
1. Fixed: Cumulative width of the contents of a container, including padding
2. Fluid: Relative width to the screen or layout grid of the app
By default, a basic container is in a circular shape, where the icon is placed in the center.
FABβs visibility, motion, and even animations are highly customizable making it quite relevant and easy to access in a screen. As mentioned above, FABs are fixed, but they hover over the content making it completely out of context from the screenβs content. So, using the relevant FABs for a particular screen is a highly recommended one.
FABs when clicked perform actions that either happens on the same screen or in a different one. The FAB transitions can be in the following forms:
1. Speed Dial (FABs with icons and labels)
2. Menu
3. Sub-surfaces (new surface in the same screen)
4. New screen
Speed dial is a transition type of FAB, where a stack of action emits from a FAB when clicked, in the same screen. These actions are in the form of FABs with icons and labels on them. A speed dial can be achieved by using a plugin/dependency named βflutter_speed_dialβ.
Step 1: Open βpubspec.yamlβ file from the project folder.
Step 2: In the pubspec.yaml file, type flutter_speed_dial: under dependencies.
The code looks like this:
Dart
dependencies: flutter: sdk: flutter flutter_speed_dial:
Step 3: Now click βPub Getβ button in the top of the application (Android Studio).
Step 4: The βProcess finished with exit code 0β in the console shows that the dependency is been added successfully.
Step 5: Now import the plugin or package by adding the import βpackage:flutter_speed_dial/flutter_speed_dial.dartβ; code to the top of the main.dart file.
Dart
import 'package:flutter/material.dart';import 'package:flutter/rendering.dart';import 'package:flutter_speed_dial/flutter_speed_dial.dart'; void main() => runApp(MyApp()); class MyApp extends StatelessWidget { SpeedDial buildSpeedDial() { return SpeedDial( animatedIcon: AnimatedIcons.menu_close, animatedIconTheme: IconThemeData(size: 28.0), backgroundColor: Colors.green[900], visible: true, curve: Curves.bounceInOut, children: [ SpeedDialChild( child: Icon(Icons.chrome_reader_mode, color: Colors.white), backgroundColor: Colors.green, onTap: () => print('Pressed Read Later'), label: 'Read', labelStyle: TextStyle(fontWeight: FontWeight.w500, color: Colors.white), labelBackgroundColor: Colors.black, ), SpeedDialChild( child: Icon(Icons.create, color: Colors.white), backgroundColor: Colors.green, onTap: () => print('Pressed Write'), label: 'Write', labelStyle: TextStyle(fontWeight: FontWeight.w500, color: Colors.white), labelBackgroundColor: Colors.black, ), SpeedDialChild( child: Icon(Icons.laptop_chromebook, color: Colors.white), backgroundColor: Colors.green, onTap: () => print('Pressed Code'), label: 'Code', labelStyle: TextStyle(fontWeight: FontWeight.w500, color: Colors.white), labelBackgroundColor: Colors.black, ), ], ); } Widget build(BuildContext context) { return MaterialApp( home: Scaffold( appBar: AppBar( title: Text('Geeks for Geeks'), backgroundColor: Colors.green, ), body: SafeArea( child: Center( child: Text( 'Welcome to GFG!', style: TextStyle( fontSize: 30.0, color: Colors.green, fontWeight: FontWeight.bold, ), ), ), ), floatingActionButton: buildSpeedDial(), ), ); }}
1. A basic screen with an app bar, text, and a FAB is created.
2. This FAB is assigned with an action named buildSpeedDial.
3. The buildSpeedDial function has a main FAB called SpeedDial and multiple other SpeedDialChild FABs attached to it.
4. SpeedDial is nothing but the main FAB thatβs on the screen, which when clicked expands to emit those multiple SpeedDialChild.
5. The SpeedDial can be customized using many features like animatedIcon, animatedIconTheme, visible (visibility of the FAB on screen), curve (the way in which the FAB acts when clicked), and much more.
6. The SpeedDialChild is a completely customizable one too, with features like backgroundColor, onTap, label, labelStyle, Child(Icon), labelBackgroundColor, etc.
Note: The onTap: () => print(βPressedβ), command will be executed in the flutter console.
android
Flutter
Android
Dart
Flutter
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Android Architecture
How to Create and Add Data to SQLite Database in Android?
MVVM (Model View ViewModel) Architecture Pattern in Android
Broadcast Receiver in Android With Example
Resource Raw Folder in Android Studio
Flutter - DropDownButton Widget
Listview.builder in Flutter
Flutter - Asset Image
Splash Screen in Flutter
Flutter - Custom Bottom Navigation Bar | [
{
"code": null,
"e": 27185,
"s": 27157,
"text": "\n23 Sep, 2020"
},
{
"code": null,
"e": 27476,
"s": 27185,
"text": "Floating action button, commonly abbreviated as FAB, is a primary action button that has a fixed position hovering over in an app, without altering the contents of the screen. Speed dial is a transition type of FAB, where it emits multiple entities as an action of a FAB in the same screen."
},
{
"code": null,
"e": 27591,
"s": 27476,
"text": "FAB has three parts. They are containers, icons, and text. Based on these parts, FAB is classified into two types."
},
{
"code": null,
"e": 27645,
"s": 27591,
"text": " 1. Regular: Container with only an Icon (Default)"
},
{
"code": null,
"e": 27664,
"s": 27645,
"text": " 2. Extended: "
},
{
"code": null,
"e": 27702,
"s": 27664,
"text": " i. Container with only Text"
},
{
"code": null,
"e": 27750,
"s": 27702,
"text": " ii. Container with both Icon and Text"
},
{
"code": null,
"e": 27891,
"s": 27750,
"text": "FAB containers have two default sizes. They are default (56 x 56 dp) and mini (40 x 40 dp). FAB containerβs shape or width are of two types."
},
{
"code": null,
"e": 27972,
"s": 27891,
"text": " 1. Fixed: Cumulative width of the contents of a container, including padding"
},
{
"code": null,
"e": 28041,
"s": 27972,
"text": " 2. Fluid: Relative width to the screen or layout grid of the app"
},
{
"code": null,
"e": 28135,
"s": 28041,
"text": "By default, a basic container is in a circular shape, where the icon is placed in the center."
},
{
"code": null,
"e": 28474,
"s": 28135,
"text": "FABβs visibility, motion, and even animations are highly customizable making it quite relevant and easy to access in a screen. As mentioned above, FABs are fixed, but they hover over the content making it completely out of context from the screenβs content. So, using the relevant FABs for a particular screen is a highly recommended one."
},
{
"code": null,
"e": 28622,
"s": 28474,
"text": "FABs when clicked perform actions that either happens on the same screen or in a different one. The FAB transitions can be in the following forms:"
},
{
"code": null,
"e": 28671,
"s": 28622,
"text": " 1. Speed Dial (FABs with icons and labels) "
},
{
"code": null,
"e": 28683,
"s": 28671,
"text": " 2. Menu"
},
{
"code": null,
"e": 28738,
"s": 28683,
"text": " 3. Sub-surfaces (new surface in the same screen) "
},
{
"code": null,
"e": 28756,
"s": 28738,
"text": " 4. New screen"
},
{
"code": null,
"e": 29027,
"s": 28756,
"text": "Speed dial is a transition type of FAB, where a stack of action emits from a FAB when clicked, in the same screen. These actions are in the form of FABs with icons and labels on them. A speed dial can be achieved by using a plugin/dependency named βflutter_speed_dialβ."
},
{
"code": null,
"e": 29085,
"s": 29027,
"text": "Step 1: Open βpubspec.yamlβ file from the project folder."
},
{
"code": null,
"e": 29164,
"s": 29085,
"text": "Step 2: In the pubspec.yaml file, type flutter_speed_dial: under dependencies."
},
{
"code": null,
"e": 29190,
"s": 29164,
"text": "The code looks like this:"
},
{
"code": null,
"e": 29195,
"s": 29190,
"text": "Dart"
},
{
"code": "dependencies: flutter: sdk: flutter flutter_speed_dial:",
"e": 29256,
"s": 29195,
"text": null
},
{
"code": null,
"e": 29339,
"s": 29256,
"text": "Step 3: Now click βPub Getβ button in the top of the application (Android Studio)."
},
{
"code": null,
"e": 29456,
"s": 29339,
"text": "Step 4: The βProcess finished with exit code 0β in the console shows that the dependency is been added successfully."
},
{
"code": null,
"e": 29611,
"s": 29456,
"text": "Step 5: Now import the plugin or package by adding the import βpackage:flutter_speed_dial/flutter_speed_dial.dartβ; code to the top of the main.dart file."
},
{
"code": null,
"e": 29616,
"s": 29611,
"text": "Dart"
},
{
"code": "import 'package:flutter/material.dart';import 'package:flutter/rendering.dart';import 'package:flutter_speed_dial/flutter_speed_dial.dart'; void main() => runApp(MyApp()); class MyApp extends StatelessWidget { SpeedDial buildSpeedDial() { return SpeedDial( animatedIcon: AnimatedIcons.menu_close, animatedIconTheme: IconThemeData(size: 28.0), backgroundColor: Colors.green[900], visible: true, curve: Curves.bounceInOut, children: [ SpeedDialChild( child: Icon(Icons.chrome_reader_mode, color: Colors.white), backgroundColor: Colors.green, onTap: () => print('Pressed Read Later'), label: 'Read', labelStyle: TextStyle(fontWeight: FontWeight.w500, color: Colors.white), labelBackgroundColor: Colors.black, ), SpeedDialChild( child: Icon(Icons.create, color: Colors.white), backgroundColor: Colors.green, onTap: () => print('Pressed Write'), label: 'Write', labelStyle: TextStyle(fontWeight: FontWeight.w500, color: Colors.white), labelBackgroundColor: Colors.black, ), SpeedDialChild( child: Icon(Icons.laptop_chromebook, color: Colors.white), backgroundColor: Colors.green, onTap: () => print('Pressed Code'), label: 'Code', labelStyle: TextStyle(fontWeight: FontWeight.w500, color: Colors.white), labelBackgroundColor: Colors.black, ), ], ); } Widget build(BuildContext context) { return MaterialApp( home: Scaffold( appBar: AppBar( title: Text('Geeks for Geeks'), backgroundColor: Colors.green, ), body: SafeArea( child: Center( child: Text( 'Welcome to GFG!', style: TextStyle( fontSize: 30.0, color: Colors.green, fontWeight: FontWeight.bold, ), ), ), ), floatingActionButton: buildSpeedDial(), ), ); }}",
"e": 31710,
"s": 29616,
"text": null
},
{
"code": null,
"e": 31773,
"s": 31710,
"text": "1. A basic screen with an app bar, text, and a FAB is created."
},
{
"code": null,
"e": 31834,
"s": 31773,
"text": "2. This FAB is assigned with an action named buildSpeedDial."
},
{
"code": null,
"e": 31952,
"s": 31834,
"text": "3. The buildSpeedDial function has a main FAB called SpeedDial and multiple other SpeedDialChild FABs attached to it."
},
{
"code": null,
"e": 32081,
"s": 31952,
"text": "4. SpeedDial is nothing but the main FAB thatβs on the screen, which when clicked expands to emit those multiple SpeedDialChild."
},
{
"code": null,
"e": 32284,
"s": 32081,
"text": "5. The SpeedDial can be customized using many features like animatedIcon, animatedIconTheme, visible (visibility of the FAB on screen), curve (the way in which the FAB acts when clicked), and much more."
},
{
"code": null,
"e": 32448,
"s": 32284,
"text": "6. The SpeedDialChild is a completely customizable one too, with features like backgroundColor, onTap, label, labelStyle, Child(Icon), labelBackgroundColor, etc. "
},
{
"code": null,
"e": 32538,
"s": 32448,
"text": "Note: The onTap: () => print(βPressedβ), command will be executed in the flutter console."
},
{
"code": null,
"e": 32546,
"s": 32538,
"text": "android"
},
{
"code": null,
"e": 32554,
"s": 32546,
"text": "Flutter"
},
{
"code": null,
"e": 32562,
"s": 32554,
"text": "Android"
},
{
"code": null,
"e": 32567,
"s": 32562,
"text": "Dart"
},
{
"code": null,
"e": 32575,
"s": 32567,
"text": "Flutter"
},
{
"code": null,
"e": 32583,
"s": 32575,
"text": "Android"
},
{
"code": null,
"e": 32681,
"s": 32583,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 32702,
"s": 32681,
"text": "Android Architecture"
},
{
"code": null,
"e": 32760,
"s": 32702,
"text": "How to Create and Add Data to SQLite Database in Android?"
},
{
"code": null,
"e": 32820,
"s": 32760,
"text": "MVVM (Model View ViewModel) Architecture Pattern in Android"
},
{
"code": null,
"e": 32863,
"s": 32820,
"text": "Broadcast Receiver in Android With Example"
},
{
"code": null,
"e": 32901,
"s": 32863,
"text": "Resource Raw Folder in Android Studio"
},
{
"code": null,
"e": 32933,
"s": 32901,
"text": "Flutter - DropDownButton Widget"
},
{
"code": null,
"e": 32961,
"s": 32933,
"text": "Listview.builder in Flutter"
},
{
"code": null,
"e": 32983,
"s": 32961,
"text": "Flutter - Asset Image"
},
{
"code": null,
"e": 33008,
"s": 32983,
"text": "Splash Screen in Flutter"
}
] |
Difference Between TreeSet and SortedSet in Java - GeeksforGeeks | 01 Nov, 2021
TreeSet is one of the implementations of the Navigable sub-interface. It is underlying data structure is a red-black tree. The elements are stored in ascending order and more methods are available in TreeSet compare to SortedSet. We can also change the sorting parameter using a Comparator. For example, Comparator provided at set creation time, depending on which constructor is used.
It also implements NavigableSet interface.
NavigableSet extends SortedSet and Set interfaces.
Example
Java
// Java Program to Illustrate TreeSet // Importing required classesimport java.util.*; // Main classclass GFG { // Main driver method public static void main(String args[]) { // Creating an empty TreeSet of string type elements TreeSet<String> al = new TreeSet<String>(); // Adding elements // using add() method al.add("Welcome"); al.add("to"); al.add("Geeks for Geeks"); // Traversing elements via help of iterators Iterator<String> itr = al.iterator(); // Holds true until there is element remaining in object while (itr.hasNext()) { // Moving onto next element with help of next() method System.out.println(itr.next()); } }}
Geeks for Geeks
Welcome
to
Sorted Set
The SortedSet is a sub-interface, which is available in java.util.package which extends the Set interface. This interface contains the methods inherited from the Set interface. For example, headSet, tailSet, subSet, Comparator, first, last, and many more.
Example
Java
// Java program to Illustrate SortedSet // Importing utility classesimport java.util.*; // Main classclass GFG { // Main driver method public static void main(String[] args) { // Creating an instance of SortedSet // String type SortedSet<String> ts = new TreeSet<String>(); // Adding elements into the TreeSet // using add() ts.add("Sravan"); ts.add("Ojaswi"); ts.add("Bobby"); ts.add("Rohith"); ts.add("Gnanesh"); ts.add("Devi2"); // Adding the duplicate element // again simply using add() method ts.add("Sravan"); // Print and display TreeSet System.out.println(ts); // Removing items from TreeSet // using remove() method ts.remove("Ojaswi"); // Display message System.out.println("Iterating over set:"); // Iterating over TreeSet items Iterator<String> i = ts.iterator(); // Condition holds true till there is single element // remaining in the object while (i.hasNext()) // Printing elements System.out.println(i.next()); }}
[Bobby, Devi2, Gnanesh, Ojaswi, Rohith, Sravan]
Iterating over set:
Bobby
Devi2
Gnanesh
Rohith
Sravan
Now after having adequate understanding and internal working of both TreeSet and SortedSet, now let us see the differences between TreeSet and SortedSet which is as depicted from the table provided below as follows:
TreeSet
SortedSet
Syntax:
TreeSet<Datatype> treeset = new TreeSet<>();
Syntax:
It can not be instantiated as it is a sub-Interface.
Conclusion: Basically in simple words letβs assume this way, TreeSet is a class of NavigableSet which contains all of the methods for better traversing and searching for values. SortedSet is a sub-set of NavigableSet in terms of methods compare to TreeSet(NavigableSet)
harish garg
shivesh01
Java-SortedSet
java-treeset
Picked
Difference Between
Java
Java
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
Difference Between Method Overloading and Method Overriding in Java
Difference between Prim's and Kruskal's algorithm for MST
Difference between Internal and External fragmentation
Difference between Compile-time and Run-time Polymorphism in Java
Arrays in Java
Split() String method in Java with examples
For-each loop in Java
Object Oriented Programming (OOPs) Concept in Java
HashMap in Java with Examples | [
{
"code": null,
"e": 26129,
"s": 26101,
"text": "\n01 Nov, 2021"
},
{
"code": null,
"e": 26515,
"s": 26129,
"text": "TreeSet is one of the implementations of the Navigable sub-interface. It is underlying data structure is a red-black tree. The elements are stored in ascending order and more methods are available in TreeSet compare to SortedSet. We can also change the sorting parameter using a Comparator. For example, Comparator provided at set creation time, depending on which constructor is used."
},
{
"code": null,
"e": 26558,
"s": 26515,
"text": "It also implements NavigableSet interface."
},
{
"code": null,
"e": 26609,
"s": 26558,
"text": "NavigableSet extends SortedSet and Set interfaces."
},
{
"code": null,
"e": 26617,
"s": 26609,
"text": "Example"
},
{
"code": null,
"e": 26622,
"s": 26617,
"text": "Java"
},
{
"code": "// Java Program to Illustrate TreeSet // Importing required classesimport java.util.*; // Main classclass GFG { // Main driver method public static void main(String args[]) { // Creating an empty TreeSet of string type elements TreeSet<String> al = new TreeSet<String>(); // Adding elements // using add() method al.add(\"Welcome\"); al.add(\"to\"); al.add(\"Geeks for Geeks\"); // Traversing elements via help of iterators Iterator<String> itr = al.iterator(); // Holds true until there is element remaining in object while (itr.hasNext()) { // Moving onto next element with help of next() method System.out.println(itr.next()); } }}",
"e": 27372,
"s": 26622,
"text": null
},
{
"code": null,
"e": 27399,
"s": 27372,
"text": "Geeks for Geeks\nWelcome\nto"
},
{
"code": null,
"e": 27410,
"s": 27399,
"text": "Sorted Set"
},
{
"code": null,
"e": 27666,
"s": 27410,
"text": "The SortedSet is a sub-interface, which is available in java.util.package which extends the Set interface. This interface contains the methods inherited from the Set interface. For example, headSet, tailSet, subSet, Comparator, first, last, and many more."
},
{
"code": null,
"e": 27674,
"s": 27666,
"text": "Example"
},
{
"code": null,
"e": 27679,
"s": 27674,
"text": "Java"
},
{
"code": "// Java program to Illustrate SortedSet // Importing utility classesimport java.util.*; // Main classclass GFG { // Main driver method public static void main(String[] args) { // Creating an instance of SortedSet // String type SortedSet<String> ts = new TreeSet<String>(); // Adding elements into the TreeSet // using add() ts.add(\"Sravan\"); ts.add(\"Ojaswi\"); ts.add(\"Bobby\"); ts.add(\"Rohith\"); ts.add(\"Gnanesh\"); ts.add(\"Devi2\"); // Adding the duplicate element // again simply using add() method ts.add(\"Sravan\"); // Print and display TreeSet System.out.println(ts); // Removing items from TreeSet // using remove() method ts.remove(\"Ojaswi\"); // Display message System.out.println(\"Iterating over set:\"); // Iterating over TreeSet items Iterator<String> i = ts.iterator(); // Condition holds true till there is single element // remaining in the object while (i.hasNext()) // Printing elements System.out.println(i.next()); }}",
"e": 28836,
"s": 27679,
"text": null
},
{
"code": null,
"e": 28938,
"s": 28836,
"text": "[Bobby, Devi2, Gnanesh, Ojaswi, Rohith, Sravan]\nIterating over set:\nBobby\nDevi2\nGnanesh\nRohith\nSravan"
},
{
"code": null,
"e": 29154,
"s": 28938,
"text": "Now after having adequate understanding and internal working of both TreeSet and SortedSet, now let us see the differences between TreeSet and SortedSet which is as depicted from the table provided below as follows:"
},
{
"code": null,
"e": 29162,
"s": 29154,
"text": "TreeSet"
},
{
"code": null,
"e": 29172,
"s": 29162,
"text": "SortedSet"
},
{
"code": null,
"e": 29180,
"s": 29172,
"text": "Syntax:"
},
{
"code": null,
"e": 29225,
"s": 29180,
"text": "TreeSet<Datatype> treeset = new TreeSet<>();"
},
{
"code": null,
"e": 29233,
"s": 29225,
"text": "Syntax:"
},
{
"code": null,
"e": 29286,
"s": 29233,
"text": "It can not be instantiated as it is a sub-Interface."
},
{
"code": null,
"e": 29556,
"s": 29286,
"text": "Conclusion: Basically in simple words letβs assume this way, TreeSet is a class of NavigableSet which contains all of the methods for better traversing and searching for values. SortedSet is a sub-set of NavigableSet in terms of methods compare to TreeSet(NavigableSet)"
},
{
"code": null,
"e": 29568,
"s": 29556,
"text": "harish garg"
},
{
"code": null,
"e": 29578,
"s": 29568,
"text": "shivesh01"
},
{
"code": null,
"e": 29593,
"s": 29578,
"text": "Java-SortedSet"
},
{
"code": null,
"e": 29606,
"s": 29593,
"text": "java-treeset"
},
{
"code": null,
"e": 29613,
"s": 29606,
"text": "Picked"
},
{
"code": null,
"e": 29632,
"s": 29613,
"text": "Difference Between"
},
{
"code": null,
"e": 29637,
"s": 29632,
"text": "Java"
},
{
"code": null,
"e": 29642,
"s": 29637,
"text": "Java"
},
{
"code": null,
"e": 29740,
"s": 29642,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29801,
"s": 29740,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 29869,
"s": 29801,
"text": "Difference Between Method Overloading and Method Overriding in Java"
},
{
"code": null,
"e": 29927,
"s": 29869,
"text": "Difference between Prim's and Kruskal's algorithm for MST"
},
{
"code": null,
"e": 29982,
"s": 29927,
"text": "Difference between Internal and External fragmentation"
},
{
"code": null,
"e": 30048,
"s": 29982,
"text": "Difference between Compile-time and Run-time Polymorphism in Java"
},
{
"code": null,
"e": 30063,
"s": 30048,
"text": "Arrays in Java"
},
{
"code": null,
"e": 30107,
"s": 30063,
"text": "Split() String method in Java with examples"
},
{
"code": null,
"e": 30129,
"s": 30107,
"text": "For-each loop in Java"
},
{
"code": null,
"e": 30180,
"s": 30129,
"text": "Object Oriented Programming (OOPs) Concept in Java"
}
] |
Explain typecasting in Javascript? | Converting a data type into another is known as type casting. Sometimes there is a need to convert the data type of one value to another. Under some circumstances JavaScript will perform automatic type conversion.
Automatic Type Conversion
JavaScript expects a boolean in a conditional expression. So JavaScript will temporarily convert the value in parentheses to a boolean to evaluate the if expression β
if (val) {
console.log( 'yes, val exists' );
}
The following values evaluate to false: 0, -0, '' (empty string), NaN, undefined, and null. All other values evaluate to true, even empty arrays and objects.
Type conversion is also performed when comparing values using the equal (==) and not equal (!=) operators. So when you compare the number 125 with a string '125' using the equals (==) operator, the expression evaluates to true β
console.log( 125 == '125' );
Type conversion is not performed when using the identical (===) and not identical (!==) operators.
parseInt and parseFloat
The parseInt function converts its first argument to a string, parses that string, then returns an integer or NaN.
The parseFloat() function parses an argument (converting it to a string first if needed) and returns a floating point number.
toString
The toString() method returns a string representing the object, ie, it tries to convert object to string.
let a = 1.015
console.log(a)
console.log(typeof a)
console.log(a.toString())
console.log(typeof a.toString())
1.015
number
1.015
string | [
{
"code": null,
"e": 1276,
"s": 1062,
"text": "Converting a data type into another is known as type casting. Sometimes there is a need to convert the data type of one value to another. Under some circumstances JavaScript will perform automatic type conversion."
},
{
"code": null,
"e": 1302,
"s": 1276,
"text": "Automatic Type Conversion"
},
{
"code": null,
"e": 1469,
"s": 1302,
"text": "JavaScript expects a boolean in a conditional expression. So JavaScript will temporarily convert the value in parentheses to a boolean to evaluate the if expression β"
},
{
"code": null,
"e": 1519,
"s": 1469,
"text": "if (val) {\n console.log( 'yes, val exists' );\n}"
},
{
"code": null,
"e": 1677,
"s": 1519,
"text": "The following values evaluate to false: 0, -0, '' (empty string), NaN, undefined, and null. All other values evaluate to true, even empty arrays and objects."
},
{
"code": null,
"e": 1906,
"s": 1677,
"text": "Type conversion is also performed when comparing values using the equal (==) and not equal (!=) operators. So when you compare the number 125 with a string '125' using the equals (==) operator, the expression evaluates to true β"
},
{
"code": null,
"e": 1935,
"s": 1906,
"text": "console.log( 125 == '125' );"
},
{
"code": null,
"e": 2034,
"s": 1935,
"text": "Type conversion is not performed when using the identical (===) and not identical (!==) operators."
},
{
"code": null,
"e": 2058,
"s": 2034,
"text": "parseInt and parseFloat"
},
{
"code": null,
"e": 2173,
"s": 2058,
"text": "The parseInt function converts its first argument to a string, parses that string, then returns an integer or NaN."
},
{
"code": null,
"e": 2299,
"s": 2173,
"text": "The parseFloat() function parses an argument (converting it to a string first if needed) and returns a floating point number."
},
{
"code": null,
"e": 2308,
"s": 2299,
"text": "toString"
},
{
"code": null,
"e": 2414,
"s": 2308,
"text": "The toString() method returns a string representing the object, ie, it tries to convert object to string."
},
{
"code": null,
"e": 2524,
"s": 2414,
"text": "let a = 1.015\nconsole.log(a)\nconsole.log(typeof a)\nconsole.log(a.toString())\nconsole.log(typeof a.toString())"
},
{
"code": null,
"e": 2550,
"s": 2524,
"text": "1.015\nnumber\n1.015\nstring"
}
] |
Print Matrix in spiral way
| This algorithm is used to print the array elements in a spiral way. At first starting from the first row, print the whole content and then follow the last column to print, then the last row and so on, thus it prints the elements in spiral fashion.
The time complexity of this algorithm is O(MN), M is the number of rows and N is the number of columns.
Input:
The matrix:
1 2 3 4 5 6
7 8 9 10 11 12
13 14 15 16 17 18
Output:
Contents of an array as the spiral form
1 2 3 4 5 6 12 18 17 16 15 14 13 7 8 9 10 11 15 16
dispSpiral(mat, m, n)
Input: The matrix mat, row and column m and n.
Output: Print the elements of the matrix in a spiral way.
Begin
currRow := 0 and currCol := 0
while currRow and currCol are in the matrix range, do
for i in range currCol and n-1, do
display mat[currRow, i]
done
increase currRow by 1
for i in range currRow and m-1, do
display mat[i, n-1]
done
decrease n by 1
if currRow < m, then
for i := n-1 down to currCol, do
display mat[m-1, i]
done
decrease m by 1
if currCol < n, then
for i := m-1 down to currRow, do
display mat[i, currCol]
done
increase currCol by 1
done
End
#include <iostream>
#define ROW 3
#define COL 6
using namespace std;
int array[ROW][COL] = {
{1, 2, 3, 4, 5, 6},
{7, 8, 9, 10, 11, 12},
{13, 14, 15, 16, 17, 18}
};
void dispSpiral(int m, int n) {
int i, currRow = 0, currCol = 0;
while (currRow < ROW && currCol <COL) {
for (i = currCol; i < n; i++) { //print the first row normally
cout << array[currRow][i]<<" ";
}
currRow++; //point to next row
for (i = currRow; i < m; ++i) { //Print the last column
cout << array[i][n-1]<<" ";
}
n--; //set the n-1th column is current last column
if ( currRow< m) { //when currRow is in the range, print the last row
for (i = n-1; i >= currCol; --i) {
cout << array[m-1][i]<<" ";
}
m--; //decrease the row range
}
if (currCol <n) { //when currCol is in the range, print the fist column
for (i = m-1; i >= currRow; --i) {
cout << array[i][currCol]<<" ";
}
currCol++;
}
}
}
int main() {
dispSpiral(ROW, COL);
}
1 2 3 4 5 6 12 18 17 16 15 14 13 7 8 9 10 11 15 16 | [
{
"code": null,
"e": 1311,
"s": 1062,
"text": "This algorithm is used to print the array elements in a spiral way. At first starting from the first row, print the whole content and then follow the last column to print, then the last row and so on, thus it prints the elements in spiral fashion. "
},
{
"code": null,
"e": 1415,
"s": 1311,
"text": "The time complexity of this algorithm is O(MN), M is the number of rows and N is the number of columns."
},
{
"code": null,
"e": 1603,
"s": 1415,
"text": "Input:\nThe matrix:\n 1 2 3 4 5 6\n 7 8 9 10 11 12\n13 14 15 16 17 18\n\nOutput:\nContents of an array as the spiral form\n1 2 3 4 5 6 12 18 17 16 15 14 13 7 8 9 10 11 15 16"
},
{
"code": null,
"e": 1625,
"s": 1603,
"text": "dispSpiral(mat, m, n)"
},
{
"code": null,
"e": 1672,
"s": 1625,
"text": "Input: The matrix mat, row and column m and n."
},
{
"code": null,
"e": 1730,
"s": 1672,
"text": "Output: Print the elements of the matrix in a spiral way."
},
{
"code": null,
"e": 2346,
"s": 1730,
"text": "Begin\n currRow := 0 and currCol := 0\n while currRow and currCol are in the matrix range, do\n for i in range currCol and n-1, do\n display mat[currRow, i]\n done\n\n increase currRow by 1\n for i in range currRow and m-1, do\n display mat[i, n-1]\n done\n\n decrease n by 1\n if currRow < m, then\n for i := n-1 down to currCol, do\n display mat[m-1, i]\n done\n decrease m by 1\n if currCol < n, then\n for i := m-1 down to currRow, do\n display mat[i, currCol]\n done\n increase currCol by 1\n done\nEnd"
},
{
"code": null,
"e": 3478,
"s": 2346,
"text": "#include <iostream>\n#define ROW 3\n#define COL 6\nusing namespace std;\n\nint array[ROW][COL] = {\n {1, 2, 3, 4, 5, 6},\n {7, 8, 9, 10, 11, 12},\n {13, 14, 15, 16, 17, 18}\n};\n\nvoid dispSpiral(int m, int n) {\n int i, currRow = 0, currCol = 0;\n while (currRow < ROW && currCol <COL) {\n for (i = currCol; i < n; i++) { //print the first row normally\n cout << array[currRow][i]<<\" \";\n }\n currRow++; //point to next row\n\n for (i = currRow; i < m; ++i) { //Print the last column\n cout << array[i][n-1]<<\" \";\n }\n\n n--; //set the n-1th column is current last column\n\n if ( currRow< m) { //when currRow is in the range, print the last row\n for (i = n-1; i >= currCol; --i) {\n cout << array[m-1][i]<<\" \";\n }\n m--; //decrease the row range\n }\n\n if (currCol <n) { //when currCol is in the range, print the fist column\n for (i = m-1; i >= currRow; --i) {\n cout << array[i][currCol]<<\" \";\n }\n currCol++;\n }\n }\n}\n\nint main() {\n dispSpiral(ROW, COL);\n}"
},
{
"code": null,
"e": 3529,
"s": 3478,
"text": "1 2 3 4 5 6 12 18 17 16 15 14 13 7 8 9 10 11 15 16"
}
] |
A Data Scientistβs Guide to Data Structures & Algorithms, Part 1 | by Paulina Zheng | Towards Data Science | Note: This is part 1 of a 2-part series. For the follow-up post, see here.
In data science, computer science and statistics converge. As data scientists, we use statistical principles to write code such that we can effectively explore the problem at hand.
This necessitates at least a basic understanding of data structures, algorithms, and time-space complexity so that we can program more efficiently and understand the tools that we use. With larger datasets, this becomes particularly important. The way that we write our code influences the speed at which our data is analyzed and conclusions can be reached accordingly. In this post, I will describe Big O notation as a method for describing time-space complexity and briefly go over some algorithms that relate to time complexity. In a later post, I will discuss algorithms that relate to space complexity.
In programming, an algorithm is a process or set of rules to be followed in order to achieve a particular goal. An algorithm is characterized by its running time (run-time), whether in terms of space or time. As data scientists, we are interested in the most efficient algorithm so that we can optimize our workflow.
In computer science, Big O notation is used to describe how βfastβ an algorithm grows, by comparing the number of operations within the algorithm. This will be explained in further detail later on but for now, letβs understand all of the formal notation.
Formal Notation
Big Ξ©: the best-case scenario. The Big Ξ© of an algorithm describes how quickly an algorithm can run under the best of circumstances.
Big O: the worst-case scenario. Typically, we are most concerned with the Big O time because we are interested in how slowly a given algorithm will run, at worst. How do we essentially make the βworst-caseβ not as bad as it could be?
Big ΞΈ: this can only be used to describe the run-time of an algorithm if the Big Ξ© and the Big O are the same. That is, the algorithmβs run time is the same in both the best and worst cases.
Because we are most concerned with the Big O of an algorithm, the rest of this post will only focus on Big O.
How do we use Big O to describe an algorithm? Suppose you wish to search for someoneβs name in a phone book.
Whatβs the most straightforward way of finding this person? Well, you could go through every single name in the phone book until you find your target. This is known as a simple search.
If the phone book is very small, with only 10 names, this is a fairly fast process. But what if there are 1,000 names in the phone book?
At best, your targetβs name is at the front of the list and you only need to need to check the first item. At worst, your targetβs name is at the very end of the phone book and you will need to have searched all 1000 names. As the βdatasetβ (or the phone book) increases in size, the maximum time it takes to run a simple search also linearly increases.
In this case, our algorithm is a simple search. Big O notation allows us to describe what our worst case is. Our worst case is that we will have to search through all elements (n) in the phone book. We can describe the run-time as:
O(n) where n: number of operations
Because the maximum number of operations is equal to the maximum number of elements in our phone book (you might need to search through them all to find your targetβs name), we say the Big O of a simple search is O(n). A simple search will never be slower than O(n) time.
Different Big O Run Times
Different algorithms have different run-times. That is, algorithms grow at different rates. The most common Big O run-times, from fastest to slowest, are:
O(log n): aka log time
O(n): aka linear time
O(n log n)
O(n2)
O(n!)
The Big O cheatsheet is also very useful for a quick graphical representation of the different run times and how they compare to each other.
In this post and its following post, I will describe common algorithms which are described by these different run-times.
Here are some principles that are important to understand before discussing some of the common algorithms.
Recursion: Recursion is when a function calls itself. Perhaps the quintessential example of recursion is in implementation of a factorial function:
def factorial(n): if n < 1: #base case return 1 else: #recursive case return n * factorial(n-1)
The function is called within the function itself and will continue calling itself until the base case (in this case, when n is 1) is reached.
Divide and Conquer (D&C): A recursive approach for problem-solving, D&C (1) determines the simplest case for the problem (AKA the base case) and (2) reduces the problem until it is now the base case.
That is, a complex problem is broken down into simpler sub-problems. These sub-problems are solved and their solutions are then combined to solve the original, larger problem.
Search and sort algorithms are perhaps the most important algorithms to first understand.
Simple SearchThis was described earlier with the phone book example, where the worst case would require that you search through all the names in the phone book before you find the name of interest. In general, simple search has a O(n) time. The maximum time required is linearly related to the number of elements in your list.
Binary SearchLetβs stick with the phone book example. Weβre still interested in finding someoneβs name in the phone book, only this time weβre going to try to be more efficient about it. Instead of tediously going through each and every name in the phone book, weβre going to start in the middle of the phone book and go from there.
Say our targetβs name begins with an P. We open to the Ms which is roughly in the middle of the alphabet. We know M is earlier than P in the alphabet, so we can eliminate the section from A to M. Now we can look at the later half of the phone book (N to Z), split that section in the middle (to the Ts), and compare to our target. T is later in the alphabet than P. We then know to eliminate the later half (T to Z). We focus on N to S now, dividing this in half and so on until we find our name of interest.
Generally, in binary search, you take your sorted (this is important) data and find the midpoint. Each time, you compare your target to the middle value. If the target value is the same as the middle value, then your job is done. Otherwise, you know which half of the list to eliminate based on the comparison. You continue dividing until the target is found or the dataset can no longer be halved.
Because binary search involves the halving of your dataset, the Big O time is O(log n). As such, it is faster than simple search, especially as your dataset grows (the algorithmβs growth is not linear but logarithmic so it grows slower, relative to a linear run-time of O(n)).
As an aside, binary search can be written recursively but is not considered a D&C algorithm. Although the larger input is indeed broken down into subsets, these subsets are ignored if they do not contain the value of interest. Solutions are not produced for these subsets so that they can be combined to solve the larger input.
Selection SortMuch like simple search for search algorithms, selection sort is perhaps the most straightforward, βbrute forceβ way to sort your data. Essentially, you go through every element in your list and append each element to a new list in your desired order. For example, if you are interested in sorting a list of numbers from greatest to smallest, you would:
Search through the list to find the largest numberAdd that number to a new listGo to the original list, search through it again to find the next largest numberAdd that number to the new list and so on...
Search through the list to find the largest number
Add that number to a new list
Go to the original list, search through it again to find the next largest number
Add that number to the new list and so on...
For selection sort, you have to go through each item in the list (this takes n times, just as it would for a simple search) and you have to do this n times (not just once, because you have to keep going back to the original list to find the next item you want to add to the new list). Thus, this takes O(n2) time.
QuicksortHow would quicksort differ from selection sort? If we work with a list of numbers, just as before:
Pick an element from your list, known as the pivot. The selection of a pivot is important in determining how quickly a quicksort algorithm will run. For now, we can select the last element each time as the pivot. (For additional information on pivot selection, I recommend the Stanford Coursera algorithms course.)Partition the list so that all numbers smaller than the pivot are to its left and all numbers greater than the pivot are to its right.For each βhalfβ of the list, you can treat it as a new list with a new pivot and rearrange each half until it is sorted.
Pick an element from your list, known as the pivot. The selection of a pivot is important in determining how quickly a quicksort algorithm will run. For now, we can select the last element each time as the pivot. (For additional information on pivot selection, I recommend the Stanford Coursera algorithms course.)
Partition the list so that all numbers smaller than the pivot are to its left and all numbers greater than the pivot are to its right.
For each βhalfβ of the list, you can treat it as a new list with a new pivot and rearrange each half until it is sorted.
Quicksort is an example of a D&C algorithm because it divides the original list into smaller and smaller lists which are ordered. These smaller, ordered lists are then combined to result in a larger, ordered list.
Quicksort is unique because its speed is dependent on the pivot selection. At worst, it can take O(n2) time, which is as slow as selection sort. However, if the pivot is always some random element in the list, quicksort runs in O(n log n) time on average.
MergesortAssume we are still working with our list of numbers. For the merge sort algorithm, the list would be broken down into its individual elements. Ordered pairs are then created from these elements (with the smaller number to the left). These ordered pairs are then grouped into ordered groups of four and this continues until the final merged, sorted list is created.
As with quicksort, mergesort is a D&C algorithm because the input list is broken down and sorted, before being combined to produce an ordered version of the larger, original list.
Mergesort runs on O(n log n) time because the entire list is halved (O(log n)) and this is done for n items.
Knowledge of algorithms and data structures is useful for data scientists because our solutions are inevitably written in code. As such, it is important to understand the structure of our data and how to think in terms of algorithms. In my next post, I describe common data structures, space complexity, and common related algorithms.
Additional Helpful Resources:
Grokking Algorithms by Aditya Y. Bhargava
Cracking the Coding Interview by Gayle Laakmann McDowell
Stanford University Coursera Algorithms specialization
Big O cheat sheet | [
{
"code": null,
"e": 247,
"s": 172,
"text": "Note: This is part 1 of a 2-part series. For the follow-up post, see here."
},
{
"code": null,
"e": 428,
"s": 247,
"text": "In data science, computer science and statistics converge. As data scientists, we use statistical principles to write code such that we can effectively explore the problem at hand."
},
{
"code": null,
"e": 1036,
"s": 428,
"text": "This necessitates at least a basic understanding of data structures, algorithms, and time-space complexity so that we can program more efficiently and understand the tools that we use. With larger datasets, this becomes particularly important. The way that we write our code influences the speed at which our data is analyzed and conclusions can be reached accordingly. In this post, I will describe Big O notation as a method for describing time-space complexity and briefly go over some algorithms that relate to time complexity. In a later post, I will discuss algorithms that relate to space complexity."
},
{
"code": null,
"e": 1353,
"s": 1036,
"text": "In programming, an algorithm is a process or set of rules to be followed in order to achieve a particular goal. An algorithm is characterized by its running time (run-time), whether in terms of space or time. As data scientists, we are interested in the most efficient algorithm so that we can optimize our workflow."
},
{
"code": null,
"e": 1608,
"s": 1353,
"text": "In computer science, Big O notation is used to describe how βfastβ an algorithm grows, by comparing the number of operations within the algorithm. This will be explained in further detail later on but for now, letβs understand all of the formal notation."
},
{
"code": null,
"e": 1624,
"s": 1608,
"text": "Formal Notation"
},
{
"code": null,
"e": 1757,
"s": 1624,
"text": "Big Ξ©: the best-case scenario. The Big Ξ© of an algorithm describes how quickly an algorithm can run under the best of circumstances."
},
{
"code": null,
"e": 1991,
"s": 1757,
"text": "Big O: the worst-case scenario. Typically, we are most concerned with the Big O time because we are interested in how slowly a given algorithm will run, at worst. How do we essentially make the βworst-caseβ not as bad as it could be?"
},
{
"code": null,
"e": 2182,
"s": 1991,
"text": "Big ΞΈ: this can only be used to describe the run-time of an algorithm if the Big Ξ© and the Big O are the same. That is, the algorithmβs run time is the same in both the best and worst cases."
},
{
"code": null,
"e": 2292,
"s": 2182,
"text": "Because we are most concerned with the Big O of an algorithm, the rest of this post will only focus on Big O."
},
{
"code": null,
"e": 2401,
"s": 2292,
"text": "How do we use Big O to describe an algorithm? Suppose you wish to search for someoneβs name in a phone book."
},
{
"code": null,
"e": 2586,
"s": 2401,
"text": "Whatβs the most straightforward way of finding this person? Well, you could go through every single name in the phone book until you find your target. This is known as a simple search."
},
{
"code": null,
"e": 2723,
"s": 2586,
"text": "If the phone book is very small, with only 10 names, this is a fairly fast process. But what if there are 1,000 names in the phone book?"
},
{
"code": null,
"e": 3077,
"s": 2723,
"text": "At best, your targetβs name is at the front of the list and you only need to need to check the first item. At worst, your targetβs name is at the very end of the phone book and you will need to have searched all 1000 names. As the βdatasetβ (or the phone book) increases in size, the maximum time it takes to run a simple search also linearly increases."
},
{
"code": null,
"e": 3309,
"s": 3077,
"text": "In this case, our algorithm is a simple search. Big O notation allows us to describe what our worst case is. Our worst case is that we will have to search through all elements (n) in the phone book. We can describe the run-time as:"
},
{
"code": null,
"e": 3344,
"s": 3309,
"text": "O(n) where n: number of operations"
},
{
"code": null,
"e": 3616,
"s": 3344,
"text": "Because the maximum number of operations is equal to the maximum number of elements in our phone book (you might need to search through them all to find your targetβs name), we say the Big O of a simple search is O(n). A simple search will never be slower than O(n) time."
},
{
"code": null,
"e": 3642,
"s": 3616,
"text": "Different Big O Run Times"
},
{
"code": null,
"e": 3797,
"s": 3642,
"text": "Different algorithms have different run-times. That is, algorithms grow at different rates. The most common Big O run-times, from fastest to slowest, are:"
},
{
"code": null,
"e": 3820,
"s": 3797,
"text": "O(log n): aka log time"
},
{
"code": null,
"e": 3842,
"s": 3820,
"text": "O(n): aka linear time"
},
{
"code": null,
"e": 3853,
"s": 3842,
"text": "O(n log n)"
},
{
"code": null,
"e": 3859,
"s": 3853,
"text": "O(n2)"
},
{
"code": null,
"e": 3865,
"s": 3859,
"text": "O(n!)"
},
{
"code": null,
"e": 4006,
"s": 3865,
"text": "The Big O cheatsheet is also very useful for a quick graphical representation of the different run times and how they compare to each other."
},
{
"code": null,
"e": 4127,
"s": 4006,
"text": "In this post and its following post, I will describe common algorithms which are described by these different run-times."
},
{
"code": null,
"e": 4234,
"s": 4127,
"text": "Here are some principles that are important to understand before discussing some of the common algorithms."
},
{
"code": null,
"e": 4382,
"s": 4234,
"text": "Recursion: Recursion is when a function calls itself. Perhaps the quintessential example of recursion is in implementation of a factorial function:"
},
{
"code": null,
"e": 4517,
"s": 4382,
"text": "def factorial(n): if n < 1: #base case return 1 else: #recursive case return n * factorial(n-1)"
},
{
"code": null,
"e": 4660,
"s": 4517,
"text": "The function is called within the function itself and will continue calling itself until the base case (in this case, when n is 1) is reached."
},
{
"code": null,
"e": 4860,
"s": 4660,
"text": "Divide and Conquer (D&C): A recursive approach for problem-solving, D&C (1) determines the simplest case for the problem (AKA the base case) and (2) reduces the problem until it is now the base case."
},
{
"code": null,
"e": 5036,
"s": 4860,
"text": "That is, a complex problem is broken down into simpler sub-problems. These sub-problems are solved and their solutions are then combined to solve the original, larger problem."
},
{
"code": null,
"e": 5126,
"s": 5036,
"text": "Search and sort algorithms are perhaps the most important algorithms to first understand."
},
{
"code": null,
"e": 5453,
"s": 5126,
"text": "Simple SearchThis was described earlier with the phone book example, where the worst case would require that you search through all the names in the phone book before you find the name of interest. In general, simple search has a O(n) time. The maximum time required is linearly related to the number of elements in your list."
},
{
"code": null,
"e": 5786,
"s": 5453,
"text": "Binary SearchLetβs stick with the phone book example. Weβre still interested in finding someoneβs name in the phone book, only this time weβre going to try to be more efficient about it. Instead of tediously going through each and every name in the phone book, weβre going to start in the middle of the phone book and go from there."
},
{
"code": null,
"e": 6295,
"s": 5786,
"text": "Say our targetβs name begins with an P. We open to the Ms which is roughly in the middle of the alphabet. We know M is earlier than P in the alphabet, so we can eliminate the section from A to M. Now we can look at the later half of the phone book (N to Z), split that section in the middle (to the Ts), and compare to our target. T is later in the alphabet than P. We then know to eliminate the later half (T to Z). We focus on N to S now, dividing this in half and so on until we find our name of interest."
},
{
"code": null,
"e": 6694,
"s": 6295,
"text": "Generally, in binary search, you take your sorted (this is important) data and find the midpoint. Each time, you compare your target to the middle value. If the target value is the same as the middle value, then your job is done. Otherwise, you know which half of the list to eliminate based on the comparison. You continue dividing until the target is found or the dataset can no longer be halved."
},
{
"code": null,
"e": 6971,
"s": 6694,
"text": "Because binary search involves the halving of your dataset, the Big O time is O(log n). As such, it is faster than simple search, especially as your dataset grows (the algorithmβs growth is not linear but logarithmic so it grows slower, relative to a linear run-time of O(n))."
},
{
"code": null,
"e": 7299,
"s": 6971,
"text": "As an aside, binary search can be written recursively but is not considered a D&C algorithm. Although the larger input is indeed broken down into subsets, these subsets are ignored if they do not contain the value of interest. Solutions are not produced for these subsets so that they can be combined to solve the larger input."
},
{
"code": null,
"e": 7667,
"s": 7299,
"text": "Selection SortMuch like simple search for search algorithms, selection sort is perhaps the most straightforward, βbrute forceβ way to sort your data. Essentially, you go through every element in your list and append each element to a new list in your desired order. For example, if you are interested in sorting a list of numbers from greatest to smallest, you would:"
},
{
"code": null,
"e": 7871,
"s": 7667,
"text": "Search through the list to find the largest numberAdd that number to a new listGo to the original list, search through it again to find the next largest numberAdd that number to the new list and so on..."
},
{
"code": null,
"e": 7922,
"s": 7871,
"text": "Search through the list to find the largest number"
},
{
"code": null,
"e": 7952,
"s": 7922,
"text": "Add that number to a new list"
},
{
"code": null,
"e": 8033,
"s": 7952,
"text": "Go to the original list, search through it again to find the next largest number"
},
{
"code": null,
"e": 8078,
"s": 8033,
"text": "Add that number to the new list and so on..."
},
{
"code": null,
"e": 8392,
"s": 8078,
"text": "For selection sort, you have to go through each item in the list (this takes n times, just as it would for a simple search) and you have to do this n times (not just once, because you have to keep going back to the original list to find the next item you want to add to the new list). Thus, this takes O(n2) time."
},
{
"code": null,
"e": 8500,
"s": 8392,
"text": "QuicksortHow would quicksort differ from selection sort? If we work with a list of numbers, just as before:"
},
{
"code": null,
"e": 9069,
"s": 8500,
"text": "Pick an element from your list, known as the pivot. The selection of a pivot is important in determining how quickly a quicksort algorithm will run. For now, we can select the last element each time as the pivot. (For additional information on pivot selection, I recommend the Stanford Coursera algorithms course.)Partition the list so that all numbers smaller than the pivot are to its left and all numbers greater than the pivot are to its right.For each βhalfβ of the list, you can treat it as a new list with a new pivot and rearrange each half until it is sorted."
},
{
"code": null,
"e": 9384,
"s": 9069,
"text": "Pick an element from your list, known as the pivot. The selection of a pivot is important in determining how quickly a quicksort algorithm will run. For now, we can select the last element each time as the pivot. (For additional information on pivot selection, I recommend the Stanford Coursera algorithms course.)"
},
{
"code": null,
"e": 9519,
"s": 9384,
"text": "Partition the list so that all numbers smaller than the pivot are to its left and all numbers greater than the pivot are to its right."
},
{
"code": null,
"e": 9640,
"s": 9519,
"text": "For each βhalfβ of the list, you can treat it as a new list with a new pivot and rearrange each half until it is sorted."
},
{
"code": null,
"e": 9854,
"s": 9640,
"text": "Quicksort is an example of a D&C algorithm because it divides the original list into smaller and smaller lists which are ordered. These smaller, ordered lists are then combined to result in a larger, ordered list."
},
{
"code": null,
"e": 10110,
"s": 9854,
"text": "Quicksort is unique because its speed is dependent on the pivot selection. At worst, it can take O(n2) time, which is as slow as selection sort. However, if the pivot is always some random element in the list, quicksort runs in O(n log n) time on average."
},
{
"code": null,
"e": 10485,
"s": 10110,
"text": "MergesortAssume we are still working with our list of numbers. For the merge sort algorithm, the list would be broken down into its individual elements. Ordered pairs are then created from these elements (with the smaller number to the left). These ordered pairs are then grouped into ordered groups of four and this continues until the final merged, sorted list is created."
},
{
"code": null,
"e": 10665,
"s": 10485,
"text": "As with quicksort, mergesort is a D&C algorithm because the input list is broken down and sorted, before being combined to produce an ordered version of the larger, original list."
},
{
"code": null,
"e": 10774,
"s": 10665,
"text": "Mergesort runs on O(n log n) time because the entire list is halved (O(log n)) and this is done for n items."
},
{
"code": null,
"e": 11109,
"s": 10774,
"text": "Knowledge of algorithms and data structures is useful for data scientists because our solutions are inevitably written in code. As such, it is important to understand the structure of our data and how to think in terms of algorithms. In my next post, I describe common data structures, space complexity, and common related algorithms."
},
{
"code": null,
"e": 11139,
"s": 11109,
"text": "Additional Helpful Resources:"
},
{
"code": null,
"e": 11181,
"s": 11139,
"text": "Grokking Algorithms by Aditya Y. Bhargava"
},
{
"code": null,
"e": 11238,
"s": 11181,
"text": "Cracking the Coding Interview by Gayle Laakmann McDowell"
},
{
"code": null,
"e": 11293,
"s": 11238,
"text": "Stanford University Coursera Algorithms specialization"
}
] |
Design IIR Bandpass Chebyshev Type-1 Filter using Scipy - Python - GeeksforGeeks | 10 Nov, 2021
IIR stands for Infinite Impulse Response, It is one of the striking features of many linear-time invariant systems that are distinguished by having an impulse response h(t)/h(n) which does not become zero after some point but instead continues infinitely.
IIR Chebyshev is a filter that is linear-time invariant filter just like the Butterworth however, it has a steeper roll off compared to the Butterworth Filter. Chebyshev Filter is further classified as Chebyshev Type-I and Chebyshev Type-II according to the parameters such as pass band ripple and stop ripple.
Chebyshev Filter has a steeper roll-off compared to the Butterworth Filter.
Chebyshev Type-I minimizes the absolute difference between the ideal and actual frequency response over the entire passband by incorporating an equal ripple in the passband.
The specifications are as follows:
Pass band frequency: 1400-2100 Hz
Stop band frequency: 1050-24500 Hz
Pass band ripple: 0.4dB
Stop band attenuation: 50 dB
Sampling frequency: 7 kHz
We will plot the magnitude, phase, impulse, step response of the filter.
Step-by-step Approach:
Step 1: Importing all the necessary libraries.
Python3
import numpy as npimport scipy.signal as signalimport matplotlib.pyplot as plt
Step 2:Defining the user defined functions such as mfreqz() and impz().
Python3
def mfreqz(b, a, Fs): # Compute frequency response of the filter # using signal.freqz function wz, hz = signal.freqz(b, a) # Calculate Magnitude from hz in dB Mag = 20*np.log10(abs(hz)) # Calculate phase angle in degree from hz Phase = np.unwrap(np.arctan2(np.imag(hz), np.real(hz)))*(180/np.pi) # Calculate frequency in Hz from wz Freq = wz*Fs/(2*np.pi) # Plot filter magnitude and phase responses using subplot. fig = plt.figure(figsize=(10, 6)) # Plot Magnitude response sub1 = plt.subplot(2, 1, 1) sub1.plot(Freq, Mag, 'r', linewidth=2) sub1.axis([1, Fs/2, -100, 5]) sub1.set_title('Magnitude Response', fontsize=20) sub1.set_xlabel('Frequency [Hz]', fontsize=20) sub1.set_ylabel('Magnitude [dB]', fontsize=20) sub1.grid() # Plot phase angle sub2 = plt.subplot(2, 1, 2) sub2.plot(Freq, Phase, 'g', linewidth=2) sub2.set_ylabel('Phase (degree)', fontsize=20) sub2.set_xlabel(r'Frequency (Hz)', fontsize=20) sub2.set_title(r'Phase response', fontsize=20) sub2.grid() plt.subplots_adjust(hspace=0.5) fig.tight_layout() plt.show() # Define impz(b,a) to calculate impulse response# and step response of a system# input: b= an array containing numerator coefficients,#a= an array containing denominator coefficientsdef impz(b, a): # Define the impulse sequence of length 60 impulse = np.repeat(0., 60) impulse[0] = 1. x = np.arange(0, 60) # Compute the impulse response response = signal.lfilter(b, a, impulse) # Plot filter impulse and step response: fig = plt.figure(figsize=(10, 6)) plt.subplot(211) plt.stem(x, response, 'm', use_line_collection=True) plt.ylabel('Amplitude', fontsize=15) plt.xlabel(r'n (samples)', fontsize=15) plt.title(r'Impulse response', fontsize=15) plt.subplot(212) step = np.cumsum(response) # Compute step response of the system plt.stem(x, step, 'g', use_line_collection=True) plt.ylabel('Amplitude', fontsize=15) plt.xlabel(r'n (samples)', fontsize=15) plt.title(r'Step response', fontsize=15) plt.subplots_adjust(hspace=0.5) fig.tight_layout() plt.show()
Step 3:Define variables with the given specifications of the filter.
Python3
# Given specificationFs = 7000 # Sampling frequency in Hzfp = np.array([1400, 2100]) # Pass band frequency in Hzfs = np.array([1050, 2450]) # Stop band frequency in HzAp = 0.4 # Pass band ripple in dBAs = 50 # stop band attenuation in dB
Step 4: Computing the cut-off frequency
Python3
# Compute pass band and stop band edge frequencieswp = fp/(Fs/2) # Normalized passband edge frequencies w.r.t. Nyquist ratews = fs/(Fs/2) # Normalized stopband edge frequencies
Step 5: Compute cut-off frequency & order
Python3
# Compute order of the Chebyshev type-1 filter using signal.cheb1ordN, wc = signal.cheb1ord(wp, ws, Ap, As) # Print the order of the filter and cutoff frequenciesprint('Order of the filter=', N)print('Cut-off frequency=', wc)
Output:
Step 6: Compute the filter co-efficient
Python
# Design digital Chebyshev type-1 filter# using signal.cheby1 functionz, p = signal.cheby1(N, Ap, wc, 'bandpass') # Print numerator and denomerator coefficients# of the filterprint('Numerator Coefficients:', z)print('Denominator Coefficients:', p)
Output:
Step 7: Plotting the Magnitude & Phase Response
Python3
# Call mfreqz to plot the magnitude and phase responsemfreqz(z, p, Fs)
Output:
Step 8: Plotting the Impulse and Step Response
Python3
# Call impz function to plot impulse# and step response of the filterimpz(z,p)
Output:
Full Code:
Python3
# import required libraryimport numpy as npimport scipy.signal as signalimport matplotlib.pyplot as plt def mfreqz(b, a, Fs): # Compute frequency response of the filter # using signal.freqz function wz, hz = signal.freqz(b, a) # Calculate Magnitude from hz in dB Mag = 20*np.log10(abs(hz)) # Calculate phase angle in degree from hz Phase = np.unwrap(np.arctan2(np.imag(hz), np.real(hz)))*(180/np.pi) # Calculate frequency in Hz from wz Freq = wz*Fs/(2*np.pi) # Plot filter magnitude and phase responses using subplot. fig = plt.figure(figsize=(10, 6)) # Plot Magnitude response sub1 = plt.subplot(2, 1, 1) sub1.plot(Freq, Mag, 'r', linewidth=2) sub1.axis([1, Fs/2, -100, 5]) sub1.set_title('Magnitude Response', fontsize=20) sub1.set_xlabel('Frequency [Hz]', fontsize=20) sub1.set_ylabel('Magnitude [dB]', fontsize=20) sub1.grid() # Plot phase angle sub2 = plt.subplot(2, 1, 2) sub2.plot(Freq, Phase, 'g', linewidth=2) sub2.set_ylabel('Phase (degree)', fontsize=20) sub2.set_xlabel(r'Frequency (Hz)', fontsize=20) sub2.set_title(r'Phase response', fontsize=20) sub2.grid() plt.subplots_adjust(hspace=0.5) fig.tight_layout() plt.show() # Define impz(b,a) to calculate impulse response# and step response of a system# input: b= an array containing numerator coefficients,# a= an array containing denominator coefficientsdef impz(b, a): # Define the impulse sequence of length 60 impulse = np.repeat(0., 60) impulse[0] = 1. x = np.arange(0, 60) # Compute the impulse response response = signal.lfilter(b, a, impulse) # Plot filter impulse and step response: fig = plt.figure(figsize=(10, 6)) plt.subplot(211) plt.stem(x, response, 'm', use_line_collection=True) plt.ylabel('Amplitude', fontsize=15) plt.xlabel(r'n (samples)', fontsize=15) plt.title(r'Impulse response', fontsize=15) plt.subplot(212) step = np.cumsum(response) # Compute step response of the system plt.stem(x, step, 'g', use_line_collection=True) plt.ylabel('Amplitude', fontsize=15) plt.xlabel(r'n (samples)', fontsize=15) plt.title(r'Step response', fontsize=15) plt.subplots_adjust(hspace=0.5) fig.tight_layout() plt.show() # Given specificationFs = 7000 # Sampling frequency in Hzfp = np.array([1400, 2100]) # Pass band frequency in Hzfs = np.array([1050, 2450]) # Stop band frequency in HzAp = 0.4 # Pass band ripple in dBAs = 50 # stop band attenuation in dB # Compute pass band and stop band edge frequencieswp = fp/(Fs/2) # Normalized passband edge frequencies w.r.t. Nyquist ratews = fs/(Fs/2) # Normalized stopband edge frequencies # Compute order of the Chebyshev type-1# filter using signal.cheb1ordN, wc = signal.cheb1ord(wp, ws, Ap, As) # Print the order of the filter and cutoff frequenciesprint('Order of the filter=', N)print('Cut-off frequency=', wc) # Design digital Chebyshev type-1 filter using# signal.cheby1 functionz, p = signal.cheby1(N, Ap, wc, 'bandpass') # Print numerator and denomerator coefficients of the filterprint('Numerator Coefficients:', z)print('Denominator Coefficients:', p) # Call mfreqz to plot the magnitude and phase responsemfreqz(z, p, Fs) # Call impz function to plot impulse and# step response of the filterimpz(z, p)
Output:
gulshankumarar231
Data Visualization
Python-scipy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
Read a file line by line in Python
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
Different ways to create Pandas Dataframe
Python String | replace()
Create a Pandas DataFrame from Lists
Python program to convert a list to string
Selecting rows in pandas DataFrame based on conditions | [
{
"code": null,
"e": 24620,
"s": 24592,
"text": "\n10 Nov, 2021"
},
{
"code": null,
"e": 24876,
"s": 24620,
"text": "IIR stands for Infinite Impulse Response, It is one of the striking features of many linear-time invariant systems that are distinguished by having an impulse response h(t)/h(n) which does not become zero after some point but instead continues infinitely."
},
{
"code": null,
"e": 25187,
"s": 24876,
"text": "IIR Chebyshev is a filter that is linear-time invariant filter just like the Butterworth however, it has a steeper roll off compared to the Butterworth Filter. Chebyshev Filter is further classified as Chebyshev Type-I and Chebyshev Type-II according to the parameters such as pass band ripple and stop ripple."
},
{
"code": null,
"e": 25263,
"s": 25187,
"text": "Chebyshev Filter has a steeper roll-off compared to the Butterworth Filter."
},
{
"code": null,
"e": 25437,
"s": 25263,
"text": "Chebyshev Type-I minimizes the absolute difference between the ideal and actual frequency response over the entire passband by incorporating an equal ripple in the passband."
},
{
"code": null,
"e": 25474,
"s": 25437,
"text": "The specifications are as follows: "
},
{
"code": null,
"e": 25508,
"s": 25474,
"text": "Pass band frequency: 1400-2100 Hz"
},
{
"code": null,
"e": 25543,
"s": 25508,
"text": "Stop band frequency: 1050-24500 Hz"
},
{
"code": null,
"e": 25567,
"s": 25543,
"text": "Pass band ripple: 0.4dB"
},
{
"code": null,
"e": 25596,
"s": 25567,
"text": "Stop band attenuation: 50 dB"
},
{
"code": null,
"e": 25622,
"s": 25596,
"text": "Sampling frequency: 7 kHz"
},
{
"code": null,
"e": 25695,
"s": 25622,
"text": "We will plot the magnitude, phase, impulse, step response of the filter."
},
{
"code": null,
"e": 25718,
"s": 25695,
"text": "Step-by-step Approach:"
},
{
"code": null,
"e": 25765,
"s": 25718,
"text": "Step 1: Importing all the necessary libraries."
},
{
"code": null,
"e": 25773,
"s": 25765,
"text": "Python3"
},
{
"code": "import numpy as npimport scipy.signal as signalimport matplotlib.pyplot as plt",
"e": 25852,
"s": 25773,
"text": null
},
{
"code": null,
"e": 25924,
"s": 25852,
"text": "Step 2:Defining the user defined functions such as mfreqz() and impz()."
},
{
"code": null,
"e": 25932,
"s": 25924,
"text": "Python3"
},
{
"code": "def mfreqz(b, a, Fs): # Compute frequency response of the filter # using signal.freqz function wz, hz = signal.freqz(b, a) # Calculate Magnitude from hz in dB Mag = 20*np.log10(abs(hz)) # Calculate phase angle in degree from hz Phase = np.unwrap(np.arctan2(np.imag(hz), np.real(hz)))*(180/np.pi) # Calculate frequency in Hz from wz Freq = wz*Fs/(2*np.pi) # Plot filter magnitude and phase responses using subplot. fig = plt.figure(figsize=(10, 6)) # Plot Magnitude response sub1 = plt.subplot(2, 1, 1) sub1.plot(Freq, Mag, 'r', linewidth=2) sub1.axis([1, Fs/2, -100, 5]) sub1.set_title('Magnitude Response', fontsize=20) sub1.set_xlabel('Frequency [Hz]', fontsize=20) sub1.set_ylabel('Magnitude [dB]', fontsize=20) sub1.grid() # Plot phase angle sub2 = plt.subplot(2, 1, 2) sub2.plot(Freq, Phase, 'g', linewidth=2) sub2.set_ylabel('Phase (degree)', fontsize=20) sub2.set_xlabel(r'Frequency (Hz)', fontsize=20) sub2.set_title(r'Phase response', fontsize=20) sub2.grid() plt.subplots_adjust(hspace=0.5) fig.tight_layout() plt.show() # Define impz(b,a) to calculate impulse response# and step response of a system# input: b= an array containing numerator coefficients,#a= an array containing denominator coefficientsdef impz(b, a): # Define the impulse sequence of length 60 impulse = np.repeat(0., 60) impulse[0] = 1. x = np.arange(0, 60) # Compute the impulse response response = signal.lfilter(b, a, impulse) # Plot filter impulse and step response: fig = plt.figure(figsize=(10, 6)) plt.subplot(211) plt.stem(x, response, 'm', use_line_collection=True) plt.ylabel('Amplitude', fontsize=15) plt.xlabel(r'n (samples)', fontsize=15) plt.title(r'Impulse response', fontsize=15) plt.subplot(212) step = np.cumsum(response) # Compute step response of the system plt.stem(x, step, 'g', use_line_collection=True) plt.ylabel('Amplitude', fontsize=15) plt.xlabel(r'n (samples)', fontsize=15) plt.title(r'Step response', fontsize=15) plt.subplots_adjust(hspace=0.5) fig.tight_layout() plt.show()",
"e": 28104,
"s": 25932,
"text": null
},
{
"code": null,
"e": 28173,
"s": 28104,
"text": "Step 3:Define variables with the given specifications of the filter."
},
{
"code": null,
"e": 28181,
"s": 28173,
"text": "Python3"
},
{
"code": "# Given specificationFs = 7000 # Sampling frequency in Hzfp = np.array([1400, 2100]) # Pass band frequency in Hzfs = np.array([1050, 2450]) # Stop band frequency in HzAp = 0.4 # Pass band ripple in dBAs = 50 # stop band attenuation in dB",
"e": 28424,
"s": 28181,
"text": null
},
{
"code": null,
"e": 28464,
"s": 28424,
"text": "Step 4: Computing the cut-off frequency"
},
{
"code": null,
"e": 28472,
"s": 28464,
"text": "Python3"
},
{
"code": "# Compute pass band and stop band edge frequencieswp = fp/(Fs/2) # Normalized passband edge frequencies w.r.t. Nyquist ratews = fs/(Fs/2) # Normalized stopband edge frequencies",
"e": 28651,
"s": 28472,
"text": null
},
{
"code": null,
"e": 28693,
"s": 28651,
"text": "Step 5: Compute cut-off frequency & order"
},
{
"code": null,
"e": 28701,
"s": 28693,
"text": "Python3"
},
{
"code": "# Compute order of the Chebyshev type-1 filter using signal.cheb1ordN, wc = signal.cheb1ord(wp, ws, Ap, As) # Print the order of the filter and cutoff frequenciesprint('Order of the filter=', N)print('Cut-off frequency=', wc)",
"e": 28928,
"s": 28701,
"text": null
},
{
"code": null,
"e": 28936,
"s": 28928,
"text": "Output:"
},
{
"code": null,
"e": 28976,
"s": 28936,
"text": "Step 6: Compute the filter co-efficient"
},
{
"code": null,
"e": 28983,
"s": 28976,
"text": "Python"
},
{
"code": "# Design digital Chebyshev type-1 filter# using signal.cheby1 functionz, p = signal.cheby1(N, Ap, wc, 'bandpass') # Print numerator and denomerator coefficients# of the filterprint('Numerator Coefficients:', z)print('Denominator Coefficients:', p)",
"e": 29231,
"s": 28983,
"text": null
},
{
"code": null,
"e": 29239,
"s": 29231,
"text": "Output:"
},
{
"code": null,
"e": 29287,
"s": 29239,
"text": "Step 7: Plotting the Magnitude & Phase Response"
},
{
"code": null,
"e": 29295,
"s": 29287,
"text": "Python3"
},
{
"code": "# Call mfreqz to plot the magnitude and phase responsemfreqz(z, p, Fs)",
"e": 29366,
"s": 29295,
"text": null
},
{
"code": null,
"e": 29374,
"s": 29366,
"text": "Output:"
},
{
"code": null,
"e": 29421,
"s": 29374,
"text": "Step 8: Plotting the Impulse and Step Response"
},
{
"code": null,
"e": 29429,
"s": 29421,
"text": "Python3"
},
{
"code": "# Call impz function to plot impulse# and step response of the filterimpz(z,p)",
"e": 29508,
"s": 29429,
"text": null
},
{
"code": null,
"e": 29519,
"s": 29511,
"text": "Output:"
},
{
"code": null,
"e": 29534,
"s": 29523,
"text": "Full Code:"
},
{
"code": null,
"e": 29544,
"s": 29536,
"text": "Python3"
},
{
"code": "# import required libraryimport numpy as npimport scipy.signal as signalimport matplotlib.pyplot as plt def mfreqz(b, a, Fs): # Compute frequency response of the filter # using signal.freqz function wz, hz = signal.freqz(b, a) # Calculate Magnitude from hz in dB Mag = 20*np.log10(abs(hz)) # Calculate phase angle in degree from hz Phase = np.unwrap(np.arctan2(np.imag(hz), np.real(hz)))*(180/np.pi) # Calculate frequency in Hz from wz Freq = wz*Fs/(2*np.pi) # Plot filter magnitude and phase responses using subplot. fig = plt.figure(figsize=(10, 6)) # Plot Magnitude response sub1 = plt.subplot(2, 1, 1) sub1.plot(Freq, Mag, 'r', linewidth=2) sub1.axis([1, Fs/2, -100, 5]) sub1.set_title('Magnitude Response', fontsize=20) sub1.set_xlabel('Frequency [Hz]', fontsize=20) sub1.set_ylabel('Magnitude [dB]', fontsize=20) sub1.grid() # Plot phase angle sub2 = plt.subplot(2, 1, 2) sub2.plot(Freq, Phase, 'g', linewidth=2) sub2.set_ylabel('Phase (degree)', fontsize=20) sub2.set_xlabel(r'Frequency (Hz)', fontsize=20) sub2.set_title(r'Phase response', fontsize=20) sub2.grid() plt.subplots_adjust(hspace=0.5) fig.tight_layout() plt.show() # Define impz(b,a) to calculate impulse response# and step response of a system# input: b= an array containing numerator coefficients,# a= an array containing denominator coefficientsdef impz(b, a): # Define the impulse sequence of length 60 impulse = np.repeat(0., 60) impulse[0] = 1. x = np.arange(0, 60) # Compute the impulse response response = signal.lfilter(b, a, impulse) # Plot filter impulse and step response: fig = plt.figure(figsize=(10, 6)) plt.subplot(211) plt.stem(x, response, 'm', use_line_collection=True) plt.ylabel('Amplitude', fontsize=15) plt.xlabel(r'n (samples)', fontsize=15) plt.title(r'Impulse response', fontsize=15) plt.subplot(212) step = np.cumsum(response) # Compute step response of the system plt.stem(x, step, 'g', use_line_collection=True) plt.ylabel('Amplitude', fontsize=15) plt.xlabel(r'n (samples)', fontsize=15) plt.title(r'Step response', fontsize=15) plt.subplots_adjust(hspace=0.5) fig.tight_layout() plt.show() # Given specificationFs = 7000 # Sampling frequency in Hzfp = np.array([1400, 2100]) # Pass band frequency in Hzfs = np.array([1050, 2450]) # Stop band frequency in HzAp = 0.4 # Pass band ripple in dBAs = 50 # stop band attenuation in dB # Compute pass band and stop band edge frequencieswp = fp/(Fs/2) # Normalized passband edge frequencies w.r.t. Nyquist ratews = fs/(Fs/2) # Normalized stopband edge frequencies # Compute order of the Chebyshev type-1# filter using signal.cheb1ordN, wc = signal.cheb1ord(wp, ws, Ap, As) # Print the order of the filter and cutoff frequenciesprint('Order of the filter=', N)print('Cut-off frequency=', wc) # Design digital Chebyshev type-1 filter using# signal.cheby1 functionz, p = signal.cheby1(N, Ap, wc, 'bandpass') # Print numerator and denomerator coefficients of the filterprint('Numerator Coefficients:', z)print('Denominator Coefficients:', p) # Call mfreqz to plot the magnitude and phase responsemfreqz(z, p, Fs) # Call impz function to plot impulse and# step response of the filterimpz(z, p)",
"e": 32866,
"s": 29544,
"text": null
},
{
"code": null,
"e": 32874,
"s": 32866,
"text": "Output:"
},
{
"code": null,
"e": 32892,
"s": 32874,
"text": "gulshankumarar231"
},
{
"code": null,
"e": 32911,
"s": 32892,
"text": "Data Visualization"
},
{
"code": null,
"e": 32924,
"s": 32911,
"text": "Python-scipy"
},
{
"code": null,
"e": 32931,
"s": 32924,
"text": "Python"
},
{
"code": null,
"e": 33029,
"s": 32931,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 33038,
"s": 33029,
"text": "Comments"
},
{
"code": null,
"e": 33051,
"s": 33038,
"text": "Old Comments"
},
{
"code": null,
"e": 33069,
"s": 33051,
"text": "Python Dictionary"
},
{
"code": null,
"e": 33104,
"s": 33069,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 33126,
"s": 33104,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 33158,
"s": 33126,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 33188,
"s": 33158,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 33230,
"s": 33188,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 33256,
"s": 33230,
"text": "Python String | replace()"
},
{
"code": null,
"e": 33293,
"s": 33256,
"text": "Create a Pandas DataFrame from Lists"
},
{
"code": null,
"e": 33336,
"s": 33293,
"text": "Python program to convert a list to string"
}
] |
Selection Sort | In the selection sort technique, the list is divided into two parts. In one part all elements are sorted and in another part the items are unsorted. At first, we take the maximum or minimum data from the array. After getting the data (say minimum) we place it at the beginning of the list by replacing the data of first place with the minimum data. After performing the array is getting smaller. Thus this sorting technique is done.
Time Complexity: O(n^2)
Space Complexity: O(1)
Input:
The unsorted list: 5 9 7 23 78 20
Output:
Array before Sorting: 5 9 7 23 78 20
Array after Sorting: 5 7 9 20 23 78
selectionSort(array, size)
Input β An array of data, and the total number in the array
Output β The sorted Array
Begin
for i := 0 to size-2 do //find minimum from ith location to size
iMin := i;
for j:= i+1 to size β 1 do
if array[j] < array[iMin] then
iMin := j
done
swap array[i] with array[iMin].
done
End
#include<iostream>
using namespace std;
void swapping(int &a, int &b) { //swap the content of a and b
int temp;
temp = a;
a = b;
b = temp;
}
void display(int *array, int size) {
for(int i = 0; i<size; i++)
cout << array[i] << " ";
cout << endl;
}
void selectionSort(int *array, int size) {
int i, j, imin;
for(i = 0; i<size-1; i++) {
imin = i;//get index of minimum data
for(j = i+1; j<size; j++)
if(array[j] < array[imin])
imin = j;
//placing in correct position
swap(array[i], array[imin]);
}
}
int main() {
int n;
cout << "Enter the number of elements: ";
cin >> n;
int arr[n]; //create an array with given number of elements
cout << "Enter elements:" << endl;
for(int i = 0; i<n; i++) {
cin >> arr[i];
}
cout << "Array before Sorting: ";
display(arr, n);
selectionSort(arr, n);
cout << "Array after Sorting: ";
display(arr, n);
}
Enter the number of elements: 6
Enter elements:
5 9 7 23 78 20
Array before Sorting: 5 9 7 23 78 20
Array after Sorting: 5 7 9 20 23 78 | [
{
"code": null,
"e": 1495,
"s": 1062,
"text": "In the selection sort technique, the list is divided into two parts. In one part all elements are sorted and in another part the items are unsorted. At first, we take the maximum or minimum data from the array. After getting the data (say minimum) we place it at the beginning of the list by replacing the data of first place with the minimum data. After performing the array is getting smaller. Thus this sorting technique is done."
},
{
"code": null,
"e": 1519,
"s": 1495,
"text": "Time Complexity: O(n^2)"
},
{
"code": null,
"e": 1542,
"s": 1519,
"text": "Space Complexity: O(1)"
},
{
"code": null,
"e": 1664,
"s": 1542,
"text": "Input:\nThe unsorted list: 5 9 7 23 78 20\nOutput:\nArray before Sorting: 5 9 7 23 78 20\nArray after Sorting: 5 7 9 20 23 78"
},
{
"code": null,
"e": 1691,
"s": 1664,
"text": "selectionSort(array, size)"
},
{
"code": null,
"e": 1751,
"s": 1691,
"text": "Input β An array of data, and the total number in the array"
},
{
"code": null,
"e": 1777,
"s": 1751,
"text": "Output β The sorted Array"
},
{
"code": null,
"e": 2024,
"s": 1777,
"text": "Begin\n for i := 0 to size-2 do //find minimum from ith location to size\n iMin := i;\n for j:= i+1 to size β 1 do\n if array[j] < array[iMin] then\n iMin := j\n done\n swap array[i] with array[iMin].\n done\nEnd"
},
{
"code": null,
"e": 2985,
"s": 2024,
"text": "#include<iostream>\nusing namespace std;\n\nvoid swapping(int &a, int &b) { //swap the content of a and b\n int temp;\n temp = a;\n a = b;\n b = temp;\n}\n\nvoid display(int *array, int size) {\n for(int i = 0; i<size; i++)\n cout << array[i] << \" \";\n cout << endl;\n}\n\nvoid selectionSort(int *array, int size) {\n int i, j, imin;\n\n for(i = 0; i<size-1; i++) {\n imin = i;//get index of minimum data\n for(j = i+1; j<size; j++)\n if(array[j] < array[imin])\n imin = j;\n //placing in correct position\n swap(array[i], array[imin]);\n }\n}\n\nint main() {\n int n;\n cout << \"Enter the number of elements: \";\n cin >> n;\n int arr[n]; //create an array with given number of elements\n cout << \"Enter elements:\" << endl;\n\n for(int i = 0; i<n; i++) {\n cin >> arr[i];\n }\n\n cout << \"Array before Sorting: \";\n display(arr, n);\n selectionSort(arr, n);\n cout << \"Array after Sorting: \";\n display(arr, n);\n}"
},
{
"code": null,
"e": 3127,
"s": 2985,
"text": "Enter the number of elements: 6\nEnter elements:\n5 9 7 23 78 20 \nArray before Sorting: 5 9 7 23 78 20\nArray after Sorting: 5 7 9 20 23 78"
}
] |
Append data to an empty Pandas DataFrame - GeeksforGeeks | 17 Aug, 2020
Let us see how to append data to an empty Pandas DataFrame.
Creating the Data Frame and assigning the columns to it
# importing the moduleimport pandas as pd # creating the DataFrame of int and floata = [[1, 1.2], [2, 1.4], [3, 1.5], [4, 1.8]]t = pd.DataFrame(a, columns =["A", "B"]) # displaying the DataFrameprint(t)print(t.dtypes)
Output :
On appending the float values to the int valued data type column the resultant data frame column type-caste into float in order to accommodate the float value
If we use the argument ignore_index = True => that the index values will remain continuous instead of starting again from 0, be default itβs value is False
# Appending a Data Frame of float and ints = pd.DataFrame([[1.3, 9]], columns = ["A", "B"])display(s) # makes index continuoust = t.append(s, ignore_index = True) display(t) # Resultant data frame is of type float and floatdisplay(t.dtypes)
Output :
When we appended the boolean format data into the data frame that was already of the type of float columns then it will change the values accordingly in order to accommodate the boolean values in the float data type domain only.
# Appending a Data Frame of bool and boolu = pd.DataFrame([[True, False]], columns =["A", "B"])display(u)display(u.dtypes) t = t.append(u)display(t)display(t.dtypes) # type casted into float and float
Output :
On appending the data of different data types to the previously formed Data Frame then the resultant Data Frame columns type will always be of the wider spectrum data type.
# Appending a Data Frame of object and objectx = pd.DataFrame([["1.3", "9.2"]], columns = ["A", "B"])display(x)display(x.dtypes) t = t.append(x)display(t)display(t.dtypes)
Output :
If we aim to create a data frame through a for loop then the most efficient way of doing that is as follows :
# Creating a DataFrame using a for loop in efficient mannery = pd.concat([pd.DataFrame([[i, i * 10]], columns = ["A", "B"]) for i in range(7, 10)], ignore_index = True) # makes index continuoust = t.append(y, ignore_index = True) display(t)display(t.dtypes)
Output
If we attempt to add different column than already in the data frame then results are as follows :
# Appending Different Columnsz = pd.DataFrame([["1.3", "9.2"]], columns = ["E", "F"])t = t.append(z)print(t)print(t.dtypes)print()
Output :
Python pandas-dataFrame
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 | os.path.join() method
Python | Get unique values from a list
Create a directory in Python
Defaultdict in Python
Python | Pandas dataframe.groupby() | [
{
"code": null,
"e": 25555,
"s": 25527,
"text": "\n17 Aug, 2020"
},
{
"code": null,
"e": 25615,
"s": 25555,
"text": "Let us see how to append data to an empty Pandas DataFrame."
},
{
"code": null,
"e": 25671,
"s": 25615,
"text": "Creating the Data Frame and assigning the columns to it"
},
{
"code": "# importing the moduleimport pandas as pd # creating the DataFrame of int and floata = [[1, 1.2], [2, 1.4], [3, 1.5], [4, 1.8]]t = pd.DataFrame(a, columns =[\"A\", \"B\"]) # displaying the DataFrameprint(t)print(t.dtypes)",
"e": 25891,
"s": 25671,
"text": null
},
{
"code": null,
"e": 25900,
"s": 25891,
"text": "Output :"
},
{
"code": null,
"e": 26060,
"s": 25900,
"text": "On appending the float values to the int valued data type column the resultant data frame column type-caste into float in order to accommodate the float value"
},
{
"code": null,
"e": 26217,
"s": 26060,
"text": "If we use the argument ignore_index = True => that the index values will remain continuous instead of starting again from 0, be default itβs value is False"
},
{
"code": "# Appending a Data Frame of float and ints = pd.DataFrame([[1.3, 9]], columns = [\"A\", \"B\"])display(s) # makes index continuoust = t.append(s, ignore_index = True) display(t) # Resultant data frame is of type float and floatdisplay(t.dtypes) ",
"e": 26463,
"s": 26217,
"text": null
},
{
"code": null,
"e": 26472,
"s": 26463,
"text": "Output :"
},
{
"code": null,
"e": 26701,
"s": 26472,
"text": "When we appended the boolean format data into the data frame that was already of the type of float columns then it will change the values accordingly in order to accommodate the boolean values in the float data type domain only."
},
{
"code": "# Appending a Data Frame of bool and boolu = pd.DataFrame([[True, False]], columns =[\"A\", \"B\"])display(u)display(u.dtypes) t = t.append(u)display(t)display(t.dtypes) # type casted into float and float",
"e": 26904,
"s": 26701,
"text": null
},
{
"code": null,
"e": 26913,
"s": 26904,
"text": "Output :"
},
{
"code": null,
"e": 27086,
"s": 26913,
"text": "On appending the data of different data types to the previously formed Data Frame then the resultant Data Frame columns type will always be of the wider spectrum data type."
},
{
"code": "# Appending a Data Frame of object and objectx = pd.DataFrame([[\"1.3\", \"9.2\"]], columns = [\"A\", \"B\"])display(x)display(x.dtypes) t = t.append(x)display(t)display(t.dtypes)",
"e": 27259,
"s": 27086,
"text": null
},
{
"code": null,
"e": 27268,
"s": 27259,
"text": "Output :"
},
{
"code": null,
"e": 27378,
"s": 27268,
"text": "If we aim to create a data frame through a for loop then the most efficient way of doing that is as follows :"
},
{
"code": "# Creating a DataFrame using a for loop in efficient mannery = pd.concat([pd.DataFrame([[i, i * 10]], columns = [\"A\", \"B\"]) for i in range(7, 10)], ignore_index = True) # makes index continuoust = t.append(y, ignore_index = True) display(t)display(t.dtypes)",
"e": 27652,
"s": 27378,
"text": null
},
{
"code": null,
"e": 27659,
"s": 27652,
"text": "Output"
},
{
"code": null,
"e": 27758,
"s": 27659,
"text": "If we attempt to add different column than already in the data frame then results are as follows :"
},
{
"code": "# Appending Different Columnsz = pd.DataFrame([[\"1.3\", \"9.2\"]], columns = [\"E\", \"F\"])t = t.append(z)print(t)print(t.dtypes)print()",
"e": 27889,
"s": 27758,
"text": null
},
{
"code": null,
"e": 27898,
"s": 27889,
"text": "Output :"
},
{
"code": null,
"e": 27922,
"s": 27898,
"text": "Python pandas-dataFrame"
},
{
"code": null,
"e": 27936,
"s": 27922,
"text": "Python-pandas"
},
{
"code": null,
"e": 27943,
"s": 27936,
"text": "Python"
},
{
"code": null,
"e": 28041,
"s": 27943,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28073,
"s": 28041,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 28115,
"s": 28073,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 28157,
"s": 28115,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 28213,
"s": 28157,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 28240,
"s": 28213,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 28271,
"s": 28240,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 28310,
"s": 28271,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 28339,
"s": 28310,
"text": "Create a directory in Python"
},
{
"code": null,
"e": 28361,
"s": 28339,
"text": "Defaultdict in Python"
}
] |
How to check if one date is between two dates in JavaScript ? | 20 Jun, 2022
The task is to determine if the given date is in between the given 2 dates or not? Here are a few of the most used techniques discussed with the help of JavaScript. In the first approach, we will use .split() method and the new Date() constructor. And in the second approach we will use the .getTime() method with the new Date() constructor. Approach 1: Use .split() method to split the date on β/β to get the day, month and year in an array. The we have to construct the date from the array obtained in previous step for that we will use the new Date() constructor . Because this method returns the number of seconds from 1 Jan 1970, So it becomes easy to compare the dates.
Example: This example uses the approach discussed above.
html
<!DOCTYPE HTML><html> <head> <title> How to Check if one Date is between two dates using JavaScript ? </title> <style> body { text-align: center; } h1 { color: green; } #geeks { font-weight: bold; } </style></head> <body> <h1>GeeksforGeeks</h1> <p> Date 1 = "06/04/2019" Date 2 = "07/10/2019" <br>Date_to_check = "02/12/2019" </p> <button onclick="gfg_Run()"> Click Here </button> <p id="geeks"></p> <script> var el_down = document.getElementById("geeks"); // Format - MM/DD/YYYY var Date_1 = "06/04/2019"; var Date_2 = "07/10/2019"; var Date_to_check = "02/12/2019"; function gfg_Run() { D_1 = Date_1.split("/"); D_2 = Date_2.split("/"); D_3 = Date_to_check.split("/"); var d1 = new Date(D_1[2], parseInt(D_1[1]) - 1, D_1[0]); var d2 = new Date(D_2[2], parseInt(D_2[1]) - 1, D_2[0]); var d3 = new Date(D_3[2], parseInt(D_3[1]) - 1, D_3[0]); if (d3 > d1 && d3 < d2) { el_down.innerHTML = "Date is in between the " + "Date 1 and Date 2"; } else { el_down.innerHTML = "Date is not in between " + "the Date 1 and Date 2"; } } </script></body> </html>
Output:
Approach 2: Here first use new Date() constructor and pass the string in it which makes a Date Object. The .getTime() method which returns the number of seconds from 1 Jan 1970 and Seconds can be easily compared.
Example: This example uses the approach discussed above.
html
<!DOCTYPE HTML><html> <head> <title> How to Check if one Date is between two dates using JavaScript ? </title> <style> body { text-align: center; } h1 { color: green; } #geeks { font-weight: bold; } </style></head> <body> <h1>GeeksforGeeks</h1> <p> Date 1 = "06/04/2019" Date 2 = "07/10/2019" <br>Date_to_check = "02/8/2019" </p> <button onclick="gfg_Run()"> Click Here </button> <p id="geeks"></p> <script> var el_down = document.getElementById("geeks"); // Format - MM/DD/YYYY var D1 = "06/04/2019"; var D2 = "07/10/2019"; var D3 = "02/8/2019"; function gfg_Run() { D1 = new Date(D1); D2 = new Date(D2); D3 = new Date(D3); if (D3.getTime() <= D2.getTime() && D3.getTime() >= D1.getTime()) { el_down.innerHTML = "Date is in between" + " the Date 1 and Date 2"; } else { el_down.innerHTML = "Date is not in" + " between the Date 1 and Date 2"; } } </script></body> </html>
Output:
surinderdawra388
javascript-date
JavaScript-Misc
JavaScript
Web Technologies
Web technologies Questions
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
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
Hide or show elements in HTML using display property
Difference Between PUT and PATCH Request
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ? | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n20 Jun, 2022"
},
{
"code": null,
"e": 704,
"s": 28,
"text": "The task is to determine if the given date is in between the given 2 dates or not? Here are a few of the most used techniques discussed with the help of JavaScript. In the first approach, we will use .split() method and the new Date() constructor. And in the second approach we will use the .getTime() method with the new Date() constructor. Approach 1: Use .split() method to split the date on β/β to get the day, month and year in an array. The we have to construct the date from the array obtained in previous step for that we will use the new Date() constructor . Because this method returns the number of seconds from 1 Jan 1970, So it becomes easy to compare the dates."
},
{
"code": null,
"e": 762,
"s": 704,
"text": "Example: This example uses the approach discussed above. "
},
{
"code": null,
"e": 767,
"s": 762,
"text": "html"
},
{
"code": "<!DOCTYPE HTML><html> <head> <title> How to Check if one Date is between two dates using JavaScript ? </title> <style> body { text-align: center; } h1 { color: green; } #geeks { font-weight: bold; } </style></head> <body> <h1>GeeksforGeeks</h1> <p> Date 1 = \"06/04/2019\" Date 2 = \"07/10/2019\" <br>Date_to_check = \"02/12/2019\" </p> <button onclick=\"gfg_Run()\"> Click Here </button> <p id=\"geeks\"></p> <script> var el_down = document.getElementById(\"geeks\"); // Format - MM/DD/YYYY var Date_1 = \"06/04/2019\"; var Date_2 = \"07/10/2019\"; var Date_to_check = \"02/12/2019\"; function gfg_Run() { D_1 = Date_1.split(\"/\"); D_2 = Date_2.split(\"/\"); D_3 = Date_to_check.split(\"/\"); var d1 = new Date(D_1[2], parseInt(D_1[1]) - 1, D_1[0]); var d2 = new Date(D_2[2], parseInt(D_2[1]) - 1, D_2[0]); var d3 = new Date(D_3[2], parseInt(D_3[1]) - 1, D_3[0]); if (d3 > d1 && d3 < d2) { el_down.innerHTML = \"Date is in between the \" + \"Date 1 and Date 2\"; } else { el_down.innerHTML = \"Date is not in between \" + \"the Date 1 and Date 2\"; } } </script></body> </html>",
"e": 2273,
"s": 767,
"text": null
},
{
"code": null,
"e": 2282,
"s": 2273,
"text": "Output: "
},
{
"code": null,
"e": 2495,
"s": 2282,
"text": "Approach 2: Here first use new Date() constructor and pass the string in it which makes a Date Object. The .getTime() method which returns the number of seconds from 1 Jan 1970 and Seconds can be easily compared."
},
{
"code": null,
"e": 2553,
"s": 2495,
"text": "Example: This example uses the approach discussed above. "
},
{
"code": null,
"e": 2558,
"s": 2553,
"text": "html"
},
{
"code": "<!DOCTYPE HTML><html> <head> <title> How to Check if one Date is between two dates using JavaScript ? </title> <style> body { text-align: center; } h1 { color: green; } #geeks { font-weight: bold; } </style></head> <body> <h1>GeeksforGeeks</h1> <p> Date 1 = \"06/04/2019\" Date 2 = \"07/10/2019\" <br>Date_to_check = \"02/8/2019\" </p> <button onclick=\"gfg_Run()\"> Click Here </button> <p id=\"geeks\"></p> <script> var el_down = document.getElementById(\"geeks\"); // Format - MM/DD/YYYY var D1 = \"06/04/2019\"; var D2 = \"07/10/2019\"; var D3 = \"02/8/2019\"; function gfg_Run() { D1 = new Date(D1); D2 = new Date(D2); D3 = new Date(D3); if (D3.getTime() <= D2.getTime() && D3.getTime() >= D1.getTime()) { el_down.innerHTML = \"Date is in between\" + \" the Date 1 and Date 2\"; } else { el_down.innerHTML = \"Date is not in\" + \" between the Date 1 and Date 2\"; } } </script></body> </html>",
"e": 3826,
"s": 2558,
"text": null
},
{
"code": null,
"e": 3835,
"s": 3826,
"text": "Output: "
},
{
"code": null,
"e": 3852,
"s": 3835,
"text": "surinderdawra388"
},
{
"code": null,
"e": 3868,
"s": 3852,
"text": "javascript-date"
},
{
"code": null,
"e": 3884,
"s": 3868,
"text": "JavaScript-Misc"
},
{
"code": null,
"e": 3895,
"s": 3884,
"text": "JavaScript"
},
{
"code": null,
"e": 3912,
"s": 3895,
"text": "Web Technologies"
},
{
"code": null,
"e": 3939,
"s": 3912,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 4037,
"s": 3939,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4098,
"s": 4037,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 4170,
"s": 4098,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 4210,
"s": 4170,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 4263,
"s": 4210,
"text": "Hide or show elements in HTML using display property"
},
{
"code": null,
"e": 4304,
"s": 4263,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 4337,
"s": 4304,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 4399,
"s": 4337,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 4460,
"s": 4399,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 4510,
"s": 4460,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
Python β Resolve Float Keys in Dictionary | 01 Aug, 2020
Given a dictionary with variety of floating-point keys, find a way to access them as single value.
Input : test_dict = {β010.78β : βGfgβ, β9.0β : βisβ, β10β : βBestβ}, K = β09.0βOutput : βisβExplanation : 09.0 -> 9.0 whose value is βisβ.
Input : test_dict = {β010.78β : βGfgβ, β9.0β : βisβ, β10β : βBestβ}, K = β10.0βOutput : βBestβExplanation : 10.0 -> 10 whose value is βBestβ.
Method #1 : Using float() + loop
This is one of the ways to solve this problem. In this, strategy used is to convert key into float value using float(), it resolves to single value, and perform check of input string after conversion to float(), both resolve to common float value.
Python3
# Python3 code to demonstrate working of # Resolve Float Keys in Dictionary# Using float() + loop() # initializing dictionarytest_dict = {"010.78" : "Gfg", "9.0" : "is", "10" : "Best"} # printing original dictionaryprint("The original dictionary is : " + str(test_dict)) # initializing K K = "10.78" # performing resolutionres = dict()for key in test_dict: res[float(key)] = test_dict[key] # converting compare value to float convK = float(K) # performing value access res = res[convK] # printing result print("Value of resolved float Key : " + str(res))
The original dictionary is : {'010.78': 'Gfg', '9.0': 'is', '10': 'Best'}
Value of resolved float Key : Gfg
Method #2 : Using dictionary comprehension + float()
This computes in similar way as above method. The difference being for conversion one liner dictionary comprehension is employed.
Python3
# Python3 code to demonstrate working of # Resolve Float Keys in Dictionary# Using dictionary comprehension + float() # initializing dictionarytest_dict = {"010.78" : "Gfg", "9.0" : "is", "10" : "Best"} # printing original dictionaryprint("The original dictionary is : " + str(test_dict)) # initializing K K = "10.78" # performing resolution using dictionary comprehensionres = {float(key) : test_dict[key] for key in test_dict} # converting compare value to float convK = float(K) # performing value access res = res[convK] # printing result print("Value of resolved float Key : " + str(res))
The original dictionary is : {'010.78': 'Gfg', '9.0': 'is', '10': 'Best'}
Value of resolved float Key : Gfg
Python dictionary-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n01 Aug, 2020"
},
{
"code": null,
"e": 127,
"s": 28,
"text": "Given a dictionary with variety of floating-point keys, find a way to access them as single value."
},
{
"code": null,
"e": 266,
"s": 127,
"text": "Input : test_dict = {β010.78β : βGfgβ, β9.0β : βisβ, β10β : βBestβ}, K = β09.0βOutput : βisβExplanation : 09.0 -> 9.0 whose value is βisβ."
},
{
"code": null,
"e": 408,
"s": 266,
"text": "Input : test_dict = {β010.78β : βGfgβ, β9.0β : βisβ, β10β : βBestβ}, K = β10.0βOutput : βBestβExplanation : 10.0 -> 10 whose value is βBestβ."
},
{
"code": null,
"e": 441,
"s": 408,
"text": "Method #1 : Using float() + loop"
},
{
"code": null,
"e": 689,
"s": 441,
"text": "This is one of the ways to solve this problem. In this, strategy used is to convert key into float value using float(), it resolves to single value, and perform check of input string after conversion to float(), both resolve to common float value."
},
{
"code": null,
"e": 697,
"s": 689,
"text": "Python3"
},
{
"code": "# Python3 code to demonstrate working of # Resolve Float Keys in Dictionary# Using float() + loop() # initializing dictionarytest_dict = {\"010.78\" : \"Gfg\", \"9.0\" : \"is\", \"10\" : \"Best\"} # printing original dictionaryprint(\"The original dictionary is : \" + str(test_dict)) # initializing K K = \"10.78\" # performing resolutionres = dict()for key in test_dict: res[float(key)] = test_dict[key] # converting compare value to float convK = float(K) # performing value access res = res[convK] # printing result print(\"Value of resolved float Key : \" + str(res)) ",
"e": 1263,
"s": 697,
"text": null
},
{
"code": null,
"e": 1372,
"s": 1263,
"text": "The original dictionary is : {'010.78': 'Gfg', '9.0': 'is', '10': 'Best'}\nValue of resolved float Key : Gfg\n"
},
{
"code": null,
"e": 1425,
"s": 1372,
"text": "Method #2 : Using dictionary comprehension + float()"
},
{
"code": null,
"e": 1555,
"s": 1425,
"text": "This computes in similar way as above method. The difference being for conversion one liner dictionary comprehension is employed."
},
{
"code": null,
"e": 1563,
"s": 1555,
"text": "Python3"
},
{
"code": "# Python3 code to demonstrate working of # Resolve Float Keys in Dictionary# Using dictionary comprehension + float() # initializing dictionarytest_dict = {\"010.78\" : \"Gfg\", \"9.0\" : \"is\", \"10\" : \"Best\"} # printing original dictionaryprint(\"The original dictionary is : \" + str(test_dict)) # initializing K K = \"10.78\" # performing resolution using dictionary comprehensionres = {float(key) : test_dict[key] for key in test_dict} # converting compare value to float convK = float(K) # performing value access res = res[convK] # printing result print(\"Value of resolved float Key : \" + str(res)) ",
"e": 2165,
"s": 1563,
"text": null
},
{
"code": null,
"e": 2274,
"s": 2165,
"text": "The original dictionary is : {'010.78': 'Gfg', '9.0': 'is', '10': 'Best'}\nValue of resolved float Key : Gfg\n"
},
{
"code": null,
"e": 2301,
"s": 2274,
"text": "Python dictionary-programs"
},
{
"code": null,
"e": 2308,
"s": 2301,
"text": "Python"
},
{
"code": null,
"e": 2324,
"s": 2308,
"text": "Python Programs"
}
] |
Python | Get duplicate tuples from list | 21 Nov, 2019
Sometimes, while working with records, we can have a problem of extracting those records which occur more than once. This kind of application can occur in web development domain. Letβs discuss certain ways in which this task can be performed.
Method #1 : Using list comprehension + set() + count()Initial approach that can be applied is that we can iterate on each tuple and check itβs count in list using count(), if greater than one, we can add to list. To remove multiple additions, we can convert the result to set using set().
# Python3 code to demonstrate working of# Get duplicate tuples from list# Using list comprehension + set() + count() # initialize listtest_list = [(3, 4), (4, 5), (3, 4), (3, 4), (4, 5), (6, 7)] # printing original list print("The original list : " + str(test_list)) # Get duplicate tuples from list# Using list comprehension + set() + count()res = list(set([ele for ele in test_list if test_list.count(ele) > 1])) # printing resultprint("All the duplicates from list are : " + str(res))
The original list : [(3, 4), (4, 5), (3, 4), (3, 4), (4, 5), (6, 7)]
All the duplicates from list are : [(4, 5), (3, 4)]
Method #2 : Using Counter() + items() + list comprehensionThe combination of above functions can also be used to perform this particular task. In this, we just get the count of each occurrence of element using Counter() as dictionary and then extract all those whose value is above 1.
# Python3 code to demonstrate working of# Get duplicate tuples from list# Using list comprehension + Counter() + items()from collections import Counter # initialize listtest_list = [(3, 4), (4, 5), (3, 4), (3, 4), (4, 5), (6, 7)] # printing original list print("The original list : " + str(test_list)) # Get duplicate tuples from list# Using list comprehension + Counter() + items()res = [ele for ele, count in Counter(test_list).items() if count > 1] # printing resultprint("All the duplicates from list are : " + str(res))
The original list : [(3, 4), (4, 5), (3, 4), (3, 4), (4, 5), (6, 7)]
All the duplicates from list are : [(4, 5), (3, 4)]
Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to iterate through Excel rows in Python?
Rotate axis tick labels in Seaborn and Matplotlib
Deque in Python
Queue in Python
Defaultdict in Python
Defaultdict in Python
Python program to add two numbers
Python | Get dictionary keys as a list
Python Program for Fibonacci numbers
Python Program for factorial of a number | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n21 Nov, 2019"
},
{
"code": null,
"e": 271,
"s": 28,
"text": "Sometimes, while working with records, we can have a problem of extracting those records which occur more than once. This kind of application can occur in web development domain. Letβs discuss certain ways in which this task can be performed."
},
{
"code": null,
"e": 560,
"s": 271,
"text": "Method #1 : Using list comprehension + set() + count()Initial approach that can be applied is that we can iterate on each tuple and check itβs count in list using count(), if greater than one, we can add to list. To remove multiple additions, we can convert the result to set using set()."
},
{
"code": "# Python3 code to demonstrate working of# Get duplicate tuples from list# Using list comprehension + set() + count() # initialize listtest_list = [(3, 4), (4, 5), (3, 4), (3, 4), (4, 5), (6, 7)] # printing original list print(\"The original list : \" + str(test_list)) # Get duplicate tuples from list# Using list comprehension + set() + count()res = list(set([ele for ele in test_list if test_list.count(ele) > 1])) # printing resultprint(\"All the duplicates from list are : \" + str(res))",
"e": 1076,
"s": 560,
"text": null
},
{
"code": null,
"e": 1198,
"s": 1076,
"text": "The original list : [(3, 4), (4, 5), (3, 4), (3, 4), (4, 5), (6, 7)]\nAll the duplicates from list are : [(4, 5), (3, 4)]\n"
},
{
"code": null,
"e": 1485,
"s": 1200,
"text": "Method #2 : Using Counter() + items() + list comprehensionThe combination of above functions can also be used to perform this particular task. In this, we just get the count of each occurrence of element using Counter() as dictionary and then extract all those whose value is above 1."
},
{
"code": "# Python3 code to demonstrate working of# Get duplicate tuples from list# Using list comprehension + Counter() + items()from collections import Counter # initialize listtest_list = [(3, 4), (4, 5), (3, 4), (3, 4), (4, 5), (6, 7)] # printing original list print(\"The original list : \" + str(test_list)) # Get duplicate tuples from list# Using list comprehension + Counter() + items()res = [ele for ele, count in Counter(test_list).items() if count > 1] # printing resultprint(\"All the duplicates from list are : \" + str(res))",
"e": 2068,
"s": 1485,
"text": null
},
{
"code": null,
"e": 2190,
"s": 2068,
"text": "The original list : [(3, 4), (4, 5), (3, 4), (3, 4), (4, 5), (6, 7)]\nAll the duplicates from list are : [(4, 5), (3, 4)]\n"
},
{
"code": null,
"e": 2211,
"s": 2190,
"text": "Python list-programs"
},
{
"code": null,
"e": 2218,
"s": 2211,
"text": "Python"
},
{
"code": null,
"e": 2234,
"s": 2218,
"text": "Python Programs"
},
{
"code": null,
"e": 2332,
"s": 2234,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2377,
"s": 2332,
"text": "How to iterate through Excel rows in Python?"
},
{
"code": null,
"e": 2427,
"s": 2377,
"text": "Rotate axis tick labels in Seaborn and Matplotlib"
},
{
"code": null,
"e": 2443,
"s": 2427,
"text": "Deque in Python"
},
{
"code": null,
"e": 2459,
"s": 2443,
"text": "Queue in Python"
},
{
"code": null,
"e": 2481,
"s": 2459,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 2503,
"s": 2481,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 2537,
"s": 2503,
"text": "Python program to add two numbers"
},
{
"code": null,
"e": 2576,
"s": 2537,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 2613,
"s": 2576,
"text": "Python Program for Fibonacci numbers"
}
] |
Program to find the sum of the series 1 + x + x^2+ x^3+ .. + x^n | 08 Nov, 2021
Given an integer X, the task is to print the series and find the sum of the series Examples :
Input: X = 2, N = 5 Output: Sum = 31 1 2 4 8 16Input: X = 1, N = 10 Output: Sum = 10 1 1 1 1 1 1 1 1 1 1
Approach: The idea is to traverse over the series and compute the sum of the N terms of the series. The Nth term of the series can be computed as:
Nth Term = (N-1)th Term * X
Below is the implementation of the above approach:
C++
C
Java
Python3
C#
Javascript
// C++ implementation to find// sum of series of// 1 + x^2 + x^3 + ....+ x^n #include <bits/stdc++.h> using namespace std; // Function to find the sum of// the series and print N terms// of the given seriesdouble sum(int x, int n){ double i, total = 1.0, multi = x; // First Term cout << total << " "; // Loop to print the N terms // of the series and find their sum for (i = 1; i < n; i++) { total = total + multi; cout << multi << " "; multi = multi * x; } cout << "\n"; return total;} // Driver codeint main(){ int x = 2; int n = 5; cout << fixed << setprecision(2) << sum(x, n); return 0;}
// C implementation to find the sum// of series 1 + x^2 + x^3 + ....+ x^n #include <math.h>#include <stdio.h> // Function to print the sum// of the seriesdouble sum(int x, int n){ double i, total = 1.0, multi = x; // First Term of series printf("1 "); // Loop to find the N // terms of the series for (i = 1; i < n; i++) { total = total + multi; printf("%.1f ", multi); multi = multi * x; } printf("\n"); return total;} // Driver Codeint main(){ int x = 2; int n = 5; printf("%.2f", sum(x, n)); return 0;}
// Java implementation to find// the sum of series// 1 + x^2 + x^3 + ....+ x^n class GFG { // Java code to print the sum // of the given series static double sum(int x, int n) { double i, total = 1.0, multi = x; // First Term System.out.print("1 "); // Loop to print the N terms // of the series and compute // their sum for (i = 1; i < n; i++) { total = total + multi; System.out.print(multi); System.out.print(" "); multi = multi * x; } System.out.println(); return total; } // Driver Code public static void main(String[] args) { int x = 2; int n = 5; System.out.printf( "%.2f", sum(x, n)); }}
# Python3 program to find sum of# series of 1 + x^2 + x^3 + ....+ x^n # Function to find the sum of# the series and print N terms# of the given seriesdef sum(x, n): total = 1.0 multi = x # First Term print(1, end = " ") # Loop to print the N terms # of the series and find their sum for i in range(1, n): total = total + multi print('%.1f' % multi, end = " ") multi = multi * x print('\n') return total; # Driver codex = 2n = 5print('%.2f' % sum(x, n)) # This code is contributed by Pratik Basu
// C# implementation to find// the sum of series// 1 + x^2 + x^3 + ....+ x^nusing System;class GFG{ // C# code to print the sum// of the given seriesstatic double sum(int x, int n){ double i, total = 1.0, multi = x; // First Term Console.Write("1 "); // Loop to print the N terms // of the series and compute // their sum for (i = 1; i < n; i++) { total = total + multi; Console.Write(multi); Console.Write(" "); multi = multi * x; } Console.WriteLine(); return total;} // Driver Codepublic static void Main(String[] args){ int x = 2; int n = 5; Console.Write("{0:F2}", sum(x, n));}} // This code is contributed by Rajput-Ji
<script>// JavaScript implementation to find// sum of series of// 1 + x^2 + x^3 + ....+ x^n // Function to find the sum of// the series and print N terms// of the given seriesfunction sum(x, n){ let i, total = 1.0, multi = x; // First Term document.write(total + " "); // Loop to print the N terms // of the series and find their sum for (i = 1; i < n; i++) { total = total + multi; document.write(multi + " "); multi = multi * x; } document.write("<br>"); return total;} // Driver code let x = 2; let n = 5; document.write(sum(x, n).toFixed(2)); // This code is contributed by Surbhi Tyagi.</script>
1 2.0 4.0 8.0 16.0
31.00
Time Complexity: O(n)
Auxiliary Space: O(1)
PratikBasu
Rajput-Ji
surbhityagi15
ruhelaa48
sushmitamittal1329
series
series-sum
Mathematical
School Programming
Write From Home
Mathematical
series
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Operators in C / C++
Find minimum number of coins that make a given value
Minimum number of jumps to reach end
Algorithm to solve Rubik's Cube
Modulo 10^9+7 (1000000007)
Python Dictionary
Reverse a string in Java
Arrays in C/C++
Introduction To PYTHON
Interfaces in Java | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n08 Nov, 2021"
},
{
"code": null,
"e": 124,
"s": 28,
"text": "Given an integer X, the task is to print the series and find the sum of the series Examples : "
},
{
"code": null,
"e": 231,
"s": 124,
"text": "Input: X = 2, N = 5 Output: Sum = 31 1 2 4 8 16Input: X = 1, N = 10 Output: Sum = 10 1 1 1 1 1 1 1 1 1 1 "
},
{
"code": null,
"e": 382,
"s": 233,
"text": "Approach: The idea is to traverse over the series and compute the sum of the N terms of the series. The Nth term of the series can be computed as: "
},
{
"code": null,
"e": 412,
"s": 382,
"text": "Nth Term = (N-1)th Term * X "
},
{
"code": null,
"e": 464,
"s": 412,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 468,
"s": 464,
"text": "C++"
},
{
"code": null,
"e": 470,
"s": 468,
"text": "C"
},
{
"code": null,
"e": 475,
"s": 470,
"text": "Java"
},
{
"code": null,
"e": 483,
"s": 475,
"text": "Python3"
},
{
"code": null,
"e": 486,
"s": 483,
"text": "C#"
},
{
"code": null,
"e": 497,
"s": 486,
"text": "Javascript"
},
{
"code": "// C++ implementation to find// sum of series of// 1 + x^2 + x^3 + ....+ x^n #include <bits/stdc++.h> using namespace std; // Function to find the sum of// the series and print N terms// of the given seriesdouble sum(int x, int n){ double i, total = 1.0, multi = x; // First Term cout << total << \" \"; // Loop to print the N terms // of the series and find their sum for (i = 1; i < n; i++) { total = total + multi; cout << multi << \" \"; multi = multi * x; } cout << \"\\n\"; return total;} // Driver codeint main(){ int x = 2; int n = 5; cout << fixed << setprecision(2) << sum(x, n); return 0;}",
"e": 1171,
"s": 497,
"text": null
},
{
"code": "// C implementation to find the sum// of series 1 + x^2 + x^3 + ....+ x^n #include <math.h>#include <stdio.h> // Function to print the sum// of the seriesdouble sum(int x, int n){ double i, total = 1.0, multi = x; // First Term of series printf(\"1 \"); // Loop to find the N // terms of the series for (i = 1; i < n; i++) { total = total + multi; printf(\"%.1f \", multi); multi = multi * x; } printf(\"\\n\"); return total;} // Driver Codeint main(){ int x = 2; int n = 5; printf(\"%.2f\", sum(x, n)); return 0;}",
"e": 1740,
"s": 1171,
"text": null
},
{
"code": "// Java implementation to find// the sum of series// 1 + x^2 + x^3 + ....+ x^n class GFG { // Java code to print the sum // of the given series static double sum(int x, int n) { double i, total = 1.0, multi = x; // First Term System.out.print(\"1 \"); // Loop to print the N terms // of the series and compute // their sum for (i = 1; i < n; i++) { total = total + multi; System.out.print(multi); System.out.print(\" \"); multi = multi * x; } System.out.println(); return total; } // Driver Code public static void main(String[] args) { int x = 2; int n = 5; System.out.printf( \"%.2f\", sum(x, n)); }}",
"e": 2515,
"s": 1740,
"text": null
},
{
"code": "# Python3 program to find sum of# series of 1 + x^2 + x^3 + ....+ x^n # Function to find the sum of# the series and print N terms# of the given seriesdef sum(x, n): total = 1.0 multi = x # First Term print(1, end = \" \") # Loop to print the N terms # of the series and find their sum for i in range(1, n): total = total + multi print('%.1f' % multi, end = \" \") multi = multi * x print('\\n') return total; # Driver codex = 2n = 5print('%.2f' % sum(x, n)) # This code is contributed by Pratik Basu",
"e": 3083,
"s": 2515,
"text": null
},
{
"code": "// C# implementation to find// the sum of series// 1 + x^2 + x^3 + ....+ x^nusing System;class GFG{ // C# code to print the sum// of the given seriesstatic double sum(int x, int n){ double i, total = 1.0, multi = x; // First Term Console.Write(\"1 \"); // Loop to print the N terms // of the series and compute // their sum for (i = 1; i < n; i++) { total = total + multi; Console.Write(multi); Console.Write(\" \"); multi = multi * x; } Console.WriteLine(); return total;} // Driver Codepublic static void Main(String[] args){ int x = 2; int n = 5; Console.Write(\"{0:F2}\", sum(x, n));}} // This code is contributed by Rajput-Ji",
"e": 3780,
"s": 3083,
"text": null
},
{
"code": "<script>// JavaScript implementation to find// sum of series of// 1 + x^2 + x^3 + ....+ x^n // Function to find the sum of// the series and print N terms// of the given seriesfunction sum(x, n){ let i, total = 1.0, multi = x; // First Term document.write(total + \" \"); // Loop to print the N terms // of the series and find their sum for (i = 1; i < n; i++) { total = total + multi; document.write(multi + \" \"); multi = multi * x; } document.write(\"<br>\"); return total;} // Driver code let x = 2; let n = 5; document.write(sum(x, n).toFixed(2)); // This code is contributed by Surbhi Tyagi.</script>",
"e": 4442,
"s": 3780,
"text": null
},
{
"code": null,
"e": 4468,
"s": 4442,
"text": "1 2.0 4.0 8.0 16.0 \n31.00"
},
{
"code": null,
"e": 4492,
"s": 4470,
"text": "Time Complexity: O(n)"
},
{
"code": null,
"e": 4514,
"s": 4492,
"text": "Auxiliary Space: O(1)"
},
{
"code": null,
"e": 4525,
"s": 4514,
"text": "PratikBasu"
},
{
"code": null,
"e": 4535,
"s": 4525,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 4549,
"s": 4535,
"text": "surbhityagi15"
},
{
"code": null,
"e": 4559,
"s": 4549,
"text": "ruhelaa48"
},
{
"code": null,
"e": 4578,
"s": 4559,
"text": "sushmitamittal1329"
},
{
"code": null,
"e": 4585,
"s": 4578,
"text": "series"
},
{
"code": null,
"e": 4596,
"s": 4585,
"text": "series-sum"
},
{
"code": null,
"e": 4609,
"s": 4596,
"text": "Mathematical"
},
{
"code": null,
"e": 4628,
"s": 4609,
"text": "School Programming"
},
{
"code": null,
"e": 4644,
"s": 4628,
"text": "Write From Home"
},
{
"code": null,
"e": 4657,
"s": 4644,
"text": "Mathematical"
},
{
"code": null,
"e": 4664,
"s": 4657,
"text": "series"
},
{
"code": null,
"e": 4762,
"s": 4664,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4783,
"s": 4762,
"text": "Operators in C / C++"
},
{
"code": null,
"e": 4836,
"s": 4783,
"text": "Find minimum number of coins that make a given value"
},
{
"code": null,
"e": 4873,
"s": 4836,
"text": "Minimum number of jumps to reach end"
},
{
"code": null,
"e": 4905,
"s": 4873,
"text": "Algorithm to solve Rubik's Cube"
},
{
"code": null,
"e": 4932,
"s": 4905,
"text": "Modulo 10^9+7 (1000000007)"
},
{
"code": null,
"e": 4950,
"s": 4932,
"text": "Python Dictionary"
},
{
"code": null,
"e": 4975,
"s": 4950,
"text": "Reverse a string in Java"
},
{
"code": null,
"e": 4991,
"s": 4975,
"text": "Arrays in C/C++"
},
{
"code": null,
"e": 5014,
"s": 4991,
"text": "Introduction To PYTHON"
}
] |
Test whether the elements of a given NumPy array is zero or not in Python | 02 Sep, 2020
In numpy, we can check that whether none of the elements of given array is zero or not with the help of numpy.all() function. In this function pass an array as parameter. If any of one element of the passed array is zero then it returns False otherwise it returns True boolean value.
Syntax: numpy.all()
Parameters: An array
Return: A boolean value (True or False)
Letβs see the examples:
Example 1:
Python
# import numpy libraryimport numpy as np # create an arrayx = np.array([34, 56, 89, 23, 69, 980, 567]) # print arrayprint(x) # Test if none of the elements # of the said array is zeroprint(np.all(x))
Output:
[34,56,89,23,69,980,567]
True
Example 2:
Python
# import numpy libraryimport numpy as np # create an arrayx = np.array([1, 2, 3, 4, 6, 7, 8, 9, 10, 0, 89, 67]) # print arrayprint(x) # Test if none of the elements# of the said array is zeroprint(np.all(x))
Output:
False
Python numpy-ndarray
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
Python | os.path.join() method
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | datetime.timedelta() function
Python | Get unique values from a list | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n02 Sep, 2020"
},
{
"code": null,
"e": 312,
"s": 28,
"text": "In numpy, we can check that whether none of the elements of given array is zero or not with the help of numpy.all() function. In this function pass an array as parameter. If any of one element of the passed array is zero then it returns False otherwise it returns True boolean value."
},
{
"code": null,
"e": 332,
"s": 312,
"text": "Syntax: numpy.all()"
},
{
"code": null,
"e": 353,
"s": 332,
"text": "Parameters: An array"
},
{
"code": null,
"e": 393,
"s": 353,
"text": "Return: A boolean value (True or False)"
},
{
"code": null,
"e": 417,
"s": 393,
"text": "Letβs see the examples:"
},
{
"code": null,
"e": 428,
"s": 417,
"text": "Example 1:"
},
{
"code": null,
"e": 435,
"s": 428,
"text": "Python"
},
{
"code": "# import numpy libraryimport numpy as np # create an arrayx = np.array([34, 56, 89, 23, 69, 980, 567]) # print arrayprint(x) # Test if none of the elements # of the said array is zeroprint(np.all(x))",
"e": 664,
"s": 435,
"text": null
},
{
"code": null,
"e": 672,
"s": 664,
"text": "Output:"
},
{
"code": null,
"e": 703,
"s": 672,
"text": "[34,56,89,23,69,980,567]\nTrue\n"
},
{
"code": null,
"e": 714,
"s": 703,
"text": "Example 2:"
},
{
"code": null,
"e": 721,
"s": 714,
"text": "Python"
},
{
"code": "# import numpy libraryimport numpy as np # create an arrayx = np.array([1, 2, 3, 4, 6, 7, 8, 9, 10, 0, 89, 67]) # print arrayprint(x) # Test if none of the elements# of the said array is zeroprint(np.all(x))",
"e": 971,
"s": 721,
"text": null
},
{
"code": null,
"e": 979,
"s": 971,
"text": "Output:"
},
{
"code": null,
"e": 986,
"s": 979,
"text": "False\n"
},
{
"code": null,
"e": 1007,
"s": 986,
"text": "Python numpy-ndarray"
},
{
"code": null,
"e": 1020,
"s": 1007,
"text": "Python-numpy"
},
{
"code": null,
"e": 1027,
"s": 1020,
"text": "Python"
},
{
"code": null,
"e": 1125,
"s": 1027,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1157,
"s": 1125,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 1184,
"s": 1157,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 1205,
"s": 1184,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 1228,
"s": 1205,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 1284,
"s": 1228,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 1315,
"s": 1284,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 1357,
"s": 1315,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 1399,
"s": 1357,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 1438,
"s": 1399,
"text": "Python | datetime.timedelta() function"
}
] |
Python β Store Function as dictionary value | 14 Oct, 2020
Given a dictionary, assign its keys as function calls.
Case 1 : Without Params.
The way that is employed to achieve this task is that, function name is kept as dictionary values, and while calling with keys, brackets β()β are added.
Python3
# Python3 code to demonstrate working of # Functions as dictionary values# Using Without params # call Gfg fnc def print_key1(): return "This is Gfg's value" # initializing dictionary# check for function name as keytest_dict = {"Gfg": print_key1, "is" : 5, "best" : 9} # printing original dictionaryprint("The original dictionary is : " + str(test_dict)) # calling function using brackets res = test_dict['Gfg']() # printing result print("The required call result : " + str(res))
The original dictionary is : {'Gfg': <function print_key1 at 0x7f1c0445be18>, 'is': 5, 'best': 9}
The required call result : This is Gfg's value
Case 2 : With params
The task of calling with params is similar to above case, the values are passed during function call inside brackets as in usual function calls.
Python3
# Python3 code to demonstrate working of # Functions as dictionary values# Using With params # call Gfg fnc def sum_key(a, b): return a + b # initializing dictionary# check for function name as keytest_dict = {"Gfg": sum_key, "is" : 5, "best" : 9} # printing original dictionaryprint("The original dictionary is : " + str(test_dict)) # calling function using brackets # params inside bracketsres = test_dict['Gfg'](10, 34) # printing result print("The required call result : " + str(res))
The original dictionary is : {'Gfg': <function sum_key at 0x7f538d017e18>, 'is': 5, 'best': 9}
The required call result : 44
Python dictionary-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Python String | replace()
How to Install PIP on Windows ?
Python program to convert a list to string
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python | Convert string dictionary to dictionary | [
{
"code": null,
"e": 53,
"s": 25,
"text": "\n14 Oct, 2020"
},
{
"code": null,
"e": 108,
"s": 53,
"text": "Given a dictionary, assign its keys as function calls."
},
{
"code": null,
"e": 134,
"s": 108,
"text": "Case 1 : Without Params. "
},
{
"code": null,
"e": 287,
"s": 134,
"text": "The way that is employed to achieve this task is that, function name is kept as dictionary values, and while calling with keys, brackets β()β are added."
},
{
"code": null,
"e": 295,
"s": 287,
"text": "Python3"
},
{
"code": "# Python3 code to demonstrate working of # Functions as dictionary values# Using Without params # call Gfg fnc def print_key1(): return \"This is Gfg's value\" # initializing dictionary# check for function name as keytest_dict = {\"Gfg\": print_key1, \"is\" : 5, \"best\" : 9} # printing original dictionaryprint(\"The original dictionary is : \" + str(test_dict)) # calling function using brackets res = test_dict['Gfg']() # printing result print(\"The required call result : \" + str(res)) ",
"e": 784,
"s": 295,
"text": null
},
{
"code": null,
"e": 930,
"s": 784,
"text": "The original dictionary is : {'Gfg': <function print_key1 at 0x7f1c0445be18>, 'is': 5, 'best': 9}\nThe required call result : This is Gfg's value\n"
},
{
"code": null,
"e": 952,
"s": 930,
"text": "Case 2 : With params "
},
{
"code": null,
"e": 1097,
"s": 952,
"text": "The task of calling with params is similar to above case, the values are passed during function call inside brackets as in usual function calls."
},
{
"code": null,
"e": 1105,
"s": 1097,
"text": "Python3"
},
{
"code": "# Python3 code to demonstrate working of # Functions as dictionary values# Using With params # call Gfg fnc def sum_key(a, b): return a + b # initializing dictionary# check for function name as keytest_dict = {\"Gfg\": sum_key, \"is\" : 5, \"best\" : 9} # printing original dictionaryprint(\"The original dictionary is : \" + str(test_dict)) # calling function using brackets # params inside bracketsres = test_dict['Gfg'](10, 34) # printing result print(\"The required call result : \" + str(res)) ",
"e": 1604,
"s": 1105,
"text": null
},
{
"code": null,
"e": 1730,
"s": 1604,
"text": "The original dictionary is : {'Gfg': <function sum_key at 0x7f538d017e18>, 'is': 5, 'best': 9}\nThe required call result : 44\n"
},
{
"code": null,
"e": 1757,
"s": 1730,
"text": "Python dictionary-programs"
},
{
"code": null,
"e": 1764,
"s": 1757,
"text": "Python"
},
{
"code": null,
"e": 1780,
"s": 1764,
"text": "Python Programs"
},
{
"code": null,
"e": 1878,
"s": 1780,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1896,
"s": 1878,
"text": "Python Dictionary"
},
{
"code": null,
"e": 1938,
"s": 1896,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 1960,
"s": 1938,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 1986,
"s": 1960,
"text": "Python String | replace()"
},
{
"code": null,
"e": 2018,
"s": 1986,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 2061,
"s": 2018,
"text": "Python program to convert a list to string"
},
{
"code": null,
"e": 2083,
"s": 2061,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 2122,
"s": 2083,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 2160,
"s": 2122,
"text": "Python | Convert a list to dictionary"
}
] |
Python | Three element sum in list | 23 Nov, 2021
The problem of getting the number of pairs that lead to a particular solution has been dealt with many times, this article aims at extending that to 3 numbers and discussing several ways in which this particular problem can be solved. Letβs discuss certain ways in which this can be performed.Method #1: Using Nested loopsThis is the naive method in which this particular problem can be solved and takes the outer loop to iterate for each element and the inner loop checks for the remaining difference adding the pairs to the result.
Python3
# Python3 code to demonstrate# 3 element sum# using nested loops # initializing listtest_list = [4, 1, 3, 2, 6, 5] # initializing sumsum = 9 # printing original listprint("The original list : " + str(test_list)) # using nested loops# 3 element sumres = []for i in range(0, len(test_list)-2): for j in range(i + 1, len(test_list)-1): for k in range(j + 1, len(test_list)): if test_list[i] + test_list[j] + test_list[k] == sum: temp = [] temp.append(test_list[i]) temp.append(test_list[j]) temp.append(test_list[k]) res.append(tuple(temp)) # print resultprint("The 3 sum element list is : " + str(res))
The original list : [4, 1, 3, 2, 6, 5]
The 3 sum element list is : [(4, 3, 2), (1, 3, 5), (1, 2, 6)]
Method #2 : Using itertools.combination() This particular problem can also be done in a concise manner using the inbuilt function of a function. The combination function finds all the combinations taking K arguments leading to a particular sum.
Python3
# Python3 code to demonstrate# 3 element sum# using itertools.combination()from itertools import combinations # function to get the sumdef test(val): return sum(val) == 9 # initializing listtest_list = [4, 1, 3, 2, 6, 5] # initializing sumsummation = 9 # printing original listprint("The original list : " + str(test_list)) # using itertools.combination()# 3 element sumres = list(filter(test, list(combinations(test_list, 3)))) # print resultprint("The 3 sum element list is : " + str(res))
The original list : [4, 1, 3, 2, 6, 5]
The 3 sum element list is : [(4, 3, 2), (1, 3, 5), (1, 2, 6)]
Method #3: Using itertools.combination() and additional check to improve runtime for 1000 items. also, it only checks if a match exists or not, if a match is found then output the combination.
Python3
import itertools def solve(nums, k): # rule out cases where no of elements are less then 3 if len(nums)<=2: return False else: # get all unique combinations permut = itertools.combinations(nums, 3) #rule out the loop if even the max * 3 < target max_value = max(nums) if max_value*3 < k: return False else: #check until a match is found for i in permut: if i[0]+i[1]+i[2]==k: return True return False nums = [4,1,3,1]k=5print("Test case :-\nk=",k," \nnums = ",nums)print("-----------------------------------------")Solution.solve(nums, k)print("-----------------------------------------") nums = [2, 4, 3, 0, 1]k = 0print("Test case :-\nk=",k," \nnums = ",nums)print("-----------------------------------------")Solution.solve(nums, k)print("-----------------------------------------") nums = [0]k = 0print("Test case :-\nk=",k," \nnums = ",nums)print("-----------------------------------------")Solution.solve(nums, k)print("-----------------------------------------") nums = [1, 0]k = 1print("Test case :-\nk=",k," \nnums = ",nums)print("-----------------------------------------")Solution.solve(nums, k)print("-----------------------------------------") nums = [2, 0, 1]k = 3print("Test case :-\nk=",k," \nnums = ",nums)print("-----------------------------------------")Solution.solve(nums, k)print("-----------------------------------------") nums = [13, 76, 35, 89, 15, 76, 54, 4, 66, 4, 9, 25, 9, 48, 26, 76, 95, 80, 19, 66, 74, 15, 18, 96, 36, 78, 80, 42, 42, 76, 85, 74, 96, 9, 95, 29, 58, 43, 57, 14, 38, 21, 55, 56, 18, 25, 3, 11, 76, 77, 72, 36, 44, 88, 93, 2, 95, 86, 77, 47, 3, 51, 34, 46, 70, 90, 4, 24, 58, 6, 91, 93, 59, 69, 89, 5, 58, 87, 23, 15, 98, 24, 62, 64, 15, 43, 93, 68, 17, 4, 78, 6, 2, 10, 52, 17, 28, 82, 20, 44, 78, 91, 1, 79, 17, 23, 27, 66, 88, 57, 60, 78, 68, 6, 35, 43, 73, 37, 12, 22, 47, 59, 40, 36, 0, 70, 91, 68, 33, 54, 44, 78, 23, 69, 60, 44, 32, 15, 20, 28, 36, 55, 73, 12, 55, 26, 43, 57, 63, 46, 0, 43, 24, 91, 86, 61, 15, 10, 29, 8, 51, 84, 94, 18, 5, 63, 90, 4, 38, 28, 84, 67, 18, 33, 85, 93, 31, 38, 97, 14, 79, 11, 92, 3, 8, 27, 65, 39, 1, 83, 38, 8, 83, 53, 53, 44, 57, 64, 78, 1, 44, 72, 100, 86, 85, 16, 5, 27, 24, 2, 56, 74, 16, 90, 65, 8, 93, 64, 72, 45, 47, 7, 83, 100, 99, 62, 89, 38, 38, 42, 98, 18, 29, 88, 48, 35, 0, 82, 56, 22, 64, 13, 54, 66, 32, 9, 2, 52, 80, 28, 19, 9, 38, 98, 38, 21, 41, 65, 78, 63, 97, 71, 99, 41, 89, 78, 48, 47, 72, 67, 79, 45, 43, 92, 30, 28, 42, 52, 56, 24, 46, 55, 82, 22, 86, 67, 43, 84, 41, 26, 66, 26, 32, 8, 93, 65, 10, 47, 19, 70, 84, 43, 99, 74, 78, 51, 59, 58, 38, 75, 86, 24, 48, 27, 72, 32, 15, 28, 98, 11, 70, 74, 91, 89, 90, 74, 69, 60, 78, 6, 67, 34, 100, 70, 98, 70, 60, 12, 58, 26, 21, 44, 64, 15, 82, 81, 52, 9, 82, 94, 99, 43, 22, 14, 16, 27, 68, 72, 69, 45, 60, 10, 91, 31, 58, 91, 71, 42, 19, 43, 42, 80, 61, 50, 2, 81, 45, 40, 44, 100, 68, 74, 19, 0, 33, 24, 58, 59, 1, 26, 65, 69, 19, 60, 12, 50, 82, 44, 18, 96, 77, 43, 33, 31, 53, 9, 36, 86, 24, 46, 11, 26, 3, 43, 8, 42, 17, 55, 60, 56, 33, 66, 90, 64, 42, 73, 61, 34, 13, 43, 9, 59, 46, 0, 68, 93, 60, 78, 92, 76, 45, 20, 31, 47, 21, 44, 2, 23, 78, 72, 62, 65, 56, 26, 80, 65, 87, 61, 88, 22, 38, 70, 98, 48, 25, 95, 55, 3, 32, 28, 50, 13, 57, 18, 95, 11, 23, 57, 21, 93, 35, 38, 75, 79, 39, 87, 30, 95, 73, 37, 47, 43, 15, 73, 59, 0, 29, 29, 30, 50, 13, 73, 1, 32, 7, 46, 7, 24, 43, 21, 84, 1, 6, 96, 33, 69, 2, 70, 98, 2, 90, 31, 66, 74, 58, 66, 56, 33, 5, 78, 19, 21, 98, 76, 1, 55, 97, 39, 43, 43, 44, 7, 61, 84, 31, 0, 67, 46, 39, 23, 7, 31, 29, 2, 71, 7, 35, 60, 20, 94, 23, 81, 40, 79, 11, 46, 71, 25, 42, 54, 10, 21, 11, 72, 86, 48, 53, 67, 36, 55, 49, 98, 65, 37, 27, 63, 20, 86, 60, 29, 63, 75, 91, 30, 55, 23, 82, 88, 53, 62, 44, 25, 27, 99, 39, 4, 40, 41, 35, 35, 61, 62, 10, 98, 9, 82, 21, 39, 82, 89, 41, 71, 26, 51, 2, 73, 30, 49, 92, 16, 66, 60, 68, 2, 99, 91, 15, 77, 43, 44, 46, 69, 79, 100, 47, 9, 66, 33, 25, 15, 5, 77, 86, 81, 82, 69, 10, 0, 98, 4, 90, 30, 89, 87, 83, 97, 35, 96, 71, 15, 50, 12, 82, 79, 91, 79, 28, 62, 24, 75, 77, 68, 59, 87, 29, 81, 66, 92, 85, 4, 17, 48, 69, 28, 37, 55, 39, 11, 92, 57, 26, 64, 91, 44, 37, 3, 44, 57, 13, 75, 21, 39, 17, 29, 18, 74, 43, 93, 53, 6, 61, 71, 89, 99, 13, 92, 23, 99, 18, 13, 38, 14, 9, 82, 10, 7, 41, 24, 40, 61, 42, 26, 2, 43, 38, 3, 50, 43, 75, 47, 95, 16, 41, 40, 43, 14, 26, 40, 79, 11, 30, 16, 39, 46, 45, 25, 44, 79, 21, 48, 48, 23, 38, 79, 62, 71, 8, 53, 12, 72, 64, 71, 50, 90, 38, 77, 6, 48, 74, 77, 53, 85, 82, 19, 18, 43, 97, 67, 56, 25, 46, 87, 27, 99, 21, 13, 56, 71, 87, 73, 25, 0, 52, 82, 18, 65, 34, 96, 33, 99, 43, 45, 2, 59, 29, 53, 34, 78, 27, 41, 74, 74, 59, 96, 74, 45, 74, 44, 28, 62, 4, 90, 62, 31, 89, 72, 88, 69, 5, 29, 26, 81, 66, 96, 53, 87, 72, 89, 9, 30, 71, 75, 83, 46, 71, 57, 12, 77, 24, 44, 71, 34, 42, 11, 67, 9, 69, 47, 95, 93, 72, 12, 40, 98, 83, 25, 27, 91, 21, 31, 0, 44, 56, 1, 76, 30, 100, 18, 46, 35, 72, 61, 39, 90, 25, 78, 42, 77, 13, 72, 32, 3, 84, 63, 59, 100, 60, 22, 57, 50, 40, 63, 65, 2, 27, 88, 63, 40, 97, 94, 69, 72, 98, 2, 68, 13, 62, 76, 97, 14, 36, 15, 91, 80, 55, 45, 67, 50, 13, 49, 54, 72, 84, 36, 69, 74, 35, 30, 47, 64, 91, 24, 16, 41, 41, 19, 96, 25, 38, 60, 43, 86, 6, 23, 81, 71, 73, 56, 12, 44, 67, 28, 39, 1, 52, 40, 28, 45, 44, 53, 63, 7, 66, 45, 44, 68, 6, 98, 100, 95]k = 787 print("Test case :-\nk=",k," \nnums = ",nums[0:10],".....")print("-----------------------------------------")Solution.solve(nums, k)print("-----------------------------------------") nums = [0, 0, 0]k = 0print("Test case :-\nk=",k," \nnums = ",nums)print("-----------------------------------------")Solution.solve(nums, k)print("-----------------------------------------")
Output :
Test case :-
k= 5
nums = [4, 1, 3, 1]
-----------------------------------------
Found match : (1, 3, 1) 5
-----------------------------------------
Test case :-
k= 0
nums = [2, 4, 3, 0, 1]
-----------------------------------------
Match not found.
-----------------------------------------
Test case :-
k= 0
nums = [0]
-----------------------------------------
Match not found.
-----------------------------------------
Test case :-
k= 1
nums = [1, 0]
-----------------------------------------
Match not found.
-----------------------------------------
Test case :-
k= 3
nums = [2, 0, 1]
-----------------------------------------
Found match : (2, 0, 1) 3
-----------------------------------------
Test case :-
k= 787
nums = [13, 76, 35, 89, 15, 76, 54, 4, 66, 4] .....
-----------------------------------------
Match not found.
-----------------------------------------
Test case :-
k= 0
nums = [0, 0, 0]
-----------------------------------------
Found match : (0, 0, 0) 0
-----------------------------------------
contact2js
Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n23 Nov, 2021"
},
{
"code": null,
"e": 563,
"s": 28,
"text": "The problem of getting the number of pairs that lead to a particular solution has been dealt with many times, this article aims at extending that to 3 numbers and discussing several ways in which this particular problem can be solved. Letβs discuss certain ways in which this can be performed.Method #1: Using Nested loopsThis is the naive method in which this particular problem can be solved and takes the outer loop to iterate for each element and the inner loop checks for the remaining difference adding the pairs to the result. "
},
{
"code": null,
"e": 571,
"s": 563,
"text": "Python3"
},
{
"code": "# Python3 code to demonstrate# 3 element sum# using nested loops # initializing listtest_list = [4, 1, 3, 2, 6, 5] # initializing sumsum = 9 # printing original listprint(\"The original list : \" + str(test_list)) # using nested loops# 3 element sumres = []for i in range(0, len(test_list)-2): for j in range(i + 1, len(test_list)-1): for k in range(j + 1, len(test_list)): if test_list[i] + test_list[j] + test_list[k] == sum: temp = [] temp.append(test_list[i]) temp.append(test_list[j]) temp.append(test_list[k]) res.append(tuple(temp)) # print resultprint(\"The 3 sum element list is : \" + str(res))",
"e": 1268,
"s": 571,
"text": null
},
{
"code": null,
"e": 1369,
"s": 1268,
"text": "The original list : [4, 1, 3, 2, 6, 5]\nThe 3 sum element list is : [(4, 3, 2), (1, 3, 5), (1, 2, 6)]"
},
{
"code": null,
"e": 1619,
"s": 1371,
"text": " Method #2 : Using itertools.combination() This particular problem can also be done in a concise manner using the inbuilt function of a function. The combination function finds all the combinations taking K arguments leading to a particular sum. "
},
{
"code": null,
"e": 1627,
"s": 1619,
"text": "Python3"
},
{
"code": "# Python3 code to demonstrate# 3 element sum# using itertools.combination()from itertools import combinations # function to get the sumdef test(val): return sum(val) == 9 # initializing listtest_list = [4, 1, 3, 2, 6, 5] # initializing sumsummation = 9 # printing original listprint(\"The original list : \" + str(test_list)) # using itertools.combination()# 3 element sumres = list(filter(test, list(combinations(test_list, 3)))) # print resultprint(\"The 3 sum element list is : \" + str(res))",
"e": 2122,
"s": 1627,
"text": null
},
{
"code": null,
"e": 2223,
"s": 2122,
"text": "The original list : [4, 1, 3, 2, 6, 5]\nThe 3 sum element list is : [(4, 3, 2), (1, 3, 5), (1, 2, 6)]"
},
{
"code": null,
"e": 2418,
"s": 2225,
"text": "Method #3: Using itertools.combination() and additional check to improve runtime for 1000 items. also, it only checks if a match exists or not, if a match is found then output the combination."
},
{
"code": null,
"e": 2426,
"s": 2418,
"text": "Python3"
},
{
"code": "import itertools def solve(nums, k): # rule out cases where no of elements are less then 3 if len(nums)<=2: return False else: # get all unique combinations permut = itertools.combinations(nums, 3) #rule out the loop if even the max * 3 < target max_value = max(nums) if max_value*3 < k: return False else: #check until a match is found for i in permut: if i[0]+i[1]+i[2]==k: return True return False nums = [4,1,3,1]k=5print(\"Test case :-\\nk=\",k,\" \\nnums = \",nums)print(\"-----------------------------------------\")Solution.solve(nums, k)print(\"-----------------------------------------\") nums = [2, 4, 3, 0, 1]k = 0print(\"Test case :-\\nk=\",k,\" \\nnums = \",nums)print(\"-----------------------------------------\")Solution.solve(nums, k)print(\"-----------------------------------------\") nums = [0]k = 0print(\"Test case :-\\nk=\",k,\" \\nnums = \",nums)print(\"-----------------------------------------\")Solution.solve(nums, k)print(\"-----------------------------------------\") nums = [1, 0]k = 1print(\"Test case :-\\nk=\",k,\" \\nnums = \",nums)print(\"-----------------------------------------\")Solution.solve(nums, k)print(\"-----------------------------------------\") nums = [2, 0, 1]k = 3print(\"Test case :-\\nk=\",k,\" \\nnums = \",nums)print(\"-----------------------------------------\")Solution.solve(nums, k)print(\"-----------------------------------------\") nums = [13, 76, 35, 89, 15, 76, 54, 4, 66, 4, 9, 25, 9, 48, 26, 76, 95, 80, 19, 66, 74, 15, 18, 96, 36, 78, 80, 42, 42, 76, 85, 74, 96, 9, 95, 29, 58, 43, 57, 14, 38, 21, 55, 56, 18, 25, 3, 11, 76, 77, 72, 36, 44, 88, 93, 2, 95, 86, 77, 47, 3, 51, 34, 46, 70, 90, 4, 24, 58, 6, 91, 93, 59, 69, 89, 5, 58, 87, 23, 15, 98, 24, 62, 64, 15, 43, 93, 68, 17, 4, 78, 6, 2, 10, 52, 17, 28, 82, 20, 44, 78, 91, 1, 79, 17, 23, 27, 66, 88, 57, 60, 78, 68, 6, 35, 43, 73, 37, 12, 22, 47, 59, 40, 36, 0, 70, 91, 68, 33, 54, 44, 78, 23, 69, 60, 44, 32, 15, 20, 28, 36, 55, 73, 12, 55, 26, 43, 57, 63, 46, 0, 43, 24, 91, 86, 61, 15, 10, 29, 8, 51, 84, 94, 18, 5, 63, 90, 4, 38, 28, 84, 67, 18, 33, 85, 93, 31, 38, 97, 14, 79, 11, 92, 3, 8, 27, 65, 39, 1, 83, 38, 8, 83, 53, 53, 44, 57, 64, 78, 1, 44, 72, 100, 86, 85, 16, 5, 27, 24, 2, 56, 74, 16, 90, 65, 8, 93, 64, 72, 45, 47, 7, 83, 100, 99, 62, 89, 38, 38, 42, 98, 18, 29, 88, 48, 35, 0, 82, 56, 22, 64, 13, 54, 66, 32, 9, 2, 52, 80, 28, 19, 9, 38, 98, 38, 21, 41, 65, 78, 63, 97, 71, 99, 41, 89, 78, 48, 47, 72, 67, 79, 45, 43, 92, 30, 28, 42, 52, 56, 24, 46, 55, 82, 22, 86, 67, 43, 84, 41, 26, 66, 26, 32, 8, 93, 65, 10, 47, 19, 70, 84, 43, 99, 74, 78, 51, 59, 58, 38, 75, 86, 24, 48, 27, 72, 32, 15, 28, 98, 11, 70, 74, 91, 89, 90, 74, 69, 60, 78, 6, 67, 34, 100, 70, 98, 70, 60, 12, 58, 26, 21, 44, 64, 15, 82, 81, 52, 9, 82, 94, 99, 43, 22, 14, 16, 27, 68, 72, 69, 45, 60, 10, 91, 31, 58, 91, 71, 42, 19, 43, 42, 80, 61, 50, 2, 81, 45, 40, 44, 100, 68, 74, 19, 0, 33, 24, 58, 59, 1, 26, 65, 69, 19, 60, 12, 50, 82, 44, 18, 96, 77, 43, 33, 31, 53, 9, 36, 86, 24, 46, 11, 26, 3, 43, 8, 42, 17, 55, 60, 56, 33, 66, 90, 64, 42, 73, 61, 34, 13, 43, 9, 59, 46, 0, 68, 93, 60, 78, 92, 76, 45, 20, 31, 47, 21, 44, 2, 23, 78, 72, 62, 65, 56, 26, 80, 65, 87, 61, 88, 22, 38, 70, 98, 48, 25, 95, 55, 3, 32, 28, 50, 13, 57, 18, 95, 11, 23, 57, 21, 93, 35, 38, 75, 79, 39, 87, 30, 95, 73, 37, 47, 43, 15, 73, 59, 0, 29, 29, 30, 50, 13, 73, 1, 32, 7, 46, 7, 24, 43, 21, 84, 1, 6, 96, 33, 69, 2, 70, 98, 2, 90, 31, 66, 74, 58, 66, 56, 33, 5, 78, 19, 21, 98, 76, 1, 55, 97, 39, 43, 43, 44, 7, 61, 84, 31, 0, 67, 46, 39, 23, 7, 31, 29, 2, 71, 7, 35, 60, 20, 94, 23, 81, 40, 79, 11, 46, 71, 25, 42, 54, 10, 21, 11, 72, 86, 48, 53, 67, 36, 55, 49, 98, 65, 37, 27, 63, 20, 86, 60, 29, 63, 75, 91, 30, 55, 23, 82, 88, 53, 62, 44, 25, 27, 99, 39, 4, 40, 41, 35, 35, 61, 62, 10, 98, 9, 82, 21, 39, 82, 89, 41, 71, 26, 51, 2, 73, 30, 49, 92, 16, 66, 60, 68, 2, 99, 91, 15, 77, 43, 44, 46, 69, 79, 100, 47, 9, 66, 33, 25, 15, 5, 77, 86, 81, 82, 69, 10, 0, 98, 4, 90, 30, 89, 87, 83, 97, 35, 96, 71, 15, 50, 12, 82, 79, 91, 79, 28, 62, 24, 75, 77, 68, 59, 87, 29, 81, 66, 92, 85, 4, 17, 48, 69, 28, 37, 55, 39, 11, 92, 57, 26, 64, 91, 44, 37, 3, 44, 57, 13, 75, 21, 39, 17, 29, 18, 74, 43, 93, 53, 6, 61, 71, 89, 99, 13, 92, 23, 99, 18, 13, 38, 14, 9, 82, 10, 7, 41, 24, 40, 61, 42, 26, 2, 43, 38, 3, 50, 43, 75, 47, 95, 16, 41, 40, 43, 14, 26, 40, 79, 11, 30, 16, 39, 46, 45, 25, 44, 79, 21, 48, 48, 23, 38, 79, 62, 71, 8, 53, 12, 72, 64, 71, 50, 90, 38, 77, 6, 48, 74, 77, 53, 85, 82, 19, 18, 43, 97, 67, 56, 25, 46, 87, 27, 99, 21, 13, 56, 71, 87, 73, 25, 0, 52, 82, 18, 65, 34, 96, 33, 99, 43, 45, 2, 59, 29, 53, 34, 78, 27, 41, 74, 74, 59, 96, 74, 45, 74, 44, 28, 62, 4, 90, 62, 31, 89, 72, 88, 69, 5, 29, 26, 81, 66, 96, 53, 87, 72, 89, 9, 30, 71, 75, 83, 46, 71, 57, 12, 77, 24, 44, 71, 34, 42, 11, 67, 9, 69, 47, 95, 93, 72, 12, 40, 98, 83, 25, 27, 91, 21, 31, 0, 44, 56, 1, 76, 30, 100, 18, 46, 35, 72, 61, 39, 90, 25, 78, 42, 77, 13, 72, 32, 3, 84, 63, 59, 100, 60, 22, 57, 50, 40, 63, 65, 2, 27, 88, 63, 40, 97, 94, 69, 72, 98, 2, 68, 13, 62, 76, 97, 14, 36, 15, 91, 80, 55, 45, 67, 50, 13, 49, 54, 72, 84, 36, 69, 74, 35, 30, 47, 64, 91, 24, 16, 41, 41, 19, 96, 25, 38, 60, 43, 86, 6, 23, 81, 71, 73, 56, 12, 44, 67, 28, 39, 1, 52, 40, 28, 45, 44, 53, 63, 7, 66, 45, 44, 68, 6, 98, 100, 95]k = 787 print(\"Test case :-\\nk=\",k,\" \\nnums = \",nums[0:10],\".....\")print(\"-----------------------------------------\")Solution.solve(nums, k)print(\"-----------------------------------------\") nums = [0, 0, 0]k = 0print(\"Test case :-\\nk=\",k,\" \\nnums = \",nums)print(\"-----------------------------------------\")Solution.solve(nums, k)print(\"-----------------------------------------\")",
"e": 8656,
"s": 2426,
"text": null
},
{
"code": null,
"e": 8666,
"s": 8656,
"text": "Output : "
},
{
"code": null,
"e": 9706,
"s": 8666,
"text": "Test case :-\nk= 5 \nnums = [4, 1, 3, 1]\n-----------------------------------------\nFound match : (1, 3, 1) 5\n-----------------------------------------\nTest case :-\nk= 0 \nnums = [2, 4, 3, 0, 1]\n-----------------------------------------\nMatch not found.\n-----------------------------------------\nTest case :-\nk= 0 \nnums = [0]\n-----------------------------------------\nMatch not found.\n-----------------------------------------\nTest case :-\nk= 1 \nnums = [1, 0]\n-----------------------------------------\nMatch not found.\n-----------------------------------------\nTest case :-\nk= 3 \nnums = [2, 0, 1]\n-----------------------------------------\nFound match : (2, 0, 1) 3\n-----------------------------------------\nTest case :-\nk= 787 \nnums = [13, 76, 35, 89, 15, 76, 54, 4, 66, 4] .....\n-----------------------------------------\nMatch not found.\n-----------------------------------------\nTest case :-\nk= 0 \nnums = [0, 0, 0]\n-----------------------------------------\nFound match : (0, 0, 0) 0\n-----------------------------------------"
},
{
"code": null,
"e": 9717,
"s": 9706,
"text": "contact2js"
},
{
"code": null,
"e": 9738,
"s": 9717,
"text": "Python list-programs"
},
{
"code": null,
"e": 9745,
"s": 9738,
"text": "Python"
},
{
"code": null,
"e": 9761,
"s": 9745,
"text": "Python Programs"
}
] |
Initialize an ArrayList in Java | 13 May, 2022
ArrayList is a part of collection framework and is present in java.util package. It provides us dynamic arrays in Java. Though, it may be slower than standard arrays but can be helpful in programs where lots of manipulation in the array is needed.
ArrayList inherits AbstractList class and implements List interface.
ArrayList is initialized by a size, however the size can increase if collection grows or shrink if objects are removed from the collection.
Java ArrayList allows us to randomly access the list.
ArrayList can not be used for primitive types, like int, char, etc. We need a wrapper class for such cases (see this for details).
ArrayList in Java can be seen as similar to vector in C++.
Below are the various methods to initialize an ArrayList in Java:
Initialization with add()Syntax:ArrayList<Type> str = new ArrayList<Type>();
str.add("Geeks");
str.add("for");
str.add("Geeks");
Examples:// Java code to illustrate initialization// of ArrayList using add() method import java.util.*; public class GFG { public static void main(String args[]) { // create a ArrayList String type ArrayList<String> gfg = new ArrayList<String>(); // Initialize an ArrayList with add() gfg.add("Geeks"); gfg.add("for"); gfg.add("Geeks"); // print ArrayList System.out.println("ArrayList : " + gfg); }}Output:ArrayList : [Geeks, for, Geeks]
Examples: Using shorthand version of this method// Java code to illustrate initialization// of ArrayList using add() method import java.util.*; public class GFG { public static void main(String args[]) { // create a ArrayList String type // and Initialize an ArrayList with add() ArrayList<String> gfg = new ArrayList<String>() { { add("Geeks"); add("for"); add("Geeks"); } }; // print ArrayList System.out.println("ArrayList : " + gfg); }}Output:ArrayList : [Geeks, for, Geeks]
Initialization using asList()Syntax:ArrayList<Type> obj = new ArrayList<Type>(
Arrays.asList(Obj A, Obj B, Obj C, ....so on));
Examples:// Java code to illustrate initialization// of ArrayList using asList method import java.util.*; public class GFG { public static void main(String args[]) { // create a ArrayList String type // and Initialize an ArrayList with asList() ArrayList<String> gfg = new ArrayList<String>( Arrays.asList("Geeks", "for", "Geeks")); // print ArrayList System.out.println("ArrayList : " + gfg); }}Output:ArrayList : [Geeks, for, Geeks]
Initialization using List.of() methodSyntax:List<Type> obj = new ArrayList<>(
List.of(Obj A, Obj B, Obj C, ....so on));
Examples:// Java code to illustrate initialization// of ArrayList using List.of() method import java.util.*; public class GFG { public static void main(String args[]) { // create a ArrayList String type // and Initialize an ArrayList with List.of() List<String> gfg = new ArrayList<>( List.of("Geeks", "for", "Geeks")); // print ArrayList System.out.println("ArrayList : " + gfg); }}Output:ArrayList : [Geeks, for, Geeks]
Initialization using another CollectionSyntax:List gfg = new ArrayList(collection);
Examples:// Java code to illustrate initialization// of ArrayList using another collection import java.util.*; public class GFG { public static void main(String args[]) { // create another collection List<Integer> arr = new ArrayList<>(); arr.add(1); arr.add(2); arr.add(3); arr.add(4); arr.add(5); // create a ArrayList Integer type // and Initialize an ArrayList with arr List<Integer> gfg = new ArrayList<Integer>(arr); // print ArrayList System.out.println("ArrayList : " + gfg); }}Output:ArrayList : [1, 2, 3, 4, 5]
My Personal Notes
arrow_drop_upSave
Initialization with add()Syntax:ArrayList<Type> str = new ArrayList<Type>();
str.add("Geeks");
str.add("for");
str.add("Geeks");
Examples:// Java code to illustrate initialization// of ArrayList using add() method import java.util.*; public class GFG { public static void main(String args[]) { // create a ArrayList String type ArrayList<String> gfg = new ArrayList<String>(); // Initialize an ArrayList with add() gfg.add("Geeks"); gfg.add("for"); gfg.add("Geeks"); // print ArrayList System.out.println("ArrayList : " + gfg); }}Output:ArrayList : [Geeks, for, Geeks]
Examples: Using shorthand version of this method// Java code to illustrate initialization// of ArrayList using add() method import java.util.*; public class GFG { public static void main(String args[]) { // create a ArrayList String type // and Initialize an ArrayList with add() ArrayList<String> gfg = new ArrayList<String>() { { add("Geeks"); add("for"); add("Geeks"); } }; // print ArrayList System.out.println("ArrayList : " + gfg); }}Output:ArrayList : [Geeks, for, Geeks]
Syntax:
ArrayList<Type> str = new ArrayList<Type>();
str.add("Geeks");
str.add("for");
str.add("Geeks");
Examples:
// Java code to illustrate initialization// of ArrayList using add() method import java.util.*; public class GFG { public static void main(String args[]) { // create a ArrayList String type ArrayList<String> gfg = new ArrayList<String>(); // Initialize an ArrayList with add() gfg.add("Geeks"); gfg.add("for"); gfg.add("Geeks"); // print ArrayList System.out.println("ArrayList : " + gfg); }}
ArrayList : [Geeks, for, Geeks]
Examples: Using shorthand version of this method
// Java code to illustrate initialization// of ArrayList using add() method import java.util.*; public class GFG { public static void main(String args[]) { // create a ArrayList String type // and Initialize an ArrayList with add() ArrayList<String> gfg = new ArrayList<String>() { { add("Geeks"); add("for"); add("Geeks"); } }; // print ArrayList System.out.println("ArrayList : " + gfg); }}
ArrayList : [Geeks, for, Geeks]
Initialization using asList()Syntax:ArrayList<Type> obj = new ArrayList<Type>(
Arrays.asList(Obj A, Obj B, Obj C, ....so on));
Examples:// Java code to illustrate initialization// of ArrayList using asList method import java.util.*; public class GFG { public static void main(String args[]) { // create a ArrayList String type // and Initialize an ArrayList with asList() ArrayList<String> gfg = new ArrayList<String>( Arrays.asList("Geeks", "for", "Geeks")); // print ArrayList System.out.println("ArrayList : " + gfg); }}Output:ArrayList : [Geeks, for, Geeks]
Syntax:
ArrayList<Type> obj = new ArrayList<Type>(
Arrays.asList(Obj A, Obj B, Obj C, ....so on));
Examples:
// Java code to illustrate initialization// of ArrayList using asList method import java.util.*; public class GFG { public static void main(String args[]) { // create a ArrayList String type // and Initialize an ArrayList with asList() ArrayList<String> gfg = new ArrayList<String>( Arrays.asList("Geeks", "for", "Geeks")); // print ArrayList System.out.println("ArrayList : " + gfg); }}
ArrayList : [Geeks, for, Geeks]
Initialization using List.of() methodSyntax:List<Type> obj = new ArrayList<>(
List.of(Obj A, Obj B, Obj C, ....so on));
Examples:// Java code to illustrate initialization// of ArrayList using List.of() method import java.util.*; public class GFG { public static void main(String args[]) { // create a ArrayList String type // and Initialize an ArrayList with List.of() List<String> gfg = new ArrayList<>( List.of("Geeks", "for", "Geeks")); // print ArrayList System.out.println("ArrayList : " + gfg); }}Output:ArrayList : [Geeks, for, Geeks]
Syntax:
List<Type> obj = new ArrayList<>(
List.of(Obj A, Obj B, Obj C, ....so on));
Examples:
// Java code to illustrate initialization// of ArrayList using List.of() method import java.util.*; public class GFG { public static void main(String args[]) { // create a ArrayList String type // and Initialize an ArrayList with List.of() List<String> gfg = new ArrayList<>( List.of("Geeks", "for", "Geeks")); // print ArrayList System.out.println("ArrayList : " + gfg); }}
ArrayList : [Geeks, for, Geeks]
Initialization using another CollectionSyntax:List gfg = new ArrayList(collection);
Examples:// Java code to illustrate initialization// of ArrayList using another collection import java.util.*; public class GFG { public static void main(String args[]) { // create another collection List<Integer> arr = new ArrayList<>(); arr.add(1); arr.add(2); arr.add(3); arr.add(4); arr.add(5); // create a ArrayList Integer type // and Initialize an ArrayList with arr List<Integer> gfg = new ArrayList<Integer>(arr); // print ArrayList System.out.println("ArrayList : " + gfg); }}Output:ArrayList : [1, 2, 3, 4, 5]
Syntax:
List gfg = new ArrayList(collection);
Examples:
// Java code to illustrate initialization// of ArrayList using another collection import java.util.*; public class GFG { public static void main(String args[]) { // create another collection List<Integer> arr = new ArrayList<>(); arr.add(1); arr.add(2); arr.add(3); arr.add(4); arr.add(5); // create a ArrayList Integer type // and Initialize an ArrayList with arr List<Integer> gfg = new ArrayList<Integer>(arr); // print ArrayList System.out.println("ArrayList : " + gfg); }}
ArrayList : [1, 2, 3, 4, 5]
Java-ArrayList
Java-List-Programs
Picked
Technical Scripter 2018
Java
Technical Scripter
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Object Oriented Programming (OOPs) Concept in Java
How to iterate any Map in Java
Interfaces in Java
HashMap in Java with Examples
ArrayList in Java
Stream In Java
Collections in Java
Multidimensional Arrays in Java
Singleton Class in Java
Set in Java | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n13 May, 2022"
},
{
"code": null,
"e": 302,
"s": 54,
"text": "ArrayList is a part of collection framework and is present in java.util package. It provides us dynamic arrays in Java. Though, it may be slower than standard arrays but can be helpful in programs where lots of manipulation in the array is needed."
},
{
"code": null,
"e": 371,
"s": 302,
"text": "ArrayList inherits AbstractList class and implements List interface."
},
{
"code": null,
"e": 511,
"s": 371,
"text": "ArrayList is initialized by a size, however the size can increase if collection grows or shrink if objects are removed from the collection."
},
{
"code": null,
"e": 565,
"s": 511,
"text": "Java ArrayList allows us to randomly access the list."
},
{
"code": null,
"e": 696,
"s": 565,
"text": "ArrayList can not be used for primitive types, like int, char, etc. We need a wrapper class for such cases (see this for details)."
},
{
"code": null,
"e": 755,
"s": 696,
"text": "ArrayList in Java can be seen as similar to vector in C++."
},
{
"code": null,
"e": 821,
"s": 755,
"text": "Below are the various methods to initialize an ArrayList in Java:"
},
{
"code": null,
"e": 4157,
"s": 821,
"text": "Initialization with add()Syntax:ArrayList<Type> str = new ArrayList<Type>();\n str.add(\"Geeks\");\n str.add(\"for\");\n str.add(\"Geeks\");\nExamples:// Java code to illustrate initialization// of ArrayList using add() method import java.util.*; public class GFG { public static void main(String args[]) { // create a ArrayList String type ArrayList<String> gfg = new ArrayList<String>(); // Initialize an ArrayList with add() gfg.add(\"Geeks\"); gfg.add(\"for\"); gfg.add(\"Geeks\"); // print ArrayList System.out.println(\"ArrayList : \" + gfg); }}Output:ArrayList : [Geeks, for, Geeks]\nExamples: Using shorthand version of this method// Java code to illustrate initialization// of ArrayList using add() method import java.util.*; public class GFG { public static void main(String args[]) { // create a ArrayList String type // and Initialize an ArrayList with add() ArrayList<String> gfg = new ArrayList<String>() { { add(\"Geeks\"); add(\"for\"); add(\"Geeks\"); } }; // print ArrayList System.out.println(\"ArrayList : \" + gfg); }}Output:ArrayList : [Geeks, for, Geeks]\nInitialization using asList()Syntax:ArrayList<Type> obj = new ArrayList<Type>(\n Arrays.asList(Obj A, Obj B, Obj C, ....so on));\nExamples:// Java code to illustrate initialization// of ArrayList using asList method import java.util.*; public class GFG { public static void main(String args[]) { // create a ArrayList String type // and Initialize an ArrayList with asList() ArrayList<String> gfg = new ArrayList<String>( Arrays.asList(\"Geeks\", \"for\", \"Geeks\")); // print ArrayList System.out.println(\"ArrayList : \" + gfg); }}Output:ArrayList : [Geeks, for, Geeks]\nInitialization using List.of() methodSyntax:List<Type> obj = new ArrayList<>(\n List.of(Obj A, Obj B, Obj C, ....so on));\nExamples:// Java code to illustrate initialization// of ArrayList using List.of() method import java.util.*; public class GFG { public static void main(String args[]) { // create a ArrayList String type // and Initialize an ArrayList with List.of() List<String> gfg = new ArrayList<>( List.of(\"Geeks\", \"for\", \"Geeks\")); // print ArrayList System.out.println(\"ArrayList : \" + gfg); }}Output:ArrayList : [Geeks, for, Geeks]\nInitialization using another CollectionSyntax:List gfg = new ArrayList(collection);\nExamples:// Java code to illustrate initialization// of ArrayList using another collection import java.util.*; public class GFG { public static void main(String args[]) { // create another collection List<Integer> arr = new ArrayList<>(); arr.add(1); arr.add(2); arr.add(3); arr.add(4); arr.add(5); // create a ArrayList Integer type // and Initialize an ArrayList with arr List<Integer> gfg = new ArrayList<Integer>(arr); // print ArrayList System.out.println(\"ArrayList : \" + gfg); }}Output:ArrayList : [1, 2, 3, 4, 5]\nMy Personal Notes\narrow_drop_upSave"
},
{
"code": null,
"e": 5424,
"s": 4157,
"text": "Initialization with add()Syntax:ArrayList<Type> str = new ArrayList<Type>();\n str.add(\"Geeks\");\n str.add(\"for\");\n str.add(\"Geeks\");\nExamples:// Java code to illustrate initialization// of ArrayList using add() method import java.util.*; public class GFG { public static void main(String args[]) { // create a ArrayList String type ArrayList<String> gfg = new ArrayList<String>(); // Initialize an ArrayList with add() gfg.add(\"Geeks\"); gfg.add(\"for\"); gfg.add(\"Geeks\"); // print ArrayList System.out.println(\"ArrayList : \" + gfg); }}Output:ArrayList : [Geeks, for, Geeks]\nExamples: Using shorthand version of this method// Java code to illustrate initialization// of ArrayList using add() method import java.util.*; public class GFG { public static void main(String args[]) { // create a ArrayList String type // and Initialize an ArrayList with add() ArrayList<String> gfg = new ArrayList<String>() { { add(\"Geeks\"); add(\"for\"); add(\"Geeks\"); } }; // print ArrayList System.out.println(\"ArrayList : \" + gfg); }}Output:ArrayList : [Geeks, for, Geeks]\n"
},
{
"code": null,
"e": 5432,
"s": 5424,
"text": "Syntax:"
},
{
"code": null,
"e": 5551,
"s": 5432,
"text": "ArrayList<Type> str = new ArrayList<Type>();\n str.add(\"Geeks\");\n str.add(\"for\");\n str.add(\"Geeks\");\n"
},
{
"code": null,
"e": 5561,
"s": 5551,
"text": "Examples:"
},
{
"code": "// Java code to illustrate initialization// of ArrayList using add() method import java.util.*; public class GFG { public static void main(String args[]) { // create a ArrayList String type ArrayList<String> gfg = new ArrayList<String>(); // Initialize an ArrayList with add() gfg.add(\"Geeks\"); gfg.add(\"for\"); gfg.add(\"Geeks\"); // print ArrayList System.out.println(\"ArrayList : \" + gfg); }}",
"e": 6027,
"s": 5561,
"text": null
},
{
"code": null,
"e": 6060,
"s": 6027,
"text": "ArrayList : [Geeks, for, Geeks]\n"
},
{
"code": null,
"e": 6109,
"s": 6060,
"text": "Examples: Using shorthand version of this method"
},
{
"code": "// Java code to illustrate initialization// of ArrayList using add() method import java.util.*; public class GFG { public static void main(String args[]) { // create a ArrayList String type // and Initialize an ArrayList with add() ArrayList<String> gfg = new ArrayList<String>() { { add(\"Geeks\"); add(\"for\"); add(\"Geeks\"); } }; // print ArrayList System.out.println(\"ArrayList : \" + gfg); }}",
"e": 6626,
"s": 6109,
"text": null
},
{
"code": null,
"e": 6659,
"s": 6626,
"text": "ArrayList : [Geeks, for, Geeks]\n"
},
{
"code": null,
"e": 7339,
"s": 6659,
"text": "Initialization using asList()Syntax:ArrayList<Type> obj = new ArrayList<Type>(\n Arrays.asList(Obj A, Obj B, Obj C, ....so on));\nExamples:// Java code to illustrate initialization// of ArrayList using asList method import java.util.*; public class GFG { public static void main(String args[]) { // create a ArrayList String type // and Initialize an ArrayList with asList() ArrayList<String> gfg = new ArrayList<String>( Arrays.asList(\"Geeks\", \"for\", \"Geeks\")); // print ArrayList System.out.println(\"ArrayList : \" + gfg); }}Output:ArrayList : [Geeks, for, Geeks]\n"
},
{
"code": null,
"e": 7347,
"s": 7339,
"text": "Syntax:"
},
{
"code": null,
"e": 7445,
"s": 7347,
"text": "ArrayList<Type> obj = new ArrayList<Type>(\n Arrays.asList(Obj A, Obj B, Obj C, ....so on));\n"
},
{
"code": null,
"e": 7455,
"s": 7445,
"text": "Examples:"
},
{
"code": "// Java code to illustrate initialization// of ArrayList using asList method import java.util.*; public class GFG { public static void main(String args[]) { // create a ArrayList String type // and Initialize an ArrayList with asList() ArrayList<String> gfg = new ArrayList<String>( Arrays.asList(\"Geeks\", \"for\", \"Geeks\")); // print ArrayList System.out.println(\"ArrayList : \" + gfg); }}",
"e": 7954,
"s": 7455,
"text": null
},
{
"code": null,
"e": 7987,
"s": 7954,
"text": "ArrayList : [Geeks, for, Geeks]\n"
},
{
"code": null,
"e": 8637,
"s": 7987,
"text": "Initialization using List.of() methodSyntax:List<Type> obj = new ArrayList<>(\n List.of(Obj A, Obj B, Obj C, ....so on));\nExamples:// Java code to illustrate initialization// of ArrayList using List.of() method import java.util.*; public class GFG { public static void main(String args[]) { // create a ArrayList String type // and Initialize an ArrayList with List.of() List<String> gfg = new ArrayList<>( List.of(\"Geeks\", \"for\", \"Geeks\")); // print ArrayList System.out.println(\"ArrayList : \" + gfg); }}Output:ArrayList : [Geeks, for, Geeks]\n"
},
{
"code": null,
"e": 8645,
"s": 8637,
"text": "Syntax:"
},
{
"code": null,
"e": 8730,
"s": 8645,
"text": "List<Type> obj = new ArrayList<>(\n List.of(Obj A, Obj B, Obj C, ....so on));\n"
},
{
"code": null,
"e": 8740,
"s": 8730,
"text": "Examples:"
},
{
"code": "// Java code to illustrate initialization// of ArrayList using List.of() method import java.util.*; public class GFG { public static void main(String args[]) { // create a ArrayList String type // and Initialize an ArrayList with List.of() List<String> gfg = new ArrayList<>( List.of(\"Geeks\", \"for\", \"Geeks\")); // print ArrayList System.out.println(\"ArrayList : \" + gfg); }}",
"e": 9214,
"s": 8740,
"text": null
},
{
"code": null,
"e": 9247,
"s": 9214,
"text": "ArrayList : [Geeks, for, Geeks]\n"
},
{
"code": null,
"e": 9954,
"s": 9247,
"text": "Initialization using another CollectionSyntax:List gfg = new ArrayList(collection);\nExamples:// Java code to illustrate initialization// of ArrayList using another collection import java.util.*; public class GFG { public static void main(String args[]) { // create another collection List<Integer> arr = new ArrayList<>(); arr.add(1); arr.add(2); arr.add(3); arr.add(4); arr.add(5); // create a ArrayList Integer type // and Initialize an ArrayList with arr List<Integer> gfg = new ArrayList<Integer>(arr); // print ArrayList System.out.println(\"ArrayList : \" + gfg); }}Output:ArrayList : [1, 2, 3, 4, 5]\n"
},
{
"code": null,
"e": 9962,
"s": 9954,
"text": "Syntax:"
},
{
"code": null,
"e": 10001,
"s": 9962,
"text": "List gfg = new ArrayList(collection);\n"
},
{
"code": null,
"e": 10011,
"s": 10001,
"text": "Examples:"
},
{
"code": "// Java code to illustrate initialization// of ArrayList using another collection import java.util.*; public class GFG { public static void main(String args[]) { // create another collection List<Integer> arr = new ArrayList<>(); arr.add(1); arr.add(2); arr.add(3); arr.add(4); arr.add(5); // create a ArrayList Integer type // and Initialize an ArrayList with arr List<Integer> gfg = new ArrayList<Integer>(arr); // print ArrayList System.out.println(\"ArrayList : \" + gfg); }}",
"e": 10590,
"s": 10011,
"text": null
},
{
"code": null,
"e": 10619,
"s": 10590,
"text": "ArrayList : [1, 2, 3, 4, 5]\n"
},
{
"code": null,
"e": 10634,
"s": 10619,
"text": "Java-ArrayList"
},
{
"code": null,
"e": 10653,
"s": 10634,
"text": "Java-List-Programs"
},
{
"code": null,
"e": 10660,
"s": 10653,
"text": "Picked"
},
{
"code": null,
"e": 10684,
"s": 10660,
"text": "Technical Scripter 2018"
},
{
"code": null,
"e": 10689,
"s": 10684,
"text": "Java"
},
{
"code": null,
"e": 10708,
"s": 10689,
"text": "Technical Scripter"
},
{
"code": null,
"e": 10713,
"s": 10708,
"text": "Java"
},
{
"code": null,
"e": 10811,
"s": 10713,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 10862,
"s": 10811,
"text": "Object Oriented Programming (OOPs) Concept in Java"
},
{
"code": null,
"e": 10893,
"s": 10862,
"text": "How to iterate any Map in Java"
},
{
"code": null,
"e": 10912,
"s": 10893,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 10942,
"s": 10912,
"text": "HashMap in Java with Examples"
},
{
"code": null,
"e": 10960,
"s": 10942,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 10975,
"s": 10960,
"text": "Stream In Java"
},
{
"code": null,
"e": 10995,
"s": 10975,
"text": "Collections in Java"
},
{
"code": null,
"e": 11027,
"s": 10995,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 11051,
"s": 11027,
"text": "Singleton Class in Java"
}
] |
Python | Pandas Series.median() | 11 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.median() function return the median of the underlying data in the given Series object.
Syntax: Series.median(axis=None, skipna=None, level=None, numeric_only=None, **kwargs)
Parameter :axis : Axis for the function to be applied on.skipna : Exclude NA/null values when computing the result.level : If the axis is a MultiIndex (hierarchical), count along a particular level, collapsing into a scalar.numeric_only : Include only float, int, boolean columns**kwargs : Additional keyword arguments to be passed to the function.
Returns : median : scalar or Series (if level specified)
Example #1: Use Series.median() function to find the median of the underlying data in the given series object.
# importing pandas as pdimport pandas as pd # Creating the Seriessr = pd.Series([10, 25, 3, 25, 24, 6]) # 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.median() function to find the median of the given series object.
# return the medianresult = sr.median() # Print the resultprint(result)
Output :As we can see in the output, the Series.median() function has successfully returned the median of the given series object. Example #2: Use Series.median() function to find the median of the underlying data in the given series object. The given series object contains some missing values.
# importing pandas as pdimport pandas as pd # Creating the Seriessr = pd.Series([19.5, 16.8, None, 22.78, 16.8, 20.124, None, 18.1002, 19.5]) # Print the seriesprint(sr)
Output :
Now we will use Series.median() function to find the median of the given series object. we are going to skip the missing values while calculating the median in the given series object.
# return the medianresult = sr.median(skipna = True) # Print the resultprint(result)
Output :As we can see in the output, the Series.median() function has successfully returned the median of the given 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. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n11 Feb, 2019"
},
{
"code": null,
"e": 285,
"s": 28,
"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": 386,
"s": 285,
"text": "Pandas Series.median() function return the median of the underlying data in the given Series object."
},
{
"code": null,
"e": 473,
"s": 386,
"text": "Syntax: Series.median(axis=None, skipna=None, level=None, numeric_only=None, **kwargs)"
},
{
"code": null,
"e": 822,
"s": 473,
"text": "Parameter :axis : Axis for the function to be applied on.skipna : Exclude NA/null values when computing the result.level : If the axis is a MultiIndex (hierarchical), count along a particular level, collapsing into a scalar.numeric_only : Include only float, int, boolean columns**kwargs : Additional keyword arguments to be passed to the function."
},
{
"code": null,
"e": 879,
"s": 822,
"text": "Returns : median : scalar or Series (if level specified)"
},
{
"code": null,
"e": 990,
"s": 879,
"text": "Example #1: Use Series.median() function to find the median of the underlying data in the given series object."
},
{
"code": "# importing pandas as pdimport pandas as pd # Creating the Seriessr = pd.Series([10, 25, 3, 25, 24, 6]) # Create the Indexindex_ = ['Coca Cola', 'Sprite', 'Coke', 'Fanta', 'Dew', 'ThumbsUp'] # set the indexsr.index = index_ # Print the seriesprint(sr)",
"e": 1246,
"s": 990,
"text": null
},
{
"code": null,
"e": 1255,
"s": 1246,
"text": "Output :"
},
{
"code": null,
"e": 1343,
"s": 1255,
"text": "Now we will use Series.median() function to find the median of the given series object."
},
{
"code": "# return the medianresult = sr.median() # Print the resultprint(result)",
"e": 1416,
"s": 1343,
"text": null
},
{
"code": null,
"e": 1712,
"s": 1416,
"text": "Output :As we can see in the output, the Series.median() function has successfully returned the median of the given series object. Example #2: Use Series.median() function to find the median of the underlying data in the given series object. The given series object contains some missing values."
},
{
"code": "# importing pandas as pdimport pandas as pd # Creating the Seriessr = pd.Series([19.5, 16.8, None, 22.78, 16.8, 20.124, None, 18.1002, 19.5]) # Print the seriesprint(sr)",
"e": 1884,
"s": 1712,
"text": null
},
{
"code": null,
"e": 1893,
"s": 1884,
"text": "Output :"
},
{
"code": null,
"e": 2078,
"s": 1893,
"text": "Now we will use Series.median() function to find the median of the given series object. we are going to skip the missing values while calculating the median in the given series object."
},
{
"code": "# return the medianresult = sr.median(skipna = True) # Print the resultprint(result)",
"e": 2164,
"s": 2078,
"text": null
},
{
"code": null,
"e": 2295,
"s": 2164,
"text": "Output :As we can see in the output, the Series.median() function has successfully returned the median of the given series object."
},
{
"code": null,
"e": 2316,
"s": 2295,
"text": "Python pandas-series"
},
{
"code": null,
"e": 2345,
"s": 2316,
"text": "Python pandas-series-methods"
},
{
"code": null,
"e": 2359,
"s": 2345,
"text": "Python-pandas"
},
{
"code": null,
"e": 2366,
"s": 2359,
"text": "Python"
}
] |
Express.js res.set() Function | 05 May, 2021
The res.set() function is used to set the response HTTP header field to value. To set multiple fields at once, pass an object as the parameter.Syntax:
res.set(field [, value])
Parameters: The field parameter is the name of the field and the value parameter is the value assigned to the field parameter.Return Value: It returns a an Object.Installation of express module:
You can visit the link to Install express module. You can install this package by using this command.
You can visit the link to Install express module. You can install this package by using this command.
npm install express
After installing the express module, you can check your express version in command prompt using the command.
After installing the express module, you can check your express version in command prompt using the command.
npm version express
After that, you can just create a folder and add a file for example, index.js. To run this file you need to run the following command.
After that, you can just create a folder and add a file for example, index.js. To run this file you need to run the following command.
node index.js
Example 1: Filename: index.js
javascript
var express = require('express');var app = express();var PORT = 3000; // Without middlewareapp.get('/', function(req, res){ // Setting the response res.set({ 'Content-Type': 'application/json' }); // "application/json" console.log(res.get('Content-Type')); res.end();}); app.listen(PORT, function(err){ if (err) console.log(err); console.log("Server listening on PORT", PORT);});
Steps to run the program:
The project structure will look like this:
The project structure will look like this:
Make sure you have installed express module using the following command:
Make sure you have installed express module using the following command:
npm install express
Run index.js file using below command:
Run index.js file using below command:
node index.js
Output:
Output:
Server listening on PORT 3000
Now open browser and go to http://localhost:3000/, now check your console and you will see the following output:
Now open browser and go to http://localhost:3000/, now check your console and you will see the following output:
Server listening on PORT 3000
application/json; charset=utf-8
Example 2: Filename: index.js
javascript
var express = require('express');var app = express();var PORT = 3000; // With middlewareapp.use('/', function(req, res, next){ res.set({ 'Content-Type': 'application/xml' }); next();}) // Using middlewareapp.get('/', function(req, res){ console.log(res.get('Content-Type')); res.end();}); app.listen(PORT, function(err){ if (err) console.log(err); console.log("Server listening on PORT", PORT);});
Run index.js file using below command:
node index.js
Now open browser and go to http://localhost:3000/, now check your console and you will see the following output:
Server listening on PORT 3000
application/xml; charset=utf-8
Reference: https://expressjs.com/en/4x/api.html#res.set
simmytarika5
Express.js
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n05 May, 2021"
},
{
"code": null,
"e": 181,
"s": 28,
"text": "The res.set() function is used to set the response HTTP header field to value. To set multiple fields at once, pass an object as the parameter.Syntax: "
},
{
"code": null,
"e": 206,
"s": 181,
"text": "res.set(field [, value])"
},
{
"code": null,
"e": 403,
"s": 206,
"text": "Parameters: The field parameter is the name of the field and the value parameter is the value assigned to the field parameter.Return Value: It returns a an Object.Installation of express module: "
},
{
"code": null,
"e": 507,
"s": 403,
"text": "You can visit the link to Install express module. You can install this package by using this command. "
},
{
"code": null,
"e": 611,
"s": 507,
"text": "You can visit the link to Install express module. You can install this package by using this command. "
},
{
"code": null,
"e": 631,
"s": 611,
"text": "npm install express"
},
{
"code": null,
"e": 742,
"s": 631,
"text": "After installing the express module, you can check your express version in command prompt using the command. "
},
{
"code": null,
"e": 853,
"s": 742,
"text": "After installing the express module, you can check your express version in command prompt using the command. "
},
{
"code": null,
"e": 873,
"s": 853,
"text": "npm version express"
},
{
"code": null,
"e": 1010,
"s": 873,
"text": "After that, you can just create a folder and add a file for example, index.js. To run this file you need to run the following command. "
},
{
"code": null,
"e": 1147,
"s": 1010,
"text": "After that, you can just create a folder and add a file for example, index.js. To run this file you need to run the following command. "
},
{
"code": null,
"e": 1161,
"s": 1147,
"text": "node index.js"
},
{
"code": null,
"e": 1193,
"s": 1161,
"text": "Example 1: Filename: index.js "
},
{
"code": null,
"e": 1204,
"s": 1193,
"text": "javascript"
},
{
"code": "var express = require('express');var app = express();var PORT = 3000; // Without middlewareapp.get('/', function(req, res){ // Setting the response res.set({ 'Content-Type': 'application/json' }); // \"application/json\" console.log(res.get('Content-Type')); res.end();}); app.listen(PORT, function(err){ if (err) console.log(err); console.log(\"Server listening on PORT\", PORT);});",
"e": 1622,
"s": 1204,
"text": null
},
{
"code": null,
"e": 1650,
"s": 1622,
"text": "Steps to run the program: "
},
{
"code": null,
"e": 1695,
"s": 1650,
"text": "The project structure will look like this: "
},
{
"code": null,
"e": 1740,
"s": 1695,
"text": "The project structure will look like this: "
},
{
"code": null,
"e": 1815,
"s": 1740,
"text": "Make sure you have installed express module using the following command: "
},
{
"code": null,
"e": 1890,
"s": 1815,
"text": "Make sure you have installed express module using the following command: "
},
{
"code": null,
"e": 1910,
"s": 1890,
"text": "npm install express"
},
{
"code": null,
"e": 1951,
"s": 1910,
"text": "Run index.js file using below command: "
},
{
"code": null,
"e": 1992,
"s": 1951,
"text": "Run index.js file using below command: "
},
{
"code": null,
"e": 2006,
"s": 1992,
"text": "node index.js"
},
{
"code": null,
"e": 2016,
"s": 2006,
"text": "Output: "
},
{
"code": null,
"e": 2026,
"s": 2016,
"text": "Output: "
},
{
"code": null,
"e": 2056,
"s": 2026,
"text": "Server listening on PORT 3000"
},
{
"code": null,
"e": 2172,
"s": 2056,
"text": " Now open browser and go to http://localhost:3000/, now check your console and you will see the following output: "
},
{
"code": null,
"e": 2289,
"s": 2174,
"text": "Now open browser and go to http://localhost:3000/, now check your console and you will see the following output: "
},
{
"code": null,
"e": 2351,
"s": 2289,
"text": "Server listening on PORT 3000\napplication/json; charset=utf-8"
},
{
"code": null,
"e": 2387,
"s": 2355,
"text": "Example 2: Filename: index.js "
},
{
"code": null,
"e": 2398,
"s": 2387,
"text": "javascript"
},
{
"code": "var express = require('express');var app = express();var PORT = 3000; // With middlewareapp.use('/', function(req, res, next){ res.set({ 'Content-Type': 'application/xml' }); next();}) // Using middlewareapp.get('/', function(req, res){ console.log(res.get('Content-Type')); res.end();}); app.listen(PORT, function(err){ if (err) console.log(err); console.log(\"Server listening on PORT\", PORT);});",
"e": 2830,
"s": 2398,
"text": null
},
{
"code": null,
"e": 2871,
"s": 2830,
"text": "Run index.js file using below command: "
},
{
"code": null,
"e": 2885,
"s": 2871,
"text": "node index.js"
},
{
"code": null,
"e": 3000,
"s": 2885,
"text": "Now open browser and go to http://localhost:3000/, now check your console and you will see the following output: "
},
{
"code": null,
"e": 3061,
"s": 3000,
"text": "Server listening on PORT 3000\napplication/xml; charset=utf-8"
},
{
"code": null,
"e": 3118,
"s": 3061,
"text": "Reference: https://expressjs.com/en/4x/api.html#res.set "
},
{
"code": null,
"e": 3131,
"s": 3118,
"text": "simmytarika5"
},
{
"code": null,
"e": 3142,
"s": 3131,
"text": "Express.js"
},
{
"code": null,
"e": 3150,
"s": 3142,
"text": "Node.js"
},
{
"code": null,
"e": 3167,
"s": 3150,
"text": "Web Technologies"
}
] |
How to Add Axes to a Figure in Matplotlib with Python? | 02 Dec, 2020
Matplotlib is a library in Python used to create figures and provide tools for customizing it. It allows plotting different types of data, geometrical figures. In this article, we will see how to add axes to a figure in matplotlib.
We can add axes to a figure in matplotlib by passing a list argument in the add_axes() method.
Syntax: matplotlib.pyplot.figure.add_axes(rect)
Parameters:
rect: This parameter is the dimensions [xmin, ymin, dx, dy] of the new axes. It takes the below elements as arguments in the list:
xmin: Horizontal coordinate of the lower left corner.
ymin: Vertical coordinate of the lower left corner.
dx: Width of the subplot.
dy: Height of the subplot.
Returns: This method return the axes class depends on the projection used.
Example 1:
Python3
# Importing libraryimport matplotlib # Create figure() objects# This acts as a container# for the different plotsfig = matplotlib.pyplot.figure() # Creating axis# add_axes([xmin,ymin,dx,dy])axes = fig.add_axes([0.5, 1, 0.5, 1]) # Depict illustrationfig.show()
Output:
Example 2:
Python3
# Importing libraryimport matplotlib # Create figure() objects# This acts as a container # for the different plotsfig=matplotlib.pyplot.figure() # Creating two axes# add_axes([xmin,ymin,dx,dy])axes=fig.add_axes([0,0,2,2]) axes1=fig.add_axes([0,1,2,2]) # Depict illustrationfig.show()
Output:
Example 3:
Python3
# Import librariesimport matplotlibimport numpy # Create figure() objects# This acts as a container# for the different plotsfig = matplotlib.pyplot.figure() # Generate line graphx = numpy.arange(0, 1.414*2, 0.05)y1 = numpy.sin(x)y2 = numpy.cos(x) # Creating two axes# add_axes([xmin,ymin,dx,dy])axes1 = fig.add_axes([0, 0, 1, 1])axes1.plot(x, y1)axes2 = fig.add_axes([0, 1, 1, 1])axes2.plot(x, y2) # Show plotplt.show()
Output:
Python-matplotlib
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n02 Dec, 2020"
},
{
"code": null,
"e": 284,
"s": 52,
"text": "Matplotlib is a library in Python used to create figures and provide tools for customizing it. It allows plotting different types of data, geometrical figures. In this article, we will see how to add axes to a figure in matplotlib."
},
{
"code": null,
"e": 379,
"s": 284,
"text": "We can add axes to a figure in matplotlib by passing a list argument in the add_axes() method."
},
{
"code": null,
"e": 427,
"s": 379,
"text": "Syntax: matplotlib.pyplot.figure.add_axes(rect)"
},
{
"code": null,
"e": 439,
"s": 427,
"text": "Parameters:"
},
{
"code": null,
"e": 570,
"s": 439,
"text": "rect: This parameter is the dimensions [xmin, ymin, dx, dy] of the new axes. It takes the below elements as arguments in the list:"
},
{
"code": null,
"e": 624,
"s": 570,
"text": "xmin: Horizontal coordinate of the lower left corner."
},
{
"code": null,
"e": 676,
"s": 624,
"text": "ymin: Vertical coordinate of the lower left corner."
},
{
"code": null,
"e": 702,
"s": 676,
"text": "dx: Width of the subplot."
},
{
"code": null,
"e": 729,
"s": 702,
"text": "dy: Height of the subplot."
},
{
"code": null,
"e": 805,
"s": 729,
"text": "Returns: This method return the axes class depends on the projection used. "
},
{
"code": null,
"e": 816,
"s": 805,
"text": "Example 1:"
},
{
"code": null,
"e": 824,
"s": 816,
"text": "Python3"
},
{
"code": "# Importing libraryimport matplotlib # Create figure() objects# This acts as a container# for the different plotsfig = matplotlib.pyplot.figure() # Creating axis# add_axes([xmin,ymin,dx,dy])axes = fig.add_axes([0.5, 1, 0.5, 1]) # Depict illustrationfig.show()",
"e": 1087,
"s": 824,
"text": null
},
{
"code": null,
"e": 1095,
"s": 1087,
"text": "Output:"
},
{
"code": null,
"e": 1106,
"s": 1095,
"text": "Example 2:"
},
{
"code": null,
"e": 1114,
"s": 1106,
"text": "Python3"
},
{
"code": "# Importing libraryimport matplotlib # Create figure() objects# This acts as a container # for the different plotsfig=matplotlib.pyplot.figure() # Creating two axes# add_axes([xmin,ymin,dx,dy])axes=fig.add_axes([0,0,2,2]) axes1=fig.add_axes([0,1,2,2]) # Depict illustrationfig.show()",
"e": 1402,
"s": 1114,
"text": null
},
{
"code": null,
"e": 1410,
"s": 1402,
"text": "Output:"
},
{
"code": null,
"e": 1421,
"s": 1410,
"text": "Example 3:"
},
{
"code": null,
"e": 1429,
"s": 1421,
"text": "Python3"
},
{
"code": "# Import librariesimport matplotlibimport numpy # Create figure() objects# This acts as a container# for the different plotsfig = matplotlib.pyplot.figure() # Generate line graphx = numpy.arange(0, 1.414*2, 0.05)y1 = numpy.sin(x)y2 = numpy.cos(x) # Creating two axes# add_axes([xmin,ymin,dx,dy])axes1 = fig.add_axes([0, 0, 1, 1])axes1.plot(x, y1)axes2 = fig.add_axes([0, 1, 1, 1])axes2.plot(x, y2) # Show plotplt.show()",
"e": 1853,
"s": 1429,
"text": null
},
{
"code": null,
"e": 1861,
"s": 1853,
"text": "Output:"
},
{
"code": null,
"e": 1879,
"s": 1861,
"text": "Python-matplotlib"
},
{
"code": null,
"e": 1886,
"s": 1879,
"text": "Python"
}
] |
How to Append Text to End of File in Linux? | 07 Mar, 2021
On Linux, while working with files in a terminal sometimes we need to append the same data of a command output or file content. Append means simply add the data to the file without erasing existing data. Today we are going to see how can we append the text in the file on the terminal.
The >> operator redirects output to a file. If the mentioned file doesnβt exist the file is created and then the text is appended to the file.
Examples:
We can use the echo command to append the text to the file, like
echo "Which is the best Linux Distro?" >> file.txt
Alternatively, we can use printf command to append text into a file.
printf "Which is the best Linux Distro?\n" >> file.txt
We can also use the cat command to append the content of one file to another file.
Example:
In this example, we have to append the content of file file1.txt to the file file2.txt
cat file1.txt >> file2.txt
Note: Donβt use > of >> This will erase the data of the target file. This may cause data loss.
The tee command copies the text from standard input and writes it to the standard output file. The tee provides -a option to append the text to the file.
echo "Which is the best Linux Distro?" | tee -a file.txt
We can also append the content of a file into another file using the tee command
Example:
In this example, we have to append the content of file file1.txt to the file file2.txt
cat file1.txt | tee -a file2.txt
This is how we append the text into a file in Linux.
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Docker - COPY Instruction
scp command in Linux with Examples
chown command in Linux with Examples
SED command in Linux | Set 2
nohup Command in Linux with Examples
mv command in Linux with examples
chmod command in Linux with examples
Array Basics in Shell Scripting | Set 1
Introduction to Linux Operating System
Basic Operators in Shell Scripting | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n07 Mar, 2021"
},
{
"code": null,
"e": 314,
"s": 28,
"text": "On Linux, while working with files in a terminal sometimes we need to append the same data of a command output or file content. Append means simply add the data to the file without erasing existing data. Today we are going to see how can we append the text in the file on the terminal."
},
{
"code": null,
"e": 457,
"s": 314,
"text": "The >> operator redirects output to a file. If the mentioned file doesnβt exist the file is created and then the text is appended to the file."
},
{
"code": null,
"e": 467,
"s": 457,
"text": "Examples:"
},
{
"code": null,
"e": 532,
"s": 467,
"text": "We can use the echo command to append the text to the file, like"
},
{
"code": null,
"e": 585,
"s": 532,
"text": "echo \"Which is the best Linux Distro?\" >> file.txt"
},
{
"code": null,
"e": 654,
"s": 585,
"text": "Alternatively, we can use printf command to append text into a file."
},
{
"code": null,
"e": 711,
"s": 654,
"text": "printf \"Which is the best Linux Distro?\\n\" >> file.txt"
},
{
"code": null,
"e": 794,
"s": 711,
"text": "We can also use the cat command to append the content of one file to another file."
},
{
"code": null,
"e": 803,
"s": 794,
"text": "Example:"
},
{
"code": null,
"e": 890,
"s": 803,
"text": "In this example, we have to append the content of file file1.txt to the file file2.txt"
},
{
"code": null,
"e": 917,
"s": 890,
"text": "cat file1.txt >> file2.txt"
},
{
"code": null,
"e": 1012,
"s": 917,
"text": "Note: Donβt use > of >> This will erase the data of the target file. This may cause data loss."
},
{
"code": null,
"e": 1166,
"s": 1012,
"text": "The tee command copies the text from standard input and writes it to the standard output file. The tee provides -a option to append the text to the file."
},
{
"code": null,
"e": 1225,
"s": 1166,
"text": "echo \"Which is the best Linux Distro?\" | tee -a file.txt"
},
{
"code": null,
"e": 1306,
"s": 1225,
"text": "We can also append the content of a file into another file using the tee command"
},
{
"code": null,
"e": 1315,
"s": 1306,
"text": "Example:"
},
{
"code": null,
"e": 1402,
"s": 1315,
"text": "In this example, we have to append the content of file file1.txt to the file file2.txt"
},
{
"code": null,
"e": 1435,
"s": 1402,
"text": "cat file1.txt | tee -a file2.txt"
},
{
"code": null,
"e": 1488,
"s": 1435,
"text": "This is how we append the text into a file in Linux."
},
{
"code": null,
"e": 1499,
"s": 1488,
"text": "Linux-Unix"
},
{
"code": null,
"e": 1597,
"s": 1499,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1623,
"s": 1597,
"text": "Docker - COPY Instruction"
},
{
"code": null,
"e": 1658,
"s": 1623,
"text": "scp command in Linux with Examples"
},
{
"code": null,
"e": 1695,
"s": 1658,
"text": "chown command in Linux with Examples"
},
{
"code": null,
"e": 1724,
"s": 1695,
"text": "SED command in Linux | Set 2"
},
{
"code": null,
"e": 1761,
"s": 1724,
"text": "nohup Command in Linux with Examples"
},
{
"code": null,
"e": 1795,
"s": 1761,
"text": "mv command in Linux with examples"
},
{
"code": null,
"e": 1832,
"s": 1795,
"text": "chmod command in Linux with examples"
},
{
"code": null,
"e": 1872,
"s": 1832,
"text": "Array Basics in Shell Scripting | Set 1"
},
{
"code": null,
"e": 1911,
"s": 1872,
"text": "Introduction to Linux Operating System"
}
] |
Buffer clear() methods in Java with Examples | 18 Jul, 2019
The clear() method of java.nio.ByteBuffer Class is used to clear this buffer. The position is set to zero, the limit is set to the capacity, and the mark is discarded. Invoke this method before using a sequence of channel-read or put operations to fill this buffer.
For example:
buf.clear(); // Prepare buffer for reading
in.read(buf); // Read data
This method does not actually erase the data in the buffer, but it is named as if it did because it will most often be used in situations in which that might as well be the case.
Syntax:
public Buffer clear()
Return Value: This method returns this buffer.
Below are the examples to illustrate the clear() method:
Examples 1:
// Java program to demonstrate// clear() method import java.nio.*;import java.util.*; public class GFG { public static void main(String[] args) { try { byte[] barr = { 10, 20, 30, 40 }; // creating object of ByteBuffer // and allocating size capacity ByteBuffer bb = ByteBuffer.wrap(barr); // Typecasting ByteBuffer into Buffer Buffer bb1 = (Buffer)bb; // try to set the position at index 2 bb1.position(2); // Set this buffer mark position // using mark() method bb1.mark(); // try to set the position at index 4 bb1.position(4); // display position System.out.println("position before reset: " + bb1.position()); // try to call clear() to restore // to the position at index 0 // by discarding the mark bb1.clear(); // display position System.out.println("position after reset: " + bb1.position()); } catch (InvalidMarkException e) { System.out.println("new position is less than " + "the position we marked before "); System.out.println("Exception throws: " + e); } }}
position before reset: 4
position after reset: 0
Examples 2:
// Java program to demonstrate// clear() method import java.nio.*;import java.util.*; public class GFG { public static void main(String[] args) { try { byte[] barr = { 10, 20, 30, 40 }; // creating object of ByteBuffer // and allocating size capacity ByteBuffer bb = ByteBuffer.wrap(barr); // Typecasting ByteBuffer into Buffer Buffer bb1 = (Buffer)bb; // try to set the position at index 2 bb1.position(3); // display position System.out.println("position before clear: " + bb1.position()); // try to call clear() to restore // to the position at index 0 // by discarding the mark bb1.clear(); // display position System.out.println("position after clear: " + bb1.position()); } catch (InvalidMarkException e) { System.out.println("new position is less than " + "the position we marked before "); System.out.println("Exception throws: " + e); } }}
position before clear: 3
position after clear: 0
Reference: https://docs.oracle.com/javase/9/docs/api/java/nio/Buffer.html#clearβ
Java-Buffer
Java-Functions
Java-NIO package
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Object Oriented Programming (OOPs) Concept in Java
How to iterate any Map in Java
Interfaces in Java
HashMap in Java with Examples
ArrayList in Java
Collections in Java
Multidimensional Arrays in Java
Stream In Java
Set in Java
Singleton Class in Java | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n18 Jul, 2019"
},
{
"code": null,
"e": 294,
"s": 28,
"text": "The clear() method of java.nio.ByteBuffer Class is used to clear this buffer. The position is set to zero, the limit is set to the capacity, and the mark is discarded. Invoke this method before using a sequence of channel-read or put operations to fill this buffer."
},
{
"code": null,
"e": 307,
"s": 294,
"text": "For example:"
},
{
"code": null,
"e": 387,
"s": 307,
"text": " \nbuf.clear(); // Prepare buffer for reading\nin.read(buf); // Read data\n"
},
{
"code": null,
"e": 566,
"s": 387,
"text": "This method does not actually erase the data in the buffer, but it is named as if it did because it will most often be used in situations in which that might as well be the case."
},
{
"code": null,
"e": 574,
"s": 566,
"text": "Syntax:"
},
{
"code": null,
"e": 596,
"s": 574,
"text": "public Buffer clear()"
},
{
"code": null,
"e": 643,
"s": 596,
"text": "Return Value: This method returns this buffer."
},
{
"code": null,
"e": 700,
"s": 643,
"text": "Below are the examples to illustrate the clear() method:"
},
{
"code": null,
"e": 712,
"s": 700,
"text": "Examples 1:"
},
{
"code": "// Java program to demonstrate// clear() method import java.nio.*;import java.util.*; public class GFG { public static void main(String[] args) { try { byte[] barr = { 10, 20, 30, 40 }; // creating object of ByteBuffer // and allocating size capacity ByteBuffer bb = ByteBuffer.wrap(barr); // Typecasting ByteBuffer into Buffer Buffer bb1 = (Buffer)bb; // try to set the position at index 2 bb1.position(2); // Set this buffer mark position // using mark() method bb1.mark(); // try to set the position at index 4 bb1.position(4); // display position System.out.println(\"position before reset: \" + bb1.position()); // try to call clear() to restore // to the position at index 0 // by discarding the mark bb1.clear(); // display position System.out.println(\"position after reset: \" + bb1.position()); } catch (InvalidMarkException e) { System.out.println(\"new position is less than \" + \"the position we marked before \"); System.out.println(\"Exception throws: \" + e); } }}",
"e": 2090,
"s": 712,
"text": null
},
{
"code": null,
"e": 2140,
"s": 2090,
"text": "position before reset: 4\nposition after reset: 0\n"
},
{
"code": null,
"e": 2152,
"s": 2140,
"text": "Examples 2:"
},
{
"code": "// Java program to demonstrate// clear() method import java.nio.*;import java.util.*; public class GFG { public static void main(String[] args) { try { byte[] barr = { 10, 20, 30, 40 }; // creating object of ByteBuffer // and allocating size capacity ByteBuffer bb = ByteBuffer.wrap(barr); // Typecasting ByteBuffer into Buffer Buffer bb1 = (Buffer)bb; // try to set the position at index 2 bb1.position(3); // display position System.out.println(\"position before clear: \" + bb1.position()); // try to call clear() to restore // to the position at index 0 // by discarding the mark bb1.clear(); // display position System.out.println(\"position after clear: \" + bb1.position()); } catch (InvalidMarkException e) { System.out.println(\"new position is less than \" + \"the position we marked before \"); System.out.println(\"Exception throws: \" + e); } }}",
"e": 3348,
"s": 2152,
"text": null
},
{
"code": null,
"e": 3398,
"s": 3348,
"text": "position before clear: 3\nposition after clear: 0\n"
},
{
"code": null,
"e": 3479,
"s": 3398,
"text": "Reference: https://docs.oracle.com/javase/9/docs/api/java/nio/Buffer.html#clearβ"
},
{
"code": null,
"e": 3491,
"s": 3479,
"text": "Java-Buffer"
},
{
"code": null,
"e": 3506,
"s": 3491,
"text": "Java-Functions"
},
{
"code": null,
"e": 3523,
"s": 3506,
"text": "Java-NIO package"
},
{
"code": null,
"e": 3528,
"s": 3523,
"text": "Java"
},
{
"code": null,
"e": 3533,
"s": 3528,
"text": "Java"
},
{
"code": null,
"e": 3631,
"s": 3533,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3682,
"s": 3631,
"text": "Object Oriented Programming (OOPs) Concept in Java"
},
{
"code": null,
"e": 3713,
"s": 3682,
"text": "How to iterate any Map in Java"
},
{
"code": null,
"e": 3732,
"s": 3713,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 3762,
"s": 3732,
"text": "HashMap in Java with Examples"
},
{
"code": null,
"e": 3780,
"s": 3762,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 3800,
"s": 3780,
"text": "Collections in Java"
},
{
"code": null,
"e": 3832,
"s": 3800,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 3847,
"s": 3832,
"text": "Stream In Java"
},
{
"code": null,
"e": 3859,
"s": 3847,
"text": "Set in Java"
}
] |
PHP - MySQL Login | This tutorial demonstrates how to create a login page with MySQL Data base. Before enter into the code part, You would need special privileges to create or to delete a MySQL database. So assuming you have access to root user, you can create any database using mysql mysqladmin binary.
Config.php file is having information about MySQL Data base configuration.
<?php
define('DB_SERVER', 'localhost:3036');
define('DB_USERNAME', 'root');
define('DB_PASSWORD', 'rootpassword');
define('DB_DATABASE', 'database');
$db = mysqli_connect(DB_SERVER,DB_USERNAME,DB_PASSWORD,DB_DATABASE);
?>
Login PHP is having information about php script and HTML script to do login.
<?php
include("config.php");
session_start();
if($_SERVER["REQUEST_METHOD"] == "POST") {
// username and password sent from form
$myusername = mysqli_real_escape_string($db,$_POST['username']);
$mypassword = mysqli_real_escape_string($db,$_POST['password']);
$sql = "SELECT id FROM admin WHERE username = '$myusername' and passcode = '$mypassword'";
$result = mysqli_query($db,$sql);
$row = mysqli_fetch_array($result,MYSQLI_ASSOC);
$active = $row['active'];
$count = mysqli_num_rows($result);
// If result matched $myusername and $mypassword, table row must be 1 row
if($count == 1) {
session_register("myusername");
$_SESSION['login_user'] = $myusername;
header("location: welcome.php");
}else {
$error = "Your Login Name or Password is invalid";
}
}
?>
<html>
<head>
<title>Login Page</title>
<style type = "text/css">
body {
font-family:Arial, Helvetica, sans-serif;
font-size:14px;
}
label {
font-weight:bold;
width:100px;
font-size:14px;
}
.box {
border:#666666 solid 1px;
}
</style>
</head>
<body bgcolor = "#FFFFFF">
<div align = "center">
<div style = "width:300px; border: solid 1px #333333; " align = "left">
<div style = "background-color:#333333; color:#FFFFFF; padding:3px;"><b>Login</b></div>
<div style = "margin:30px">
<form action = "" method = "post">
<label>UserName :</label><input type = "text" name = "username" class = "box"/><br /><br />
<label>Password :</label><input type = "password" name = "password" class = "box" /><br/><br />
<input type = "submit" value = " Submit "/><br />
</form>
<div style = "font-size:11px; color:#cc0000; margin-top:10px"><?php echo $error; ?></div>
</div>
</div>
</div>
</body>
</html>
After successful login, it will display welcome page.
<?php
include('session.php');
?>
<html">
<head>
<title>Welcome </title>
</head>
<body>
<h1>Welcome <?php echo $login_session; ?></h1>
<h2><a href = "logout.php">Sign Out</a></h2>
</body>
</html>
Logout page is having information about how to logout from login session.
<?php
session_start();
if(session_destroy()) {
header("Location: login.php");
}
?>
Session.php will verify the session, if there is no session it will redirect to login page.
<?php
include('config.php');
session_start();
$user_check = $_SESSION['login_user'];
$ses_sql = mysqli_query($db,"select username from admin where username = '$user_check' ");
$row = mysqli_fetch_array($ses_sql,MYSQLI_ASSOC);
$login_session = $row['username'];
if(!isset($_SESSION['login_user'])){
header("location:login.php");
die();
}
?>
45 Lectures
9 hours
Malhar Lathkar
34 Lectures
4 hours
Syed Raza
84 Lectures
5.5 hours
Frahaan Hussain
17 Lectures
1 hours
Nivedita Jain
100 Lectures
34 hours
Azaz Patel
43 Lectures
5.5 hours
Vijay Kumar Parvatha Reddy
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 3042,
"s": 2757,
"text": "This tutorial demonstrates how to create a login page with MySQL Data base. Before enter into the code part, You would need special privileges to create or to delete a MySQL database. So assuming you have access to root user, you can create any database using mysql mysqladmin binary."
},
{
"code": null,
"e": 3117,
"s": 3042,
"text": "Config.php file is having information about MySQL Data base configuration."
},
{
"code": null,
"e": 3354,
"s": 3117,
"text": "<?php\n define('DB_SERVER', 'localhost:3036');\n define('DB_USERNAME', 'root');\n define('DB_PASSWORD', 'rootpassword');\n define('DB_DATABASE', 'database');\n $db = mysqli_connect(DB_SERVER,DB_USERNAME,DB_PASSWORD,DB_DATABASE);\n?>"
},
{
"code": null,
"e": 3432,
"s": 3354,
"text": "Login PHP is having information about php script and HTML script to do login."
},
{
"code": null,
"e": 5643,
"s": 3432,
"text": "<?php\n include(\"config.php\");\n session_start();\n \n if($_SERVER[\"REQUEST_METHOD\"] == \"POST\") {\n // username and password sent from form \n \n $myusername = mysqli_real_escape_string($db,$_POST['username']);\n $mypassword = mysqli_real_escape_string($db,$_POST['password']); \n \n $sql = \"SELECT id FROM admin WHERE username = '$myusername' and passcode = '$mypassword'\";\n $result = mysqli_query($db,$sql);\n $row = mysqli_fetch_array($result,MYSQLI_ASSOC);\n $active = $row['active'];\n \n $count = mysqli_num_rows($result);\n \n // If result matched $myusername and $mypassword, table row must be 1 row\n\t\t\n if($count == 1) {\n session_register(\"myusername\");\n $_SESSION['login_user'] = $myusername;\n \n header(\"location: welcome.php\");\n }else {\n $error = \"Your Login Name or Password is invalid\";\n }\n }\n?>\n<html>\n \n <head>\n <title>Login Page</title>\n \n <style type = \"text/css\">\n body {\n font-family:Arial, Helvetica, sans-serif;\n font-size:14px;\n }\n label {\n font-weight:bold;\n width:100px;\n font-size:14px;\n }\n .box {\n border:#666666 solid 1px;\n }\n </style>\n \n </head>\n \n <body bgcolor = \"#FFFFFF\">\n\t\n <div align = \"center\">\n <div style = \"width:300px; border: solid 1px #333333; \" align = \"left\">\n <div style = \"background-color:#333333; color:#FFFFFF; padding:3px;\"><b>Login</b></div>\n\t\t\t\t\n <div style = \"margin:30px\">\n \n <form action = \"\" method = \"post\">\n <label>UserName :</label><input type = \"text\" name = \"username\" class = \"box\"/><br /><br />\n <label>Password :</label><input type = \"password\" name = \"password\" class = \"box\" /><br/><br />\n <input type = \"submit\" value = \" Submit \"/><br />\n </form>\n \n <div style = \"font-size:11px; color:#cc0000; margin-top:10px\"><?php echo $error; ?></div>\n\t\t\t\t\t\n </div>\n\t\t\t\t\n </div>\n\t\t\t\n </div>\n\n </body>\n</html>"
},
{
"code": null,
"e": 5697,
"s": 5643,
"text": "After successful login, it will display welcome page."
},
{
"code": null,
"e": 5938,
"s": 5697,
"text": "<?php\n include('session.php');\n?>\n<html\">\n \n <head>\n <title>Welcome </title>\n </head>\n \n <body>\n <h1>Welcome <?php echo $login_session; ?></h1> \n <h2><a href = \"logout.php\">Sign Out</a></h2>\n </body>\n \n</html>"
},
{
"code": null,
"e": 6012,
"s": 5938,
"text": "Logout page is having information about how to logout from login session."
},
{
"code": null,
"e": 6114,
"s": 6012,
"text": "<?php\n session_start();\n \n if(session_destroy()) {\n header(\"Location: login.php\");\n }\n?>"
},
{
"code": null,
"e": 6206,
"s": 6114,
"text": "Session.php will verify the session, if there is no session it will redirect to login page."
},
{
"code": null,
"e": 6602,
"s": 6206,
"text": "<?php\n include('config.php');\n session_start();\n \n $user_check = $_SESSION['login_user'];\n \n $ses_sql = mysqli_query($db,\"select username from admin where username = '$user_check' \");\n \n $row = mysqli_fetch_array($ses_sql,MYSQLI_ASSOC);\n \n $login_session = $row['username'];\n \n if(!isset($_SESSION['login_user'])){\n header(\"location:login.php\");\n die();\n }\n?>"
},
{
"code": null,
"e": 6635,
"s": 6602,
"text": "\n 45 Lectures \n 9 hours \n"
},
{
"code": null,
"e": 6651,
"s": 6635,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 6684,
"s": 6651,
"text": "\n 34 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 6695,
"s": 6684,
"text": " Syed Raza"
},
{
"code": null,
"e": 6730,
"s": 6695,
"text": "\n 84 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 6747,
"s": 6730,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 6780,
"s": 6747,
"text": "\n 17 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 6795,
"s": 6780,
"text": " Nivedita Jain"
},
{
"code": null,
"e": 6830,
"s": 6795,
"text": "\n 100 Lectures \n 34 hours \n"
},
{
"code": null,
"e": 6842,
"s": 6830,
"text": " Azaz Patel"
},
{
"code": null,
"e": 6877,
"s": 6842,
"text": "\n 43 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 6905,
"s": 6877,
"text": " Vijay Kumar Parvatha Reddy"
},
{
"code": null,
"e": 6912,
"s": 6905,
"text": " Print"
},
{
"code": null,
"e": 6923,
"s": 6912,
"text": " Add Notes"
}
] |
Program to find valid matrix given row and column sums in Python | Suppose we have two arrays rowSum and colSum with non-negative values where rowSum[i] has the sum of the elements in the ith row and colSum[j] has the sum of the elements in the jth column of a 2D matrix. We have to find any matrix with non-negative values of size (rowSum size x colSum size) that satisfies the given rowSum and colSum values.
So, if the input is like rowSum = [13,14,12] colSum = [9,13,17], then the output will be
To solve this, we will follow these steps β
matrix := create empty matrix
visited := a new set
Define a function minimum() . This will take r,c
min_total := infinity
type := blank string
for i in range 0 to size of r - 1, doif r[i] < min_total, thenindex := itype := 'row'min_total := r[i]
if r[i] < min_total, thenindex := itype := 'row'min_total := r[i]
index := i
type := 'row'
min_total := r[i]
for i in range 0 to size of c - 1, doif c[i] < min_total, thenmin_total := c[i]type := 'col'index := i
if c[i] < min_total, thenmin_total := c[i]type := 'col'index := i
min_total := c[i]
type := 'col'
index := i
if type is same as 'row', thenr[index] := infinityfor i in range 0 to size of c - 1, doif c[i] is not same as infinity and c[i] >= min_total, thenc[i] := c[i] - min_totalmatrix[index, i] := min_totalcome out from loop
r[index] := infinity
for i in range 0 to size of c - 1, doif c[i] is not same as infinity and c[i] >= min_total, thenc[i] := c[i] - min_totalmatrix[index, i] := min_totalcome out from loop
if c[i] is not same as infinity and c[i] >= min_total, thenc[i] := c[i] - min_totalmatrix[index, i] := min_totalcome out from loop
c[i] := c[i] - min_total
matrix[index, i] := min_total
come out from loop
if type is same as 'col', thenc[index] := infinityfor i in range 0 to size of r - 1, doif r[i] is not same as infinity and r[i] >= min_total, thenr[i] := r[i] - min_totalmatrix[i, index] := min_totalcome out from loop
c[index] := infinity
for i in range 0 to size of r - 1, doif r[i] is not same as infinity and r[i] >= min_total, thenr[i] := r[i] - min_totalmatrix[i, index] := min_totalcome out from loop
if r[i] is not same as infinity and r[i] >= min_total, thenr[i] := r[i] - min_totalmatrix[i, index] := min_totalcome out from loop
r[i] := r[i] - min_total
matrix[i, index] := min_total
come out from loop
insert pair (index,type) into visited
From the main method do the following β
while size of visited is not same as size of r +len(c) , do
minimum(r, c)
return matrix
Let us see the following implementation to get better understanding β
def solve(r, c):
matrix = [[0]*len(c) for _ in range(len(r))]
visited = set()
def minimum(r,c):
min_total = float('inf')
type = ''
for i in range(len(r)):
if(r[i] < min_total):
index = i
type = 'row'
min_total = r[i]
for i in range(len(c)):
if(c[i] < min_total):
min_total = c[i]
type = 'col'
index = i
if(type == 'row'):
r[index] = float('inf')
for i in range(len(c)):
if(c[i] != float('inf') and c[i] >= min_total):
c[i] -= min_total
matrix[index][i] = min_total
break
if(type == 'col'):
c[index] = float('inf')
for i in range(len(r)):
if(r[i] != float('inf') and r[i] >= min_total):
r[i] -= min_total
matrix[i][index] = min_total
break
visited.add((index,type))
while len(visited) != len(r)+len(c):
minimum(r,c)
return matrix
rowSum = [13,14,12]
colSum = [9,13,17]
print(solve(rowSum, colSum))
[13,14,12], [9,13,17]
[[9, 4, 0], [0, 9, 5], [0, 0, 12]] | [
{
"code": null,
"e": 1406,
"s": 1062,
"text": "Suppose we have two arrays rowSum and colSum with non-negative values where rowSum[i] has the sum of the elements in the ith row and colSum[j] has the sum of the elements in the jth column of a 2D matrix. We have to find any matrix with non-negative values of size (rowSum size x colSum size) that satisfies the given rowSum and colSum values."
},
{
"code": null,
"e": 1495,
"s": 1406,
"text": "So, if the input is like rowSum = [13,14,12] colSum = [9,13,17], then the output will be"
},
{
"code": null,
"e": 1539,
"s": 1495,
"text": "To solve this, we will follow these steps β"
},
{
"code": null,
"e": 1569,
"s": 1539,
"text": "matrix := create empty matrix"
},
{
"code": null,
"e": 1590,
"s": 1569,
"text": "visited := a new set"
},
{
"code": null,
"e": 1639,
"s": 1590,
"text": "Define a function minimum() . This will take r,c"
},
{
"code": null,
"e": 1661,
"s": 1639,
"text": "min_total := infinity"
},
{
"code": null,
"e": 1682,
"s": 1661,
"text": "type := blank string"
},
{
"code": null,
"e": 1785,
"s": 1682,
"text": "for i in range 0 to size of r - 1, doif r[i] < min_total, thenindex := itype := 'row'min_total := r[i]"
},
{
"code": null,
"e": 1851,
"s": 1785,
"text": "if r[i] < min_total, thenindex := itype := 'row'min_total := r[i]"
},
{
"code": null,
"e": 1862,
"s": 1851,
"text": "index := i"
},
{
"code": null,
"e": 1876,
"s": 1862,
"text": "type := 'row'"
},
{
"code": null,
"e": 1894,
"s": 1876,
"text": "min_total := r[i]"
},
{
"code": null,
"e": 1997,
"s": 1894,
"text": "for i in range 0 to size of c - 1, doif c[i] < min_total, thenmin_total := c[i]type := 'col'index := i"
},
{
"code": null,
"e": 2063,
"s": 1997,
"text": "if c[i] < min_total, thenmin_total := c[i]type := 'col'index := i"
},
{
"code": null,
"e": 2081,
"s": 2063,
"text": "min_total := c[i]"
},
{
"code": null,
"e": 2095,
"s": 2081,
"text": "type := 'col'"
},
{
"code": null,
"e": 2106,
"s": 2095,
"text": "index := i"
},
{
"code": null,
"e": 2324,
"s": 2106,
"text": "if type is same as 'row', thenr[index] := infinityfor i in range 0 to size of c - 1, doif c[i] is not same as infinity and c[i] >= min_total, thenc[i] := c[i] - min_totalmatrix[index, i] := min_totalcome out from loop"
},
{
"code": null,
"e": 2345,
"s": 2324,
"text": "r[index] := infinity"
},
{
"code": null,
"e": 2513,
"s": 2345,
"text": "for i in range 0 to size of c - 1, doif c[i] is not same as infinity and c[i] >= min_total, thenc[i] := c[i] - min_totalmatrix[index, i] := min_totalcome out from loop"
},
{
"code": null,
"e": 2644,
"s": 2513,
"text": "if c[i] is not same as infinity and c[i] >= min_total, thenc[i] := c[i] - min_totalmatrix[index, i] := min_totalcome out from loop"
},
{
"code": null,
"e": 2669,
"s": 2644,
"text": "c[i] := c[i] - min_total"
},
{
"code": null,
"e": 2699,
"s": 2669,
"text": "matrix[index, i] := min_total"
},
{
"code": null,
"e": 2718,
"s": 2699,
"text": "come out from loop"
},
{
"code": null,
"e": 2936,
"s": 2718,
"text": "if type is same as 'col', thenc[index] := infinityfor i in range 0 to size of r - 1, doif r[i] is not same as infinity and r[i] >= min_total, thenr[i] := r[i] - min_totalmatrix[i, index] := min_totalcome out from loop"
},
{
"code": null,
"e": 2957,
"s": 2936,
"text": "c[index] := infinity"
},
{
"code": null,
"e": 3125,
"s": 2957,
"text": "for i in range 0 to size of r - 1, doif r[i] is not same as infinity and r[i] >= min_total, thenr[i] := r[i] - min_totalmatrix[i, index] := min_totalcome out from loop"
},
{
"code": null,
"e": 3256,
"s": 3125,
"text": "if r[i] is not same as infinity and r[i] >= min_total, thenr[i] := r[i] - min_totalmatrix[i, index] := min_totalcome out from loop"
},
{
"code": null,
"e": 3281,
"s": 3256,
"text": "r[i] := r[i] - min_total"
},
{
"code": null,
"e": 3311,
"s": 3281,
"text": "matrix[i, index] := min_total"
},
{
"code": null,
"e": 3330,
"s": 3311,
"text": "come out from loop"
},
{
"code": null,
"e": 3368,
"s": 3330,
"text": "insert pair (index,type) into visited"
},
{
"code": null,
"e": 3408,
"s": 3368,
"text": "From the main method do the following β"
},
{
"code": null,
"e": 3468,
"s": 3408,
"text": "while size of visited is not same as size of r +len(c) , do"
},
{
"code": null,
"e": 3482,
"s": 3468,
"text": "minimum(r, c)"
},
{
"code": null,
"e": 3496,
"s": 3482,
"text": "return matrix"
},
{
"code": null,
"e": 3566,
"s": 3496,
"text": "Let us see the following implementation to get better understanding β"
},
{
"code": null,
"e": 4679,
"s": 3566,
"text": "def solve(r, c):\n matrix = [[0]*len(c) for _ in range(len(r))]\n visited = set()\n\n def minimum(r,c):\n min_total = float('inf')\n \n type = ''\n for i in range(len(r)):\n if(r[i] < min_total):\n index = i\n type = 'row'\n min_total = r[i]\n\n for i in range(len(c)):\n if(c[i] < min_total):\n min_total = c[i]\n type = 'col'\n index = i\n\n if(type == 'row'):\n r[index] = float('inf')\n\n for i in range(len(c)):\n if(c[i] != float('inf') and c[i] >= min_total):\n c[i] -= min_total\n matrix[index][i] = min_total\n break\n\n if(type == 'col'):\n c[index] = float('inf')\n for i in range(len(r)):\n if(r[i] != float('inf') and r[i] >= min_total):\n r[i] -= min_total\n matrix[i][index] = min_total\n break\n\n visited.add((index,type))\n\n while len(visited) != len(r)+len(c):\n minimum(r,c)\n\n return matrix\n\nrowSum = [13,14,12]\ncolSum = [9,13,17]\nprint(solve(rowSum, colSum))"
},
{
"code": null,
"e": 4701,
"s": 4679,
"text": "[13,14,12], [9,13,17]"
},
{
"code": null,
"e": 4736,
"s": 4701,
"text": "[[9, 4, 0], [0, 9, 5], [0, 0, 12]]"
}
] |
Program to find longest common prefix from list of strings in Python | Suppose we have a list of lowercase strings, we have to find the longest common prefix.
So, if the input is like ["antivirus", "anticlockwise", "antigravity"], then the output will be "anti"
To solve this, we will follow these steps β
sort the list words alphabetically
prefix := a new list
flag := 0
for i in range 0 to size of words[0], dofor each j in words, doif j[i] is not same as last element of prefix, thendelete last element from prefixflag := 1come out from the loopif flag is same as 1, thencome out from the loop
for each j in words, doif j[i] is not same as last element of prefix, thendelete last element from prefixflag := 1come out from the loop
if j[i] is not same as last element of prefix, thendelete last element from prefixflag := 1come out from the loop
delete last element from prefix
flag := 1
come out from the loop
if flag is same as 1, thencome out from the loop
come out from the loop
return string after concatenating all elements present in prefix array
Let us see the following implementation to get better understanding β
Live Demo
class Solution:
def solve(self, words):
words.sort()
prefix = []
flag = 0
for i in range(len(words[0])):
prefix.append(words[0][i])
for j in words:
if j[i] != prefix[-1]:
prefix.pop()
flag = 1
break
if flag == 1:
break
return ''.join(prefix)
ob = Solution()
words = ["antivirus", "anticlockwise", "antigravity"]
print(ob.solve(words))
["antivirus", "anticlockwise", "antigravity"]
anti | [
{
"code": null,
"e": 1150,
"s": 1062,
"text": "Suppose we have a list of lowercase strings, we have to find the longest common prefix."
},
{
"code": null,
"e": 1253,
"s": 1150,
"text": "So, if the input is like [\"antivirus\", \"anticlockwise\", \"antigravity\"], then the output will be \"anti\""
},
{
"code": null,
"e": 1297,
"s": 1253,
"text": "To solve this, we will follow these steps β"
},
{
"code": null,
"e": 1332,
"s": 1297,
"text": "sort the list words alphabetically"
},
{
"code": null,
"e": 1353,
"s": 1332,
"text": "prefix := a new list"
},
{
"code": null,
"e": 1363,
"s": 1353,
"text": "flag := 0"
},
{
"code": null,
"e": 1588,
"s": 1363,
"text": "for i in range 0 to size of words[0], dofor each j in words, doif j[i] is not same as last element of prefix, thendelete last element from prefixflag := 1come out from the loopif flag is same as 1, thencome out from the loop"
},
{
"code": null,
"e": 1725,
"s": 1588,
"text": "for each j in words, doif j[i] is not same as last element of prefix, thendelete last element from prefixflag := 1come out from the loop"
},
{
"code": null,
"e": 1839,
"s": 1725,
"text": "if j[i] is not same as last element of prefix, thendelete last element from prefixflag := 1come out from the loop"
},
{
"code": null,
"e": 1871,
"s": 1839,
"text": "delete last element from prefix"
},
{
"code": null,
"e": 1881,
"s": 1871,
"text": "flag := 1"
},
{
"code": null,
"e": 1904,
"s": 1881,
"text": "come out from the loop"
},
{
"code": null,
"e": 1953,
"s": 1904,
"text": "if flag is same as 1, thencome out from the loop"
},
{
"code": null,
"e": 1976,
"s": 1953,
"text": "come out from the loop"
},
{
"code": null,
"e": 2047,
"s": 1976,
"text": "return string after concatenating all elements present in prefix array"
},
{
"code": null,
"e": 2117,
"s": 2047,
"text": "Let us see the following implementation to get better understanding β"
},
{
"code": null,
"e": 2128,
"s": 2117,
"text": " Live Demo"
},
{
"code": null,
"e": 2595,
"s": 2128,
"text": "class Solution:\n def solve(self, words):\n words.sort()\n prefix = []\n flag = 0\n for i in range(len(words[0])):\n prefix.append(words[0][i])\n for j in words:\n if j[i] != prefix[-1]:\n prefix.pop()\n flag = 1\n break\n if flag == 1:\n break\n return ''.join(prefix)\nob = Solution()\nwords = [\"antivirus\", \"anticlockwise\", \"antigravity\"]\nprint(ob.solve(words))"
},
{
"code": null,
"e": 2641,
"s": 2595,
"text": "[\"antivirus\", \"anticlockwise\", \"antigravity\"]"
},
{
"code": null,
"e": 2646,
"s": 2641,
"text": "anti"
}
] |
How to preselect Dropdown Using JavaScript Programmatically? | To preselect a dropdown item using JavaScript, use the selectedIndex property. Add an index of what item you want to be selected.
Dropdown item list is created in HTML using the <select> tag. For JavaScript, we use the <script> tag. Here, under the <script> tag, add_select_id is the id of the <select> tag, whereas add_item_index is the index in numbers. This index is the list item index; you need to add for the item you want to be preselected.
You can try to run the following code to preselect dropdown using JavaScript programmatically β
Live Demo
<!DOCTYPE html>
<html>
<head>
<title>HTML select tag</title>
</head>
<body>
<p> Select any one:</p>
<form>
<select id="dropdown" name="dropdown" class="form-control">
<option value = "Android">Android</option>
<option value = "CSS">CSS</option>
<option value = "Python">Python</option>
</select>
</form>
<script>
document.getElementById("dropdown").selectedIndex = "1";
</script>
</body>
</html> | [
{
"code": null,
"e": 1192,
"s": 1062,
"text": "To preselect a dropdown item using JavaScript, use the selectedIndex property. Add an index of what item you want to be selected."
},
{
"code": null,
"e": 1510,
"s": 1192,
"text": "Dropdown item list is created in HTML using the <select> tag. For JavaScript, we use the <script> tag. Here, under the <script> tag, add_select_id is the id of the <select> tag, whereas add_item_index is the index in numbers. This index is the list item index; you need to add for the item you want to be preselected."
},
{
"code": null,
"e": 1606,
"s": 1510,
"text": "You can try to run the following code to preselect dropdown using JavaScript programmatically β"
},
{
"code": null,
"e": 1616,
"s": 1606,
"text": "Live Demo"
},
{
"code": null,
"e": 2123,
"s": 1616,
"text": "<!DOCTYPE html>\n<html>\n <head>\n <title>HTML select tag</title>\n </head>\n <body>\n <p> Select any one:</p>\n <form>\n <select id=\"dropdown\" name=\"dropdown\" class=\"form-control\">\n <option value = \"Android\">Android</option>\n <option value = \"CSS\">CSS</option>\n <option value = \"Python\">Python</option>\n </select>\n </form>\n <script>\n document.getElementById(\"dropdown\").selectedIndex = \"1\";\n </script>\n </body>\n</html>"
}
] |
Binary Search in C++ program? | binary search, also known as half-interval search, logarithmic search, or binary chop, is a search algorithm that finds the position of a target value within a sorted array. Binary search compares the target value to the middle element of the array. If they are not equal, the half in which the target cannot lie is eliminated and the search continues on the remaining half, again taking the middle element to compare to the target value, and repeating this until the target value is found. If the search ends with the remaining half being empty, the target is not in the array. Even though the idea is simple, implementing binary search correctly requires attention to some subtleties about its exit conditions and midpoint calculation, particularly if the values in the array are not all of the whole numbers in the range.
Binary search is the most popular search algorithm. It is efficient and also one of the most commonly used techniques that are used to solve problems.
If all the names in the world are written down together in order and you want to search for the position of a specific name, binary search will accomplish this in a maximum of 35 iterations.
Binary search works only on a sorted set of elements. To use binary search on a collection, the collection must first be sorted.
When a binary search is used to perform operations on a sorted set, the number of iterations can always be reduced on the basis of the value that is being searched.
Let us consider the following array β
By using a linear search, the position of element 8 will be determined in the 9th iteration.
Let's see how the number of iterations can be reduced by using a binary search. Before we start the search, we need to know the start and end of the range. Let's call them Low and High.
Low = 0
High = n-1
Now, compare the search value K with the element located at the median of the lower and upper bounds. If the value K is greater, increase the lower bound, else decrease the upper bound.
Referring to the image above, the lower bound is 0 and the upper bound is
9
The median of the lower and upper bounds is (lower_bound + upper_bound) / 2 = 4. Here a[4] = 4. The value 4>2, which is the value that you are searching for. Therefore, we do not need to conduct a search on any element beyond 4 as the elements beyond it will obviously be greater than 2.
Therefore, we can always drop the upper bound of the array to the position of element 4. Now, we follow the same procedure on the same array with the following values β
Low: 0
High: 3
Repeat this procedure recursively until Low > High. If at any iteration, we get a[mid]=key, we return value of mid. This is the position of key in the array. If key is not present in the array, we return β1.
int binarySearch(int low,int high,int key){
while(low<=high){
int mid=(low+high)/2;
if(a[mid]<key){
low=mid+1;
}
else if(a[mid]>key){
high=mid-1;
}
else{
return mid;
}
}
return -1; //key not found
} | [
{
"code": null,
"e": 1887,
"s": 1062,
"text": "binary search, also known as half-interval search, logarithmic search, or binary chop, is a search algorithm that finds the position of a target value within a sorted array. Binary search compares the target value to the middle element of the array. If they are not equal, the half in which the target cannot lie is eliminated and the search continues on the remaining half, again taking the middle element to compare to the target value, and repeating this until the target value is found. If the search ends with the remaining half being empty, the target is not in the array. Even though the idea is simple, implementing binary search correctly requires attention to some subtleties about its exit conditions and midpoint calculation, particularly if the values in the array are not all of the whole numbers in the range."
},
{
"code": null,
"e": 2038,
"s": 1887,
"text": "Binary search is the most popular search algorithm. It is efficient and also one of the most commonly used techniques that are used to solve problems."
},
{
"code": null,
"e": 2229,
"s": 2038,
"text": "If all the names in the world are written down together in order and you want to search for the position of a specific name, binary search will accomplish this in a maximum of 35 iterations."
},
{
"code": null,
"e": 2358,
"s": 2229,
"text": "Binary search works only on a sorted set of elements. To use binary search on a collection, the collection must first be sorted."
},
{
"code": null,
"e": 2523,
"s": 2358,
"text": "When a binary search is used to perform operations on a sorted set, the number of iterations can always be reduced on the basis of the value that is being searched."
},
{
"code": null,
"e": 2561,
"s": 2523,
"text": "Let us consider the following array β"
},
{
"code": null,
"e": 2654,
"s": 2561,
"text": "By using a linear search, the position of element 8 will be determined in the 9th iteration."
},
{
"code": null,
"e": 2840,
"s": 2654,
"text": "Let's see how the number of iterations can be reduced by using a binary search. Before we start the search, we need to know the start and end of the range. Let's call them Low and High."
},
{
"code": null,
"e": 2859,
"s": 2840,
"text": "Low = 0\nHigh = n-1"
},
{
"code": null,
"e": 3045,
"s": 2859,
"text": "Now, compare the search value K with the element located at the median of the lower and upper bounds. If the value K is greater, increase the lower bound, else decrease the upper bound."
},
{
"code": null,
"e": 3121,
"s": 3045,
"text": "Referring to the image above, the lower bound is 0 and the upper bound is\n9"
},
{
"code": null,
"e": 3409,
"s": 3121,
"text": "The median of the lower and upper bounds is (lower_bound + upper_bound) / 2 = 4. Here a[4] = 4. The value 4>2, which is the value that you are searching for. Therefore, we do not need to conduct a search on any element beyond 4 as the elements beyond it will obviously be greater than 2."
},
{
"code": null,
"e": 3578,
"s": 3409,
"text": "Therefore, we can always drop the upper bound of the array to the position of element 4. Now, we follow the same procedure on the same array with the following values β"
},
{
"code": null,
"e": 3593,
"s": 3578,
"text": "Low: 0\nHigh: 3"
},
{
"code": null,
"e": 3801,
"s": 3593,
"text": "Repeat this procedure recursively until Low > High. If at any iteration, we get a[mid]=key, we return value of mid. This is the position of key in the array. If key is not present in the array, we return β1."
},
{
"code": null,
"e": 4078,
"s": 3801,
"text": "int binarySearch(int low,int high,int key){\n while(low<=high){\n int mid=(low+high)/2;\n if(a[mid]<key){\n low=mid+1;\n }\n else if(a[mid]>key){\n high=mid-1;\n }\n else{\n return mid;\n }\n }\n return -1; //key not found\n}"
}
] |
DHTML JavaScript - GeeksforGeeks | 03 Dec, 2018
DHTML stands for Dynamic HTML. Dynamic means that the content of the web page can be customized or changed according to user inputs i.e. a page that is interactive with the user. In earlier times, HTML was used to create a static page. It only defined the structure of the content that was displayed on the page. With the help of CSS, we can beautify the HTML page by changing various properties like text size, background color etc. The HTML and CSS could manage to navigate between static pages but couldnβt do anything else. If 1000 users view a page that had their information for eg. Admit card then there was a problem because 1000 static pages for this application build to work. As the number of users increase, the problem also increases and at some point it becomes impossible to handle this problem.
To overcome this problem, DHTML came into existence. DHTML included JavaScript along with HTML and CSS to make the page dynamic. This combo made the web pages dynamic and eliminated this problem of creating static page for each user. To integrate JavaScript into HTML, a Document Object Model(DOM) is made for the HTML document. In DOM, the document is represented as nodes and objects which are accessed by different languages like JavaScript to manipulate the document.
HTML document include JavaScript:: The JavaScript document is included in our html page using the html tag. <src> tag is used to specify the source of external JavaScript file.Following are some of the tasks that can be performed with JavaScript:
Performing html tasks
Performing CSS tasks
Handling events
Validating inputs
Example 1: Example to understand how to use JavaScript in DHTML.
<html> <head> <title>DOM programming</title> </head> <body> <h1>GeeksforGeeks</h1> <p id = "geeks">Hello Geeks!</p> <script style = "text/javascript"> document.getElementById("geeks").innerHTML = "A computer science portal for geeks"; </script> </body></html>
Output:Explanation: In the above example, change the text of paragraph which using id. Document is an object of html that is displayed in the current window or object of DOM. The getElementById(id) gives the element id. The innerHTML defines the content within the id element. The id attribute is used to change HTML document and its property. Paragraph content changed by document id. For example: document.getElementById(βgeeksβ).style.color = βblueβ; It is used to set the paragraph color using id of elements.
Example 2: Creating an alert on click of a button.
<html> <head> <title>Create an alert</title> </head> <body> <h1 id = "para1">GeeksforGeeks</h1> <input type = "Submit" onclick = "Click()"/> <script style = "text/javascript"> function Click() { document.getElementById("para1").style.color = "#009900"; window.alert("Color changed to green"); } </script> </body></html>
Output:Explanation: In this example, creating a function that will be invoked on click of a button and it changes the color of text and display the alert on the screen. window is an object of current window whose inbuilt method alert() is invoked in Click() function.
Example 3: Validate input data using JavaScript.
<html> <head> <title>Validate input data</title> </head> <body> <p>Enter graduation percentage:</p> <input id="perc"> <button type="button" onclick="Validate()">Submit</button> <p id="demo"></p> <script> function Validate() { var x, text; x = document.getElementById("perc").value; if (isNaN(x) || x < 60) { window.alert("Not selected in GeeksforGeeks"); } else { document.getElementById("demo").innerHTML = "Selected: Welcome to GeeksforGeeks"; document.getElementById("demo").style.color = "#009900"; } } </script> </body></html>
Output:Explanation: In this example, make a validate() function which ensures the user is illegible or not. If user enters > 60 then selected otherwise not selected.
Attention reader! Donβt stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course.
HTML-Misc
javascript-basics
Picked
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
How to set the default value for an HTML <select> element ?
How to update Node.js and NPM to next version ?
How to set input type date in dd-mm-yyyy format using HTML ?
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS? | [
{
"code": null,
"e": 23885,
"s": 23857,
"text": "\n03 Dec, 2018"
},
{
"code": null,
"e": 24696,
"s": 23885,
"text": "DHTML stands for Dynamic HTML. Dynamic means that the content of the web page can be customized or changed according to user inputs i.e. a page that is interactive with the user. In earlier times, HTML was used to create a static page. It only defined the structure of the content that was displayed on the page. With the help of CSS, we can beautify the HTML page by changing various properties like text size, background color etc. The HTML and CSS could manage to navigate between static pages but couldnβt do anything else. If 1000 users view a page that had their information for eg. Admit card then there was a problem because 1000 static pages for this application build to work. As the number of users increase, the problem also increases and at some point it becomes impossible to handle this problem."
},
{
"code": null,
"e": 25168,
"s": 24696,
"text": "To overcome this problem, DHTML came into existence. DHTML included JavaScript along with HTML and CSS to make the page dynamic. This combo made the web pages dynamic and eliminated this problem of creating static page for each user. To integrate JavaScript into HTML, a Document Object Model(DOM) is made for the HTML document. In DOM, the document is represented as nodes and objects which are accessed by different languages like JavaScript to manipulate the document."
},
{
"code": null,
"e": 25415,
"s": 25168,
"text": "HTML document include JavaScript:: The JavaScript document is included in our html page using the html tag. <src> tag is used to specify the source of external JavaScript file.Following are some of the tasks that can be performed with JavaScript:"
},
{
"code": null,
"e": 25437,
"s": 25415,
"text": "Performing html tasks"
},
{
"code": null,
"e": 25458,
"s": 25437,
"text": "Performing CSS tasks"
},
{
"code": null,
"e": 25474,
"s": 25458,
"text": "Handling events"
},
{
"code": null,
"e": 25492,
"s": 25474,
"text": "Validating inputs"
},
{
"code": null,
"e": 25557,
"s": 25492,
"text": "Example 1: Example to understand how to use JavaScript in DHTML."
},
{
"code": "<html> <head> <title>DOM programming</title> </head> <body> <h1>GeeksforGeeks</h1> <p id = \"geeks\">Hello Geeks!</p> <script style = \"text/javascript\"> document.getElementById(\"geeks\").innerHTML = \"A computer science portal for geeks\"; </script> </body></html> ",
"e": 25911,
"s": 25557,
"text": null
},
{
"code": null,
"e": 26425,
"s": 25911,
"text": "Output:Explanation: In the above example, change the text of paragraph which using id. Document is an object of html that is displayed in the current window or object of DOM. The getElementById(id) gives the element id. The innerHTML defines the content within the id element. The id attribute is used to change HTML document and its property. Paragraph content changed by document id. For example: document.getElementById(βgeeksβ).style.color = βblueβ; It is used to set the paragraph color using id of elements."
},
{
"code": null,
"e": 26476,
"s": 26425,
"text": "Example 2: Creating an alert on click of a button."
},
{
"code": "<html> <head> <title>Create an alert</title> </head> <body> <h1 id = \"para1\">GeeksforGeeks</h1> <input type = \"Submit\" onclick = \"Click()\"/> <script style = \"text/javascript\"> function Click() { document.getElementById(\"para1\").style.color = \"#009900\"; window.alert(\"Color changed to green\"); } </script> </body></html> ",
"e": 26921,
"s": 26476,
"text": null
},
{
"code": null,
"e": 27189,
"s": 26921,
"text": "Output:Explanation: In this example, creating a function that will be invoked on click of a button and it changes the color of text and display the alert on the screen. window is an object of current window whose inbuilt method alert() is invoked in Click() function."
},
{
"code": null,
"e": 27238,
"s": 27189,
"text": "Example 3: Validate input data using JavaScript."
},
{
"code": "<html> <head> <title>Validate input data</title> </head> <body> <p>Enter graduation percentage:</p> <input id=\"perc\"> <button type=\"button\" onclick=\"Validate()\">Submit</button> <p id=\"demo\"></p> <script> function Validate() { var x, text; x = document.getElementById(\"perc\").value; if (isNaN(x) || x < 60) { window.alert(\"Not selected in GeeksforGeeks\"); } else { document.getElementById(\"demo\").innerHTML = \"Selected: Welcome to GeeksforGeeks\"; document.getElementById(\"demo\").style.color = \"#009900\"; } } </script> </body></html> ",
"e": 28033,
"s": 27238,
"text": null
},
{
"code": null,
"e": 28199,
"s": 28033,
"text": "Output:Explanation: In this example, make a validate() function which ensures the user is illegible or not. If user enters > 60 then selected otherwise not selected."
},
{
"code": null,
"e": 28336,
"s": 28199,
"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": 28346,
"s": 28336,
"text": "HTML-Misc"
},
{
"code": null,
"e": 28364,
"s": 28346,
"text": "javascript-basics"
},
{
"code": null,
"e": 28371,
"s": 28364,
"text": "Picked"
},
{
"code": null,
"e": 28376,
"s": 28371,
"text": "HTML"
},
{
"code": null,
"e": 28393,
"s": 28376,
"text": "Web Technologies"
},
{
"code": null,
"e": 28398,
"s": 28393,
"text": "HTML"
},
{
"code": null,
"e": 28496,
"s": 28398,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28505,
"s": 28496,
"text": "Comments"
},
{
"code": null,
"e": 28518,
"s": 28505,
"text": "Old Comments"
},
{
"code": null,
"e": 28580,
"s": 28518,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 28630,
"s": 28580,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
},
{
"code": null,
"e": 28690,
"s": 28630,
"text": "How to set the default value for an HTML <select> element ?"
},
{
"code": null,
"e": 28738,
"s": 28690,
"text": "How to update Node.js and NPM to next version ?"
},
{
"code": null,
"e": 28799,
"s": 28738,
"text": "How to set input type date in dd-mm-yyyy format using HTML ?"
},
{
"code": null,
"e": 28841,
"s": 28799,
"text": "Roadmap to Become a Web Developer in 2022"
},
{
"code": null,
"e": 28874,
"s": 28841,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 28936,
"s": 28874,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 28979,
"s": 28936,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
Understanding Scope & Lifetime of Variables - onlinetutorialspoint | PROGRAMMINGJava ExamplesC Examples
Java Examples
C Examples
C Tutorials
aws
JAVAEXCEPTIONSCOLLECTIONSSWINGJDBC
EXCEPTIONS
COLLECTIONS
SWING
JDBC
JAVA 8
SPRING
SPRING BOOT
HIBERNATE
PYTHON
PHP
JQUERY
PROGRAMMINGJava ExamplesC Examples
Java Examples
C Examples
C Tutorials
aws
In this tutorial, we are going to learn about different storage classes, scope and lifetime of variables.
In C language, each variable has a storage class which decides scope and lifetime of that variable. The storage class of a variable determines whether the variable has a global or local scope and lifetime or A Storage Class defines the scope (visibility) and life-time of variables and/or functions within a βCβ program.
All variables defined in a C program are allocated some physical location in memory where the variableβs value is stored. Memory and CPU registers are examples of memory locations where a variableβs value can be stored.
Storage classes provide the following information:
Where the variable would be stored.
What will be the initial value of the variable; i.e., the default value for the variable.
What is the scope of the variable; i.e., if the variable is accessible globally or is local to a function.
What is the life of the variable; i.e., how long would the variable exist in memory.
A keyword which specifies the storage class(auto, register, extern and static).
The scope determines the parts of a program in which a variable is available for use.
The lifetime refers to the period during which a variable retains a given value during execution of the program. It is also referred to as longevity.
There are four storage class specifiers in C language, they are:
auto
extern
static
register
The general form of a variable declaration that uses a storage class is:
storage_class_specifier data_type variable_name;
At most one storage_class_specifier may be given in a declaration. If no storage_class_specifier is specified then the following rules are used:
Variables declared inside a function are taken to be auto.
Variables declared outside a function are taken to be global.
Automatic variables are declared inside a block/function in which they are to be utilized.
These variables are created when a function is called and destroyed automatically when a function is exited.
Automatic variables are private to the function where they are declared. Because of this property, automatic variables are also referred to as local or internal variables.
A variable declared inside a function without any storage class specification is by default an automatic variable.
Auto variables can be only accessed within the block/function they have been declared and not outside them.
We seldom use the auto keyword in declarations because all block-scoped variables which are not explicitly declared with other storage classes are implicitly auto.
The format for specifying the automatic variables are:
auto data_type variable_1, variable_2,..., variable_n;
Some of the important points regarding auto variables are:
Storage: CPU memory
Initial value: undefined (can be any value)
Keyword: auto
Scope: local to the block in which it is defined
Lifetime: till control remains within the block in which
it is defined
Consider the following code:
#include <stdio.h>
void main( ) {
auto int i = 9;
{
auto int i = 99;
{
auto int i = 999;
printf("Third inner block value = %d\n", i);
}
printf("Second inner block value = %d\n", i);
}
printf("First block value = %d\n", i);
}
Output:
Third inner block value = 999
Second inner block value = 99
First block value = 9
In the above code, you can see three definitions for variable i. Here, there will be no error and the program will compile and execute successfully.
When the code executes, first the printf in the innermost block will print 999 and the variable i defined in the innermost block will no longer be visible as soon as control exits from the block.
Later, the control enters into the second outer block and prints 99 and later the control enters into the outermost block and prints 9.
Note: automatic variables must always be initialized properly, otherwise you are likely to get unexpected results because automatic variables are not given an initial value by default.
Variables that are declared outside a function are by default global variables. Unlike the local variables, global variables are visible in all functions in that program. Any function can use and also change its value.
Let us consider the below example:
void main() {
int y = 4;
y = y + x; // Compiler flags this as an error
...
}
int x = 5;
void function1() {
x = x + 10;
printf ("%d", x);
}
Even though the variable declaration int x; outside the main() function is a valid global declaration, since the compiler scans from the top of the file, when it reaches the statement y = y + x;, it raises an error saying the variable x is not declared before its usage.
One solution is to move the declaration int x; above the main() function. The second solution is to declare the variable before it is used inside the main method with the keyword extern, as extern int x;.
The extern keyword used before the variable informs the compiler that this variable is declared somewhere else globally and that it has to refer to it. The extern declaration does not allocate storage space for variables because it is only trying to refer to the already declared global variable.
For this reason, we cannot initialize the variable in the extern declaration. A normal global variable can be made extern when it is being used much before its declaration.
The format for specifying the external variables is
extern data_type variable_1, variable_2,..., variable_n;
Some of the important points regarding extern variables are:
Storage: Memory
Initial value: zero (0)
Keyword: extern
Scope: entire program
Lifetime: throughout the program execution
Auto variables are stored in memory. CPU also has a small storage area called registers which are used for quick storage and retrieval. In C, we can suggest the compiler store certain variables in the CPU registers by specifying them with the storage class register. Apart from their physical storage location, register variables follow the same rules of scope as automatic variables.
The syntax for declaring register variables is
register data_type variable_1;
There may be some special cases when we want some frequently accessed variables to be stored in registers to increase the performance of the program. In such cases, we use the register storage class while declaring the variable.
It should be noted that there is no guarantee that these variables will always be stored in registers. When there isnβt enough space in registers, they will be stored in the memory along with other auto variables.
Care should be taken that we do not specify too many variables as register variables, as it may even degrade the performance. If there are too many, the CPU might end up spending too much time moving data back and forth between registers and temporary storage area, if there are not enough registers to hold all such variables.
Ideally, registers should be used only when one has good knowledge of the compiler and computer architecture being used.
A few points regarding register variables are given below:
Storage: CPU registers
Initial value: garbage value
Keyword: register
Scope: local to the block in which it is defined
Lifetime: till control remains within the block in which
it is defined
A variable can be declared as a static variable by using the keyword static. Auto variables are created each time they are initialized in a block and are destroyed when they go out of scope. However, static variables are initialized only once and they remain in existence till the end of the program.
A static variable can either be local (to a function) or global. The format for specifying static variables is
static data_type variable_1, variable_2,..., variable_n;
The static variables which are declared inside a function are stored in the statically allocated memory and remain alive throughout the execution of the program, but remember that their scope remains local to the function. The main difference between auto and static is that the static variables do not disappear when the function is no longer active (in scope) and their values persist across multiple calls of the same function.
Some of the important points regarding static variables are:
Storage: Memory
Initial value: zero (0)
Keyword: static
Scope: local to the block in which it is defined
Lifetime: throughout the program execution
Wiki β Scope
C- Variables and Keywords
Happy Learning π
PHP Variables Example Tutorials
Variables & Keywords in C Language
Dynamic Memory Allocation in C
Understanding the structure of a C Program
User defined Functions in C
C β Derived and User Defined Data Types
Functions in C
C β One Dimensional Arrays
Java Static Variable Method Block Class Example
Java variable types Example
C Multi Dimensional Arrays
PHP Functions Example Tutorials
Try with Resources Example in Java
C β Integer Data Types β int, short int, long int and char
PHP Superglobals Example Tutorials
PHP Variables Example Tutorials
Variables & Keywords in C Language
Dynamic Memory Allocation in C
Understanding the structure of a C Program
User defined Functions in C
C β Derived and User Defined Data Types
Functions in C
C β One Dimensional Arrays
Java Static Variable Method Block Class Example
Java variable types Example
C Multi Dimensional Arrays
PHP Functions Example Tutorials
Try with Resources Example in Java
C β Integer Data Types β int, short int, long int and char
PHP Superglobals Example Tutorials
Ξ
C β Introduction
C β Features
C β Variables & Keywords
C β Program Structure
C β Comment Lines & Tokens
C β Number System
C β Local and Global Variables
C β Scope & Lifetime of Variables
C β Data Types
C β Integer Data Types
C β Floating Data Types
C β Derived, Defined Data Types
C β Type Conversions
C β Arithmetic Operators
C β Bitwise Operators
C β Logical Operators
C β Comma and sizeof Operators
C β Operator Precedence and Associativity
C β Relational Operators
C Flow Control β if, if-else, nested if-else, if-else-if
C β Switch Case
C Iterative β for, while, dowhile loops
C Unconditional β break, continue, goto statements
C β Expressions and Statements
C β Header Files & Preprocessor Directives
C β One Dimensional Arrays
C β Multi Dimensional Arrays
C β Pointers Basics
C β Pointers with Arrays
C β Functions
C β How to Pass Arrays to Functions
C β Categories of Functions
C β User defined Functions
C β Formal and Actual Arguments
C β Recursion functions
C β Structures Part -1
C β Structures Part -2
C β Unions
C β File Handling
C β File Operations
C β Dynamic Memory Allocation
C Program β Fibonacci Series
C Program β Prime or Not
C Program β Factorial of Number
C Program β Even or Odd
C Program β Sum of digits till Single Digit
C Program β Sum of digits
C Program β Reverse of a number
C Program β Armstrong Numbers
C Program β Print prime Numbers
C Program β GCD of two Numbers
C Program β Number Palindrome or Not
C Program β Find Largest and Smallest number in an Array
C Program β Add elements of an Array
C Program β Addition of Matrices
C Program β Multiplication of Matrices
C Program β Reverse of an Array
C Program β Bubble Sort
C Program β Add and Sub without using + β | [
{
"code": null,
"e": 158,
"s": 123,
"text": "PROGRAMMINGJava ExamplesC Examples"
},
{
"code": null,
"e": 172,
"s": 158,
"text": "Java Examples"
},
{
"code": null,
"e": 183,
"s": 172,
"text": "C Examples"
},
{
"code": null,
"e": 195,
"s": 183,
"text": "C Tutorials"
},
{
"code": null,
"e": 199,
"s": 195,
"text": "aws"
},
{
"code": null,
"e": 234,
"s": 199,
"text": "JAVAEXCEPTIONSCOLLECTIONSSWINGJDBC"
},
{
"code": null,
"e": 245,
"s": 234,
"text": "EXCEPTIONS"
},
{
"code": null,
"e": 257,
"s": 245,
"text": "COLLECTIONS"
},
{
"code": null,
"e": 263,
"s": 257,
"text": "SWING"
},
{
"code": null,
"e": 268,
"s": 263,
"text": "JDBC"
},
{
"code": null,
"e": 275,
"s": 268,
"text": "JAVA 8"
},
{
"code": null,
"e": 282,
"s": 275,
"text": "SPRING"
},
{
"code": null,
"e": 294,
"s": 282,
"text": "SPRING BOOT"
},
{
"code": null,
"e": 304,
"s": 294,
"text": "HIBERNATE"
},
{
"code": null,
"e": 311,
"s": 304,
"text": "PYTHON"
},
{
"code": null,
"e": 315,
"s": 311,
"text": "PHP"
},
{
"code": null,
"e": 322,
"s": 315,
"text": "JQUERY"
},
{
"code": null,
"e": 357,
"s": 322,
"text": "PROGRAMMINGJava ExamplesC Examples"
},
{
"code": null,
"e": 371,
"s": 357,
"text": "Java Examples"
},
{
"code": null,
"e": 382,
"s": 371,
"text": "C Examples"
},
{
"code": null,
"e": 394,
"s": 382,
"text": "C Tutorials"
},
{
"code": null,
"e": 398,
"s": 394,
"text": "aws"
},
{
"code": null,
"e": 504,
"s": 398,
"text": "In this tutorial, we are going to learn about different storage classes, scope and lifetime of variables."
},
{
"code": null,
"e": 825,
"s": 504,
"text": "In C language, each variable has a storage class which decides scope and lifetime of that variable. The storage class of a variable determines whether the variable has a global or local scope and lifetime or A Storage Class defines the scope (visibility) and life-time of variables and/or functions within a βCβ program."
},
{
"code": null,
"e": 1045,
"s": 825,
"text": "All variables defined in a C program are allocated some physical location in memory where the variableβs value is stored. Memory and CPU registers are examples of memory locations where a variableβs value can be stored."
},
{
"code": null,
"e": 1096,
"s": 1045,
"text": "Storage classes provide the following information:"
},
{
"code": null,
"e": 1132,
"s": 1096,
"text": "Where the variable would be stored."
},
{
"code": null,
"e": 1222,
"s": 1132,
"text": "What will be the initial value of the variable; i.e., the default value for the variable."
},
{
"code": null,
"e": 1329,
"s": 1222,
"text": "What is the scope of the variable; i.e., if the variable is accessible globally or is local to a function."
},
{
"code": null,
"e": 1414,
"s": 1329,
"text": "What is the life of the variable; i.e., how long would the variable exist in memory."
},
{
"code": null,
"e": 1494,
"s": 1414,
"text": "A keyword which specifies the storage class(auto, register, extern and static)."
},
{
"code": null,
"e": 1580,
"s": 1494,
"text": "The scope determines the parts of a program in which a variable is available for use."
},
{
"code": null,
"e": 1730,
"s": 1580,
"text": "The lifetime refers to the period during which a variable retains a given value during execution of the program. It is also referred to as longevity."
},
{
"code": null,
"e": 1795,
"s": 1730,
"text": "There are four storage class specifiers in C language, they are:"
},
{
"code": null,
"e": 1800,
"s": 1795,
"text": "auto"
},
{
"code": null,
"e": 1807,
"s": 1800,
"text": "extern"
},
{
"code": null,
"e": 1814,
"s": 1807,
"text": "static"
},
{
"code": null,
"e": 1823,
"s": 1814,
"text": "register"
},
{
"code": null,
"e": 1896,
"s": 1823,
"text": "The general form of a variable declaration that uses a storage class is:"
},
{
"code": null,
"e": 1945,
"s": 1896,
"text": "storage_class_specifier data_type variable_name;"
},
{
"code": null,
"e": 2090,
"s": 1945,
"text": "At most one storage_class_specifier may be given in a declaration. If no storage_class_specifier is specified then the following rules are used:"
},
{
"code": null,
"e": 2149,
"s": 2090,
"text": "Variables declared inside a function are taken to be auto."
},
{
"code": null,
"e": 2211,
"s": 2149,
"text": "Variables declared outside a function are taken to be global."
},
{
"code": null,
"e": 2302,
"s": 2211,
"text": "Automatic variables are declared inside a block/function in which they are to be utilized."
},
{
"code": null,
"e": 2411,
"s": 2302,
"text": "These variables are created when a function is called and destroyed automatically when a function is exited."
},
{
"code": null,
"e": 2583,
"s": 2411,
"text": "Automatic variables are private to the function where they are declared. Because of this property, automatic variables are also referred to as local or internal variables."
},
{
"code": null,
"e": 2698,
"s": 2583,
"text": "A variable declared inside a function without any storage class specification is by default an automatic variable."
},
{
"code": null,
"e": 2806,
"s": 2698,
"text": "Auto variables can be only accessed within the block/function they have been declared and not outside them."
},
{
"code": null,
"e": 2970,
"s": 2806,
"text": "We seldom use the auto keyword in declarations because all block-scoped variables which are not explicitly declared with other storage classes are implicitly auto."
},
{
"code": null,
"e": 3025,
"s": 2970,
"text": "The format for specifying the automatic variables are:"
},
{
"code": null,
"e": 3080,
"s": 3025,
"text": "auto data_type variable_1, variable_2,..., variable_n;"
},
{
"code": null,
"e": 3139,
"s": 3080,
"text": "Some of the important points regarding auto variables are:"
},
{
"code": null,
"e": 3402,
"s": 3139,
"text": " Storage:\t CPU memory\n\tInitial value:\t undefined (can be any value)\n\tKeyword:\t\tauto\n\tScope:\t\t\tlocal to the block in which it is defined\n\tLifetime:\t\ttill control remains within the block in which \n it is defined"
},
{
"code": null,
"e": 3431,
"s": 3402,
"text": "Consider the following code:"
},
{
"code": null,
"e": 3692,
"s": 3431,
"text": "#include <stdio.h>\nvoid main( ) {\n auto int i = 9;\n {\n auto int i = 99;\n {\n auto int i = 999;\n printf(\"Third inner block value = %d\\n\", i);\n }\n printf(\"Second inner block value = %d\\n\", i);\n }\n printf(\"First block value = %d\\n\", i);\n}"
},
{
"code": null,
"e": 3700,
"s": 3692,
"text": "Output:"
},
{
"code": null,
"e": 3783,
"s": 3700,
"text": "Third inner block value = 999\nSecond inner block value = 99\nFirst block value = 9\n"
},
{
"code": null,
"e": 3932,
"s": 3783,
"text": "In the above code, you can see three definitions for variable i. Here, there will be no error and the program will compile and execute successfully."
},
{
"code": null,
"e": 4128,
"s": 3932,
"text": "When the code executes, first the printf in the innermost block will print 999 and the variable i defined in the innermost block will no longer be visible as soon as control exits from the block."
},
{
"code": null,
"e": 4264,
"s": 4128,
"text": "Later, the control enters into the second outer block and prints 99 and later the control enters into the outermost block and prints 9."
},
{
"code": null,
"e": 4449,
"s": 4264,
"text": "Note: automatic variables must always be initialized properly, otherwise you are likely to get unexpected results because automatic variables are not given an initial value by default."
},
{
"code": null,
"e": 4668,
"s": 4449,
"text": "Variables that are declared outside a function are by default global variables. Unlike the local variables, global variables are visible in all functions in that program. Any function can use and also change its value."
},
{
"code": null,
"e": 4703,
"s": 4668,
"text": "Let us consider the below example:"
},
{
"code": null,
"e": 4852,
"s": 4703,
"text": "void main() {\n int y = 4;\n y = y + x; // Compiler flags this as an error\n ...\n}\nint x = 5;\nvoid function1() {\n x = x + 10;\n printf (\"%d\", x);\n}"
},
{
"code": null,
"e": 5123,
"s": 4852,
"text": "Even though the variable declaration int x; outside the main() function is a valid global declaration, since the compiler scans from the top of the file, when it reaches the statement y = y + x;, it raises an error saying the variable x is not declared before its usage."
},
{
"code": null,
"e": 5328,
"s": 5123,
"text": "One solution is to move the declaration int x; above the main() function. The second solution is to declare the variable before it is used inside the main method with the keyword extern, as extern int x;."
},
{
"code": null,
"e": 5625,
"s": 5328,
"text": "The extern keyword used before the variable informs the compiler that this variable is declared somewhere else globally and that it has to refer to it. The extern declaration does not allocate storage space for variables because it is only trying to refer to the already declared global variable."
},
{
"code": null,
"e": 5798,
"s": 5625,
"text": "For this reason, we cannot initialize the variable in the extern declaration. A normal global variable can be made extern when it is being used much before its declaration."
},
{
"code": null,
"e": 5850,
"s": 5798,
"text": "The format for specifying the external variables is"
},
{
"code": null,
"e": 5908,
"s": 5850,
"text": "extern data_type variable_1, variable_2,..., variable_n;\n"
},
{
"code": null,
"e": 5969,
"s": 5908,
"text": "Some of the important points regarding extern variables are:"
},
{
"code": null,
"e": 6109,
"s": 5969,
"text": "\tStorage:\t\tMemory\n\tInitial value:\t zero (0)\n\tKeyword:\t\textern\n\tScope:\t\t\tentire program\n\tLifetime:\t\tthroughout the program execution\n"
},
{
"code": null,
"e": 6494,
"s": 6109,
"text": "Auto variables are stored in memory. CPU also has a small storage area called registers which are used for quick storage and retrieval. In C, we can suggest the compiler store certain variables in the CPU registers by specifying them with the storage class register. Apart from their physical storage location, register variables follow the same rules of scope as automatic variables."
},
{
"code": null,
"e": 6541,
"s": 6494,
"text": "The syntax for declaring register variables is"
},
{
"code": null,
"e": 6572,
"s": 6541,
"text": "register data_type variable_1;"
},
{
"code": null,
"e": 6801,
"s": 6572,
"text": "There may be some special cases when we want some frequently accessed variables to be stored in registers to increase the performance of the program. In such cases, we use the register storage class while declaring the variable."
},
{
"code": null,
"e": 7015,
"s": 6801,
"text": "It should be noted that there is no guarantee that these variables will always be stored in registers. When there isnβt enough space in registers, they will be stored in the memory along with other auto variables."
},
{
"code": null,
"e": 7343,
"s": 7015,
"text": "Care should be taken that we do not specify too many variables as register variables, as it may even degrade the performance. If there are too many, the CPU might end up spending too much time moving data back and forth between registers and temporary storage area, if there are not enough registers to hold all such variables."
},
{
"code": null,
"e": 7464,
"s": 7343,
"text": "Ideally, registers should be used only when one has good knowledge of the compiler and computer architecture being used."
},
{
"code": null,
"e": 7523,
"s": 7464,
"text": "A few points regarding register variables are given below:"
},
{
"code": null,
"e": 7764,
"s": 7523,
"text": "\tStorage:\t\tCPU registers\n\tInitial value:\t garbage value\n\tKeyword:\t\tregister\n\tScope:\t\t\tlocal to the block in which it is defined\n\tLifetime:\t\ttill control remains within the block in which\n it is defined\n"
},
{
"code": null,
"e": 8176,
"s": 7764,
"text": "A variable can be declared as a static variable by using the keyword static. Auto variables are created each time they are initialized in a block and are destroyed when they go out of scope. However, static variables are initialized only once and they remain in existence till the end of the program.\nA static variable can either be local (to a function) or global. The format for specifying static variables is"
},
{
"code": null,
"e": 8233,
"s": 8176,
"text": "static data_type variable_1, variable_2,..., variable_n;"
},
{
"code": null,
"e": 8664,
"s": 8233,
"text": "The static variables which are declared inside a function are stored in the statically allocated memory and remain alive throughout the execution of the program, but remember that their scope remains local to the function. The main difference between auto and static is that the static variables do not disappear when the function is no longer active (in scope) and their values persist across multiple calls of the same function."
},
{
"code": null,
"e": 8725,
"s": 8664,
"text": "Some of the important points regarding static variables are:"
},
{
"code": null,
"e": 8891,
"s": 8725,
"text": "\tStorage:\t\tMemory\n\tInitial value:\t zero (0)\n\tKeyword:\t\tstatic\n\tScope:\t\t\tlocal to the block in which it is defined\n\tLifetime:\t\tthroughout the program execution"
},
{
"code": null,
"e": 8904,
"s": 8891,
"text": "Wiki β Scope"
},
{
"code": null,
"e": 8930,
"s": 8904,
"text": "C- Variables and Keywords"
},
{
"code": null,
"e": 8947,
"s": 8930,
"text": "Happy Learning π"
},
{
"code": null,
"e": 9464,
"s": 8947,
"text": "\nPHP Variables Example Tutorials\nVariables & Keywords in C Language\nDynamic Memory Allocation in C\nUnderstanding the structure of a C Program\nUser defined Functions in C\nC β Derived and User Defined Data Types\nFunctions in C\nC β One Dimensional Arrays\nJava Static Variable Method Block Class Example\nJava variable types Example\nC Multi Dimensional Arrays\nPHP Functions Example Tutorials\nTry with Resources Example in Java\nC β Integer Data Types β int, short int, long int and char\nPHP Superglobals Example Tutorials\n"
},
{
"code": null,
"e": 9496,
"s": 9464,
"text": "PHP Variables Example Tutorials"
},
{
"code": null,
"e": 9531,
"s": 9496,
"text": "Variables & Keywords in C Language"
},
{
"code": null,
"e": 9562,
"s": 9531,
"text": "Dynamic Memory Allocation in C"
},
{
"code": null,
"e": 9605,
"s": 9562,
"text": "Understanding the structure of a C Program"
},
{
"code": null,
"e": 9633,
"s": 9605,
"text": "User defined Functions in C"
},
{
"code": null,
"e": 9673,
"s": 9633,
"text": "C β Derived and User Defined Data Types"
},
{
"code": null,
"e": 9688,
"s": 9673,
"text": "Functions in C"
},
{
"code": null,
"e": 9715,
"s": 9688,
"text": "C β One Dimensional Arrays"
},
{
"code": null,
"e": 9763,
"s": 9715,
"text": "Java Static Variable Method Block Class Example"
},
{
"code": null,
"e": 9791,
"s": 9763,
"text": "Java variable types Example"
},
{
"code": null,
"e": 9818,
"s": 9791,
"text": "C Multi Dimensional Arrays"
},
{
"code": null,
"e": 9850,
"s": 9818,
"text": "PHP Functions Example Tutorials"
},
{
"code": null,
"e": 9885,
"s": 9850,
"text": "Try with Resources Example in Java"
},
{
"code": null,
"e": 9944,
"s": 9885,
"text": "C β Integer Data Types β int, short int, long int and char"
},
{
"code": null,
"e": 9979,
"s": 9944,
"text": "PHP Superglobals Example Tutorials"
},
{
"code": null,
"e": 9985,
"s": 9983,
"text": "Ξ"
},
{
"code": null,
"e": 10003,
"s": 9985,
"text": " C β Introduction"
},
{
"code": null,
"e": 10017,
"s": 10003,
"text": " C β Features"
},
{
"code": null,
"e": 10043,
"s": 10017,
"text": " C β Variables & Keywords"
},
{
"code": null,
"e": 10066,
"s": 10043,
"text": " C β Program Structure"
},
{
"code": null,
"e": 10095,
"s": 10066,
"text": " C β Comment Lines & Tokens"
},
{
"code": null,
"e": 10114,
"s": 10095,
"text": " C β Number System"
},
{
"code": null,
"e": 10146,
"s": 10114,
"text": " C β Local and Global Variables"
},
{
"code": null,
"e": 10181,
"s": 10146,
"text": " C β Scope & Lifetime of Variables"
},
{
"code": null,
"e": 10197,
"s": 10181,
"text": " C β Data Types"
},
{
"code": null,
"e": 10221,
"s": 10197,
"text": " C β Integer Data Types"
},
{
"code": null,
"e": 10246,
"s": 10221,
"text": " C β Floating Data Types"
},
{
"code": null,
"e": 10279,
"s": 10246,
"text": " C β Derived, Defined Data Types"
},
{
"code": null,
"e": 10301,
"s": 10279,
"text": " C β Type Conversions"
},
{
"code": null,
"e": 10327,
"s": 10301,
"text": " C β Arithmetic Operators"
},
{
"code": null,
"e": 10350,
"s": 10327,
"text": " C β Bitwise Operators"
},
{
"code": null,
"e": 10373,
"s": 10350,
"text": " C β Logical Operators"
},
{
"code": null,
"e": 10406,
"s": 10373,
"text": " C β Comma and sizeof Operators"
},
{
"code": null,
"e": 10449,
"s": 10406,
"text": " C β Operator Precedence and Associativity"
},
{
"code": null,
"e": 10475,
"s": 10449,
"text": " C β Relational Operators"
},
{
"code": null,
"e": 10533,
"s": 10475,
"text": " C Flow Control β if, if-else, nested if-else, if-else-if"
},
{
"code": null,
"e": 10550,
"s": 10533,
"text": " C β Switch Case"
},
{
"code": null,
"e": 10591,
"s": 10550,
"text": " C Iterative β for, while, dowhile loops"
},
{
"code": null,
"e": 10643,
"s": 10591,
"text": " C Unconditional β break, continue, goto statements"
},
{
"code": null,
"e": 10675,
"s": 10643,
"text": " C β Expressions and Statements"
},
{
"code": null,
"e": 10719,
"s": 10675,
"text": " C β Header Files & Preprocessor Directives"
},
{
"code": null,
"e": 10747,
"s": 10719,
"text": " C β One Dimensional Arrays"
},
{
"code": null,
"e": 10777,
"s": 10747,
"text": " C β Multi Dimensional Arrays"
},
{
"code": null,
"e": 10798,
"s": 10777,
"text": " C β Pointers Basics"
},
{
"code": null,
"e": 10824,
"s": 10798,
"text": " C β Pointers with Arrays"
},
{
"code": null,
"e": 10839,
"s": 10824,
"text": " C β Functions"
},
{
"code": null,
"e": 10876,
"s": 10839,
"text": " C β How to Pass Arrays to Functions"
},
{
"code": null,
"e": 10905,
"s": 10876,
"text": " C β Categories of Functions"
},
{
"code": null,
"e": 10933,
"s": 10905,
"text": " C β User defined Functions"
},
{
"code": null,
"e": 10966,
"s": 10933,
"text": " C β Formal and Actual Arguments"
},
{
"code": null,
"e": 10991,
"s": 10966,
"text": " C β Recursion functions"
},
{
"code": null,
"e": 11015,
"s": 10991,
"text": " C β Structures Part -1"
},
{
"code": null,
"e": 11039,
"s": 11015,
"text": " C β Structures Part -2"
},
{
"code": null,
"e": 11051,
"s": 11039,
"text": " C β Unions"
},
{
"code": null,
"e": 11070,
"s": 11051,
"text": " C β File Handling"
},
{
"code": null,
"e": 11091,
"s": 11070,
"text": " C β File Operations"
},
{
"code": null,
"e": 11122,
"s": 11091,
"text": " C β Dynamic Memory Allocation"
},
{
"code": null,
"e": 11152,
"s": 11122,
"text": " C Program β Fibonacci Series"
},
{
"code": null,
"e": 11178,
"s": 11152,
"text": " C Program β Prime or Not"
},
{
"code": null,
"e": 11211,
"s": 11178,
"text": " C Program β Factorial of Number"
},
{
"code": null,
"e": 11236,
"s": 11211,
"text": " C Program β Even or Odd"
},
{
"code": null,
"e": 11281,
"s": 11236,
"text": " C Program β Sum of digits till Single Digit"
},
{
"code": null,
"e": 11308,
"s": 11281,
"text": " C Program β Sum of digits"
},
{
"code": null,
"e": 11341,
"s": 11308,
"text": " C Program β Reverse of a number"
},
{
"code": null,
"e": 11372,
"s": 11341,
"text": " C Program β Armstrong Numbers"
},
{
"code": null,
"e": 11405,
"s": 11372,
"text": " C Program β Print prime Numbers"
},
{
"code": null,
"e": 11437,
"s": 11405,
"text": " C Program β GCD of two Numbers"
},
{
"code": null,
"e": 11475,
"s": 11437,
"text": " C Program β Number Palindrome or Not"
},
{
"code": null,
"e": 11533,
"s": 11475,
"text": " C Program β Find Largest and Smallest number in an Array"
},
{
"code": null,
"e": 11571,
"s": 11533,
"text": " C Program β Add elements of an Array"
},
{
"code": null,
"e": 11605,
"s": 11571,
"text": " C Program β Addition of Matrices"
},
{
"code": null,
"e": 11645,
"s": 11605,
"text": " C Program β Multiplication of Matrices"
},
{
"code": null,
"e": 11678,
"s": 11645,
"text": " C Program β Reverse of an Array"
},
{
"code": null,
"e": 11703,
"s": 11678,
"text": " C Program β Bubble Sort"
}
] |
PostgreSQL - DROP INDEX - GeeksforGeeks | 28 Aug, 2020
In PostgreSQL, the DROP INDEX statement to remove an existing index.
Syntax:
DROP INDEX [ CONCURRENTLY]
[ IF EXISTS ] index_name
[ CASCADE | RESTRICT ];
Letβs analyze the above syntax:
index_name : This is used to specify the name of the index that you want to remove after the DROP INDEX clause.
IF EXISTS: Attempting to remove a non-existent index will result in an error. To avoid this, you can use the IF EXISTS option. In case you remove a non-existent index with IF EXISTS, PostgreSQL issues a notice instead.
CASCADE: If the index has dependent objects, you use the CASCADE option to automatically drop these objects and all objects that depend on those objects.
RESTRICT: The RESTRICT option instructs PostgreSQL to refuse to drop the index if any objects depend on it. The DROP INDEX uses RESTRICT by default.
CONCURRENTLY: When you execute the DROP INDEX statement, PostgreSQL acquires an exclusive lock on the table and block other accesses until the index removal completes. To force the command waits until the conflicting transaction completes before removing the index, you can use the CONCURRENTLY option.
For the purpose of example, we will use the actor table from the sample database for the demonstration.
Example:
The following statement creates an index for the first_name column of the actor table:
CREATE INDEX idx_actor_first_name
ON actor (first_name);
Sometimes, the Query Optimizer does not use the index. For example, the following statement finds the actor with the name βJohnβ:
SELECT * FROM actor
WHERE first_name = 'John';
The query did not use the idx_actor_first_name index defined earlier as explained in the following EXPLAIN statement:
EXPLAIN SELECT *
FROM actor
WHERE first_name = 'John';
This is because the query optimizer thinks that it is more optimal to just scan the whole table to locate the row. Hence, the idx_actor_first_name is not useful in this case and we need to remove it:
DROP INDEX idx_actor_first_name;
Output:
postgreSQL-indexes
PostgreSQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
PostgreSQL - GROUP BY clause
PostgreSQL - LEFT JOIN
PostgreSQL - Rename Table
PostgreSQL - Copy Table
PostgreSQL - LIMIT with OFFSET clause
PostgreSQL - Record type variable
PostgreSQL - While Loops
PostgreSQL - Select Into
PostgreSQL - ROW_NUMBER Function
PostgreSQL - Cursor | [
{
"code": null,
"e": 23926,
"s": 23898,
"text": "\n28 Aug, 2020"
},
{
"code": null,
"e": 23995,
"s": 23926,
"text": "In PostgreSQL, the DROP INDEX statement to remove an existing index."
},
{
"code": null,
"e": 24083,
"s": 23995,
"text": "Syntax:\nDROP INDEX [ CONCURRENTLY]\n[ IF EXISTS ] index_name \n[ CASCADE | RESTRICT ];\n"
},
{
"code": null,
"e": 24115,
"s": 24083,
"text": "Letβs analyze the above syntax:"
},
{
"code": null,
"e": 24227,
"s": 24115,
"text": "index_name : This is used to specify the name of the index that you want to remove after the DROP INDEX clause."
},
{
"code": null,
"e": 24446,
"s": 24227,
"text": "IF EXISTS: Attempting to remove a non-existent index will result in an error. To avoid this, you can use the IF EXISTS option. In case you remove a non-existent index with IF EXISTS, PostgreSQL issues a notice instead."
},
{
"code": null,
"e": 24600,
"s": 24446,
"text": "CASCADE: If the index has dependent objects, you use the CASCADE option to automatically drop these objects and all objects that depend on those objects."
},
{
"code": null,
"e": 24749,
"s": 24600,
"text": "RESTRICT: The RESTRICT option instructs PostgreSQL to refuse to drop the index if any objects depend on it. The DROP INDEX uses RESTRICT by default."
},
{
"code": null,
"e": 25052,
"s": 24749,
"text": "CONCURRENTLY: When you execute the DROP INDEX statement, PostgreSQL acquires an exclusive lock on the table and block other accesses until the index removal completes. To force the command waits until the conflicting transaction completes before removing the index, you can use the CONCURRENTLY option."
},
{
"code": null,
"e": 25156,
"s": 25052,
"text": "For the purpose of example, we will use the actor table from the sample database for the demonstration."
},
{
"code": null,
"e": 25165,
"s": 25156,
"text": "Example:"
},
{
"code": null,
"e": 25252,
"s": 25165,
"text": "The following statement creates an index for the first_name column of the actor table:"
},
{
"code": null,
"e": 25311,
"s": 25252,
"text": "CREATE INDEX idx_actor_first_name \nON actor (first_name);\n"
},
{
"code": null,
"e": 25441,
"s": 25311,
"text": "Sometimes, the Query Optimizer does not use the index. For example, the following statement finds the actor with the name βJohnβ:"
},
{
"code": null,
"e": 25489,
"s": 25441,
"text": "SELECT * FROM actor\nWHERE first_name = 'John';\n"
},
{
"code": null,
"e": 25607,
"s": 25489,
"text": "The query did not use the idx_actor_first_name index defined earlier as explained in the following EXPLAIN statement:"
},
{
"code": null,
"e": 25662,
"s": 25607,
"text": "EXPLAIN SELECT *\nFROM actor\nWHERE first_name = 'John';"
},
{
"code": null,
"e": 25862,
"s": 25662,
"text": "This is because the query optimizer thinks that it is more optimal to just scan the whole table to locate the row. Hence, the idx_actor_first_name is not useful in this case and we need to remove it:"
},
{
"code": null,
"e": 25895,
"s": 25862,
"text": "DROP INDEX idx_actor_first_name;"
},
{
"code": null,
"e": 25903,
"s": 25895,
"text": "Output:"
},
{
"code": null,
"e": 25922,
"s": 25903,
"text": "postgreSQL-indexes"
},
{
"code": null,
"e": 25933,
"s": 25922,
"text": "PostgreSQL"
},
{
"code": null,
"e": 26031,
"s": 25933,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26040,
"s": 26031,
"text": "Comments"
},
{
"code": null,
"e": 26053,
"s": 26040,
"text": "Old Comments"
},
{
"code": null,
"e": 26082,
"s": 26053,
"text": "PostgreSQL - GROUP BY clause"
},
{
"code": null,
"e": 26105,
"s": 26082,
"text": "PostgreSQL - LEFT JOIN"
},
{
"code": null,
"e": 26131,
"s": 26105,
"text": "PostgreSQL - Rename Table"
},
{
"code": null,
"e": 26155,
"s": 26131,
"text": "PostgreSQL - Copy Table"
},
{
"code": null,
"e": 26193,
"s": 26155,
"text": "PostgreSQL - LIMIT with OFFSET clause"
},
{
"code": null,
"e": 26227,
"s": 26193,
"text": "PostgreSQL - Record type variable"
},
{
"code": null,
"e": 26252,
"s": 26227,
"text": "PostgreSQL - While Loops"
},
{
"code": null,
"e": 26277,
"s": 26252,
"text": "PostgreSQL - Select Into"
},
{
"code": null,
"e": 26310,
"s": 26277,
"text": "PostgreSQL - ROW_NUMBER Function"
}
] |
AutoML in Python: A comparison between Hyperopt Sklearn and TPOT | by Angelica Lo Duca | Towards Data Science | Automated Machine Learning (AutoML) involves the automation of the tasks of applying Machine Learning to real-world problems. AutoML covers the complete pipeline from the raw dataset to the deployable machine learning model.
Python provides some libraries which provide AutoML. In this tutorial I compare two popular libraries: Hyperopt Sklearn and TPOT. Another library exists, called AutoSklearn, which has not been tested in this article, because it is not compatible with some operating systems.
Both the analysed libraries are compatible with scikit-learn, the famous Python library for Machine Learning.
The complete code of this tutorial can be downloaded from my Github repository.
As use case for this tutorial, I exploit the heart.csv dataset, provided by the Kaggle repository. The dataset regards heart attacks and contains 14 input features and provides a binary classification as output (heart attack yes or no).
This library can be easily installed, as explained in the documentation and it is very simple to use. The documentation is simple but clear. It supports many scikit-learn classifiers, regressors and preprocessing models. In order to build an AutoML model, it is sufficient to create an instance of the HyperoptEstimator() , configure some parameters (e.g. type of estimation) and then fit the model. The bestmodel()of the HyperoptEstimatorreturns an object containing the full scikit-learnpipeline.
Let us suppose that X and y contain the input features and the targets respectively. We can split them into training and test sets through the scikit-learn function train_test_split():
from sklearn.model_selection import train_test_splitX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.33, random_state=42)
Now we can train the HyperoptEstimator to search for the best classifier:
from hpsklearn import HyperoptEstimatorestim = HyperoptEstimator()estim.fit( X_train, y_train )
and we can get the best model:
best_model = estim.best_model()
which gives the following output:
{'learner': ExtraTreesClassifier(criterion='entropy', max_features='sqrt', n_estimators=13, n_jobs=1, random_state=4, verbose=False), 'preprocs': (), 'ex_preprocs': ()}
The key/value pair, learner contains the best model, the second one (preproc) the preprocessing techniques applied. In this case it is empty.
The Hyperopt Sklearn library reflects the stochastic nature of Machine Learning: in fact, if we try to run again the classifier over the same training set, we obtain another result.
Running the same code with the same training set (without performing again training/test split), we obtain the following best model:
{'learner': GradientBoostingClassifier(learning_rate=0.00813591154617836, max_depth=None, max_features=0.6562885234780235, min_samples_leaf=11, n_estimators=63, random_state=0, subsample=0.68797222866341), 'preprocs': (MinMaxScaler(feature_range=(-1.0, 1.0)),), 'ex_preprocs': ()}
Anyway, we can calculate the performance of the model. We can exploit the builtin function score() or define our performance metrics. In this last case, firstly, we must apply the obtained preprocessing (if any) to the test set and compare predicted results with actual values:
X_test_norm = X_testif len(best_model['preprocs']) > 0: preprocs = best_model['preprocs'][0] X_test_norm = preprocs.transform(X_test)
The Hyperopt Sklearn library does not provide the predict_proba() function, thus we must calculate it manually:
model = best_model['learner']y_score_hp = model.predict_proba(X_test_norm)
Then, we can plot the ROC curve and the precision recall curve provided by the scikitplot library, as follows:
import matplotlib.pyplot as pltfrom sklearn.metrics import roc_curvefrom scikitplot.metrics import plot_roc,aucfrom scikitplot.metrics import plot_precision_recall# Plot metrics plot_roc(y_test, y_score_hp)plt.show() plot_precision_recall(y_test, y_score_hp)plt.show()
We can also calculate precision, recall and accuracy:
y_test_pred = model.predict(X_test_norm)accuracy = accuracy_score(y_test, y_test_pred)precision = precision_score(y_test, y_test_pred)recall = recall_score(y_test, y_test_pred)print('accuracy: %s ' %(round(accuracy, 2)))print('precision: %s ' %(round(precision, 2)))print('recall: %s ' %(round(recall, 2)))
which gives the following output:
accuracy: 0.85 precision: 0.85 recall: 0.9
In the full code available in my Github repository, I also calculate the precision, recall and accuracy of the obtained model through 10-Fold validation. The following figure shows the precision trend over the number of folds:
I note that the model is not overfitted.
TPOT is another Python library for AutoML. Its documentation is well done. However, it is not simple to install it, because it is built on the top of other libraries, thus you must install firstly them to get TPOT working and running. Personally, I encountered many problems before installing it correctly.
Once installed, we can create an estimator, either a TPOTClassifier() or a TPOTRegressor(). In our case, we build a TPOT classifier:
from tpot import TPOTClassifiertpot = TPOTClassifier(generations=5, population_size=50, random_state=42)tpot.fit(X_train, y_train)
The process is very slow and takes a while before finishing. We can calculate, precision, recall and accuracy of the model:
y_test_pred = tpot.predict(X_test)accuracy = accuracy_score(y_test, y_test_pred)precision = precision_score(y_test, y_test_pred)recall = recall_score(y_test, y_test_pred)print('accuracy: %s ' %(round(accuracy, 2)))print('precision: %s ' %(round(precision, 2)))print('recall: %s ' %(round(recall, 2)))
which gives the following output:
accuracy: 0.8 precision: 0.84 recall: 0.81
With respect to the best model obtained through Hyperopt Sklearn, TPOT behaves worse.
TPOT provides also the predict_proba() method, which can be used to calculate the ROC curve and the precision recall curve.
We can access the best model as a scikit-learnpipeline:
tpot.fitted_pipeline_
which gives the following output:
Pipeline(steps=[('logisticregression', LogisticRegression(C=20.0, random_state=42))])
Although in the documentation there is said that the model may produce different best models on the same dataset, in our case, running more times the same code on the same dataset returns the same model.
Now, I can calculate the precision, recall and accuracy through 10-Fold cross validation. TPOT provides cross validation natively. However, in this case, we calculate it manually, because we want to plot the trend of metrics versus each fold.
The following figure shows the precision trend. For the other plots (recall and accuracy), please check my Github repository:
With respect to the Hyperopt Sklearn library, TPOT seems more stables with different datasets.
In this article, we have compared two popular Python library for AutoML: Hyperopt Sklearn and TPOT.
Hyperopt Sklearn
Pros
easy to install
fast
the best model reaches high performance
Cons
different best models for the same (simple) dataset
simple and poor documentation
TPOT
Pros
always the same best model for the same (simple) dataset
well written documentation
the best model reaches good performance
Cons
very slow
difficult to install
If you wanted to be updated on my research and other activities, you can follow me on Twitter, Youtube and and Github. | [
{
"code": null,
"e": 396,
"s": 171,
"text": "Automated Machine Learning (AutoML) involves the automation of the tasks of applying Machine Learning to real-world problems. AutoML covers the complete pipeline from the raw dataset to the deployable machine learning model."
},
{
"code": null,
"e": 671,
"s": 396,
"text": "Python provides some libraries which provide AutoML. In this tutorial I compare two popular libraries: Hyperopt Sklearn and TPOT. Another library exists, called AutoSklearn, which has not been tested in this article, because it is not compatible with some operating systems."
},
{
"code": null,
"e": 781,
"s": 671,
"text": "Both the analysed libraries are compatible with scikit-learn, the famous Python library for Machine Learning."
},
{
"code": null,
"e": 861,
"s": 781,
"text": "The complete code of this tutorial can be downloaded from my Github repository."
},
{
"code": null,
"e": 1098,
"s": 861,
"text": "As use case for this tutorial, I exploit the heart.csv dataset, provided by the Kaggle repository. The dataset regards heart attacks and contains 14 input features and provides a binary classification as output (heart attack yes or no)."
},
{
"code": null,
"e": 1597,
"s": 1098,
"text": "This library can be easily installed, as explained in the documentation and it is very simple to use. The documentation is simple but clear. It supports many scikit-learn classifiers, regressors and preprocessing models. In order to build an AutoML model, it is sufficient to create an instance of the HyperoptEstimator() , configure some parameters (e.g. type of estimation) and then fit the model. The bestmodel()of the HyperoptEstimatorreturns an object containing the full scikit-learnpipeline."
},
{
"code": null,
"e": 1782,
"s": 1597,
"text": "Let us suppose that X and y contain the input features and the targets respectively. We can split them into training and test sets through the scikit-learn function train_test_split():"
},
{
"code": null,
"e": 1925,
"s": 1782,
"text": "from sklearn.model_selection import train_test_splitX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.33, random_state=42)"
},
{
"code": null,
"e": 1999,
"s": 1925,
"text": "Now we can train the HyperoptEstimator to search for the best classifier:"
},
{
"code": null,
"e": 2095,
"s": 1999,
"text": "from hpsklearn import HyperoptEstimatorestim = HyperoptEstimator()estim.fit( X_train, y_train )"
},
{
"code": null,
"e": 2126,
"s": 2095,
"text": "and we can get the best model:"
},
{
"code": null,
"e": 2158,
"s": 2126,
"text": "best_model = estim.best_model()"
},
{
"code": null,
"e": 2192,
"s": 2158,
"text": "which gives the following output:"
},
{
"code": null,
"e": 2382,
"s": 2192,
"text": "{'learner': ExtraTreesClassifier(criterion='entropy', max_features='sqrt', n_estimators=13, n_jobs=1, random_state=4, verbose=False), 'preprocs': (), 'ex_preprocs': ()}"
},
{
"code": null,
"e": 2524,
"s": 2382,
"text": "The key/value pair, learner contains the best model, the second one (preproc) the preprocessing techniques applied. In this case it is empty."
},
{
"code": null,
"e": 2706,
"s": 2524,
"text": "The Hyperopt Sklearn library reflects the stochastic nature of Machine Learning: in fact, if we try to run again the classifier over the same training set, we obtain another result."
},
{
"code": null,
"e": 2839,
"s": 2706,
"text": "Running the same code with the same training set (without performing again training/test split), we obtain the following best model:"
},
{
"code": null,
"e": 3120,
"s": 2839,
"text": "{'learner': GradientBoostingClassifier(learning_rate=0.00813591154617836, max_depth=None, max_features=0.6562885234780235, min_samples_leaf=11, n_estimators=63, random_state=0, subsample=0.68797222866341), 'preprocs': (MinMaxScaler(feature_range=(-1.0, 1.0)),), 'ex_preprocs': ()}"
},
{
"code": null,
"e": 3398,
"s": 3120,
"text": "Anyway, we can calculate the performance of the model. We can exploit the builtin function score() or define our performance metrics. In this last case, firstly, we must apply the obtained preprocessing (if any) to the test set and compare predicted results with actual values:"
},
{
"code": null,
"e": 3538,
"s": 3398,
"text": "X_test_norm = X_testif len(best_model['preprocs']) > 0: preprocs = best_model['preprocs'][0] X_test_norm = preprocs.transform(X_test)"
},
{
"code": null,
"e": 3650,
"s": 3538,
"text": "The Hyperopt Sklearn library does not provide the predict_proba() function, thus we must calculate it manually:"
},
{
"code": null,
"e": 3725,
"s": 3650,
"text": "model = best_model['learner']y_score_hp = model.predict_proba(X_test_norm)"
},
{
"code": null,
"e": 3836,
"s": 3725,
"text": "Then, we can plot the ROC curve and the precision recall curve provided by the scikitplot library, as follows:"
},
{
"code": null,
"e": 4108,
"s": 3836,
"text": "import matplotlib.pyplot as pltfrom sklearn.metrics import roc_curvefrom scikitplot.metrics import plot_roc,aucfrom scikitplot.metrics import plot_precision_recall# Plot metrics plot_roc(y_test, y_score_hp)plt.show() plot_precision_recall(y_test, y_score_hp)plt.show()"
},
{
"code": null,
"e": 4162,
"s": 4108,
"text": "We can also calculate precision, recall and accuracy:"
},
{
"code": null,
"e": 4472,
"s": 4162,
"text": "y_test_pred = model.predict(X_test_norm)accuracy = accuracy_score(y_test, y_test_pred)precision = precision_score(y_test, y_test_pred)recall = recall_score(y_test, y_test_pred)print('accuracy: %s ' %(round(accuracy, 2)))print('precision: %s ' %(round(precision, 2)))print('recall: %s ' %(round(recall, 2)))"
},
{
"code": null,
"e": 4506,
"s": 4472,
"text": "which gives the following output:"
},
{
"code": null,
"e": 4552,
"s": 4506,
"text": "accuracy: 0.85 precision: 0.85 recall: 0.9"
},
{
"code": null,
"e": 4779,
"s": 4552,
"text": "In the full code available in my Github repository, I also calculate the precision, recall and accuracy of the obtained model through 10-Fold validation. The following figure shows the precision trend over the number of folds:"
},
{
"code": null,
"e": 4820,
"s": 4779,
"text": "I note that the model is not overfitted."
},
{
"code": null,
"e": 5127,
"s": 4820,
"text": "TPOT is another Python library for AutoML. Its documentation is well done. However, it is not simple to install it, because it is built on the top of other libraries, thus you must install firstly them to get TPOT working and running. Personally, I encountered many problems before installing it correctly."
},
{
"code": null,
"e": 5260,
"s": 5127,
"text": "Once installed, we can create an estimator, either a TPOTClassifier() or a TPOTRegressor(). In our case, we build a TPOT classifier:"
},
{
"code": null,
"e": 5391,
"s": 5260,
"text": "from tpot import TPOTClassifiertpot = TPOTClassifier(generations=5, population_size=50, random_state=42)tpot.fit(X_train, y_train)"
},
{
"code": null,
"e": 5515,
"s": 5391,
"text": "The process is very slow and takes a while before finishing. We can calculate, precision, recall and accuracy of the model:"
},
{
"code": null,
"e": 5819,
"s": 5515,
"text": "y_test_pred = tpot.predict(X_test)accuracy = accuracy_score(y_test, y_test_pred)precision = precision_score(y_test, y_test_pred)recall = recall_score(y_test, y_test_pred)print('accuracy: %s ' %(round(accuracy, 2)))print('precision: %s ' %(round(precision, 2)))print('recall: %s ' %(round(recall, 2)))"
},
{
"code": null,
"e": 5853,
"s": 5819,
"text": "which gives the following output:"
},
{
"code": null,
"e": 5899,
"s": 5853,
"text": "accuracy: 0.8 precision: 0.84 recall: 0.81"
},
{
"code": null,
"e": 5985,
"s": 5899,
"text": "With respect to the best model obtained through Hyperopt Sklearn, TPOT behaves worse."
},
{
"code": null,
"e": 6109,
"s": 5985,
"text": "TPOT provides also the predict_proba() method, which can be used to calculate the ROC curve and the precision recall curve."
},
{
"code": null,
"e": 6165,
"s": 6109,
"text": "We can access the best model as a scikit-learnpipeline:"
},
{
"code": null,
"e": 6187,
"s": 6165,
"text": "tpot.fitted_pipeline_"
},
{
"code": null,
"e": 6221,
"s": 6187,
"text": "which gives the following output:"
},
{
"code": null,
"e": 6323,
"s": 6221,
"text": "Pipeline(steps=[('logisticregression', LogisticRegression(C=20.0, random_state=42))])"
},
{
"code": null,
"e": 6527,
"s": 6323,
"text": "Although in the documentation there is said that the model may produce different best models on the same dataset, in our case, running more times the same code on the same dataset returns the same model."
},
{
"code": null,
"e": 6770,
"s": 6527,
"text": "Now, I can calculate the precision, recall and accuracy through 10-Fold cross validation. TPOT provides cross validation natively. However, in this case, we calculate it manually, because we want to plot the trend of metrics versus each fold."
},
{
"code": null,
"e": 6896,
"s": 6770,
"text": "The following figure shows the precision trend. For the other plots (recall and accuracy), please check my Github repository:"
},
{
"code": null,
"e": 6991,
"s": 6896,
"text": "With respect to the Hyperopt Sklearn library, TPOT seems more stables with different datasets."
},
{
"code": null,
"e": 7091,
"s": 6991,
"text": "In this article, we have compared two popular Python library for AutoML: Hyperopt Sklearn and TPOT."
},
{
"code": null,
"e": 7108,
"s": 7091,
"text": "Hyperopt Sklearn"
},
{
"code": null,
"e": 7113,
"s": 7108,
"text": "Pros"
},
{
"code": null,
"e": 7129,
"s": 7113,
"text": "easy to install"
},
{
"code": null,
"e": 7134,
"s": 7129,
"text": "fast"
},
{
"code": null,
"e": 7174,
"s": 7134,
"text": "the best model reaches high performance"
},
{
"code": null,
"e": 7179,
"s": 7174,
"text": "Cons"
},
{
"code": null,
"e": 7231,
"s": 7179,
"text": "different best models for the same (simple) dataset"
},
{
"code": null,
"e": 7261,
"s": 7231,
"text": "simple and poor documentation"
},
{
"code": null,
"e": 7266,
"s": 7261,
"text": "TPOT"
},
{
"code": null,
"e": 7271,
"s": 7266,
"text": "Pros"
},
{
"code": null,
"e": 7328,
"s": 7271,
"text": "always the same best model for the same (simple) dataset"
},
{
"code": null,
"e": 7355,
"s": 7328,
"text": "well written documentation"
},
{
"code": null,
"e": 7395,
"s": 7355,
"text": "the best model reaches good performance"
},
{
"code": null,
"e": 7400,
"s": 7395,
"text": "Cons"
},
{
"code": null,
"e": 7410,
"s": 7400,
"text": "very slow"
},
{
"code": null,
"e": 7431,
"s": 7410,
"text": "difficult to install"
}
] |
Check if a list exists in given list of lists in Python | Lists can be nested, means the elements of a list are themselves lists. In this article we will see how to find out if a given list is present as an element in the outer bigger list.
This is a very simple and straight forward method. We use the in clause just to check if the inner list is present as an element in the bigger list.
Live Demo
listA = [[-9, -1, 3], [11, -8],[-4,434,0]]
search_list = [-4,434,0]
# Given list
print("Given List :\n", listA)
print("list to Search: ",search_list)
# Using in
if search_list in listA:
print("Present")
else:
print("Not Present")
Running the above code gives us the following result β
Given List :
[[-9, -1, 3], [11, -8], [-4, 434, 0]]
list to Search: [-4, 434, 0]
Present
We can also use the any clause where we take an element and test if it is equal to any element present in the list. Of course with help of a for loop.
Live Demo
listA = [[-9, -1, 3], [11, -8],[-4,434,0]]
search_list = [-4,434,0]
# Given list
print("Given List :\n", listA)
print("list to Search: ",search_list)
# Using in
if any (x == search_list for x in listA):
print("Present")
else:
print("Not Present")
Running the above code gives us the following result β
Given List :
[[-9, -1, 3], [11, -8], [-4, 434, 0]]
list to Search: [-4, 434, 0]
Present | [
{
"code": null,
"e": 1245,
"s": 1062,
"text": "Lists can be nested, means the elements of a list are themselves lists. In this article we will see how to find out if a given list is present as an element in the outer bigger list."
},
{
"code": null,
"e": 1394,
"s": 1245,
"text": "This is a very simple and straight forward method. We use the in clause just to check if the inner list is present as an element in the bigger list."
},
{
"code": null,
"e": 1405,
"s": 1394,
"text": " Live Demo"
},
{
"code": null,
"e": 1637,
"s": 1405,
"text": "listA = [[-9, -1, 3], [11, -8],[-4,434,0]]\nsearch_list = [-4,434,0]\n\n# Given list\nprint(\"Given List :\\n\", listA)\nprint(\"list to Search: \",search_list)\n\n# Using in\nif search_list in listA:\nprint(\"Present\")\nelse:\nprint(\"Not Present\")"
},
{
"code": null,
"e": 1692,
"s": 1637,
"text": "Running the above code gives us the following result β"
},
{
"code": null,
"e": 1780,
"s": 1692,
"text": "Given List :\n[[-9, -1, 3], [11, -8], [-4, 434, 0]]\nlist to Search: [-4, 434, 0]\nPresent"
},
{
"code": null,
"e": 1931,
"s": 1780,
"text": "We can also use the any clause where we take an element and test if it is equal to any element present in the list. Of course with help of a for loop."
},
{
"code": null,
"e": 1942,
"s": 1931,
"text": " Live Demo"
},
{
"code": null,
"e": 2191,
"s": 1942,
"text": "listA = [[-9, -1, 3], [11, -8],[-4,434,0]]\nsearch_list = [-4,434,0]\n\n# Given list\nprint(\"Given List :\\n\", listA)\nprint(\"list to Search: \",search_list)\n\n# Using in\nif any (x == search_list for x in listA):\nprint(\"Present\")\nelse:\nprint(\"Not Present\")"
},
{
"code": null,
"e": 2247,
"s": 2191,
"text": "Running the above code gives us the following result β "
},
{
"code": null,
"e": 2335,
"s": 2247,
"text": "Given List :\n[[-9, -1, 3], [11, -8], [-4, 434, 0]]\nlist to Search: [-4, 434, 0]\nPresent"
}
] |
How to fit text container width dynamically according to screen size using CSS ? - GeeksforGeeks | 12 Feb, 2021
In this article, we have given a text paragraph and the task is to fit the text width dynamically according to screen size using HTML and CSS. Some of the important properties used in the code are as follows-
display-grid: It helps us to display the content on the page in the grid structure.
grid-gap: This property sets the minimum amount of gap between two grids.
auto-fit: It takes the required constraints and fits the content according to the size of the screen.
<div>: It is the division tag and helps us to define a particular section of the HTML code so that it can be referred to and edited easily later in the CSS style sheet.
auto-fit: It makes all the available columns on the screen fit into the available space and expand them as needed to occupy the rows.
min() and max() function: This function is very much related to the mathematical function which defines a particular range of the function i.e. greater than or equal to min and less than or equal to max.
@media(min-width): It is a CSS property where the condition under this tag is only applied when the minimum screen width reaches 950px.
Example 1: It is a simple example. Here, we will use the <div> tag to specify each quote separately and repeat function in the CSS part.
HTML
<!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content= "width=device-width, initial-scale=1.0"> <style> body { margin: 0; font-family: 'Nunito'; } .top { padding: 3em; display: grid; grid-gap: 3em; grid-template-columns: repeat(4, 250px); .quote { padding: 3em; border-radius: .3em; box-shadow: 10px 10px 30px rgba(0, 0, 0, 0.1); p { margin-top: 0; } span { font-weight: bold; position: relative; margin-left: 20px; &:before { content: ''; position: absolute; height: 1px; width: 20px; border-bottom: 1px solid black; top: 20px; } } } } @media(min-width:950px) { .top { grid-template-columns: repeat(4, 1fr); } } </style> </head> <body> <div class="top"> <div class="quote"> <p> With the idea of imparting programming knowledge, Mr. Sandeep Jain, an IIT Roorkee alumnus started a dream, GeeksforGeeks. Whether programming excites you or you feel stifled, wondering how to prepare for interview questions or how to ace data structures and algorithms, GeeksforGeeks is a one-stop solution. With every tick of time, we are adding arrows in our quiver. From articles on various computer science subjects to programming problems for practice, from basic to premium courses, from technologies to entrance examinations, we have been building ample content with superior quality. </p> <br> <span>GFG</span> </div> <div class="quote span-2"> <p> With the idea of imparting programming knowledge, Mr. Sandeep Jain, an IIT Roorkee alumnus started a dream, GeeksforGeeks. Whether programming excites you or you feel stifled, wondering how to prepare for interview questions or how to ace data structures and algorithms, GeeksforGeeks is a one-stop solution. With every tick of time, we are adding arrows in our quiver. From articles on various computer science subjects to programming problems for practice, from basic to premium courses, from technologies to entrance examinations, we have been building ample content with superior quality. </p> <br> <span>GFG</span> </div> <div class="quote"> <p> With the idea of imparting programming knowledge, Mr. Sandeep Jain, an IIT Roorkee alumnus started a dream, GeeksforGeeks. Whether programming excites you or you feel stifled, wondering how to prepare for interview questions or how to ace data structures and algorithms, GeeksforGeeks is a one-stop solution. With every tick of time, we are adding arrows in our quiver. From articles on various computer science subjects to programming problems for practice, from basic to premium courses, from technologies to entrance examinations, we have been building ample content with superior quality. </p> <span>GFG</span> </div> <div class="quote"> <p> With the idea of imparting programming knowledge, Mr. Sandeep Jain, an IIT Roorkee alumnus started a dream, GeeksforGeeks. Whether programming excites you or you feel stifled, wondering how to prepare for interview questions or how to ace data structures and algorithms, GeeksforGeeks is a one-stop solution. With every tick of time, we are adding arrows in our quiver. From articles on various computer science subjects to programming problems for practice, from basic to premium courses, from technologies to entrance examinations, we have been building ample content with superior quality. </p> <span>GFG</span> </div> </div></body> </html>
Output:
Upon minimizing the output screen we are unable to see half of the text of the second row and are getting a scroll bar at the bottom of the window to scroll through. This doesnβt look nice and can cause trouble if the user is viewing the website on their mobile phone.
Example 2: This is a better approach as it gives us a more organized and hassle-free output with the addition of just one property known as auto fit.
HTML
<!DOCTYPE html><!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content= "width=device-width, initial-scale=1.0"> <style> body { margin: 0; font-family: 'Nunito'; } .top { padding: 3em; display: grid; grid-gap: 2em; grid-template-columns: repeat( auto-fit, minmax(250px, 1fr)); .quote { padding: 2em; border-radius: .3em; box-shadow: 10px 10px 30px rgba(0, 0, 0, 0.1); p { margin-top: 0; } span { font-weight: bold; position: relative; margin-left: 15px; &:before { content: ''; position: absolute; height: 1px; width: 10px; border-bottom: 1px solid black; top: 10px; left: -15px; } } } } </style></head> <body> <div class="top"> <div class="quote"> <p> With the idea of imparting programming knowledge, Mr. Sandeep Jain, an IIT Roorkee alumnus started a dream, GeeksforGeeks. Whether programming excites you or you feel stifled, wondering how to prepare for interview questions or how to ace data structures and algorithms, GeeksforGeeks is a one-stop solution. With every tick of time, we are adding arrows in our quiver. From articles on various computer science subjects to programming problems for practice, from basic to premium courses, from technologies to entrance examinations, we have been building ample content with superior quality. </p> <br> <span>GFG</span> </div> <div class="quote span-2"> <p> With the idea of imparting programming knowledge, Mr. Sandeep Jain, an IIT Roorkee alumnus started a dream, GeeksforGeeks. Whether programming excites you or you feel stifled, wondering how to prepare for interview questions or how to ace data structures and algorithms, GeeksforGeeks is a one-stop solution. With every tick of time, we are adding arrows in our quiver. From articles on various computer science subjects to programming problems for practice, from basic to premium courses, from technologies to entrance examinations, we have been building ample content with superior quality. </p> <br> <span>GFG</span> </div> <div class="quote"> <p> With the idea of imparting programming knowledge, Mr. Sandeep Jain, an IIT Roorkee alumnus started a dream, GeeksforGeeks. Whether programming excites you or you feel stifled, wondering how to prepare for interview questions or how to ace data structures and algorithms, GeeksforGeeks is a one-stop solution. With every tick of time, we are adding arrows in our quiver. From articles on various computer science subjects to programming problems for practice, from basic to premium courses, from technologies to entrance examinations, we have been building ample content with superior quality. </p> <span>GFG</span> </div> <div class="quote"> <p> With the idea of imparting programming knowledge, Mr. Sandeep Jain, an IIT Roorkee alumnus started a dream, GeeksforGeeks. Whether programming excites you or you feel stifled, wondering how to prepare for interview questions or how to ace data structures and algorithms, GeeksforGeeks is a one-stop solution. With every tick of time, we are adding arrows in our quiver. From articles on various computer science subjects to programming problems for practice, from basic to premium courses, from technologies to entrance examinations, we have been building ample content with superior quality. </p> <span>GFG</span> </div> </div> </body> </html>
Output:
In this method, we can see that upon minimizing the screen all the rows are adjusted as columns one below the other. And we are given a vertical scroll bar for the last quote. Here no text is omitted from a line and we are able to read the whole quote.
Attention reader! Donβt stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course.
CSS-Questions
HTML-Questions
CSS
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Design a web page using HTML and CSS
Form validation using jQuery
Search Bar using HTML, CSS and JavaScript
How to style a checkbox using CSS?
How to fetch data from localserver database and display on HTML table using PHP ?
How to Insert Form Data into Database using PHP ?
How to set the default value for an HTML <select> element ?
How to set input type date in dd-mm-yyyy format using HTML ?
REST API (Introduction)
Form validation using HTML and JavaScript | [
{
"code": null,
"e": 25296,
"s": 25268,
"text": "\n12 Feb, 2021"
},
{
"code": null,
"e": 25505,
"s": 25296,
"text": "In this article, we have given a text paragraph and the task is to fit the text width dynamically according to screen size using HTML and CSS. Some of the important properties used in the code are as follows-"
},
{
"code": null,
"e": 25589,
"s": 25505,
"text": "display-grid: It helps us to display the content on the page in the grid structure."
},
{
"code": null,
"e": 25663,
"s": 25589,
"text": "grid-gap: This property sets the minimum amount of gap between two grids."
},
{
"code": null,
"e": 25765,
"s": 25663,
"text": "auto-fit: It takes the required constraints and fits the content according to the size of the screen."
},
{
"code": null,
"e": 25934,
"s": 25765,
"text": "<div>: It is the division tag and helps us to define a particular section of the HTML code so that it can be referred to and edited easily later in the CSS style sheet."
},
{
"code": null,
"e": 26068,
"s": 25934,
"text": "auto-fit: It makes all the available columns on the screen fit into the available space and expand them as needed to occupy the rows."
},
{
"code": null,
"e": 26272,
"s": 26068,
"text": "min() and max() function: This function is very much related to the mathematical function which defines a particular range of the function i.e. greater than or equal to min and less than or equal to max."
},
{
"code": null,
"e": 26408,
"s": 26272,
"text": "@media(min-width): It is a CSS property where the condition under this tag is only applied when the minimum screen width reaches 950px."
},
{
"code": null,
"e": 26545,
"s": 26408,
"text": "Example 1: It is a simple example. Here, we will use the <div> tag to specify each quote separately and repeat function in the CSS part."
},
{
"code": null,
"e": 26550,
"s": 26545,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\"> <meta name=\"viewport\" content= \"width=device-width, initial-scale=1.0\"> <style> body { margin: 0; font-family: 'Nunito'; } .top { padding: 3em; display: grid; grid-gap: 3em; grid-template-columns: repeat(4, 250px); .quote { padding: 3em; border-radius: .3em; box-shadow: 10px 10px 30px rgba(0, 0, 0, 0.1); p { margin-top: 0; } span { font-weight: bold; position: relative; margin-left: 20px; &:before { content: ''; position: absolute; height: 1px; width: 20px; border-bottom: 1px solid black; top: 20px; } } } } @media(min-width:950px) { .top { grid-template-columns: repeat(4, 1fr); } } </style> </head> <body> <div class=\"top\"> <div class=\"quote\"> <p> With the idea of imparting programming knowledge, Mr. Sandeep Jain, an IIT Roorkee alumnus started a dream, GeeksforGeeks. Whether programming excites you or you feel stifled, wondering how to prepare for interview questions or how to ace data structures and algorithms, GeeksforGeeks is a one-stop solution. With every tick of time, we are adding arrows in our quiver. From articles on various computer science subjects to programming problems for practice, from basic to premium courses, from technologies to entrance examinations, we have been building ample content with superior quality. </p> <br> <span>GFG</span> </div> <div class=\"quote span-2\"> <p> With the idea of imparting programming knowledge, Mr. Sandeep Jain, an IIT Roorkee alumnus started a dream, GeeksforGeeks. Whether programming excites you or you feel stifled, wondering how to prepare for interview questions or how to ace data structures and algorithms, GeeksforGeeks is a one-stop solution. With every tick of time, we are adding arrows in our quiver. From articles on various computer science subjects to programming problems for practice, from basic to premium courses, from technologies to entrance examinations, we have been building ample content with superior quality. </p> <br> <span>GFG</span> </div> <div class=\"quote\"> <p> With the idea of imparting programming knowledge, Mr. Sandeep Jain, an IIT Roorkee alumnus started a dream, GeeksforGeeks. Whether programming excites you or you feel stifled, wondering how to prepare for interview questions or how to ace data structures and algorithms, GeeksforGeeks is a one-stop solution. With every tick of time, we are adding arrows in our quiver. From articles on various computer science subjects to programming problems for practice, from basic to premium courses, from technologies to entrance examinations, we have been building ample content with superior quality. </p> <span>GFG</span> </div> <div class=\"quote\"> <p> With the idea of imparting programming knowledge, Mr. Sandeep Jain, an IIT Roorkee alumnus started a dream, GeeksforGeeks. Whether programming excites you or you feel stifled, wondering how to prepare for interview questions or how to ace data structures and algorithms, GeeksforGeeks is a one-stop solution. With every tick of time, we are adding arrows in our quiver. From articles on various computer science subjects to programming problems for practice, from basic to premium courses, from technologies to entrance examinations, we have been building ample content with superior quality. </p> <span>GFG</span> </div> </div></body> </html>",
"e": 31599,
"s": 26550,
"text": null
},
{
"code": null,
"e": 31607,
"s": 31599,
"text": "Output:"
},
{
"code": null,
"e": 31876,
"s": 31607,
"text": "Upon minimizing the output screen we are unable to see half of the text of the second row and are getting a scroll bar at the bottom of the window to scroll through. This doesnβt look nice and can cause trouble if the user is viewing the website on their mobile phone."
},
{
"code": null,
"e": 32027,
"s": 31876,
"text": "Example 2: This is a better approach as it gives us a more organized and hassle-free output with the addition of just one property known as auto fit. "
},
{
"code": null,
"e": 32032,
"s": 32027,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\"> <meta name=\"viewport\" content= \"width=device-width, initial-scale=1.0\"> <style> body { margin: 0; font-family: 'Nunito'; } .top { padding: 3em; display: grid; grid-gap: 2em; grid-template-columns: repeat( auto-fit, minmax(250px, 1fr)); .quote { padding: 2em; border-radius: .3em; box-shadow: 10px 10px 30px rgba(0, 0, 0, 0.1); p { margin-top: 0; } span { font-weight: bold; position: relative; margin-left: 15px; &:before { content: ''; position: absolute; height: 1px; width: 10px; border-bottom: 1px solid black; top: 10px; left: -15px; } } } } </style></head> <body> <div class=\"top\"> <div class=\"quote\"> <p> With the idea of imparting programming knowledge, Mr. Sandeep Jain, an IIT Roorkee alumnus started a dream, GeeksforGeeks. Whether programming excites you or you feel stifled, wondering how to prepare for interview questions or how to ace data structures and algorithms, GeeksforGeeks is a one-stop solution. With every tick of time, we are adding arrows in our quiver. From articles on various computer science subjects to programming problems for practice, from basic to premium courses, from technologies to entrance examinations, we have been building ample content with superior quality. </p> <br> <span>GFG</span> </div> <div class=\"quote span-2\"> <p> With the idea of imparting programming knowledge, Mr. Sandeep Jain, an IIT Roorkee alumnus started a dream, GeeksforGeeks. Whether programming excites you or you feel stifled, wondering how to prepare for interview questions or how to ace data structures and algorithms, GeeksforGeeks is a one-stop solution. With every tick of time, we are adding arrows in our quiver. From articles on various computer science subjects to programming problems for practice, from basic to premium courses, from technologies to entrance examinations, we have been building ample content with superior quality. </p> <br> <span>GFG</span> </div> <div class=\"quote\"> <p> With the idea of imparting programming knowledge, Mr. Sandeep Jain, an IIT Roorkee alumnus started a dream, GeeksforGeeks. Whether programming excites you or you feel stifled, wondering how to prepare for interview questions or how to ace data structures and algorithms, GeeksforGeeks is a one-stop solution. With every tick of time, we are adding arrows in our quiver. From articles on various computer science subjects to programming problems for practice, from basic to premium courses, from technologies to entrance examinations, we have been building ample content with superior quality. </p> <span>GFG</span> </div> <div class=\"quote\"> <p> With the idea of imparting programming knowledge, Mr. Sandeep Jain, an IIT Roorkee alumnus started a dream, GeeksforGeeks. Whether programming excites you or you feel stifled, wondering how to prepare for interview questions or how to ace data structures and algorithms, GeeksforGeeks is a one-stop solution. With every tick of time, we are adding arrows in our quiver. From articles on various computer science subjects to programming problems for practice, from basic to premium courses, from technologies to entrance examinations, we have been building ample content with superior quality. </p> <span>GFG</span> </div> </div> </body> </html>",
"e": 37063,
"s": 32032,
"text": null
},
{
"code": null,
"e": 37072,
"s": 37063,
"text": "Output: "
},
{
"code": null,
"e": 37325,
"s": 37072,
"text": "In this method, we can see that upon minimizing the screen all the rows are adjusted as columns one below the other. And we are given a vertical scroll bar for the last quote. Here no text is omitted from a line and we are able to read the whole quote."
},
{
"code": null,
"e": 37462,
"s": 37325,
"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": 37476,
"s": 37462,
"text": "CSS-Questions"
},
{
"code": null,
"e": 37491,
"s": 37476,
"text": "HTML-Questions"
},
{
"code": null,
"e": 37495,
"s": 37491,
"text": "CSS"
},
{
"code": null,
"e": 37500,
"s": 37495,
"text": "HTML"
},
{
"code": null,
"e": 37517,
"s": 37500,
"text": "Web Technologies"
},
{
"code": null,
"e": 37522,
"s": 37517,
"text": "HTML"
},
{
"code": null,
"e": 37620,
"s": 37522,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 37629,
"s": 37620,
"text": "Comments"
},
{
"code": null,
"e": 37642,
"s": 37629,
"text": "Old Comments"
},
{
"code": null,
"e": 37679,
"s": 37642,
"text": "Design a web page using HTML and CSS"
},
{
"code": null,
"e": 37708,
"s": 37679,
"text": "Form validation using jQuery"
},
{
"code": null,
"e": 37750,
"s": 37708,
"text": "Search Bar using HTML, CSS and JavaScript"
},
{
"code": null,
"e": 37785,
"s": 37750,
"text": "How to style a checkbox using CSS?"
},
{
"code": null,
"e": 37867,
"s": 37785,
"text": "How to fetch data from localserver database and display on HTML table using PHP ?"
},
{
"code": null,
"e": 37917,
"s": 37867,
"text": "How to Insert Form Data into Database using PHP ?"
},
{
"code": null,
"e": 37977,
"s": 37917,
"text": "How to set the default value for an HTML <select> element ?"
},
{
"code": null,
"e": 38038,
"s": 37977,
"text": "How to set input type date in dd-mm-yyyy format using HTML ?"
},
{
"code": null,
"e": 38062,
"s": 38038,
"text": "REST API (Introduction)"
}
] |
Linear Algebra Essentials with Numpy (part 1) | by Dario RadecΜicΜ | Towards Data Science | Ah, math. You canβt avoid it forever. You can try, and then try harder, but sooner or later some basic intuition behind it will be needed, provided that you are serious in your endeavors to advance your career in data science.
When it comes to linear algebra, I really like this quote:
If Data Science was Batman, Linear Algebra would be Robin.[1]
It neatly captures the essence in a non-technical way.
Why should I study linear algebra?
Great question. Simply put, if you understand it, you will be able to develop a better intuition for machine learning and deep learning algorithms and you wonβt treat them as black boxes. Furthermore, you would also be capable of developing algorithms from scratch and making your own variations of them.
Not only that, but you will also be considered as a cool kid, like these two:
So awesome.
Why should I read this post?
This post certainly won't teach you every nitty-gritty detail about the topic, there are a plethora of books which cover those. The post also wonβt dive into proofs, again, read a book from some math or tech faculty if you are into that. This post will, however, provide you with an essential intuition behind linear algebra (and some light calculations) in 14 different areas.
Yes, youβve read that right. Iβm planning to cover 14 different topics in two articles. It will take you some time to read it (and for me to write it), but if you are new to this I would strongly advise reading 2β3 topics per day at most, and then searching the web for more practice problems.
How is the article structured?
So each of the topics is divided into 3 parts:
Theoretical explanationExample (by hand calculations)Implementation in Python (with Numpy)
Theoretical explanation
Example (by hand calculations)
Implementation in Python (with Numpy)
I wonβt lie to you β it will be a lot of work. This first part will cover Vectors, and hereβs the topic list:
AdditionScalar MultiplicationDot ProductNormUnit VectorAngle Between Vectors
Addition
Scalar Multiplication
Dot Product
Norm
Unit Vector
Angle Between Vectors
Now when the introduction is over, letβs not postpone the inevitable. Grab a cup of coffee (or something stronger) and come with me to the amazing world of linear algebra.
Yeah, no point in starting with vector addition if you have no idea what a vector is. For starters, think of a vector as an arrow in space. You need to keep in mind two quantities here:
Direction
Magnitude
By direction, I mean to where in space does βarrowβ point, and the magnitude tells you how far you should go in that direction. If you only have magnitude, but not direction, then you are talking about scalars. Once you give the scalar some direction, it becomes a vector.
I said that you should try to imagine vectors as arrows β thatβs a perfect terminology because arrow has both a clear direction and a clear magnitude (length).
Vectors are most commonly denoted with a lowercase letter and arrow above, pointing to the right:
Simple, right?Letβs jump into some vector operations now, I know how impatient you must be (*laughs*).
Letβs dive into the first vector operation, which is vector addition (subtraction works the same way, only you would use minus sign instead of the plus, obviously).
There really isnβt much to say about this basic operation, only that it is performed by adding the corresponding components. It helps to drive the point home if you think about what happens to the vector, and not just in term of pure number addition.
Take a look at this photo from Wikipedia Commons:
In a nutshell, to add vector b to the vector a (to get a+b), draw the vector a from the origin, and then draw the vector b from the tip of vector a. Now to get a+b, you only need to connect the origin to the tip of vector b.
Might seem like overkill if you hear this for the first time, but just take a pen and paper and draw this, youβll immediately get the gist of it.
And hereβs the general formula for vector addition:
Now I will do a simple example by hand and later will implement this same example in Python.
Once again, take a piece of paper and draw this β itβs pretty intuitive.
Implementation in Python:
v = np.array([3, 7])u = np.array([2, 2])print(v + u)
As you can see, Numpy allows you to use the addition operator, pretty neat!
Let me quote myself from earlier in this article:
If you only have magnitude, but not direction, then you are talking about scalars.
Which essentially means that a scalar is a single number which can only change the magnitude of the vector, but not itβs direction. What this actually means is that the vector multiplied by any scalar will remain on the same βlineβ, it will have the same direction, only its length will be altered.
Awesome, letβs see the formula for scalar multiplication:
Above, n represents any number. Letβs see an example. Scalar n will be 2, which means that every component of the vector will be multiplied by 2.
Implementation in Python:
v = np.array([3, 7])print(2 * v)
Awesome, letβs go to the next topic!
To calculate the dot product of two vectors, you first need to multiply the corresponding elements (x1 by y1, x2 by y2, and so on) and then sum the product terms.
This concept is actually much easier to under when you see the general formula, so here is it:
Now I will write down a basic example with two vectors in 2-dimensional space:
Implementation in Python:
v = np.array([3, 7])u = np.array([2, 2])print(v.dot(u))
Yeah, thatβs pretty much it about the dot product β not really much to talk about.
Norm is just another term for length or magnitude of a vector and is denoted with double pipes (||) on each side. It is defined as a square root of the sum of squares for each component of a vector, as you will see in the formula below.
The computation is a 3 step process:
Square each componentSum all squaresTake the square root
Square each component
Sum all squares
Take the square root
As you can imagine, the formula is stupidly simple:
And hereβs a practical example of a vector in 2-dimensional space:
Implementation in Python:
v = np.array([3, 2, 7])print(np.linalg.norm(v))
The main reason you are calculating unit vectors is that you care only about the direction, not about the magnitude. This process of normalization involves stripping away the magnitude so it doesnβt skew other calculations.[2]
A unit vector is most often denoted with a hat symbol (^) and is calculated by computing the norm and then dividing each component of the vector with the norm.
Without further ado, hereβs the formula:
As an example, Iβll calculate the unit vector from an arbitrary 3-dimensional vector:
You donβt have to do the last step β to divide by square root β but it makes the final result much more appealing.
Implementation in Python will be a bit different here. There is no built-in function in Numpy for calculating unit vectors (at least I donβt know about it), but because you know the formula, the computation process is trivial. Iβve declared a function which will take a vector as an input, and then return that vector divided by its norm:
def unit_vector(v): return v / np.linalg.norm(v)u = np.array([3, 6, 4])print(unit_vector(u))
This is probably the topic in linear algebra Iβm most excited about. And the reason is that I use it here and there in my daily job for some cool stuff.
Angle calculation between vectors has a lot of practical applications. Itβs widely used in NLP (Natural Language Processing) when looking for strings that are very similar. For example, when TF-IDF is used on some textual data, each input (try thinking of input as an individual email text) is converted into a vector.
By doing so you will be sure that all vectors are of the same dimensions, and if the input contains a certain word at a certain position, the value at the corresponding component of the vector will be 1, and 0 otherwise. If you then calculate the angle between vectors, the ones where angle in the smallest will be more similar (in the email example think of it like two individual emails are on the same topic).
Hope you can see the potential use-cases in your project, if not donβt worry about it, you will see it eventually.
Hereβs the formula for calculating the angle. Nothing fancy, you take the dot product of two vectors and divide that by the product of norms:
And hereβs a really simple example of two arbitrary 3-dimensional vectors:
As with the unit vectors, Numpy doesnβt have a built-in function for angle calculation. But hey, you know the formula, so how hard can it be?The only βtrickβ here is to convert radians to degrees because Numpy will return the result in radians by default. Everything else is as simple as you would expect it to be.
Hereβs the code:
def angle_between(v1, v2): dot_pr = v1.dot(v2) norms = np.linalg.norm(v1) * np.linalg.norm(v2) return np.rad2deg(np.arccos(dot_pr / norms))v = np.array([1, 4, 5])u = np.array([2, 1, 5])print(angle_between(v, u))
And that pretty much ends the talk about vectors. Wasnβt that bad, was it?
Thatβs it for some basic essence of linear algebra for data science, at least when it comes to vectors. The next article will covert matrices, and will be a bit longer than this one.
While you are waiting I would highly advise you to check this amazing channel on YouTube, this playlist in particular. It goes really deep into building intuition behind basic and advanced concepts in linear algebra. This channel is my honest recommendation if you know how to calculate stuff, but donβt really know why you are doing the calculations.
Thanks for reading.
towardsdatascience.com
Loved the article? Become a Medium member to continue learning without limits. Iβll receive a portion of your membership fee if you use the following link, with no extra cost to you. | [
{
"code": null,
"e": 399,
"s": 172,
"text": "Ah, math. You canβt avoid it forever. You can try, and then try harder, but sooner or later some basic intuition behind it will be needed, provided that you are serious in your endeavors to advance your career in data science."
},
{
"code": null,
"e": 458,
"s": 399,
"text": "When it comes to linear algebra, I really like this quote:"
},
{
"code": null,
"e": 520,
"s": 458,
"text": "If Data Science was Batman, Linear Algebra would be Robin.[1]"
},
{
"code": null,
"e": 575,
"s": 520,
"text": "It neatly captures the essence in a non-technical way."
},
{
"code": null,
"e": 610,
"s": 575,
"text": "Why should I study linear algebra?"
},
{
"code": null,
"e": 915,
"s": 610,
"text": "Great question. Simply put, if you understand it, you will be able to develop a better intuition for machine learning and deep learning algorithms and you wonβt treat them as black boxes. Furthermore, you would also be capable of developing algorithms from scratch and making your own variations of them."
},
{
"code": null,
"e": 993,
"s": 915,
"text": "Not only that, but you will also be considered as a cool kid, like these two:"
},
{
"code": null,
"e": 1005,
"s": 993,
"text": "So awesome."
},
{
"code": null,
"e": 1034,
"s": 1005,
"text": "Why should I read this post?"
},
{
"code": null,
"e": 1412,
"s": 1034,
"text": "This post certainly won't teach you every nitty-gritty detail about the topic, there are a plethora of books which cover those. The post also wonβt dive into proofs, again, read a book from some math or tech faculty if you are into that. This post will, however, provide you with an essential intuition behind linear algebra (and some light calculations) in 14 different areas."
},
{
"code": null,
"e": 1706,
"s": 1412,
"text": "Yes, youβve read that right. Iβm planning to cover 14 different topics in two articles. It will take you some time to read it (and for me to write it), but if you are new to this I would strongly advise reading 2β3 topics per day at most, and then searching the web for more practice problems."
},
{
"code": null,
"e": 1737,
"s": 1706,
"text": "How is the article structured?"
},
{
"code": null,
"e": 1784,
"s": 1737,
"text": "So each of the topics is divided into 3 parts:"
},
{
"code": null,
"e": 1875,
"s": 1784,
"text": "Theoretical explanationExample (by hand calculations)Implementation in Python (with Numpy)"
},
{
"code": null,
"e": 1899,
"s": 1875,
"text": "Theoretical explanation"
},
{
"code": null,
"e": 1930,
"s": 1899,
"text": "Example (by hand calculations)"
},
{
"code": null,
"e": 1968,
"s": 1930,
"text": "Implementation in Python (with Numpy)"
},
{
"code": null,
"e": 2078,
"s": 1968,
"text": "I wonβt lie to you β it will be a lot of work. This first part will cover Vectors, and hereβs the topic list:"
},
{
"code": null,
"e": 2155,
"s": 2078,
"text": "AdditionScalar MultiplicationDot ProductNormUnit VectorAngle Between Vectors"
},
{
"code": null,
"e": 2164,
"s": 2155,
"text": "Addition"
},
{
"code": null,
"e": 2186,
"s": 2164,
"text": "Scalar Multiplication"
},
{
"code": null,
"e": 2198,
"s": 2186,
"text": "Dot Product"
},
{
"code": null,
"e": 2203,
"s": 2198,
"text": "Norm"
},
{
"code": null,
"e": 2215,
"s": 2203,
"text": "Unit Vector"
},
{
"code": null,
"e": 2237,
"s": 2215,
"text": "Angle Between Vectors"
},
{
"code": null,
"e": 2409,
"s": 2237,
"text": "Now when the introduction is over, letβs not postpone the inevitable. Grab a cup of coffee (or something stronger) and come with me to the amazing world of linear algebra."
},
{
"code": null,
"e": 2595,
"s": 2409,
"text": "Yeah, no point in starting with vector addition if you have no idea what a vector is. For starters, think of a vector as an arrow in space. You need to keep in mind two quantities here:"
},
{
"code": null,
"e": 2605,
"s": 2595,
"text": "Direction"
},
{
"code": null,
"e": 2615,
"s": 2605,
"text": "Magnitude"
},
{
"code": null,
"e": 2888,
"s": 2615,
"text": "By direction, I mean to where in space does βarrowβ point, and the magnitude tells you how far you should go in that direction. If you only have magnitude, but not direction, then you are talking about scalars. Once you give the scalar some direction, it becomes a vector."
},
{
"code": null,
"e": 3048,
"s": 2888,
"text": "I said that you should try to imagine vectors as arrows β thatβs a perfect terminology because arrow has both a clear direction and a clear magnitude (length)."
},
{
"code": null,
"e": 3146,
"s": 3048,
"text": "Vectors are most commonly denoted with a lowercase letter and arrow above, pointing to the right:"
},
{
"code": null,
"e": 3249,
"s": 3146,
"text": "Simple, right?Letβs jump into some vector operations now, I know how impatient you must be (*laughs*)."
},
{
"code": null,
"e": 3414,
"s": 3249,
"text": "Letβs dive into the first vector operation, which is vector addition (subtraction works the same way, only you would use minus sign instead of the plus, obviously)."
},
{
"code": null,
"e": 3665,
"s": 3414,
"text": "There really isnβt much to say about this basic operation, only that it is performed by adding the corresponding components. It helps to drive the point home if you think about what happens to the vector, and not just in term of pure number addition."
},
{
"code": null,
"e": 3715,
"s": 3665,
"text": "Take a look at this photo from Wikipedia Commons:"
},
{
"code": null,
"e": 3940,
"s": 3715,
"text": "In a nutshell, to add vector b to the vector a (to get a+b), draw the vector a from the origin, and then draw the vector b from the tip of vector a. Now to get a+b, you only need to connect the origin to the tip of vector b."
},
{
"code": null,
"e": 4086,
"s": 3940,
"text": "Might seem like overkill if you hear this for the first time, but just take a pen and paper and draw this, youβll immediately get the gist of it."
},
{
"code": null,
"e": 4138,
"s": 4086,
"text": "And hereβs the general formula for vector addition:"
},
{
"code": null,
"e": 4231,
"s": 4138,
"text": "Now I will do a simple example by hand and later will implement this same example in Python."
},
{
"code": null,
"e": 4304,
"s": 4231,
"text": "Once again, take a piece of paper and draw this β itβs pretty intuitive."
},
{
"code": null,
"e": 4330,
"s": 4304,
"text": "Implementation in Python:"
},
{
"code": null,
"e": 4383,
"s": 4330,
"text": "v = np.array([3, 7])u = np.array([2, 2])print(v + u)"
},
{
"code": null,
"e": 4459,
"s": 4383,
"text": "As you can see, Numpy allows you to use the addition operator, pretty neat!"
},
{
"code": null,
"e": 4509,
"s": 4459,
"text": "Let me quote myself from earlier in this article:"
},
{
"code": null,
"e": 4592,
"s": 4509,
"text": "If you only have magnitude, but not direction, then you are talking about scalars."
},
{
"code": null,
"e": 4891,
"s": 4592,
"text": "Which essentially means that a scalar is a single number which can only change the magnitude of the vector, but not itβs direction. What this actually means is that the vector multiplied by any scalar will remain on the same βlineβ, it will have the same direction, only its length will be altered."
},
{
"code": null,
"e": 4949,
"s": 4891,
"text": "Awesome, letβs see the formula for scalar multiplication:"
},
{
"code": null,
"e": 5095,
"s": 4949,
"text": "Above, n represents any number. Letβs see an example. Scalar n will be 2, which means that every component of the vector will be multiplied by 2."
},
{
"code": null,
"e": 5121,
"s": 5095,
"text": "Implementation in Python:"
},
{
"code": null,
"e": 5154,
"s": 5121,
"text": "v = np.array([3, 7])print(2 * v)"
},
{
"code": null,
"e": 5191,
"s": 5154,
"text": "Awesome, letβs go to the next topic!"
},
{
"code": null,
"e": 5354,
"s": 5191,
"text": "To calculate the dot product of two vectors, you first need to multiply the corresponding elements (x1 by y1, x2 by y2, and so on) and then sum the product terms."
},
{
"code": null,
"e": 5449,
"s": 5354,
"text": "This concept is actually much easier to under when you see the general formula, so here is it:"
},
{
"code": null,
"e": 5528,
"s": 5449,
"text": "Now I will write down a basic example with two vectors in 2-dimensional space:"
},
{
"code": null,
"e": 5554,
"s": 5528,
"text": "Implementation in Python:"
},
{
"code": null,
"e": 5610,
"s": 5554,
"text": "v = np.array([3, 7])u = np.array([2, 2])print(v.dot(u))"
},
{
"code": null,
"e": 5693,
"s": 5610,
"text": "Yeah, thatβs pretty much it about the dot product β not really much to talk about."
},
{
"code": null,
"e": 5930,
"s": 5693,
"text": "Norm is just another term for length or magnitude of a vector and is denoted with double pipes (||) on each side. It is defined as a square root of the sum of squares for each component of a vector, as you will see in the formula below."
},
{
"code": null,
"e": 5967,
"s": 5930,
"text": "The computation is a 3 step process:"
},
{
"code": null,
"e": 6024,
"s": 5967,
"text": "Square each componentSum all squaresTake the square root"
},
{
"code": null,
"e": 6046,
"s": 6024,
"text": "Square each component"
},
{
"code": null,
"e": 6062,
"s": 6046,
"text": "Sum all squares"
},
{
"code": null,
"e": 6083,
"s": 6062,
"text": "Take the square root"
},
{
"code": null,
"e": 6135,
"s": 6083,
"text": "As you can imagine, the formula is stupidly simple:"
},
{
"code": null,
"e": 6202,
"s": 6135,
"text": "And hereβs a practical example of a vector in 2-dimensional space:"
},
{
"code": null,
"e": 6228,
"s": 6202,
"text": "Implementation in Python:"
},
{
"code": null,
"e": 6276,
"s": 6228,
"text": "v = np.array([3, 2, 7])print(np.linalg.norm(v))"
},
{
"code": null,
"e": 6503,
"s": 6276,
"text": "The main reason you are calculating unit vectors is that you care only about the direction, not about the magnitude. This process of normalization involves stripping away the magnitude so it doesnβt skew other calculations.[2]"
},
{
"code": null,
"e": 6663,
"s": 6503,
"text": "A unit vector is most often denoted with a hat symbol (^) and is calculated by computing the norm and then dividing each component of the vector with the norm."
},
{
"code": null,
"e": 6704,
"s": 6663,
"text": "Without further ado, hereβs the formula:"
},
{
"code": null,
"e": 6790,
"s": 6704,
"text": "As an example, Iβll calculate the unit vector from an arbitrary 3-dimensional vector:"
},
{
"code": null,
"e": 6905,
"s": 6790,
"text": "You donβt have to do the last step β to divide by square root β but it makes the final result much more appealing."
},
{
"code": null,
"e": 7244,
"s": 6905,
"text": "Implementation in Python will be a bit different here. There is no built-in function in Numpy for calculating unit vectors (at least I donβt know about it), but because you know the formula, the computation process is trivial. Iβve declared a function which will take a vector as an input, and then return that vector divided by its norm:"
},
{
"code": null,
"e": 7340,
"s": 7244,
"text": "def unit_vector(v): return v / np.linalg.norm(v)u = np.array([3, 6, 4])print(unit_vector(u))"
},
{
"code": null,
"e": 7493,
"s": 7340,
"text": "This is probably the topic in linear algebra Iβm most excited about. And the reason is that I use it here and there in my daily job for some cool stuff."
},
{
"code": null,
"e": 7812,
"s": 7493,
"text": "Angle calculation between vectors has a lot of practical applications. Itβs widely used in NLP (Natural Language Processing) when looking for strings that are very similar. For example, when TF-IDF is used on some textual data, each input (try thinking of input as an individual email text) is converted into a vector."
},
{
"code": null,
"e": 8225,
"s": 7812,
"text": "By doing so you will be sure that all vectors are of the same dimensions, and if the input contains a certain word at a certain position, the value at the corresponding component of the vector will be 1, and 0 otherwise. If you then calculate the angle between vectors, the ones where angle in the smallest will be more similar (in the email example think of it like two individual emails are on the same topic)."
},
{
"code": null,
"e": 8340,
"s": 8225,
"text": "Hope you can see the potential use-cases in your project, if not donβt worry about it, you will see it eventually."
},
{
"code": null,
"e": 8482,
"s": 8340,
"text": "Hereβs the formula for calculating the angle. Nothing fancy, you take the dot product of two vectors and divide that by the product of norms:"
},
{
"code": null,
"e": 8557,
"s": 8482,
"text": "And hereβs a really simple example of two arbitrary 3-dimensional vectors:"
},
{
"code": null,
"e": 8872,
"s": 8557,
"text": "As with the unit vectors, Numpy doesnβt have a built-in function for angle calculation. But hey, you know the formula, so how hard can it be?The only βtrickβ here is to convert radians to degrees because Numpy will return the result in radians by default. Everything else is as simple as you would expect it to be."
},
{
"code": null,
"e": 8889,
"s": 8872,
"text": "Hereβs the code:"
},
{
"code": null,
"e": 9111,
"s": 8889,
"text": "def angle_between(v1, v2): dot_pr = v1.dot(v2) norms = np.linalg.norm(v1) * np.linalg.norm(v2) return np.rad2deg(np.arccos(dot_pr / norms))v = np.array([1, 4, 5])u = np.array([2, 1, 5])print(angle_between(v, u))"
},
{
"code": null,
"e": 9186,
"s": 9111,
"text": "And that pretty much ends the talk about vectors. Wasnβt that bad, was it?"
},
{
"code": null,
"e": 9369,
"s": 9186,
"text": "Thatβs it for some basic essence of linear algebra for data science, at least when it comes to vectors. The next article will covert matrices, and will be a bit longer than this one."
},
{
"code": null,
"e": 9721,
"s": 9369,
"text": "While you are waiting I would highly advise you to check this amazing channel on YouTube, this playlist in particular. It goes really deep into building intuition behind basic and advanced concepts in linear algebra. This channel is my honest recommendation if you know how to calculate stuff, but donβt really know why you are doing the calculations."
},
{
"code": null,
"e": 9741,
"s": 9721,
"text": "Thanks for reading."
},
{
"code": null,
"e": 9764,
"s": 9741,
"text": "towardsdatascience.com"
}
] |
How to set initial value and auto increment in MySQL? | The AUTO_INCREMENT attribute is used to generate a unique identify for new rows. If a column is declared as βNOT NULLβ, it is possible to assign NULL to that column to generate a sequence of numbers.
When any value is inserted into an AUTO_INCREMENT column, the column gets set to that value, and the sequence also gets reset so that it generates values automatically, in the sequential range from largest column value.
An existing βAUTO_INCREMENTβ column can be updated that will reset the βAUTO_INCREMENTβ sequence as well. The most recent auto-generated βAUTO_INCREMENT; value can be retrieved using the βLAST_INSERT_ID()β function in SQL or using the βmysql_insert_id()β which is a C API function.
These functions are connection-specific, which means their return values are not affected by other connections which perform the insert operations. The smallest integer data type for βAUTO_INCREMENTβ column can be used, which would be large enough to hold the maximum sequence value which is required by the user.
The following rules need to be followed while using the AUTO_INCREMENT attribute β
Every table has only one AUTO_INCREMENT column whose data type would be an
integer typically.
Every table has only one AUTO_INCREMENT column whose data type would be an
integer typically.
The AUTO_INCREMENT column needs to be indexed. This means it can either be a
PRIMARY KEY or a UNIQUE index.
The AUTO_INCREMENT column needs to be indexed. This means it can either be a
PRIMARY KEY or a UNIQUE index.
The AUTO_INCREMENT column must have a NOT NULL constraint on it.
The AUTO_INCREMENT column must have a NOT NULL constraint on it.
When the AUTO_INCREMENT attribute is set to a column, MySQL automatically adds
the NOT NULL constraint to the column on its own.
When the AUTO_INCREMENT attribute is set to a column, MySQL automatically adds
the NOT NULL constraint to the column on its own.
If an id column hasnβt been added to the table, the below statement can be used β
ALTER TABLE tableName ADD id INT UNSIGNED NOT NULL AUTO_INCREMENT, ADD INDEX (id);
If an id column is already present, then the below command can be used β
ALTER TABLE tableName AUTO_INCREMENT=specificValue;
Here, tableName refers to the name of the table fr which the βAUTO_INCREMENTβ column needs to be set. The βspecificValueβ refers to an integer from where the βAUTO_INCREMENTβ values are specified by the user to begin. | [
{
"code": null,
"e": 1262,
"s": 1062,
"text": "The AUTO_INCREMENT attribute is used to generate a unique identify for new rows. If a column is declared as βNOT NULLβ, it is possible to assign NULL to that column to generate a sequence of numbers."
},
{
"code": null,
"e": 1482,
"s": 1262,
"text": "When any value is inserted into an AUTO_INCREMENT column, the column gets set to that value, and the sequence also gets reset so that it generates values automatically, in the sequential range from largest column value."
},
{
"code": null,
"e": 1764,
"s": 1482,
"text": "An existing βAUTO_INCREMENTβ column can be updated that will reset the βAUTO_INCREMENTβ sequence as well. The most recent auto-generated βAUTO_INCREMENT; value can be retrieved using the βLAST_INSERT_ID()β function in SQL or using the βmysql_insert_id()β which is a C API function."
},
{
"code": null,
"e": 2078,
"s": 1764,
"text": "These functions are connection-specific, which means their return values are not affected by other connections which perform the insert operations. The smallest integer data type for βAUTO_INCREMENTβ column can be used, which would be large enough to hold the maximum sequence value which is required by the user."
},
{
"code": null,
"e": 2161,
"s": 2078,
"text": "The following rules need to be followed while using the AUTO_INCREMENT attribute β"
},
{
"code": null,
"e": 2255,
"s": 2161,
"text": "Every table has only one AUTO_INCREMENT column whose data type would be an\ninteger typically."
},
{
"code": null,
"e": 2349,
"s": 2255,
"text": "Every table has only one AUTO_INCREMENT column whose data type would be an\ninteger typically."
},
{
"code": null,
"e": 2457,
"s": 2349,
"text": "The AUTO_INCREMENT column needs to be indexed. This means it can either be a\nPRIMARY KEY or a UNIQUE index."
},
{
"code": null,
"e": 2565,
"s": 2457,
"text": "The AUTO_INCREMENT column needs to be indexed. This means it can either be a\nPRIMARY KEY or a UNIQUE index."
},
{
"code": null,
"e": 2630,
"s": 2565,
"text": "The AUTO_INCREMENT column must have a NOT NULL constraint on it."
},
{
"code": null,
"e": 2695,
"s": 2630,
"text": "The AUTO_INCREMENT column must have a NOT NULL constraint on it."
},
{
"code": null,
"e": 2824,
"s": 2695,
"text": "When the AUTO_INCREMENT attribute is set to a column, MySQL automatically adds\nthe NOT NULL constraint to the column on its own."
},
{
"code": null,
"e": 2953,
"s": 2824,
"text": "When the AUTO_INCREMENT attribute is set to a column, MySQL automatically adds\nthe NOT NULL constraint to the column on its own."
},
{
"code": null,
"e": 3035,
"s": 2953,
"text": "If an id column hasnβt been added to the table, the below statement can be used β"
},
{
"code": null,
"e": 3118,
"s": 3035,
"text": "ALTER TABLE tableName ADD id INT UNSIGNED NOT NULL AUTO_INCREMENT, ADD INDEX (id);"
},
{
"code": null,
"e": 3191,
"s": 3118,
"text": "If an id column is already present, then the below command can be used β"
},
{
"code": null,
"e": 3243,
"s": 3191,
"text": "ALTER TABLE tableName AUTO_INCREMENT=specificValue;"
},
{
"code": null,
"e": 3461,
"s": 3243,
"text": "Here, tableName refers to the name of the table fr which the βAUTO_INCREMENTβ column needs to be set. The βspecificValueβ refers to an integer from where the βAUTO_INCREMENTβ values are specified by the user to begin."
}
] |
fork() and Binary Tree - GeeksforGeeks | 10 Jul, 2018
Given a program on fork() system call.
#include <stdio.h>#include <unistd.h>int main(){ fork(); fork() && fork() || fork(); fork(); printf("forked\n"); return 0;}
How many processes will be spawned after executing the above program?
A fork() system call spawn processes as leaves of growing binary tree. If we call fork() twice, it will spawn 22 = 4 processes. All these 4 processes forms the leaf children of binary tree. In general if we are level l, and fork() called unconditionally, we will have 2l processes at level (l+1). It is equivalent to number of maximum child nodes in a binary tree at level (l+1).
As another example, assume that we have invoked fork() call 3 times unconditionally. We can represent the spawned process using a full binary tree with 3 levels. At level 3, we will have 23 = 8 child nodes, which corresponds to number of processes running.
A note on C/C++ logical operators:
The logical operator && has more precedence than ||, and have left to right associativity. After executing left operand, the final result will be estimated and execution of right operand depends on outcome of left operand as well as type of operation.
In case of AND (&&), after evaluation of left operand, right operand will be evaluated only if left operand evaluates to non-zero. In case of OR (||), after evaluation of left operand, right operand will be evaluated only if left operand evaluates to zero.
Return value of fork():
The man pages of fork() cites the following excerpt on return value,
βOn success, the PID of the child process is returned in the parent, and 0 is returned in the child. On failure, -1 is returned in the parent, no child process is created, and errno is set appropriately.β
A PID is like handle of process and represented as unsigned int. We can conclude, the fork() will return a non-zero in parent and zero in child. Let us analyse the program. For easy notation, label each fork() as shown below,
#include <stdio.h>
int main()
{
fork(); /* A */
( fork() /* B */ &&
fork() /* C */ ) || /* B and C are grouped according to precedence */
fork(); /* D */
fork(); /* E */
printf("forked\n");
return 0;
}
The following diagram provides pictorial representation of fork-ing new processes. All newly created processes are propagated on right side of tree, and parents are propagated on left side of tree, in consecutive levels.
The first two fork() calls are called unconditionally.
At level 0, we have only main process. The main (m in diagram) will create child C1 and both will continue execution. The children are numbered in increasing order of their creation.
At level 1, we have m and C1 running, and ready to execute fork() β B. (Note that B, C and D named as operands of && and || operators). The initial expression B will be executed in every children and parent process running at this level.
At level 2, due to fork() β B executed by m and C1, we have m and C1 as parents and, C2 and C3 as children.
The return value of fork() β B is non-zero in parent, and zero in child. Since the first operator is &&, because of zero return value, the children C2 and C3 will not execute next expression (fork()- C). Parents processes m and C1 will continue with fork() β C. The children C2 and C3 will directly execute fork() β D, to evaluate value of logical OR operation.
At level 3, we have m, C1, C2, C3 as running processes and C4, C5 as children. The expression is now simplified to ((B && C) || D), and at this point the value of (B && C) is obvious. In parents it is non-zero and in children it is zero. Hence, the parents aware of outcome of overall B && C || D, will skip execution of fork() β D. Since, in the children (B && C) evaluated to zero, they will execute fork() β D. We should note that children C2 and C3 created at level 2, will also run fork() β D as mentioned above.
At level 4, we will have m, C1, C2, C3, C4, C5 as running processes and C6, C7, C8 and C9 as child processes. All these processes unconditionally execute fork() β E, and spawns one child.
At level 5, we will have 20 processes running. The program (on Ubuntu Maverick, GCC 4.4.5) printed βforkedβ 20 times. Once by root parent (main) and rest by children. Overall there will be 19 processes spawned.
A note on order of evaluation:
The evaluation order of expressions in binary operators is unspecified. For details read the post Evaluation order of operands. However, the logical operators are an exception. They are guaranteed to evaluate from left to right.
Contributed by Venki. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
system-programming
C++
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Operator Overloading in C++
Polymorphism in C++
Friend class and function in C++
Iterators in C++ STL
Sorting a vector in C++
Convert string to char array in C++
Inline Functions in C++
List in C++ Standard Template Library (STL)
new and delete operators in C++ for dynamic memory
Destructors in C++ | [
{
"code": null,
"e": 24122,
"s": 24094,
"text": "\n10 Jul, 2018"
},
{
"code": null,
"e": 24161,
"s": 24122,
"text": "Given a program on fork() system call."
},
{
"code": "#include <stdio.h>#include <unistd.h>int main(){ fork(); fork() && fork() || fork(); fork(); printf(\"forked\\n\"); return 0;}",
"e": 24297,
"s": 24161,
"text": null
},
{
"code": null,
"e": 24367,
"s": 24297,
"text": "How many processes will be spawned after executing the above program?"
},
{
"code": null,
"e": 24747,
"s": 24367,
"text": "A fork() system call spawn processes as leaves of growing binary tree. If we call fork() twice, it will spawn 22 = 4 processes. All these 4 processes forms the leaf children of binary tree. In general if we are level l, and fork() called unconditionally, we will have 2l processes at level (l+1). It is equivalent to number of maximum child nodes in a binary tree at level (l+1)."
},
{
"code": null,
"e": 25004,
"s": 24747,
"text": "As another example, assume that we have invoked fork() call 3 times unconditionally. We can represent the spawned process using a full binary tree with 3 levels. At level 3, we will have 23 = 8 child nodes, which corresponds to number of processes running."
},
{
"code": null,
"e": 25039,
"s": 25004,
"text": "A note on C/C++ logical operators:"
},
{
"code": null,
"e": 25291,
"s": 25039,
"text": "The logical operator && has more precedence than ||, and have left to right associativity. After executing left operand, the final result will be estimated and execution of right operand depends on outcome of left operand as well as type of operation."
},
{
"code": null,
"e": 25548,
"s": 25291,
"text": "In case of AND (&&), after evaluation of left operand, right operand will be evaluated only if left operand evaluates to non-zero. In case of OR (||), after evaluation of left operand, right operand will be evaluated only if left operand evaluates to zero."
},
{
"code": null,
"e": 25572,
"s": 25548,
"text": "Return value of fork():"
},
{
"code": null,
"e": 25641,
"s": 25572,
"text": "The man pages of fork() cites the following excerpt on return value,"
},
{
"code": null,
"e": 25848,
"s": 25641,
"text": "βOn success, the PID of the child process is returned in the parent, and 0 is returned in the child. On failure, -1 is returned in the parent, no child process is created, and errno is set appropriately.β"
},
{
"code": null,
"e": 26074,
"s": 25848,
"text": "A PID is like handle of process and represented as unsigned int. We can conclude, the fork() will return a non-zero in parent and zero in child. Let us analyse the program. For easy notation, label each fork() as shown below,"
},
{
"code": null,
"e": 26302,
"s": 26074,
"text": "#include <stdio.h>\nint main()\n{\n fork(); /* A */\n ( fork() /* B */ &&\n fork() /* C */ ) || /* B and C are grouped according to precedence */\n fork(); /* D */\n fork(); /* E */\n\n printf(\"forked\\n\");\n return 0;\n}"
},
{
"code": null,
"e": 26523,
"s": 26302,
"text": "The following diagram provides pictorial representation of fork-ing new processes. All newly created processes are propagated on right side of tree, and parents are propagated on left side of tree, in consecutive levels."
},
{
"code": null,
"e": 26578,
"s": 26523,
"text": "The first two fork() calls are called unconditionally."
},
{
"code": null,
"e": 26761,
"s": 26578,
"text": "At level 0, we have only main process. The main (m in diagram) will create child C1 and both will continue execution. The children are numbered in increasing order of their creation."
},
{
"code": null,
"e": 26999,
"s": 26761,
"text": "At level 1, we have m and C1 running, and ready to execute fork() β B. (Note that B, C and D named as operands of && and || operators). The initial expression B will be executed in every children and parent process running at this level."
},
{
"code": null,
"e": 27107,
"s": 26999,
"text": "At level 2, due to fork() β B executed by m and C1, we have m and C1 as parents and, C2 and C3 as children."
},
{
"code": null,
"e": 27469,
"s": 27107,
"text": "The return value of fork() β B is non-zero in parent, and zero in child. Since the first operator is &&, because of zero return value, the children C2 and C3 will not execute next expression (fork()- C). Parents processes m and C1 will continue with fork() β C. The children C2 and C3 will directly execute fork() β D, to evaluate value of logical OR operation."
},
{
"code": null,
"e": 27987,
"s": 27469,
"text": "At level 3, we have m, C1, C2, C3 as running processes and C4, C5 as children. The expression is now simplified to ((B && C) || D), and at this point the value of (B && C) is obvious. In parents it is non-zero and in children it is zero. Hence, the parents aware of outcome of overall B && C || D, will skip execution of fork() β D. Since, in the children (B && C) evaluated to zero, they will execute fork() β D. We should note that children C2 and C3 created at level 2, will also run fork() β D as mentioned above."
},
{
"code": null,
"e": 28175,
"s": 27987,
"text": "At level 4, we will have m, C1, C2, C3, C4, C5 as running processes and C6, C7, C8 and C9 as child processes. All these processes unconditionally execute fork() β E, and spawns one child."
},
{
"code": null,
"e": 28386,
"s": 28175,
"text": "At level 5, we will have 20 processes running. The program (on Ubuntu Maverick, GCC 4.4.5) printed βforkedβ 20 times. Once by root parent (main) and rest by children. Overall there will be 19 processes spawned."
},
{
"code": null,
"e": 28417,
"s": 28386,
"text": "A note on order of evaluation:"
},
{
"code": null,
"e": 28646,
"s": 28417,
"text": "The evaluation order of expressions in binary operators is unspecified. For details read the post Evaluation order of operands. However, the logical operators are an exception. They are guaranteed to evaluate from left to right."
},
{
"code": null,
"e": 28793,
"s": 28646,
"text": "Contributed by Venki. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 28812,
"s": 28793,
"text": "system-programming"
},
{
"code": null,
"e": 28816,
"s": 28812,
"text": "C++"
},
{
"code": null,
"e": 28820,
"s": 28816,
"text": "CPP"
},
{
"code": null,
"e": 28918,
"s": 28820,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28927,
"s": 28918,
"text": "Comments"
},
{
"code": null,
"e": 28940,
"s": 28927,
"text": "Old Comments"
},
{
"code": null,
"e": 28968,
"s": 28940,
"text": "Operator Overloading in C++"
},
{
"code": null,
"e": 28988,
"s": 28968,
"text": "Polymorphism in C++"
},
{
"code": null,
"e": 29021,
"s": 28988,
"text": "Friend class and function in C++"
},
{
"code": null,
"e": 29042,
"s": 29021,
"text": "Iterators in C++ STL"
},
{
"code": null,
"e": 29066,
"s": 29042,
"text": "Sorting a vector in C++"
},
{
"code": null,
"e": 29102,
"s": 29066,
"text": "Convert string to char array in C++"
},
{
"code": null,
"e": 29126,
"s": 29102,
"text": "Inline Functions in C++"
},
{
"code": null,
"e": 29170,
"s": 29126,
"text": "List in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 29221,
"s": 29170,
"text": "new and delete operators in C++ for dynamic memory"
}
] |
Associative arrays in C++ - GeeksforGeeks | 09 Feb, 2022
Associative arrays are also called map or dictionaries. In C++. These are special kind of arrays, where indexing can be numeric or any other data type i.e can be numeric 0, 1, 2, 3.. OR character a, b, c, d... OR string geek, computers... These indexes are referred as keys and data stored at that position is called value. So in associative array we have (key, value) pair. We use STL maps to implement the concept of associative arrays in C++.
Example: Now we have to print the marks of computer geeks whose names and marks are as follows
Name Marks
Jessie 100
Suraj 91
Praveen 99
Bisa 78
Rithvik 84
CPP
// CPP program to demonstrate associative arrays#include <bits/stdc++.h>using namespace std;int main(){ // the first data type i.e string represents // the type of key we want the second data type // i.e int represents the type of values we // want to store at that location map<string, int> marks{ { "Rithvik", 78 }, { "Suraj", 91 }, { "Jessie", 100 }, { "Praveen", 99 }, { "Bisa", 84 } }; map<string, int>::iterator i; cout << "The marks of all students are" << endl; for (i = marks.begin(); i != marks.end(); i++) cout << i->second << " "; cout << endl; // the marks of the students based on there names. cout << "the marks of Computer geek Jessie are" << " " << marks["Jessie"] << endl; cout << "the marks of geeksforgeeks contributor" " Praveen are " << marks["Praveen"] << endl;}
The marks of all students are
84 100 99 78 91
the marks of Computer geek Jessie are 100
the marks of geeksforgeeks
Praveen are 99
simranarora5sos
cpp-map
STL
C++
Technical Scripter
STL
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Inheritance in C++
Socket Programming in C/C++
C++ Classes and Objects
Operator Overloading in C++
Multidimensional Arrays in C / C++
Virtual Function in C++
Bitwise Operators in C/C++
Constructors in C++
Templates in C++ with Examples
Copy Constructor in C++ | [
{
"code": null,
"e": 24528,
"s": 24500,
"text": "\n09 Feb, 2022"
},
{
"code": null,
"e": 24975,
"s": 24528,
"text": "Associative arrays are also called map or dictionaries. In C++. These are special kind of arrays, where indexing can be numeric or any other data type i.e can be numeric 0, 1, 2, 3.. OR character a, b, c, d... OR string geek, computers... These indexes are referred as keys and data stored at that position is called value. So in associative array we have (key, value) pair. We use STL maps to implement the concept of associative arrays in C++. "
},
{
"code": null,
"e": 25072,
"s": 24975,
"text": "Example: Now we have to print the marks of computer geeks whose names and marks are as follows "
},
{
"code": null,
"e": 25211,
"s": 25072,
"text": " Name Marks\n Jessie 100\n Suraj 91\n Praveen 99 \n Bisa 78\n Rithvik 84"
},
{
"code": null,
"e": 25217,
"s": 25213,
"text": "CPP"
},
{
"code": "// CPP program to demonstrate associative arrays#include <bits/stdc++.h>using namespace std;int main(){ // the first data type i.e string represents // the type of key we want the second data type // i.e int represents the type of values we // want to store at that location map<string, int> marks{ { \"Rithvik\", 78 }, { \"Suraj\", 91 }, { \"Jessie\", 100 }, { \"Praveen\", 99 }, { \"Bisa\", 84 } }; map<string, int>::iterator i; cout << \"The marks of all students are\" << endl; for (i = marks.begin(); i != marks.end(); i++) cout << i->second << \" \"; cout << endl; // the marks of the students based on there names. cout << \"the marks of Computer geek Jessie are\" << \" \" << marks[\"Jessie\"] << endl; cout << \"the marks of geeksforgeeks contributor\" \" Praveen are \" << marks[\"Praveen\"] << endl;}",
"e": 26095,
"s": 25217,
"text": null
},
{
"code": null,
"e": 26212,
"s": 26095,
"text": "The marks of all students are\n84 100 99 78 91 \nthe marks of Computer geek Jessie are 100\nthe marks of geeksforgeeks "
},
{
"code": null,
"e": 26228,
"s": 26212,
"text": " Praveen are 99"
},
{
"code": null,
"e": 26246,
"s": 26230,
"text": "simranarora5sos"
},
{
"code": null,
"e": 26254,
"s": 26246,
"text": "cpp-map"
},
{
"code": null,
"e": 26258,
"s": 26254,
"text": "STL"
},
{
"code": null,
"e": 26262,
"s": 26258,
"text": "C++"
},
{
"code": null,
"e": 26281,
"s": 26262,
"text": "Technical Scripter"
},
{
"code": null,
"e": 26285,
"s": 26281,
"text": "STL"
},
{
"code": null,
"e": 26289,
"s": 26285,
"text": "CPP"
},
{
"code": null,
"e": 26387,
"s": 26289,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26396,
"s": 26387,
"text": "Comments"
},
{
"code": null,
"e": 26409,
"s": 26396,
"text": "Old Comments"
},
{
"code": null,
"e": 26428,
"s": 26409,
"text": "Inheritance in C++"
},
{
"code": null,
"e": 26456,
"s": 26428,
"text": "Socket Programming in C/C++"
},
{
"code": null,
"e": 26480,
"s": 26456,
"text": "C++ Classes and Objects"
},
{
"code": null,
"e": 26508,
"s": 26480,
"text": "Operator Overloading in C++"
},
{
"code": null,
"e": 26543,
"s": 26508,
"text": "Multidimensional Arrays in C / C++"
},
{
"code": null,
"e": 26567,
"s": 26543,
"text": "Virtual Function in C++"
},
{
"code": null,
"e": 26594,
"s": 26567,
"text": "Bitwise Operators in C/C++"
},
{
"code": null,
"e": 26614,
"s": 26594,
"text": "Constructors in C++"
},
{
"code": null,
"e": 26645,
"s": 26614,
"text": "Templates in C++ with Examples"
}
] |
GATE | GATE-CS-2003 | Question 79 - GeeksforGeeks | 28 Jun, 2021
A processor uses 2-level page tables for virtual to physical address translation. Page tables for both levels are stored in the main memory. Virtual and physical addresses are both 32 bits wide. The memory is byte addressable. For virtual to physical address translation, the 10 most significant bits of the virtual address are used as index into the first level page table while the next 10 bits are used as index into the second level page table. The 12 least significant bits of the virtual address are used as offset within the page. Assume that the page table entries in both levels of page tables are 4 bytes wide. Further, the processor has a translation look-aside buffer (TLB), with a hit rate of 96%. The TLB caches recently used virtual page numbers and the corresponding physical page numbers. The processor also has a physically addressed cache with a hit rate of 90%. Main memory access time is 10 ns, cache access time is 1 ns, and TLB access time is also 1 ns.
Suppose a process has only the following pages in its virtual address space: two contiguous code pages starting at virtual address 0x00000000, two contiguous data pages starting at virtual address 0Γ00400000, and a stack page starting at virtual address 0ΓFFFFF000. The amount of memory required for storing the page tables of this process is:(A) 8 KB(B) 12 KB(C) 16 KB(D) 20 KBAnswer: (C)Explanation:
Breakup of given addresses into bit form:-
32bits are broken up as 10bits (L2) | 10bits (L1) | 12bits (offset)
first code page:
0x00000000 = 0000 0000 00 | 00 0000 0000 | 0000 0000 0000
so next code page will start from
0x00001000 = 0000 0000 00 | 00 0000 0001 | 0000 0000 0000
first data page:
0x00400000 = 0000 0000 01 | 00 0000 0000 | 0000 0000 0000
so next data page will start from
0x00401000 = 0000 0000 01 | 00 0000 0001 | 0000 0000 0000
only one stack page:
0xFFFFF000 = 1111 1111 11 | 11 1111 1111 | 0000 0000 0000
Now, for second level page table, we will just require 1 Page
which will contain following 3 distinct entries i.e. 0000 0000 00,
0000 0000 01, 1111 1111 11.
Now, for each of these distinct entries, we will have 1-1 page
in Level-1.
Hence, we will have in total 4 pages and page size = 2^12 = 4KB.
Therefore, Memory required to store page table = 4*4KB = 16KB.
Quiz of this Question
GATE-CS-2003
GATE-GATE-CS-2003
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GATE | GATE-CS-2014-(Set-3) | Question 65
GATE | GATE-CS-2006 | Question 49
GATE | GATE-CS-2004 | Question 3
GATE | GATE CS 2010 | Question 24
GATE | GATE CS 2011 | Question 65
GATE | GATE CS 2019 | Question 27
GATE | GATE CS 2021 | Set 1 | Question 47
GATE | GATE CS 2011 | Question 7
GATE | GATE-CS-2017 (Set 2) | Question 42
GATE | GATE-IT-2004 | Question 71 | [
{
"code": null,
"e": 24440,
"s": 24412,
"text": "\n28 Jun, 2021"
},
{
"code": null,
"e": 25417,
"s": 24440,
"text": "A processor uses 2-level page tables for virtual to physical address translation. Page tables for both levels are stored in the main memory. Virtual and physical addresses are both 32 bits wide. The memory is byte addressable. For virtual to physical address translation, the 10 most significant bits of the virtual address are used as index into the first level page table while the next 10 bits are used as index into the second level page table. The 12 least significant bits of the virtual address are used as offset within the page. Assume that the page table entries in both levels of page tables are 4 bytes wide. Further, the processor has a translation look-aside buffer (TLB), with a hit rate of 96%. The TLB caches recently used virtual page numbers and the corresponding physical page numbers. The processor also has a physically addressed cache with a hit rate of 90%. Main memory access time is 10 ns, cache access time is 1 ns, and TLB access time is also 1 ns."
},
{
"code": null,
"e": 25819,
"s": 25417,
"text": "Suppose a process has only the following pages in its virtual address space: two contiguous code pages starting at virtual address 0x00000000, two contiguous data pages starting at virtual address 0Γ00400000, and a stack page starting at virtual address 0ΓFFFFF000. The amount of memory required for storing the page tables of this process is:(A) 8 KB(B) 12 KB(C) 16 KB(D) 20 KBAnswer: (C)Explanation:"
},
{
"code": null,
"e": 26711,
"s": 25819,
"text": "Breakup of given addresses into bit form:-\n32bits are broken up as 10bits (L2) | 10bits (L1) | 12bits (offset)\n\nfirst code page:\n0x00000000 = 0000 0000 00 | 00 0000 0000 | 0000 0000 0000\n\nso next code page will start from\n0x00001000 = 0000 0000 00 | 00 0000 0001 | 0000 0000 0000\n\nfirst data page:\n0x00400000 = 0000 0000 01 | 00 0000 0000 | 0000 0000 0000\n\nso next data page will start from\n0x00401000 = 0000 0000 01 | 00 0000 0001 | 0000 0000 0000\n\nonly one stack page:\n0xFFFFF000 = 1111 1111 11 | 11 1111 1111 | 0000 0000 0000\n\nNow, for second level page table, we will just require 1 Page \nwhich will contain following 3 distinct entries i.e. 0000 0000 00,\n0000 0000 01, 1111 1111 11.\nNow, for each of these distinct entries, we will have 1-1 page\nin Level-1.\n\nHence, we will have in total 4 pages and page size = 2^12 = 4KB.\nTherefore, Memory required to store page table = 4*4KB = 16KB."
},
{
"code": null,
"e": 26733,
"s": 26711,
"text": "Quiz of this Question"
},
{
"code": null,
"e": 26746,
"s": 26733,
"text": "GATE-CS-2003"
},
{
"code": null,
"e": 26764,
"s": 26746,
"text": "GATE-GATE-CS-2003"
},
{
"code": null,
"e": 26769,
"s": 26764,
"text": "GATE"
},
{
"code": null,
"e": 26867,
"s": 26769,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26909,
"s": 26867,
"text": "GATE | GATE-CS-2014-(Set-3) | Question 65"
},
{
"code": null,
"e": 26943,
"s": 26909,
"text": "GATE | GATE-CS-2006 | Question 49"
},
{
"code": null,
"e": 26976,
"s": 26943,
"text": "GATE | GATE-CS-2004 | Question 3"
},
{
"code": null,
"e": 27010,
"s": 26976,
"text": "GATE | GATE CS 2010 | Question 24"
},
{
"code": null,
"e": 27044,
"s": 27010,
"text": "GATE | GATE CS 2011 | Question 65"
},
{
"code": null,
"e": 27078,
"s": 27044,
"text": "GATE | GATE CS 2019 | Question 27"
},
{
"code": null,
"e": 27120,
"s": 27078,
"text": "GATE | GATE CS 2021 | Set 1 | Question 47"
},
{
"code": null,
"e": 27153,
"s": 27120,
"text": "GATE | GATE CS 2011 | Question 7"
},
{
"code": null,
"e": 27195,
"s": 27153,
"text": "GATE | GATE-CS-2017 (Set 2) | Question 42"
}
] |
Populating Next Right Pointers in Each Node in C++ | Suppose we have a complete binary tree, where each node has following fields: (data, left, right, next), the left will point to left subtree, right will point to right subtree, and the next pointer will point to the next node. If there is no node in the right hand side, then that will be null. So initially each next pointer is set to null, we have to make the links. Suppose the tree is like the first one, it will be converted to the next node β
To solve this, we will follow these steps β
set pre := root, nextPre := null and prev := null
while pre is not nullwhile pre is not nullif left of pre is not nullset next of prev := left of pre, when prev is not null, otherwise nextPre := left of preprev := left of preif right of pre is not nullset next of prev := right of pre, when prev is not null, otherwise nextPre := right of preprev := right of prepre := nextPreset nextPre as null and prev as null
while pre is not nullif left of pre is not nullset next of prev := left of pre, when prev is not null, otherwise nextPre := left of preprev := left of preif right of pre is not nullset next of prev := right of pre, when prev is not null, otherwise nextPre := right of preprev := right of pre
if left of pre is not nullset next of prev := left of pre, when prev is not null, otherwise nextPre := left of preprev := left of pre
set next of prev := left of pre, when prev is not null, otherwise nextPre := left of pre
prev := left of pre
if right of pre is not nullset next of prev := right of pre, when prev is not null, otherwise nextPre := right of preprev := right of pre
set next of prev := right of pre, when prev is not null, otherwise nextPre := right of pre
prev := right of pre
pre := nextPre
set nextPre as null and prev as null
return null
Let us see the following implementation to get better understanding β
Live Demo
#include <bits/stdc++.h>
#include <stack>
using namespace std;
class Node {
public:
int val;
Node* left;
Node* right;
Node* next;
Node() {}
Node(int _val, Node* _left, Node* _right) {
val = _val;
left = _left;
right = _right;
next = NULL;
}
};
class Solution {
public:
Node* connect(Node* root) {
Node* pre = root;
Node* nextPre = NULL;
Node* prev = NULL;
while(pre){
while(pre){
//cout << pre->val << endl;
if(pre->left){
if(prev){
prev->next = pre->left;
}else{
nextPre = pre->left;
}
prev = pre->left;
}
if(pre->right){
if(prev){
prev->next = pre->right;
}else{
nextPre = pre->right;
}
prev = pre->right;
}
pre = pre->next;
}
//cout << "*" << endl;
pre = nextPre;
nextPre = NULL;
prev = NULL;
}
return root;
}
};
void printTree(Node* root) {
cout << "[";
if (root == NULL) return;
queue<Node*> q;
Node *curr;
q.push(root);
q.push(NULL);
while (q.size() > 1) {
curr = q.front();
q.pop();
if (curr == NULL){
q.push(NULL);
}
else {
// if(curr->next)
// q.push(curr->next);
if(curr->left)
q.push(curr->left);
if(curr->right)
q.push(curr->right);
if(curr->val == 0){
cout << "null" << ", ";
}else{
cout << curr->val << ", ";
if (curr->next == NULL) cout<<"#, ";
}
}
}
cout << "]"<<endl;
}
int main() {
Node* root;
Node nodeFour(4, NULL, NULL);
Node nodeFive(5, NULL, NULL );
Node nodeSeven(7, NULL, NULL);
Node nodeSix(6, NULL, NULL);
Node nodeTwo(2,&nodeFour,&nodeFive);
Node nodeThree(3,&nodeSix,&nodeSeven);
Node nodeOne(1,&nodeTwo,&nodeThree);
root = &nodeOne;
Solution ob;
root = ob.connect(root);
printTree(root);
}
[1,2,3,4,5,6,7]
Node* root;
Node nodeFour(4, NULL, NULL);
Node nodeFive(5, NULL, NULL );
Node nodeSeven(7, NULL, NULL);
Node nodeSix(6, NULL, NULL);
Node nodeTwo(2,&nodeFour,&nodeFive);
Node nodeThree(3,&nodeSix,&nodeSeven);
Node nodeOne(1,&nodeTwo,&nodeThree);
root = &nodeOne;
Solution ob;
root = ob.connect(root);
[1, #, 2, 3, #, 4, 5, 6, 7, #, ] | [
{
"code": null,
"e": 1511,
"s": 1062,
"text": "Suppose we have a complete binary tree, where each node has following fields: (data, left, right, next), the left will point to left subtree, right will point to right subtree, and the next pointer will point to the next node. If there is no node in the right hand side, then that will be null. So initially each next pointer is set to null, we have to make the links. Suppose the tree is like the first one, it will be converted to the next node β"
},
{
"code": null,
"e": 1555,
"s": 1511,
"text": "To solve this, we will follow these steps β"
},
{
"code": null,
"e": 1605,
"s": 1555,
"text": "set pre := root, nextPre := null and prev := null"
},
{
"code": null,
"e": 1968,
"s": 1605,
"text": "while pre is not nullwhile pre is not nullif left of pre is not nullset next of prev := left of pre, when prev is not null, otherwise nextPre := left of preprev := left of preif right of pre is not nullset next of prev := right of pre, when prev is not null, otherwise nextPre := right of preprev := right of prepre := nextPreset nextPre as null and prev as null"
},
{
"code": null,
"e": 2260,
"s": 1968,
"text": "while pre is not nullif left of pre is not nullset next of prev := left of pre, when prev is not null, otherwise nextPre := left of preprev := left of preif right of pre is not nullset next of prev := right of pre, when prev is not null, otherwise nextPre := right of preprev := right of pre"
},
{
"code": null,
"e": 2394,
"s": 2260,
"text": "if left of pre is not nullset next of prev := left of pre, when prev is not null, otherwise nextPre := left of preprev := left of pre"
},
{
"code": null,
"e": 2483,
"s": 2394,
"text": "set next of prev := left of pre, when prev is not null, otherwise nextPre := left of pre"
},
{
"code": null,
"e": 2503,
"s": 2483,
"text": "prev := left of pre"
},
{
"code": null,
"e": 2641,
"s": 2503,
"text": "if right of pre is not nullset next of prev := right of pre, when prev is not null, otherwise nextPre := right of preprev := right of pre"
},
{
"code": null,
"e": 2732,
"s": 2641,
"text": "set next of prev := right of pre, when prev is not null, otherwise nextPre := right of pre"
},
{
"code": null,
"e": 2753,
"s": 2732,
"text": "prev := right of pre"
},
{
"code": null,
"e": 2768,
"s": 2753,
"text": "pre := nextPre"
},
{
"code": null,
"e": 2805,
"s": 2768,
"text": "set nextPre as null and prev as null"
},
{
"code": null,
"e": 2817,
"s": 2805,
"text": "return null"
},
{
"code": null,
"e": 2887,
"s": 2817,
"text": "Let us see the following implementation to get better understanding β"
},
{
"code": null,
"e": 2898,
"s": 2887,
"text": " Live Demo"
},
{
"code": null,
"e": 5059,
"s": 2898,
"text": "#include <bits/stdc++.h>\n#include <stack>\nusing namespace std;\nclass Node {\npublic:\n int val;\n Node* left;\n Node* right;\n Node* next;\n Node() {}\n Node(int _val, Node* _left, Node* _right) {\n val = _val;\n left = _left;\n right = _right;\n next = NULL;\n }\n};\nclass Solution {\npublic:\n Node* connect(Node* root) {\n Node* pre = root;\n Node* nextPre = NULL;\n Node* prev = NULL;\n while(pre){\n while(pre){\n //cout << pre->val << endl;\n if(pre->left){\n if(prev){\n prev->next = pre->left;\n }else{\n nextPre = pre->left;\n }\n prev = pre->left;\n }\n if(pre->right){\n if(prev){\n prev->next = pre->right;\n }else{\n nextPre = pre->right;\n }\n prev = pre->right;\n }\n pre = pre->next;\n }\n //cout << \"*\" << endl;\n pre = nextPre;\n nextPre = NULL;\n prev = NULL;\n }\n return root;\n }\n};\nvoid printTree(Node* root) {\n cout << \"[\";\n if (root == NULL) return;\n queue<Node*> q;\n Node *curr;\n q.push(root);\n q.push(NULL);\n while (q.size() > 1) {\n curr = q.front();\n q.pop();\n if (curr == NULL){\n q.push(NULL);\n }\n else {\n // if(curr->next)\n // q.push(curr->next);\n if(curr->left)\n q.push(curr->left);\n if(curr->right)\n q.push(curr->right);\n if(curr->val == 0){\n cout << \"null\" << \", \";\n }else{\n cout << curr->val << \", \";\n if (curr->next == NULL) cout<<\"#, \";\n }\n }\n }\n cout << \"]\"<<endl;\n}\nint main() {\nNode* root;\nNode nodeFour(4, NULL, NULL);\nNode nodeFive(5, NULL, NULL );\nNode nodeSeven(7, NULL, NULL);\nNode nodeSix(6, NULL, NULL);\nNode nodeTwo(2,&nodeFour,&nodeFive);\nNode nodeThree(3,&nodeSix,&nodeSeven);\nNode nodeOne(1,&nodeTwo,&nodeThree);\nroot = &nodeOne;\nSolution ob;\nroot = ob.connect(root);\nprintTree(root);\n}"
},
{
"code": null,
"e": 5376,
"s": 5059,
"text": "[1,2,3,4,5,6,7]\nNode* root;\nNode nodeFour(4, NULL, NULL);\nNode nodeFive(5, NULL, NULL );\nNode nodeSeven(7, NULL, NULL);\nNode nodeSix(6, NULL, NULL);\nNode nodeTwo(2,&nodeFour,&nodeFive);\nNode nodeThree(3,&nodeSix,&nodeSeven);\nNode nodeOne(1,&nodeTwo,&nodeThree);\nroot = &nodeOne;\nSolution ob;\nroot = ob.connect(root);"
},
{
"code": null,
"e": 5409,
"s": 5376,
"text": "[1, #, 2, 3, #, 4, 5, 6, 7, #, ]"
}
] |
Python PIL | ImageDraw.Draw.arc() - GeeksforGeeks | 02 Aug, 2019
PIL is the Python Imaging Library which provides the python interpreter with image editing capabilities. The ImageDraw module provide simple 2D graphics for Image objects. You can use this module to create new images, annotate or retouch existing images, and to generate graphics on the fly for web use.
ImageDraw.Draw.arc() draws an arc (a portion of a circle outline) between the start and end angles, inside the given bounding box.
Syntax: PIL.ImageDraw.Draw.ellipse(xy, fill=None, outline=None)
Parameters:
xy β Four points to define the bounding box. Sequence of [(x0, y0), (x1, y1)] or [x0, y0, x1, y1].start β Starting angle, in degrees. Angles are measured from 3 oβclock, increasing clockwise.end β Ending angle, in degrees.fill β Color to use for the arc.
Returns: An Image object in arc shape.
# importing image object from PILimport mathfrom PIL import Image, ImageDraw w, h = 220, 190shape = [(40, 40), (w - 10, h - 10)] # creating new Image objectimg = Image.new("RGB", (w, h)) # create rectangle imageimg1 = ImageDraw.Draw(img) img1.arc(shape, start = 20, end = 130, fill ="pink")img.show()
Output:
Another Example: Here we use different colour for filling.
# importing image object from PILimport mathfrom PIL import Image, ImageDraw w, h = 220, 190shape = [(40, 40), (w - 10, h - 10)] # creating new Image objectimg = Image.new("RGB", (w, h)) # create rectangle imageimg1 = ImageDraw.Draw(img) img1.arc(shape, start = 20, end = 130, fill ="red")img.show()
Output:
Python-pil
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Defaultdict in Python
Python | Get unique values from a list
Python | os.path.join() method
Selecting rows in pandas DataFrame based on conditions
Create a directory in Python
Python | Pandas dataframe.groupby() | [
{
"code": null,
"e": 24292,
"s": 24264,
"text": "\n02 Aug, 2019"
},
{
"code": null,
"e": 24596,
"s": 24292,
"text": "PIL is the Python Imaging Library which provides the python interpreter with image editing capabilities. The ImageDraw module provide simple 2D graphics for Image objects. You can use this module to create new images, annotate or retouch existing images, and to generate graphics on the fly for web use."
},
{
"code": null,
"e": 24727,
"s": 24596,
"text": "ImageDraw.Draw.arc() draws an arc (a portion of a circle outline) between the start and end angles, inside the given bounding box."
},
{
"code": null,
"e": 24791,
"s": 24727,
"text": "Syntax: PIL.ImageDraw.Draw.ellipse(xy, fill=None, outline=None)"
},
{
"code": null,
"e": 24803,
"s": 24791,
"text": "Parameters:"
},
{
"code": null,
"e": 25058,
"s": 24803,
"text": "xy β Four points to define the bounding box. Sequence of [(x0, y0), (x1, y1)] or [x0, y0, x1, y1].start β Starting angle, in degrees. Angles are measured from 3 oβclock, increasing clockwise.end β Ending angle, in degrees.fill β Color to use for the arc."
},
{
"code": null,
"e": 25097,
"s": 25058,
"text": "Returns: An Image object in arc shape."
},
{
"code": " # importing image object from PILimport mathfrom PIL import Image, ImageDraw w, h = 220, 190shape = [(40, 40), (w - 10, h - 10)] # creating new Image objectimg = Image.new(\"RGB\", (w, h)) # create rectangle imageimg1 = ImageDraw.Draw(img) img1.arc(shape, start = 20, end = 130, fill =\"pink\")img.show()",
"e": 25407,
"s": 25097,
"text": null
},
{
"code": null,
"e": 25415,
"s": 25407,
"text": "Output:"
},
{
"code": null,
"e": 25474,
"s": 25415,
"text": "Another Example: Here we use different colour for filling."
},
{
"code": " # importing image object from PILimport mathfrom PIL import Image, ImageDraw w, h = 220, 190shape = [(40, 40), (w - 10, h - 10)] # creating new Image objectimg = Image.new(\"RGB\", (w, h)) # create rectangle imageimg1 = ImageDraw.Draw(img) img1.arc(shape, start = 20, end = 130, fill =\"red\")img.show()",
"e": 25783,
"s": 25474,
"text": null
},
{
"code": null,
"e": 25791,
"s": 25783,
"text": "Output:"
},
{
"code": null,
"e": 25802,
"s": 25791,
"text": "Python-pil"
},
{
"code": null,
"e": 25809,
"s": 25802,
"text": "Python"
},
{
"code": null,
"e": 25907,
"s": 25809,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25939,
"s": 25907,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 25995,
"s": 25939,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 26037,
"s": 25995,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 26079,
"s": 26037,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 26101,
"s": 26079,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 26140,
"s": 26101,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 26171,
"s": 26140,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 26226,
"s": 26171,
"text": "Selecting rows in pandas DataFrame based on conditions"
},
{
"code": null,
"e": 26255,
"s": 26226,
"text": "Create a directory in Python"
}
] |
Association, Composition and Aggregation in Java - GeeksforGeeks | 04 Apr, 2022
Association is a relation between two separate classes which establishes through their Objects. Association can be one-to-one, one-to-many, many-to-one, many-to-many. In Object-Oriented programming, an Object communicates to another object to use functionality and services provided by that object. Composition and Aggregation are the two forms of association.
Example:
Java
// Java Program to illustrate the// Concept of Association // Importing required classesimport java.io.*; // Class 1// Bank classclass Bank { // Attributes of bank private String name; // Constructor of this class Bank(String name) { // this keyword refers to current instance itself this.name = name; } // Method of Bank class public String getBankName() { // Returning name of bank return this.name; }} // Class 2// Employee classclass Employee { // Attributes of employee private String name; // Employee name Employee(String name) { // This keyword refers to current instance itself this.name = name; } // Method of Employee class public String getEmployeeName() { // returning the name of employee return this.name; }} // Class 3// Association between both the// classes in main methodclass GFG { // Main driver method public static void main(String[] args) { // Creating objects of bank and Employee class Bank bank = new Bank("ICICI"); Employee emp = new Employee("Ridhi"); // Print and display name and // corresponding bank of employee System.out.println(emp.getEmployeeName() + " is employee of " + bank.getBankName()); }}
Ridhi is employee of ICICI
Output Explanation: In the above example, two separate classes Bank and Employee are associated through their Objects. Bank can have many employees, So it is a one-to-many relationship.
It is a special form of Association where:
It represents Has-Aβs relationship.
It is a unidirectional association i.e. a one-way relationship. For example, a department can have students but vice versa is not possible and thus unidirectional in nature.
In Aggregation, both the entries can survive individually which means ending one entity will not affect the other entity.
Aggregation
Example
Java
// Java program to illustrate Concept of Aggregation // Importing required classesimport java.io.*;import java.util.*; // Class 1// Student classclass Student { // Attributes of student String name; int id; String dept; // Constructor of student class Student(String name, int id, String dept) { // This keyword refers to current instance itself this.name = name; this.id = id; this.dept = dept; }} // Class 2// Department class contains list of student objects// It is associated with student class through its Objectsclass Department { // Attributes of Department class String name; private List<Student> students; Department(String name, List<Student> students) { // this keyword refers to current instance itself this.name = name; this.students = students; } // Method of Department class public List<Student> getStudents() { // Returning list of user defined type // Student type return students; }} // Class 3// Institute class contains list of Department// Objects. It is associated with Department// class through its Objectsclass Institute { // Attributes of Institute String instituteName; private List<Department> departments; // Constructor of institute class Institute(String instituteName,List<Department> departments) { // This keyword refers to current instance itself this.instituteName = instituteName; this.departments = departments; } // Method of Institute class // Counting total students of all departments // in a given institute public int getTotalStudentsInInstitute() { int noOfStudents = 0; List<Student> students; for (Department dept : departments) { students = dept.getStudents(); for (Student s : students) { noOfStudents++; } } return noOfStudents; }} // Class 4// main classclass GFG { // main driver method public static void main(String[] args) { // Creating object of Student class inside main() Student s1 = new Student("Mia", 1, "CSE"); Student s2 = new Student("Priya", 2, "CSE"); Student s3 = new Student("John", 1, "EE"); Student s4 = new Student("Rahul", 2, "EE"); // Creating a List of CSE Students List<Student> cse_students = new ArrayList<Student>(); // Adding CSE students cse_students.add(s1); cse_students.add(s2); // Creating a List of EE Students List<Student> ee_students = new ArrayList<Student>(); // Adding EE students ee_students.add(s3); ee_students.add(s4); // Creating objects of EE and CSE class inside // main() Department CSE = new Department("CSE", cse_students); Department EE = new Department("EE", ee_students); List<Department> departments = new ArrayList<Department>(); departments.add(CSE); departments.add(EE); // Lastly creating an instance of Institute Institute institute = new Institute("BITS", departments); // Display message for better readability System.out.print("Total students in institute: "); // Calling method to get total number of students // in institute and printing on console System.out.print(institute.getTotalStudentsInInstitute()); }}
Total students in institute: 4
Output Explanation: In this example, there is an Institute which has no. of departments like CSE, EE. Every department has no. of students. So, we make an Institute class that has a reference to Object or no. of Objects (i.e. List of Objects) of the Department class. That means Institute class is associated with Department class through its Object(s). And Department class has also a reference to Object or Objects (i.e. List of Objects) of the Student class means it is associated with the Student class through its Object(s).
It represents a Has-A relationship. In the above example: Student Has-A name. Student Has-A ID. Student Has-A Dept. Department Has-A Students as depicted from the below media.
When do we use Aggregation ?? Code reuse is best achieved by aggregation.
Concept 3: Composition
Composition
Composition is a restricted form of Aggregation in which two entities are highly dependent on each other.
It represents part-of relationship.
In composition, both entities are dependent on each other.
When there is a composition between two entities, the composed object cannot exist without the other entity.
Example Library
Java
// Java program to illustrate// the concept of Composition // Importing required classesimport java.io.*;import java.util.*; // Class 1// Bookclass Book { // Attributes of book public String title; public String author; // Constructor of Book class Book(String title, String author) { // This keyword refers to current instance itself this.title = title; this.author = author; }} // Class 2class Library { // Reference to refer to list of books private final List<Book> books; // Library class contains list of books Library(List<Book> books) { // Referring to same book as // this keyword refers to same instance itself this.books = books; } // Method // To get total number of books in library public List<Book> getTotalBooksInLibrary() { return books; }} // Class 3// Main classclass GFG { // Main driver method public static void main(String[] args) { // Creating objects of Book class inside main() // method Custom inputs Book b1 = new Book("EffectiveJ Java", "Joshua Bloch"); Book b2 = new Book("Thinking in Java", "Bruce Eckel"); Book b3 = new Book("Java: The Complete Reference", "Herbert Schildt"); // Creating the list which contains number of books List<Book> books = new ArrayList<Book>(); // Adding books // using add() method books.add(b1); books.add(b2); books.add(b3); Library library = new Library(books); // Calling method to get total books in library // and storing it in list of user0defined type - // Books List<Book> bks = library.getTotalBooksInLibrary(); // Iterating over books using for each loop for (Book bk : bks) { // Printing the title and author name of book on // console System.out.println("Title : " + bk.title + " and " + " Author : " + bk.author); } }}
Title : EffectiveJ Java and Author : Joshua Bloch
Title : Thinking in Java and Author : Bruce Eckel
Title : Java: The Complete Reference and Author : Herbert Schildt
Output explanation: In the above example, a library can have no. of books on the same or different subjects. So, If Library gets destroyed then All books within that particular library will be destroyed. i.e. books can not exist without libraries. Thatβs why it is composition. Book is Part-of Library.
1. Dependency: Aggregation implies a relationship where the child can exist independently of the parent. For example, Bank and Employee, delete the Bank and the Employee still exist. whereas Composition implies a relationship where the child cannot exist independent of the parent. Example: Human and heart, heart donβt exist separate to a Human
2. Type of Relationship: Aggregation relation is βhas-aβ and composition is βpart-ofβ relation.
3. Type of association: Composition is a strong Association whereas Aggregation is a weak Association.
Example:
Java
// Java Program to Illustrate Difference between// Aggregation and Composition // Importing I/O classesimport java.io.*; // Class 1// Engine class which will// be used by car. so 'Car'// class will have a field// of Engine type.class Engine { // Method to starting an engine public void work() { // Print statement whenever this method is called System.out.println( "Engine of car has been started "); }} // Class 2// Engine classfinal class Car { // For a car to move, // it needs to have an engine. // Composition private final Engine engine; // Note: Uncommented part refers to Aggregation // private Engine engine; // Constructor of this class Car(Engine engine) { // This keywords refers to same instance this.engine = engine; } // Method // Car start moving by starting engine public void move() { // if(engine != null) { // Calling method for working of engine engine.work(); // Print statement System.out.println("Car is moving "); } }} // Class 3// Main classclass GFG { // Main driver method public static void main(String[] args) { // Making an engine by creating // an instance of Engine class. Engine engine = new Engine(); // Making a car with engine so we are // passing a engine instance as an argument // while creating instance of Car Car car = new Car(engine); // Making car to move by calling // move() method inside main() car.move(); }}
Engine of car has been started
Car is moving
In case of aggregation, the Car also performs its functions through an Engine. but the Engine is not always an internal part of the Car. An engine can be swapped out or even can be removed from the car. Thatβs why we make The Engine type field non-final.
This article is contributed by Nitsdheerendra. 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.
tushargupta09
singghakshay
gabaa406
chaitanyadeshmukh321
kashishsoda
simmytarika5
surindertarika1234
varshagumber28
sumitgumber28
sagar0719kumar
simranarora5sos
arorakashish0911
java-inheritance
Java-Object Oriented
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
Singleton Class in Java
Multithreading in Java
Set in Java
Stack Class in Java
LinkedList in Java
Collections in Java
Different ways of Reading a text file in Java
Stream In Java | [
{
"code": null,
"e": 24272,
"s": 24244,
"text": "\n04 Apr, 2022"
},
{
"code": null,
"e": 24634,
"s": 24272,
"text": "Association is a relation between two separate classes which establishes through their Objects. Association can be one-to-one, one-to-many, many-to-one, many-to-many. In Object-Oriented programming, an Object communicates to another object to use functionality and services provided by that object. Composition and Aggregation are the two forms of association. "
},
{
"code": null,
"e": 24643,
"s": 24634,
"text": "Example:"
},
{
"code": null,
"e": 24648,
"s": 24643,
"text": "Java"
},
{
"code": "// Java Program to illustrate the// Concept of Association // Importing required classesimport java.io.*; // Class 1// Bank classclass Bank { // Attributes of bank private String name; // Constructor of this class Bank(String name) { // this keyword refers to current instance itself this.name = name; } // Method of Bank class public String getBankName() { // Returning name of bank return this.name; }} // Class 2// Employee classclass Employee { // Attributes of employee private String name; // Employee name Employee(String name) { // This keyword refers to current instance itself this.name = name; } // Method of Employee class public String getEmployeeName() { // returning the name of employee return this.name; }} // Class 3// Association between both the// classes in main methodclass GFG { // Main driver method public static void main(String[] args) { // Creating objects of bank and Employee class Bank bank = new Bank(\"ICICI\"); Employee emp = new Employee(\"Ridhi\"); // Print and display name and // corresponding bank of employee System.out.println(emp.getEmployeeName() + \" is employee of \" + bank.getBankName()); }}",
"e": 26010,
"s": 24648,
"text": null
},
{
"code": null,
"e": 26037,
"s": 26010,
"text": "Ridhi is employee of ICICI"
},
{
"code": null,
"e": 26224,
"s": 26037,
"text": "Output Explanation: In the above example, two separate classes Bank and Employee are associated through their Objects. Bank can have many employees, So it is a one-to-many relationship. "
},
{
"code": null,
"e": 26269,
"s": 26224,
"text": "It is a special form of Association where: "
},
{
"code": null,
"e": 26305,
"s": 26269,
"text": "It represents Has-Aβs relationship."
},
{
"code": null,
"e": 26479,
"s": 26305,
"text": "It is a unidirectional association i.e. a one-way relationship. For example, a department can have students but vice versa is not possible and thus unidirectional in nature."
},
{
"code": null,
"e": 26601,
"s": 26479,
"text": "In Aggregation, both the entries can survive individually which means ending one entity will not affect the other entity."
},
{
"code": null,
"e": 26613,
"s": 26601,
"text": "Aggregation"
},
{
"code": null,
"e": 26621,
"s": 26613,
"text": "Example"
},
{
"code": null,
"e": 26626,
"s": 26621,
"text": "Java"
},
{
"code": "// Java program to illustrate Concept of Aggregation // Importing required classesimport java.io.*;import java.util.*; // Class 1// Student classclass Student { // Attributes of student String name; int id; String dept; // Constructor of student class Student(String name, int id, String dept) { // This keyword refers to current instance itself this.name = name; this.id = id; this.dept = dept; }} // Class 2// Department class contains list of student objects// It is associated with student class through its Objectsclass Department { // Attributes of Department class String name; private List<Student> students; Department(String name, List<Student> students) { // this keyword refers to current instance itself this.name = name; this.students = students; } // Method of Department class public List<Student> getStudents() { // Returning list of user defined type // Student type return students; }} // Class 3// Institute class contains list of Department// Objects. It is associated with Department// class through its Objectsclass Institute { // Attributes of Institute String instituteName; private List<Department> departments; // Constructor of institute class Institute(String instituteName,List<Department> departments) { // This keyword refers to current instance itself this.instituteName = instituteName; this.departments = departments; } // Method of Institute class // Counting total students of all departments // in a given institute public int getTotalStudentsInInstitute() { int noOfStudents = 0; List<Student> students; for (Department dept : departments) { students = dept.getStudents(); for (Student s : students) { noOfStudents++; } } return noOfStudents; }} // Class 4// main classclass GFG { // main driver method public static void main(String[] args) { // Creating object of Student class inside main() Student s1 = new Student(\"Mia\", 1, \"CSE\"); Student s2 = new Student(\"Priya\", 2, \"CSE\"); Student s3 = new Student(\"John\", 1, \"EE\"); Student s4 = new Student(\"Rahul\", 2, \"EE\"); // Creating a List of CSE Students List<Student> cse_students = new ArrayList<Student>(); // Adding CSE students cse_students.add(s1); cse_students.add(s2); // Creating a List of EE Students List<Student> ee_students = new ArrayList<Student>(); // Adding EE students ee_students.add(s3); ee_students.add(s4); // Creating objects of EE and CSE class inside // main() Department CSE = new Department(\"CSE\", cse_students); Department EE = new Department(\"EE\", ee_students); List<Department> departments = new ArrayList<Department>(); departments.add(CSE); departments.add(EE); // Lastly creating an instance of Institute Institute institute = new Institute(\"BITS\", departments); // Display message for better readability System.out.print(\"Total students in institute: \"); // Calling method to get total number of students // in institute and printing on console System.out.print(institute.getTotalStudentsInInstitute()); }}",
"e": 30069,
"s": 26626,
"text": null
},
{
"code": null,
"e": 30100,
"s": 30069,
"text": "Total students in institute: 4"
},
{
"code": null,
"e": 30631,
"s": 30100,
"text": "Output Explanation: In this example, there is an Institute which has no. of departments like CSE, EE. Every department has no. of students. So, we make an Institute class that has a reference to Object or no. of Objects (i.e. List of Objects) of the Department class. That means Institute class is associated with Department class through its Object(s). And Department class has also a reference to Object or Objects (i.e. List of Objects) of the Student class means it is associated with the Student class through its Object(s). "
},
{
"code": null,
"e": 30809,
"s": 30631,
"text": "It represents a Has-A relationship. In the above example: Student Has-A name. Student Has-A ID. Student Has-A Dept. Department Has-A Students as depicted from the below media. "
},
{
"code": null,
"e": 30885,
"s": 30809,
"text": "When do we use Aggregation ?? Code reuse is best achieved by aggregation. "
},
{
"code": null,
"e": 30909,
"s": 30885,
"text": "Concept 3: Composition "
},
{
"code": null,
"e": 30921,
"s": 30909,
"text": "Composition"
},
{
"code": null,
"e": 31029,
"s": 30921,
"text": "Composition is a restricted form of Aggregation in which two entities are highly dependent on each other. "
},
{
"code": null,
"e": 31065,
"s": 31029,
"text": "It represents part-of relationship."
},
{
"code": null,
"e": 31124,
"s": 31065,
"text": "In composition, both entities are dependent on each other."
},
{
"code": null,
"e": 31233,
"s": 31124,
"text": "When there is a composition between two entities, the composed object cannot exist without the other entity."
},
{
"code": null,
"e": 31249,
"s": 31233,
"text": "Example Library"
},
{
"code": null,
"e": 31254,
"s": 31249,
"text": "Java"
},
{
"code": "// Java program to illustrate// the concept of Composition // Importing required classesimport java.io.*;import java.util.*; // Class 1// Bookclass Book { // Attributes of book public String title; public String author; // Constructor of Book class Book(String title, String author) { // This keyword refers to current instance itself this.title = title; this.author = author; }} // Class 2class Library { // Reference to refer to list of books private final List<Book> books; // Library class contains list of books Library(List<Book> books) { // Referring to same book as // this keyword refers to same instance itself this.books = books; } // Method // To get total number of books in library public List<Book> getTotalBooksInLibrary() { return books; }} // Class 3// Main classclass GFG { // Main driver method public static void main(String[] args) { // Creating objects of Book class inside main() // method Custom inputs Book b1 = new Book(\"EffectiveJ Java\", \"Joshua Bloch\"); Book b2 = new Book(\"Thinking in Java\", \"Bruce Eckel\"); Book b3 = new Book(\"Java: The Complete Reference\", \"Herbert Schildt\"); // Creating the list which contains number of books List<Book> books = new ArrayList<Book>(); // Adding books // using add() method books.add(b1); books.add(b2); books.add(b3); Library library = new Library(books); // Calling method to get total books in library // and storing it in list of user0defined type - // Books List<Book> bks = library.getTotalBooksInLibrary(); // Iterating over books using for each loop for (Book bk : bks) { // Printing the title and author name of book on // console System.out.println(\"Title : \" + bk.title + \" and \" + \" Author : \" + bk.author); } }}",
"e": 33359,
"s": 31254,
"text": null
},
{
"code": null,
"e": 33528,
"s": 33359,
"text": "Title : EffectiveJ Java and Author : Joshua Bloch\nTitle : Thinking in Java and Author : Bruce Eckel\nTitle : Java: The Complete Reference and Author : Herbert Schildt"
},
{
"code": null,
"e": 33832,
"s": 33528,
"text": "Output explanation: In the above example, a library can have no. of books on the same or different subjects. So, If Library gets destroyed then All books within that particular library will be destroyed. i.e. books can not exist without libraries. Thatβs why it is composition. Book is Part-of Library."
},
{
"code": null,
"e": 34178,
"s": 33832,
"text": "1. Dependency: Aggregation implies a relationship where the child can exist independently of the parent. For example, Bank and Employee, delete the Bank and the Employee still exist. whereas Composition implies a relationship where the child cannot exist independent of the parent. Example: Human and heart, heart donβt exist separate to a Human"
},
{
"code": null,
"e": 34274,
"s": 34178,
"text": "2. Type of Relationship: Aggregation relation is βhas-aβ and composition is βpart-ofβ relation."
},
{
"code": null,
"e": 34377,
"s": 34274,
"text": "3. Type of association: Composition is a strong Association whereas Aggregation is a weak Association."
},
{
"code": null,
"e": 34386,
"s": 34377,
"text": "Example:"
},
{
"code": null,
"e": 34391,
"s": 34386,
"text": "Java"
},
{
"code": "// Java Program to Illustrate Difference between// Aggregation and Composition // Importing I/O classesimport java.io.*; // Class 1// Engine class which will// be used by car. so 'Car'// class will have a field// of Engine type.class Engine { // Method to starting an engine public void work() { // Print statement whenever this method is called System.out.println( \"Engine of car has been started \"); }} // Class 2// Engine classfinal class Car { // For a car to move, // it needs to have an engine. // Composition private final Engine engine; // Note: Uncommented part refers to Aggregation // private Engine engine; // Constructor of this class Car(Engine engine) { // This keywords refers to same instance this.engine = engine; } // Method // Car start moving by starting engine public void move() { // if(engine != null) { // Calling method for working of engine engine.work(); // Print statement System.out.println(\"Car is moving \"); } }} // Class 3// Main classclass GFG { // Main driver method public static void main(String[] args) { // Making an engine by creating // an instance of Engine class. Engine engine = new Engine(); // Making a car with engine so we are // passing a engine instance as an argument // while creating instance of Car Car car = new Car(engine); // Making car to move by calling // move() method inside main() car.move(); }}",
"e": 36007,
"s": 34391,
"text": null
},
{
"code": null,
"e": 36054,
"s": 36007,
"text": "Engine of car has been started \nCar is moving "
},
{
"code": null,
"e": 36309,
"s": 36054,
"text": "In case of aggregation, the Car also performs its functions through an Engine. but the Engine is not always an internal part of the Car. An engine can be swapped out or even can be removed from the car. Thatβs why we make The Engine type field non-final."
},
{
"code": null,
"e": 36732,
"s": 36309,
"text": "This article is contributed by Nitsdheerendra. 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": 36746,
"s": 36732,
"text": "tushargupta09"
},
{
"code": null,
"e": 36759,
"s": 36746,
"text": "singghakshay"
},
{
"code": null,
"e": 36768,
"s": 36759,
"text": "gabaa406"
},
{
"code": null,
"e": 36789,
"s": 36768,
"text": "chaitanyadeshmukh321"
},
{
"code": null,
"e": 36801,
"s": 36789,
"text": "kashishsoda"
},
{
"code": null,
"e": 36814,
"s": 36801,
"text": "simmytarika5"
},
{
"code": null,
"e": 36833,
"s": 36814,
"text": "surindertarika1234"
},
{
"code": null,
"e": 36848,
"s": 36833,
"text": "varshagumber28"
},
{
"code": null,
"e": 36862,
"s": 36848,
"text": "sumitgumber28"
},
{
"code": null,
"e": 36877,
"s": 36862,
"text": "sagar0719kumar"
},
{
"code": null,
"e": 36893,
"s": 36877,
"text": "simranarora5sos"
},
{
"code": null,
"e": 36910,
"s": 36893,
"text": "arorakashish0911"
},
{
"code": null,
"e": 36927,
"s": 36910,
"text": "java-inheritance"
},
{
"code": null,
"e": 36948,
"s": 36927,
"text": "Java-Object Oriented"
},
{
"code": null,
"e": 36953,
"s": 36948,
"text": "Java"
},
{
"code": null,
"e": 36958,
"s": 36953,
"text": "Java"
},
{
"code": null,
"e": 37056,
"s": 36958,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 37065,
"s": 37056,
"text": "Comments"
},
{
"code": null,
"e": 37078,
"s": 37065,
"text": "Old Comments"
},
{
"code": null,
"e": 37097,
"s": 37078,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 37115,
"s": 37097,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 37139,
"s": 37115,
"text": "Singleton Class in Java"
},
{
"code": null,
"e": 37162,
"s": 37139,
"text": "Multithreading in Java"
},
{
"code": null,
"e": 37174,
"s": 37162,
"text": "Set in Java"
},
{
"code": null,
"e": 37194,
"s": 37174,
"text": "Stack Class in Java"
},
{
"code": null,
"e": 37213,
"s": 37194,
"text": "LinkedList in Java"
},
{
"code": null,
"e": 37233,
"s": 37213,
"text": "Collections in Java"
},
{
"code": null,
"e": 37279,
"s": 37233,
"text": "Different ways of Reading a text file in Java"
}
] |
Count ways to split a string into two subsets that are reverse of each other - GeeksforGeeks | 30 Mar, 2022
Given a string S consisting of N characters, the task is to find the number of ways to split the string into two subsets such that the first subset is the reverse of the second subset.
Examples:
Input: S = βcabaacbaβOutput: 4Explanation:Below are the ways of partitioning the string satisfying the given conditions:
Take the characters at the indices {0, 4, 6, 7} as the first subset and the remaining characters as the second subset. Then the string formed are βcabaβ and βabacβ and the second string is the reverse of the first string.Take the characters at the indices {0, 3, 6, 7} as the first subset and remaining characters as the second subset. Then the string formed are βcabaβ and βabacβ and the second string is the reverse of the first string.Take the characters at the indices {1, 2, 3, 5} as first subset and remaining characters as the second subset. Then the string formed are βabacβ and βcabaβ and the second string is the reverse of first string.Take the characters at the indices {1, 2, 4, 5} as first subset and remaining characters as the second subset. Then the string formed are βabacβ and βcabaβ and the second string is the reverse of the first string.
Take the characters at the indices {0, 4, 6, 7} as the first subset and the remaining characters as the second subset. Then the string formed are βcabaβ and βabacβ and the second string is the reverse of the first string.
Take the characters at the indices {0, 3, 6, 7} as the first subset and remaining characters as the second subset. Then the string formed are βcabaβ and βabacβ and the second string is the reverse of the first string.
Take the characters at the indices {1, 2, 3, 5} as first subset and remaining characters as the second subset. Then the string formed are βabacβ and βcabaβ and the second string is the reverse of first string.
Take the characters at the indices {1, 2, 4, 5} as first subset and remaining characters as the second subset. Then the string formed are βabacβ and βcabaβ and the second string is the reverse of the first string.
Therefore, the number of ways of splitting is 4.
Input: N = 11, S = βmippiisssisssiipsspiimβOutput: 504
Approach: The given problem can be solved by using the concept of Bitmasking to generate all possible ways of splitting the string and check if there exists any such splitting of the string which is reverse of one another. Follow the steps below to solve the problem:
Initialize a variable, say ans as 0 to store the total number of ways of partitioning the string.
Iterate over the range [0, 2N] using a variable mask and perform the following steps:Initialize two strings say X and Y to store the characters of the first subset and second subset.Iterate over the range [0, N] and if the ith bit is set in the integer mask then append the character S[i] to X. Otherwise append the character S[i] to Y.Reverse the string Y and then check if the first string X is equal to the second string Y then increment ans by 1.
Initialize two strings say X and Y to store the characters of the first subset and second subset.
Iterate over the range [0, N] and if the ith bit is set in the integer mask then append the character S[i] to X. Otherwise append the character S[i] to Y.
Reverse the string Y and then check if the first string X is equal to the second string Y then increment ans by 1.
After completing the above steps, print the value of ans as the total number of ways.
Below is the implementation of the above approach:
C++
Java
Python3
Javascript
// C++ program for the above approach #include <bits/stdc++.h>using namespace std; // Function to find the total number// of ways to partitiaon the string into// two subset satisfying the conditionsint countWays(string S, int N){ // Stores the resultant number of // ways of splitting int ans = 0; // Iterate over the range [0, 2^N] for (int mask = 0; mask < (1 << N); mask++) { string X, Y; // Traverse the string S for (int i = 0; i < N; i++) { // If ith bit is set, then // append the character // S[i] to X if (mask >> i & 1) { X += S[i]; } // Otherwise, append the // character S[i] to Y else { Y += S[i]; } } // Reverse the second string reverse(Y.begin(), Y.end()); // If X is equal to Y if (X == Y) { ans++; } } // Return the total number of ways return ans;} // Driver Codeint main(){ string S = "mippiisssisssiipsspiim"; int N = S.length(); cout << countWays(S, N); return 0;}
// Java program for the above approachimport java.lang.*;import java.io.*;import java.util.*; class GFG { // Function to find the total number // of ways to partitiaon the String into // two subset satisfying the conditions static int countWays(String S, int N) { // Stores the resultant number of // ways of splitting int ans = 0; // Iterate over the range [0, 2^N] for (int mask = 0; mask < (1 << N); mask++) { String X="" , Y=""; // Traverse the String S for (int i = 0; i < N; i++) { // If ith bit is set, then // append the character // S[i] to X if ((mask >> i & 1) == 1) { X += S.charAt(i); } // Otherwise, append the // character S[i] to Y else { Y += S.charAt(i); } } // Reverse the second String Y = new StringBuilder(Y).reverse().toString(); // If X is equal to Y if (X.equals(Y)) { ans++; } } // Return the total number of ways return ans; } // Driver Code public static void main (String[] args) { String S = "mippiisssisssiipsspiim"; int N = S.length(); System.out.println(countWays(S, N)); }} // This code is contributed by shubhamsingh10
# Python3 program for the above approach # Function to find the total number# of ways to partitiaon the string into# two subset satisfying the conditionsdef countWays(S, N): # Stores the resultant number of # ways of splitting ans = 0 # Iterate over the range [0, 2^N] for mask in range((1 << N)): X, Y = "","" # Traverse the string S for i in range(N): # If ith bit is set, then # append the character # S[i] to X if (mask >> i & 1): X += S[i] # Otherwise, append the # character S[i] to Y else: Y += S[i] # Reverse the second string Y = Y[::-1] # If X is equal to Y if (X == Y): ans += 1 # Return the total number of ways return ans # Driver Codeif __name__ == '__main__': S = "mippiisssisssiipsspiim" N = len(S) print(countWays(S, N)) # This code is contributed by mohit kumar 29
<script> // JavaScript program for the above approach // Function to find the total number// of ways to partitiaon the string into// two subset satisfying the conditionsfunction countWays(S, N){ // Stores the resultant number of // ways of splitting let ans = 0 // Iterate over the range [0, 2^N] for(let mask=0;mask<(1 << N);mask++){ let X = "" let Y = "" // Traverse the string S for(let i=0;i<N;i++){ // If ith bit is set, then // append the character // S[i] to X if (mask >> i & 1) X += S[i] // Otherwise, append the // character S[i] to Y else Y += S[i] } // Reverse the second string Y = Y.split("").reverse().join("") // If X is equal to Y if (X == Y) ans += 1 } // Return the total number of ways return ans} // Driver Code let S = "mippiisssisssiipsspiim"let N = S.length document.write(countWays(S, N)) // This code is contributed by shinjanpatra </script>
504
Time Complexity: O(N*2N)Auxiliary Space: O(N)
mohit kumar 29
SHUBHAMSINGH10
shinjanpatra
partition
subset
Mathematical
Strings
Strings
Mathematical
subset
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Merge two sorted arrays
Modulo Operator (%) in C/C++ with Examples
Program to find GCD or HCF of two numbers
Prime Numbers
Program to find sum of elements in a given array
Write a program to reverse an array or string
Reverse a string in Java
Longest Common Subsequence | DP-4
Check for Balanced Brackets in an expression (well-formedness) using Stack
Python program to check if a string is palindrome or not | [
{
"code": null,
"e": 24914,
"s": 24886,
"text": "\n30 Mar, 2022"
},
{
"code": null,
"e": 25099,
"s": 24914,
"text": "Given a string S consisting of N characters, the task is to find the number of ways to split the string into two subsets such that the first subset is the reverse of the second subset."
},
{
"code": null,
"e": 25109,
"s": 25099,
"text": "Examples:"
},
{
"code": null,
"e": 25230,
"s": 25109,
"text": "Input: S = βcabaacbaβOutput: 4Explanation:Below are the ways of partitioning the string satisfying the given conditions:"
},
{
"code": null,
"e": 26091,
"s": 25230,
"text": "Take the characters at the indices {0, 4, 6, 7} as the first subset and the remaining characters as the second subset. Then the string formed are βcabaβ and βabacβ and the second string is the reverse of the first string.Take the characters at the indices {0, 3, 6, 7} as the first subset and remaining characters as the second subset. Then the string formed are βcabaβ and βabacβ and the second string is the reverse of the first string.Take the characters at the indices {1, 2, 3, 5} as first subset and remaining characters as the second subset. Then the string formed are βabacβ and βcabaβ and the second string is the reverse of first string.Take the characters at the indices {1, 2, 4, 5} as first subset and remaining characters as the second subset. Then the string formed are βabacβ and βcabaβ and the second string is the reverse of the first string."
},
{
"code": null,
"e": 26313,
"s": 26091,
"text": "Take the characters at the indices {0, 4, 6, 7} as the first subset and the remaining characters as the second subset. Then the string formed are βcabaβ and βabacβ and the second string is the reverse of the first string."
},
{
"code": null,
"e": 26531,
"s": 26313,
"text": "Take the characters at the indices {0, 3, 6, 7} as the first subset and remaining characters as the second subset. Then the string formed are βcabaβ and βabacβ and the second string is the reverse of the first string."
},
{
"code": null,
"e": 26741,
"s": 26531,
"text": "Take the characters at the indices {1, 2, 3, 5} as first subset and remaining characters as the second subset. Then the string formed are βabacβ and βcabaβ and the second string is the reverse of first string."
},
{
"code": null,
"e": 26955,
"s": 26741,
"text": "Take the characters at the indices {1, 2, 4, 5} as first subset and remaining characters as the second subset. Then the string formed are βabacβ and βcabaβ and the second string is the reverse of the first string."
},
{
"code": null,
"e": 27004,
"s": 26955,
"text": "Therefore, the number of ways of splitting is 4."
},
{
"code": null,
"e": 27059,
"s": 27004,
"text": "Input: N = 11, S = βmippiisssisssiipsspiimβOutput: 504"
},
{
"code": null,
"e": 27327,
"s": 27059,
"text": "Approach: The given problem can be solved by using the concept of Bitmasking to generate all possible ways of splitting the string and check if there exists any such splitting of the string which is reverse of one another. Follow the steps below to solve the problem:"
},
{
"code": null,
"e": 27425,
"s": 27327,
"text": "Initialize a variable, say ans as 0 to store the total number of ways of partitioning the string."
},
{
"code": null,
"e": 27876,
"s": 27425,
"text": "Iterate over the range [0, 2N] using a variable mask and perform the following steps:Initialize two strings say X and Y to store the characters of the first subset and second subset.Iterate over the range [0, N] and if the ith bit is set in the integer mask then append the character S[i] to X. Otherwise append the character S[i] to Y.Reverse the string Y and then check if the first string X is equal to the second string Y then increment ans by 1."
},
{
"code": null,
"e": 27974,
"s": 27876,
"text": "Initialize two strings say X and Y to store the characters of the first subset and second subset."
},
{
"code": null,
"e": 28129,
"s": 27974,
"text": "Iterate over the range [0, N] and if the ith bit is set in the integer mask then append the character S[i] to X. Otherwise append the character S[i] to Y."
},
{
"code": null,
"e": 28244,
"s": 28129,
"text": "Reverse the string Y and then check if the first string X is equal to the second string Y then increment ans by 1."
},
{
"code": null,
"e": 28330,
"s": 28244,
"text": "After completing the above steps, print the value of ans as the total number of ways."
},
{
"code": null,
"e": 28381,
"s": 28330,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 28385,
"s": 28381,
"text": "C++"
},
{
"code": null,
"e": 28390,
"s": 28385,
"text": "Java"
},
{
"code": null,
"e": 28398,
"s": 28390,
"text": "Python3"
},
{
"code": null,
"e": 28409,
"s": 28398,
"text": "Javascript"
},
{
"code": "// C++ program for the above approach #include <bits/stdc++.h>using namespace std; // Function to find the total number// of ways to partitiaon the string into// two subset satisfying the conditionsint countWays(string S, int N){ // Stores the resultant number of // ways of splitting int ans = 0; // Iterate over the range [0, 2^N] for (int mask = 0; mask < (1 << N); mask++) { string X, Y; // Traverse the string S for (int i = 0; i < N; i++) { // If ith bit is set, then // append the character // S[i] to X if (mask >> i & 1) { X += S[i]; } // Otherwise, append the // character S[i] to Y else { Y += S[i]; } } // Reverse the second string reverse(Y.begin(), Y.end()); // If X is equal to Y if (X == Y) { ans++; } } // Return the total number of ways return ans;} // Driver Codeint main(){ string S = \"mippiisssisssiipsspiim\"; int N = S.length(); cout << countWays(S, N); return 0;}",
"e": 29552,
"s": 28409,
"text": null
},
{
"code": "// Java program for the above approachimport java.lang.*;import java.io.*;import java.util.*; class GFG { // Function to find the total number // of ways to partitiaon the String into // two subset satisfying the conditions static int countWays(String S, int N) { // Stores the resultant number of // ways of splitting int ans = 0; // Iterate over the range [0, 2^N] for (int mask = 0; mask < (1 << N); mask++) { String X=\"\" , Y=\"\"; // Traverse the String S for (int i = 0; i < N; i++) { // If ith bit is set, then // append the character // S[i] to X if ((mask >> i & 1) == 1) { X += S.charAt(i); } // Otherwise, append the // character S[i] to Y else { Y += S.charAt(i); } } // Reverse the second String Y = new StringBuilder(Y).reverse().toString(); // If X is equal to Y if (X.equals(Y)) { ans++; } } // Return the total number of ways return ans; } // Driver Code public static void main (String[] args) { String S = \"mippiisssisssiipsspiim\"; int N = S.length(); System.out.println(countWays(S, N)); }} // This code is contributed by shubhamsingh10",
"e": 31061,
"s": 29552,
"text": null
},
{
"code": "# Python3 program for the above approach # Function to find the total number# of ways to partitiaon the string into# two subset satisfying the conditionsdef countWays(S, N): # Stores the resultant number of # ways of splitting ans = 0 # Iterate over the range [0, 2^N] for mask in range((1 << N)): X, Y = \"\",\"\" # Traverse the string S for i in range(N): # If ith bit is set, then # append the character # S[i] to X if (mask >> i & 1): X += S[i] # Otherwise, append the # character S[i] to Y else: Y += S[i] # Reverse the second string Y = Y[::-1] # If X is equal to Y if (X == Y): ans += 1 # Return the total number of ways return ans # Driver Codeif __name__ == '__main__': S = \"mippiisssisssiipsspiim\" N = len(S) print(countWays(S, N)) # This code is contributed by mohit kumar 29",
"e": 32127,
"s": 31061,
"text": null
},
{
"code": "<script> // JavaScript program for the above approach // Function to find the total number// of ways to partitiaon the string into// two subset satisfying the conditionsfunction countWays(S, N){ // Stores the resultant number of // ways of splitting let ans = 0 // Iterate over the range [0, 2^N] for(let mask=0;mask<(1 << N);mask++){ let X = \"\" let Y = \"\" // Traverse the string S for(let i=0;i<N;i++){ // If ith bit is set, then // append the character // S[i] to X if (mask >> i & 1) X += S[i] // Otherwise, append the // character S[i] to Y else Y += S[i] } // Reverse the second string Y = Y.split(\"\").reverse().join(\"\") // If X is equal to Y if (X == Y) ans += 1 } // Return the total number of ways return ans} // Driver Code let S = \"mippiisssisssiipsspiim\"let N = S.length document.write(countWays(S, N)) // This code is contributed by shinjanpatra </script>",
"e": 33284,
"s": 32127,
"text": null
},
{
"code": null,
"e": 33288,
"s": 33284,
"text": "504"
},
{
"code": null,
"e": 33336,
"s": 33290,
"text": "Time Complexity: O(N*2N)Auxiliary Space: O(N)"
},
{
"code": null,
"e": 33351,
"s": 33336,
"text": "mohit kumar 29"
},
{
"code": null,
"e": 33366,
"s": 33351,
"text": "SHUBHAMSINGH10"
},
{
"code": null,
"e": 33379,
"s": 33366,
"text": "shinjanpatra"
},
{
"code": null,
"e": 33389,
"s": 33379,
"text": "partition"
},
{
"code": null,
"e": 33396,
"s": 33389,
"text": "subset"
},
{
"code": null,
"e": 33409,
"s": 33396,
"text": "Mathematical"
},
{
"code": null,
"e": 33417,
"s": 33409,
"text": "Strings"
},
{
"code": null,
"e": 33425,
"s": 33417,
"text": "Strings"
},
{
"code": null,
"e": 33438,
"s": 33425,
"text": "Mathematical"
},
{
"code": null,
"e": 33445,
"s": 33438,
"text": "subset"
},
{
"code": null,
"e": 33543,
"s": 33445,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 33567,
"s": 33543,
"text": "Merge two sorted arrays"
},
{
"code": null,
"e": 33610,
"s": 33567,
"text": "Modulo Operator (%) in C/C++ with Examples"
},
{
"code": null,
"e": 33652,
"s": 33610,
"text": "Program to find GCD or HCF of two numbers"
},
{
"code": null,
"e": 33666,
"s": 33652,
"text": "Prime Numbers"
},
{
"code": null,
"e": 33715,
"s": 33666,
"text": "Program to find sum of elements in a given array"
},
{
"code": null,
"e": 33761,
"s": 33715,
"text": "Write a program to reverse an array or string"
},
{
"code": null,
"e": 33786,
"s": 33761,
"text": "Reverse a string in Java"
},
{
"code": null,
"e": 33820,
"s": 33786,
"text": "Longest Common Subsequence | DP-4"
},
{
"code": null,
"e": 33895,
"s": 33820,
"text": "Check for Balanced Brackets in an expression (well-formedness) using Stack"
}
] |
Adding Filters in VueJS - GeeksforGeeks | 20 Nov, 2020
A Filter is a simple JavaScript function which is used to change the output of a data to the browser. Filters in Vue.JS donβt change the data directly wherever we store them, it only applies formatting to our data. The data remains the same only the output of a data to a browser is changed. Vue.JS doesnβt give these filters by default, so we have to make these filters. With Vue.JS , we can use filters in two different ways i.e. Global filter and Local filter. Global filter provides access all the components while Local filter only allows us to use our filter inside the component it was defined.
Prerequisites: Basics of Vue.JS
Approach: Below all the steps are described order wise to create Filters in Vue.JS .
Step 1: Firstly if we want a global filter, we register it by Vue.filter() method
Step 2: Now we add Vue.filter() method in the index.js file . This filter function takes a value as the argument and then returns the filter or the transformed value .
Vue.filter('uppercase', function(value));
Step 3: This function will be executed by Vue.JS whenever this filter is applied to something. This function will automatically receive one input one argument and thatβs the value . Vue.JS will pass this value to this function automatically and this will be the value on which we apply this filter.
Step 4: Now we return the filter or the transformed value.
Vue.filter('uppercase', function (value) {
return value.toUpperCase();
});
Step 5: Now go to your template and simply add the filter by adding a pipe symbol and then the name of the filter. Syntax to apply a filter is
{{ title | filtername }}
Below is a sample program to illustrate the above approach:
Global Filter: The scope of global filter is throughout our Vue app.
Example 1: In the below program, we will reverse a given string using global filter.
main.js
Javascript
// GLOBAL FILTER// In this example, we are // creating a filter which// reverses the given stringimport Vue from "vue"; // Importing App.vueimport App from "./App.vue"; // DeclarationVue.filter("reverseString", function (value) { return value.split("").reverse().join("");}); new Vue({ render: (h) => h(App)}).$mount("#app");
App.vue
HTML
<!--Template--> <template> <div id="app"> <!--Applying filter--> <h1>{{ name | reverseString }}</h1> </div></template> <script>export default { data: function () { return { name: "GEEKSFORGEEKS", }; },};</script>
Output
Local Filter: The scope of local filter is within a component.
Example 2: In the below program, we will change given string to uppercase using local filter.
App.vue
Javascript
<!-- Local filter in VueJS --><!-- Template --><template> <div> <!-- Applying Uppercase filter --> <h1>{{ name| uppercase }}</h1> </div></template> <!-- Filter defined locally --><script>export default { data: function() { return { name: "geeksforgeeks" }; }, filters: { uppercase: function(value) { return value.toUpperCase(); } }};</script>
Output
Vue.JS
JavaScript
Web Technologies
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
Difference Between PUT and PATCH Request
Remove elements from a JavaScript Array
How to get character array from string in JavaScript?
How to filter object array based on attributes?
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS? | [
{
"code": null,
"e": 25326,
"s": 25298,
"text": "\n20 Nov, 2020"
},
{
"code": null,
"e": 25929,
"s": 25326,
"text": "A Filter is a simple JavaScript function which is used to change the output of a data to the browser. Filters in Vue.JS donβt change the data directly wherever we store them, it only applies formatting to our data. The data remains the same only the output of a data to a browser is changed. Vue.JS doesnβt give these filters by default, so we have to make these filters. With Vue.JS , we can use filters in two different ways i.e. Global filter and Local filter. Global filter provides access all the components while Local filter only allows us to use our filter inside the component it was defined."
},
{
"code": null,
"e": 25961,
"s": 25929,
"text": "Prerequisites: Basics of Vue.JS"
},
{
"code": null,
"e": 26046,
"s": 25961,
"text": "Approach: Below all the steps are described order wise to create Filters in Vue.JS ."
},
{
"code": null,
"e": 26129,
"s": 26046,
"text": "Step 1: Firstly if we want a global filter, we register it by Vue.filter() method"
},
{
"code": null,
"e": 26298,
"s": 26129,
"text": "Step 2: Now we add Vue.filter() method in the index.js file . This filter function takes a value as the argument and then returns the filter or the transformed value ."
},
{
"code": null,
"e": 26341,
"s": 26298,
"text": "Vue.filter('uppercase', function(value));\n"
},
{
"code": null,
"e": 26640,
"s": 26341,
"text": "Step 3: This function will be executed by Vue.JS whenever this filter is applied to something. This function will automatically receive one input one argument and thatβs the value . Vue.JS will pass this value to this function automatically and this will be the value on which we apply this filter."
},
{
"code": null,
"e": 26699,
"s": 26640,
"text": "Step 4: Now we return the filter or the transformed value."
},
{
"code": null,
"e": 26777,
"s": 26699,
"text": "Vue.filter('uppercase', function (value) {\n return value.toUpperCase();\n});\n"
},
{
"code": null,
"e": 26920,
"s": 26777,
"text": "Step 5: Now go to your template and simply add the filter by adding a pipe symbol and then the name of the filter. Syntax to apply a filter is"
},
{
"code": null,
"e": 26946,
"s": 26920,
"text": "{{ title | filtername }}\n"
},
{
"code": null,
"e": 27006,
"s": 26946,
"text": "Below is a sample program to illustrate the above approach:"
},
{
"code": null,
"e": 27075,
"s": 27006,
"text": "Global Filter: The scope of global filter is throughout our Vue app."
},
{
"code": null,
"e": 27160,
"s": 27075,
"text": "Example 1: In the below program, we will reverse a given string using global filter."
},
{
"code": null,
"e": 27168,
"s": 27160,
"text": "main.js"
},
{
"code": null,
"e": 27179,
"s": 27168,
"text": "Javascript"
},
{
"code": "// GLOBAL FILTER// In this example, we are // creating a filter which// reverses the given stringimport Vue from \"vue\"; // Importing App.vueimport App from \"./App.vue\"; // DeclarationVue.filter(\"reverseString\", function (value) { return value.split(\"\").reverse().join(\"\");}); new Vue({ render: (h) => h(App)}).$mount(\"#app\");",
"e": 27514,
"s": 27179,
"text": null
},
{
"code": null,
"e": 27522,
"s": 27514,
"text": "App.vue"
},
{
"code": null,
"e": 27527,
"s": 27522,
"text": "HTML"
},
{
"code": "<!--Template--> <template> <div id=\"app\"> <!--Applying filter--> <h1>{{ name | reverseString }}</h1> </div></template> <script>export default { data: function () { return { name: \"GEEKSFORGEEKS\", }; },};</script>",
"e": 27768,
"s": 27527,
"text": null
},
{
"code": null,
"e": 27775,
"s": 27768,
"text": "Output"
},
{
"code": null,
"e": 27838,
"s": 27775,
"text": "Local Filter: The scope of local filter is within a component."
},
{
"code": null,
"e": 27932,
"s": 27838,
"text": "Example 2: In the below program, we will change given string to uppercase using local filter."
},
{
"code": null,
"e": 27940,
"s": 27932,
"text": "App.vue"
},
{
"code": null,
"e": 27951,
"s": 27940,
"text": "Javascript"
},
{
"code": "<!-- Local filter in VueJS --><!-- Template --><template> <div> <!-- Applying Uppercase filter --> <h1>{{ name| uppercase }}</h1> </div></template> <!-- Filter defined locally --><script>export default { data: function() { return { name: \"geeksforgeeks\" }; }, filters: { uppercase: function(value) { return value.toUpperCase(); } }};</script>",
"e": 28333,
"s": 27951,
"text": null
},
{
"code": null,
"e": 28340,
"s": 28333,
"text": "Output"
},
{
"code": null,
"e": 28347,
"s": 28340,
"text": "Vue.JS"
},
{
"code": null,
"e": 28358,
"s": 28347,
"text": "JavaScript"
},
{
"code": null,
"e": 28375,
"s": 28358,
"text": "Web Technologies"
},
{
"code": null,
"e": 28473,
"s": 28375,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28534,
"s": 28473,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 28575,
"s": 28534,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 28615,
"s": 28575,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 28669,
"s": 28615,
"text": "How to get character array from string in JavaScript?"
},
{
"code": null,
"e": 28717,
"s": 28669,
"text": "How to filter object array based on attributes?"
},
{
"code": null,
"e": 28759,
"s": 28717,
"text": "Roadmap to Become a Web Developer in 2022"
},
{
"code": null,
"e": 28792,
"s": 28759,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 28835,
"s": 28792,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 28897,
"s": 28835,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
}
] |
Angular Material 7 - Auto-Complete | The <mat-autocomplete>, an Angular Directive, is used as a special input control with an inbuilt dropdown to show all possible matches to a custom query. This control acts as a real-time suggestion box as soon as the user types in the input area. <mat-autocomplete> can be used to provide search results from local or remote data sources.
In this chapter, we will showcase the configuration required to draw a autocomplete control using Angular Material.
Follow the following steps to update the Angular application we created in Angular 6 - Project Setup chapter β
Following is the content of the modified module descriptor app.module.ts.
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import {BrowserAnimationsModule} from '@angular/platform-browser/animations';
import {MatAutocompleteModule,MatInputModule} from '@angular/material';
import {FormsModule, ReactiveFormsModule} from '@angular/forms';
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
BrowserAnimationsModule,
MatAutocompleteModule,
MatInputModule,
FormsModule,
ReactiveFormsModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
Following is the content of the modified HTML host file app.component.html.
<form class = "tp-form">
<mat-form-field class = "tp-full-width">
<input type = "text"
placeholder = "US State"
aria-label = "Number"
matInput
[formControl] = "myControl"
[matAutocomplete] = "auto">
<mat-autocomplete #auto = "matAutocomplete">
<mat-option *ngFor = "let state of states" [value] = "state.value">
{{state.display}}
</mat-option>
</mat-autocomplete>
</mat-form-field>
</form>
Following is the content of the modified CSS file app.component.css.
.tp-form {
min-width: 150px;
max-width: 500px;
width: 100%;
}
.tp-full-width {
width: 100%;
}
Following is the content of the modified ts file app.component.ts.
import { Component } from '@angular/core';
import { FormControl } from "@angular/forms";
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'materialApp';
myControl = new FormControl();
states;
constructor(){
this.loadStates();
}
//build list of states as map of key-value pairs
loadStates() {
var allStates = 'Alabama, Alaska, Arizona, Arkansas, California, Colorado, Connecticut, Delaware,\
Florida, Georgia, Hawaii, Idaho, Illinois, Indiana, Iowa, Kansas, Kentucky, Louisiana,\
Maine, Maryland, Massachusetts, Michigan, Minnesota, Mississippi, Missouri, Montana,\
Nebraska, Nevada, New Hampshire, New Jersey, New Mexico, New York, North Carolina,\
North Dakota, Ohio, Oklahoma, Oregon, Pennsylvania, Rhode Island, South Carolina,\
South Dakota, Tennessee, Texas, Utah, Vermont, Virginia, Washington, West Virginia,\
Wisconsin, Wyoming';
this.states = allStates.split(/, +/g).map( function (state) {
return {
value: state.toUpperCase(),
display: state
};
});
}
}
Verify the result.
As first, we've created an input box and bind an autocomplete named auto using [matAutocomplete] attribute.
As first, we've created an input box and bind an autocomplete named auto using [matAutocomplete] attribute.
Then, we've created an autocomplete named auto using mat-autocomplete tag.
Then, we've created an autocomplete named auto using mat-autocomplete tag.
As next, using *ng For loop, options are created.
As next, using *ng For loop, options are created.
16 Lectures
1.5 hours
Anadi Sharma
28 Lectures
2.5 hours
Anadi Sharma
11 Lectures
7.5 hours
SHIVPRASAD KOIRALA
16 Lectures
2.5 hours
Frahaan Hussain
69 Lectures
5 hours
Senol Atac
53 Lectures
3.5 hours
Senol Atac
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 3094,
"s": 2755,
"text": "The <mat-autocomplete>, an Angular Directive, is used as a special input control with an inbuilt dropdown to show all possible matches to a custom query. This control acts as a real-time suggestion box as soon as the user types in the input area. <mat-autocomplete> can be used to provide search results from local or remote data sources."
},
{
"code": null,
"e": 3210,
"s": 3094,
"text": "In this chapter, we will showcase the configuration required to draw a autocomplete control using Angular Material."
},
{
"code": null,
"e": 3321,
"s": 3210,
"text": "Follow the following steps to update the Angular application we created in Angular 6 - Project Setup chapter β"
},
{
"code": null,
"e": 3395,
"s": 3321,
"text": "Following is the content of the modified module descriptor app.module.ts."
},
{
"code": null,
"e": 4060,
"s": 3395,
"text": "import { BrowserModule } from '@angular/platform-browser';\nimport { NgModule } from '@angular/core';\nimport { AppComponent } from './app.component';\nimport {BrowserAnimationsModule} from '@angular/platform-browser/animations';\nimport {MatAutocompleteModule,MatInputModule} from '@angular/material';\nimport {FormsModule, ReactiveFormsModule} from '@angular/forms';\n@NgModule({\n declarations: [\n AppComponent\n ],\n imports: [\n BrowserModule,\n BrowserAnimationsModule,\n MatAutocompleteModule,\n MatInputModule,\n FormsModule,\n ReactiveFormsModule\n ],\n providers: [],\n bootstrap: [AppComponent]\n})\nexport class AppModule { }"
},
{
"code": null,
"e": 4136,
"s": 4060,
"text": "Following is the content of the modified HTML host file app.component.html."
},
{
"code": null,
"e": 4630,
"s": 4136,
"text": "<form class = \"tp-form\">\n <mat-form-field class = \"tp-full-width\">\n <input type = \"text\" \n placeholder = \"US State\" \n aria-label = \"Number\" \n matInput \n [formControl] = \"myControl\" \n [matAutocomplete] = \"auto\">\n <mat-autocomplete #auto = \"matAutocomplete\">\n <mat-option *ngFor = \"let state of states\" [value] = \"state.value\">\n {{state.display}}\n </mat-option>\n </mat-autocomplete>\n </mat-form-field>\n</form>"
},
{
"code": null,
"e": 4699,
"s": 4630,
"text": "Following is the content of the modified CSS file app.component.css."
},
{
"code": null,
"e": 4805,
"s": 4699,
"text": ".tp-form {\n min-width: 150px;\n max-width: 500px;\n width: 100%;\n}\n.tp-full-width {\n width: 100%;\n}"
},
{
"code": null,
"e": 4872,
"s": 4805,
"text": "Following is the content of the modified ts file app.component.ts."
},
{
"code": null,
"e": 6086,
"s": 4872,
"text": "import { Component } from '@angular/core';\nimport { FormControl } from \"@angular/forms\";\n@Component({\n selector: 'app-root',\n templateUrl: './app.component.html',\n styleUrls: ['./app.component.css']\n})\nexport class AppComponent {\n title = 'materialApp';\n myControl = new FormControl();\n states;\n constructor(){\n this.loadStates();\n }\n //build list of states as map of key-value pairs\n loadStates() {\n var allStates = 'Alabama, Alaska, Arizona, Arkansas, California, Colorado, Connecticut, Delaware,\\\n Florida, Georgia, Hawaii, Idaho, Illinois, Indiana, Iowa, Kansas, Kentucky, Louisiana,\\\n Maine, Maryland, Massachusetts, Michigan, Minnesota, Mississippi, Missouri, Montana,\\\n Nebraska, Nevada, New Hampshire, New Jersey, New Mexico, New York, North Carolina,\\\n North Dakota, Ohio, Oklahoma, Oregon, Pennsylvania, Rhode Island, South Carolina,\\\n South Dakota, Tennessee, Texas, Utah, Vermont, Virginia, Washington, West Virginia,\\\n Wisconsin, Wyoming';\n this.states = allStates.split(/, +/g).map( function (state) {\n return {\n value: state.toUpperCase(),\n display: state\n };\n });\n }\n}"
},
{
"code": null,
"e": 6105,
"s": 6086,
"text": "Verify the result."
},
{
"code": null,
"e": 6213,
"s": 6105,
"text": "As first, we've created an input box and bind an autocomplete named auto using [matAutocomplete] attribute."
},
{
"code": null,
"e": 6321,
"s": 6213,
"text": "As first, we've created an input box and bind an autocomplete named auto using [matAutocomplete] attribute."
},
{
"code": null,
"e": 6396,
"s": 6321,
"text": "Then, we've created an autocomplete named auto using mat-autocomplete tag."
},
{
"code": null,
"e": 6471,
"s": 6396,
"text": "Then, we've created an autocomplete named auto using mat-autocomplete tag."
},
{
"code": null,
"e": 6521,
"s": 6471,
"text": "As next, using *ng For loop, options are created."
},
{
"code": null,
"e": 6571,
"s": 6521,
"text": "As next, using *ng For loop, options are created."
},
{
"code": null,
"e": 6606,
"s": 6571,
"text": "\n 16 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 6620,
"s": 6606,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 6655,
"s": 6620,
"text": "\n 28 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 6669,
"s": 6655,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 6704,
"s": 6669,
"text": "\n 11 Lectures \n 7.5 hours \n"
},
{
"code": null,
"e": 6724,
"s": 6704,
"text": " SHIVPRASAD KOIRALA"
},
{
"code": null,
"e": 6759,
"s": 6724,
"text": "\n 16 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 6776,
"s": 6759,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 6809,
"s": 6776,
"text": "\n 69 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 6821,
"s": 6809,
"text": " Senol Atac"
},
{
"code": null,
"e": 6856,
"s": 6821,
"text": "\n 53 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 6868,
"s": 6856,
"text": " Senol Atac"
},
{
"code": null,
"e": 6875,
"s": 6868,
"text": " Print"
},
{
"code": null,
"e": 6886,
"s": 6875,
"text": " Add Notes"
}
] |
How to sum elements at the same index in array of arrays into a single array? JavaScript | We have an array of arrays and are required to write a function that takes in this array and
returns a new array that represents the sum of corresponding elements of original array.
If the original array is β
[
[43, 2, 21],[1, 2, 4, 54],[5, 84, 2],[11, 5, 3, 1]
]
Then the output should be β
[60, 93, 30, 55]
Letβs write a sample function addArray()
The full code for this function will be β
const arr = [
[43, 2, 21],[1, 2, 4, 54],[5, 84, 2],[11, 5, 3, 1]
];
const sumArray = (array) => {
const newArray = [];
array.forEach(sub => {
sub.forEach((num, index) => {
if(newArray[index]){
newArray[index] += num;
}else{
newArray[index] = num;
}
});
});
return newArray;
}
console.log(sumArray(arr));
The output in the console will be β
[ 60, 93, 30, 55 ]
Above, we iterate over each element of the original array and then each number, checking if the
sum of that index already existed, we just added the corresponding number to it othewise we
set the corresponding num equal to it. | [
{
"code": null,
"e": 1244,
"s": 1062,
"text": "We have an array of arrays and are required to write a function that takes in this array and\nreturns a new array that represents the sum of corresponding elements of original array."
},
{
"code": null,
"e": 1271,
"s": 1244,
"text": "If the original array is β"
},
{
"code": null,
"e": 1329,
"s": 1271,
"text": "[\n [43, 2, 21],[1, 2, 4, 54],[5, 84, 2],[11, 5, 3, 1]\n]"
},
{
"code": null,
"e": 1357,
"s": 1329,
"text": "Then the output should be β"
},
{
"code": null,
"e": 1374,
"s": 1357,
"text": "[60, 93, 30, 55]"
},
{
"code": null,
"e": 1415,
"s": 1374,
"text": "Letβs write a sample function addArray()"
},
{
"code": null,
"e": 1457,
"s": 1415,
"text": "The full code for this function will be β"
},
{
"code": null,
"e": 1839,
"s": 1457,
"text": "const arr = [\n [43, 2, 21],[1, 2, 4, 54],[5, 84, 2],[11, 5, 3, 1]\n];\nconst sumArray = (array) => {\n const newArray = [];\n array.forEach(sub => {\n sub.forEach((num, index) => {\n if(newArray[index]){\n newArray[index] += num;\n }else{\n newArray[index] = num;\n }\n });\n });\n return newArray;\n}\nconsole.log(sumArray(arr));"
},
{
"code": null,
"e": 1875,
"s": 1839,
"text": "The output in the console will be β"
},
{
"code": null,
"e": 1894,
"s": 1875,
"text": "[ 60, 93, 30, 55 ]"
},
{
"code": null,
"e": 2121,
"s": 1894,
"text": "Above, we iterate over each element of the original array and then each number, checking if the\nsum of that index already existed, we just added the corresponding number to it othewise we\nset the corresponding num equal to it."
}
] |
11 Examples to Master Python List Comprehensions | by Soner YΔ±ldΔ±rΔ±m | Towards Data Science | List is a built-in data structure in Python and a collection of data points in square brackets. Lists can be used to store any data type or a mixture of different data types.
In this post, we will cover list comprehensions in python with 11 examples. I tried to order the examples according to their complexity levels (in my opinion).
List comprehension is basically creating lists based on existing iterables. It can also be described as representing for and if loops with a simpler and more appealing syntax. List comprehensions are relatively faster than for loops.
So we iterate over an iterable and do something (optional!) with the items and then put them in a list. In some cases, we just take the items that fit a specified condition.
Letβs start with the examples.
#example 1import numpy as npa = [4,6,7,3,2]b = [x for x in a if x > 5]b[6, 7]
We iterate over a list (iterable) and take the elements that are greater than 5 (condition).
The equivalent for loop is:
b = []for x in a: if x > 5: b.append(x)b[6, 7]
We can also do something with items before putting them in a new list:
#example 2import numpy as npa = [4,6,7,3,2]b = [x*2 for x in a if x > 5]b[12, 14]
We multiply the items that fit the condition by 2 and then put in a list.
The third example is a list of strings:
#example 3names = ['Ch','Dh','Eh','cb','Tb','Td']new_names = [name for name in names if name.lower().startswith('c')]new_names['Ch', 'cb']
The condition is that string starts with the letter βcβ. Since we have both capital and lowercase letters, we convert all letters to lowercase first.
The iterable does not have to be a list. It can be any python iterable. For instance, we can iterate over a 2-dimensional NumPy array which is actually a matrix.
#example 4import numpy as npA = np.random.randint(10, size=(4,4))Aarray([[1, 7, 4, 4], [5, 0, 0, 6], [7, 5, 8, 4], [1, 3, 2, 2]])max_element = [max(i) for i in A]max_element[7, 6, 8, 3]
We iterate over the rows in matrix A and take the maximum number.
Lists can store any data type. Letβs do an example with a list of lists.
#example 5vals = [[1,2,3],[4,5,2],[3,2,6]]vals_max = [max(x) for x in vals]vals_max[3, 5, 6]
We create a list of the maximum values in each list.
We can have multiple conditions in a list comprehension.
#example 6names = ['Ch','Dh','Eh','cb','Tb','Td','Chb','Tdb']new_names = [name for name in names if name.lower().endswith('b') and len(name) > 2]new_names['Chb', 'Tdb']
We get the strings that end with the letter βbβ and have a length greater than 2.
We can combine multiple conditions with other logical operators:
#example 7names = ['chb', 'ydb', 'thd', 'hgh']new_names = [name for name in names if name.endswith('b') | name.startswith('c')]new_names['chb', 'ydb']
We can also have nested list comprehensions which are a little bit more complex. They represent nested for loops.
Consider the following list of lists:
vals = [[1,2,3],[4,5,2],[3,2,6]]
We want to take out each element from the nested lists so the desired output is:
vals = [1,2,3,4,5,2,3,2,6]
Here is the nested list comprehension that does this operation:
#example 8vals = [[1,2,3],[4,5,2],[3,2,6]]vals_exp = [y for x in vals for y in x]vals_exp[1, 2, 3, 4, 5, 2, 3, 2, 6]
The syntax may not seem very intuitive. It will be clear when compared with the equivalent for loop.
We put the blocks of a nested for loop into a list comprehension.
Note: There is a much easier way to do the operation in example 7 which is the explode function of pandas. I used list comprehension just to show the structure. It can be done with the explode function as follows:
pd.Series(vals).explode()
It returns a pandas series but you can easily convert it to a list.
We can also add conditions in nested list comprehensions. Consider the following list of lists with strings.
text = [['bar','foo','fooba'],['Rome','Madrid','Houston'], ['aa','bb','cc','dd']]
We only want the strings in nested lists whose length is greater than 3.
#example 9text_1 = [y for x in text if len(x)>3 for y in x]text_1['aa', 'bb', 'cc', 'dd']
We put the condition on the nested lists, not on individual elements. Thus, the equivalent nested for/if loop syntax is as follows.
We can also put a condition on individual elements.
#example 10text_2 = [y for x in text for y in x if len(y)>4]text_2['fooba', 'Madrid', 'Houston']
We now have strings that are longer than 4 characters. Since the condition is on individual elements, the equivalent nested for/if loops:
We may also need to put conditions on both nested lists and individual items.
#example 11text_3 = [y.upper() for x in text if len(x) == 3 for y in x if y.startswith('f')]text_3['FOO', 'FOOBA']
We get the items that start with the letter βfβ in nested lists with a length of 3 and then convert all the letters of selected items to uppercase.
The equivalent for/if loops:
Tip: When you are not sure and cannot find out the syntax for list comprehension, try to build it with for/if loops. Then you can convert it to a list comprehension by adding individual blocks of loops into the list comprehension.
List comprehension loads the entire output list into memory. This is acceptable or even desirable for small or medium-sized lists because it makes the operation faster. However, when we are working with large lists (e.g. 1 billion elements), list comprehension should be avoided. It may cause your computer to crash due to the extreme amount of memory requirement.
A better alternative for such large lists is using a generator that does not actually create a large data structure in memory. A generator creates items when they are used. After the items are used, the generator throws them away. Using a generator, we can ask for the next item in an iterable until we reach the end and store a single value at a time.
Thank you for reading. Please let me know if you have any feedback. | [
{
"code": null,
"e": 347,
"s": 172,
"text": "List is a built-in data structure in Python and a collection of data points in square brackets. Lists can be used to store any data type or a mixture of different data types."
},
{
"code": null,
"e": 507,
"s": 347,
"text": "In this post, we will cover list comprehensions in python with 11 examples. I tried to order the examples according to their complexity levels (in my opinion)."
},
{
"code": null,
"e": 741,
"s": 507,
"text": "List comprehension is basically creating lists based on existing iterables. It can also be described as representing for and if loops with a simpler and more appealing syntax. List comprehensions are relatively faster than for loops."
},
{
"code": null,
"e": 915,
"s": 741,
"text": "So we iterate over an iterable and do something (optional!) with the items and then put them in a list. In some cases, we just take the items that fit a specified condition."
},
{
"code": null,
"e": 946,
"s": 915,
"text": "Letβs start with the examples."
},
{
"code": null,
"e": 1024,
"s": 946,
"text": "#example 1import numpy as npa = [4,6,7,3,2]b = [x for x in a if x > 5]b[6, 7]"
},
{
"code": null,
"e": 1117,
"s": 1024,
"text": "We iterate over a list (iterable) and take the elements that are greater than 5 (condition)."
},
{
"code": null,
"e": 1145,
"s": 1117,
"text": "The equivalent for loop is:"
},
{
"code": null,
"e": 1196,
"s": 1145,
"text": "b = []for x in a: if x > 5: b.append(x)b[6, 7]"
},
{
"code": null,
"e": 1267,
"s": 1196,
"text": "We can also do something with items before putting them in a new list:"
},
{
"code": null,
"e": 1349,
"s": 1267,
"text": "#example 2import numpy as npa = [4,6,7,3,2]b = [x*2 for x in a if x > 5]b[12, 14]"
},
{
"code": null,
"e": 1423,
"s": 1349,
"text": "We multiply the items that fit the condition by 2 and then put in a list."
},
{
"code": null,
"e": 1463,
"s": 1423,
"text": "The third example is a list of strings:"
},
{
"code": null,
"e": 1602,
"s": 1463,
"text": "#example 3names = ['Ch','Dh','Eh','cb','Tb','Td']new_names = [name for name in names if name.lower().startswith('c')]new_names['Ch', 'cb']"
},
{
"code": null,
"e": 1752,
"s": 1602,
"text": "The condition is that string starts with the letter βcβ. Since we have both capital and lowercase letters, we convert all letters to lowercase first."
},
{
"code": null,
"e": 1914,
"s": 1752,
"text": "The iterable does not have to be a list. It can be any python iterable. For instance, we can iterate over a 2-dimensional NumPy array which is actually a matrix."
},
{
"code": null,
"e": 2142,
"s": 1914,
"text": "#example 4import numpy as npA = np.random.randint(10, size=(4,4))Aarray([[1, 7, 4, 4], [5, 0, 0, 6], [7, 5, 8, 4], [1, 3, 2, 2]])max_element = [max(i) for i in A]max_element[7, 6, 8, 3]"
},
{
"code": null,
"e": 2208,
"s": 2142,
"text": "We iterate over the rows in matrix A and take the maximum number."
},
{
"code": null,
"e": 2281,
"s": 2208,
"text": "Lists can store any data type. Letβs do an example with a list of lists."
},
{
"code": null,
"e": 2374,
"s": 2281,
"text": "#example 5vals = [[1,2,3],[4,5,2],[3,2,6]]vals_max = [max(x) for x in vals]vals_max[3, 5, 6]"
},
{
"code": null,
"e": 2427,
"s": 2374,
"text": "We create a list of the maximum values in each list."
},
{
"code": null,
"e": 2484,
"s": 2427,
"text": "We can have multiple conditions in a list comprehension."
},
{
"code": null,
"e": 2653,
"s": 2484,
"text": "#example 6names = ['Ch','Dh','Eh','cb','Tb','Td','Chb','Tdb']new_names = [name for name in names if name.lower().endswith('b') and len(name) > 2]new_names['Chb', 'Tdb']"
},
{
"code": null,
"e": 2735,
"s": 2653,
"text": "We get the strings that end with the letter βbβ and have a length greater than 2."
},
{
"code": null,
"e": 2800,
"s": 2735,
"text": "We can combine multiple conditions with other logical operators:"
},
{
"code": null,
"e": 2951,
"s": 2800,
"text": "#example 7names = ['chb', 'ydb', 'thd', 'hgh']new_names = [name for name in names if name.endswith('b') | name.startswith('c')]new_names['chb', 'ydb']"
},
{
"code": null,
"e": 3065,
"s": 2951,
"text": "We can also have nested list comprehensions which are a little bit more complex. They represent nested for loops."
},
{
"code": null,
"e": 3103,
"s": 3065,
"text": "Consider the following list of lists:"
},
{
"code": null,
"e": 3136,
"s": 3103,
"text": "vals = [[1,2,3],[4,5,2],[3,2,6]]"
},
{
"code": null,
"e": 3217,
"s": 3136,
"text": "We want to take out each element from the nested lists so the desired output is:"
},
{
"code": null,
"e": 3244,
"s": 3217,
"text": "vals = [1,2,3,4,5,2,3,2,6]"
},
{
"code": null,
"e": 3308,
"s": 3244,
"text": "Here is the nested list comprehension that does this operation:"
},
{
"code": null,
"e": 3425,
"s": 3308,
"text": "#example 8vals = [[1,2,3],[4,5,2],[3,2,6]]vals_exp = [y for x in vals for y in x]vals_exp[1, 2, 3, 4, 5, 2, 3, 2, 6]"
},
{
"code": null,
"e": 3526,
"s": 3425,
"text": "The syntax may not seem very intuitive. It will be clear when compared with the equivalent for loop."
},
{
"code": null,
"e": 3592,
"s": 3526,
"text": "We put the blocks of a nested for loop into a list comprehension."
},
{
"code": null,
"e": 3806,
"s": 3592,
"text": "Note: There is a much easier way to do the operation in example 7 which is the explode function of pandas. I used list comprehension just to show the structure. It can be done with the explode function as follows:"
},
{
"code": null,
"e": 3832,
"s": 3806,
"text": "pd.Series(vals).explode()"
},
{
"code": null,
"e": 3900,
"s": 3832,
"text": "It returns a pandas series but you can easily convert it to a list."
},
{
"code": null,
"e": 4009,
"s": 3900,
"text": "We can also add conditions in nested list comprehensions. Consider the following list of lists with strings."
},
{
"code": null,
"e": 4091,
"s": 4009,
"text": "text = [['bar','foo','fooba'],['Rome','Madrid','Houston'], ['aa','bb','cc','dd']]"
},
{
"code": null,
"e": 4164,
"s": 4091,
"text": "We only want the strings in nested lists whose length is greater than 3."
},
{
"code": null,
"e": 4254,
"s": 4164,
"text": "#example 9text_1 = [y for x in text if len(x)>3 for y in x]text_1['aa', 'bb', 'cc', 'dd']"
},
{
"code": null,
"e": 4386,
"s": 4254,
"text": "We put the condition on the nested lists, not on individual elements. Thus, the equivalent nested for/if loop syntax is as follows."
},
{
"code": null,
"e": 4438,
"s": 4386,
"text": "We can also put a condition on individual elements."
},
{
"code": null,
"e": 4535,
"s": 4438,
"text": "#example 10text_2 = [y for x in text for y in x if len(y)>4]text_2['fooba', 'Madrid', 'Houston']"
},
{
"code": null,
"e": 4673,
"s": 4535,
"text": "We now have strings that are longer than 4 characters. Since the condition is on individual elements, the equivalent nested for/if loops:"
},
{
"code": null,
"e": 4751,
"s": 4673,
"text": "We may also need to put conditions on both nested lists and individual items."
},
{
"code": null,
"e": 4866,
"s": 4751,
"text": "#example 11text_3 = [y.upper() for x in text if len(x) == 3 for y in x if y.startswith('f')]text_3['FOO', 'FOOBA']"
},
{
"code": null,
"e": 5014,
"s": 4866,
"text": "We get the items that start with the letter βfβ in nested lists with a length of 3 and then convert all the letters of selected items to uppercase."
},
{
"code": null,
"e": 5043,
"s": 5014,
"text": "The equivalent for/if loops:"
},
{
"code": null,
"e": 5274,
"s": 5043,
"text": "Tip: When you are not sure and cannot find out the syntax for list comprehension, try to build it with for/if loops. Then you can convert it to a list comprehension by adding individual blocks of loops into the list comprehension."
},
{
"code": null,
"e": 5639,
"s": 5274,
"text": "List comprehension loads the entire output list into memory. This is acceptable or even desirable for small or medium-sized lists because it makes the operation faster. However, when we are working with large lists (e.g. 1 billion elements), list comprehension should be avoided. It may cause your computer to crash due to the extreme amount of memory requirement."
},
{
"code": null,
"e": 5992,
"s": 5639,
"text": "A better alternative for such large lists is using a generator that does not actually create a large data structure in memory. A generator creates items when they are used. After the items are used, the generator throws them away. Using a generator, we can ask for the next item in an iterable until we reach the end and store a single value at a time."
}
] |
Are the private variables and private methods of a parent class inherited by the child class in Java? | No, a child class canβt inherit private members of the parent class, it can inherit only protected, default, and public members of it. If you try it gives you a compile time error as: β
class Super{
private int data = 30;
public void display(){
System.out.println("Hello this is the method of the super class");
}
}
public class Sub extends Super{
public void greet(){
System.out.println("Hello this is the method of the sub class");
}
public static void main(String args[]){
Sub obj = new Sub();
System.out.println(obj.data);
}
}
On executing this example it will give an compiletime error as shown below β
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
The field Super.data is not visible
at Sub.main(Sub.java:13) | [
{
"code": null,
"e": 1248,
"s": 1062,
"text": "No, a child class canβt inherit private members of the parent class, it can inherit only protected, default, and public members of it. If you try it gives you a compile time error as: β"
},
{
"code": null,
"e": 1638,
"s": 1248,
"text": "class Super{\n private int data = 30;\n public void display(){\n System.out.println(\"Hello this is the method of the super class\");\n }\n}\npublic class Sub extends Super{\n public void greet(){\n System.out.println(\"Hello this is the method of the sub class\");\n }\n public static void main(String args[]){\n Sub obj = new Sub();\n System.out.println(obj.data);\n }\n}"
},
{
"code": null,
"e": 1715,
"s": 1638,
"text": "On executing this example it will give an compiletime error as shown below β"
},
{
"code": null,
"e": 1859,
"s": 1715,
"text": "Exception in thread \"main\" java.lang.Error: Unresolved compilation problem:\n The field Super.data is not visible\n at Sub.main(Sub.java:13)\n"
}
] |
Consuming RESTful Web Services | This chapter will discuss in detail about consuming a RESTful Web Services by using jQuery AJAX.
Create a simple Spring Boot web application and write a controller class files which is used to redirects into the HTML file to consumes the RESTful web services.
We need to add the Spring Boot starter Thymeleaf and Web dependency in our build configuration file.
For Maven users, add the below dependencies in your pom.xml file.
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
For Gradle users, add the below dependencies into your build.gradle file β
compile group: βorg.springframework.bootβ, name: βspring-boot-starter-thymeleafβ
compile(βorg.springframework.boot:spring-boot-starter-webβ)
The code for @Controller class file is given below β
@Controller
public class ViewController {
}
You can define the Request URI methods to redirects into the HTML file as shown below β
@RequestMapping(β/view-productsβ)
public String viewProducts() {
return βview-productsβ;
}
@RequestMapping(β/add-productsβ)
public String addProducts() {
return βadd-productsβ;
}
This API http://localhost:9090/products should return the below JSON in response as shown below β
[
{
"id": "1",
"name": "Honey"
},
{
"id": "2",
"name": "Almond"
}
]
Now, create a view-products.html file under the templates directory in the classpath.
In the HTML file, we added the jQuery library and written the code to consume the RESTful web service on page load.
<script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$.getJSON("http://localhost:9090/products", function(result){
$.each(result, function(key,value) {
$("#productsJson").append(value.id+" "+value.name+" ");
});
});
});
</script>
The POST method and this URL http://localhost:9090/products should contains the below Request Body and Response body.
The code for Request body is given below β
{
"id":"3",
"name":"Ginger"
}
The code for Response body is given below β
Product is created successfully
Now, create the add-products.html file under the templates directory in the classpath.
In the HTML file, we added the jQuery library and written the code that submits the form to RESTful web service on clicking the button.
<script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
$("button").click(function() {
var productmodel = {
id : "3",
name : "Ginger"
};
var requestJSON = JSON.stringify(productmodel);
$.ajax({
type : "POST",
url : "http://localhost:9090/products",
headers : {
"Content-Type" : "application/json"
},
data : requestJSON,
success : function(data) {
alert(data);
},
error : function(data) {
}
});
});
});
</script>
The complete code is given below.
Maven β pom.xml file
<?xml version = "1.0" encoding = "UTF-8"?>
<project xmlns = "http://maven.apache.org/POM/4.0.0"
xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation = "http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.tutorialspoint</groupId>
<artifactId>demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>demo</name>
<description>Demo project for Spring Boot</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.8.RELEASE</version>
<relativePath />
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
The code for Gradle β build.gradle is given below β
buildscript {
ext {
springBootVersion = β1.5.8.RELEASEβ
}
repositories {
mavenCentral()
}
dependencies {
classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
}
}
apply plugin: βjavaβ
apply plugin: βeclipseβ
apply plugin: βorg.springframework.bootβ
group = βcom.tutorialspointβ
version = β0.0.1-SNAPSHOTβ
sourceCompatibility = 1.8
repositories {
mavenCentral()
}
dependencies {
compile(βorg.springframework.boot:spring-boot-starter-webβ)
compile group: βorg.springframework.bootβ, name: βspring-boot-starter-thymeleafβ
testCompile(βorg.springframework.boot:spring-boot-starter-testβ)
}
The controller class file given below β ViewController.java is given below β
package com.tutorialspoint.demo.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class ViewController {
@RequestMapping(β/view-productsβ)
public String viewProducts() {
return βview-productsβ;
}
@RequestMapping(β/add-productsβ)
public String addProducts() {
return βadd-productsβ;
}
}
The view-products.html file is given below β
<!DOCTYPE html>
<html>
<head>
<meta charset = "ISO-8859-1"/>
<title>View Products</title>
<script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$.getJSON("http://localhost:9090/products", function(result){
$.each(result, function(key,value) {
$("#productsJson").append(value.id+" "+value.name+" ");
});
});
});
</script>
</head>
<body>
<div id = "productsJson"> </div>
</body>
</html>
The add-products.html file is given below β
<!DOCTYPE html>
<html>
<head>
<meta charset = "ISO-8859-1" />
<title>Add Products</title>
<script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
$("button").click(function() {
var productmodel = {
id : "3",
name : "Ginger"
};
var requestJSON = JSON.stringify(productmodel);
$.ajax({
type : "POST",
url : "http://localhost:9090/products",
headers : {
"Content-Type" : "application/json"
},
data : requestJSON,
success : function(data) {
alert(data);
},
error : function(data) {
}
});
});
});
</script>
</head>
<body>
<button>Click here to submit the form</button>
</body>
</html>
The main Spring Boot Application class file is given below β
package com.tutorialspoint.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
Now, you can create an executable JAR file, and run the Spring Boot application by using the following Maven or Gradle commands.
For Maven, use the command as given below β
mvn clean install
After βBUILD SUCCESSβ, you can find the JAR file under the target directory.
For Gradle, use the command as given below β
gradle clean build
After βBUILD SUCCESSFULβ, you can find the JAR file under the build/libs directory.
Run the JAR file by using the following command β
java βjar <JARFILE>
Now, the application has started on the Tomcat port 8080.
Now hit the URL in your web browser and you can see the output as shown β
http://localhost:8080/view-products
http://localhost:8080/add-products
Now, click the button Click here to submit the form and you can see the result as shown β
Now, hit the view products URL and see the created product.
http://localhost:8080/view-products
To consume the APIs by using Angular JS, you can use the examples given below β
Use the following code to create the Angular JS Controller to consume the GET API - http://localhost:9090/products β
angular.module('demo', [])
.controller('Hello', function($scope, $http) {
$http.get('http://localhost:9090/products').
then(function(response) {
$scope.products = response.data;
});
});
Use the following code to create the Angular JS Controller to consume the POST API - http://localhost:9090/products β
angular.module('demo', [])
.controller('Hello', function($scope, $http) {
$http.post('http://localhost:9090/products',data).
then(function(response) {
console.log("Product created successfully");
});
});
Note β The Post method data represents the Request body in JSON format to create a product.
102 Lectures
8 hours
Karthikeya T
39 Lectures
5 hours
Chaand Sheikh
73 Lectures
5.5 hours
Senol Atac
62 Lectures
4.5 hours
Senol Atac
67 Lectures
4.5 hours
Senol Atac
69 Lectures
5 hours
Senol Atac
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 3122,
"s": 3025,
"text": "This chapter will discuss in detail about consuming a RESTful Web Services by using jQuery AJAX."
},
{
"code": null,
"e": 3285,
"s": 3122,
"text": "Create a simple Spring Boot web application and write a controller class files which is used to redirects into the HTML file to consumes the RESTful web services."
},
{
"code": null,
"e": 3386,
"s": 3285,
"text": "We need to add the Spring Boot starter Thymeleaf and Web dependency in our build configuration file."
},
{
"code": null,
"e": 3452,
"s": 3386,
"text": "For Maven users, add the below dependencies in your pom.xml file."
},
{
"code": null,
"e": 3711,
"s": 3452,
"text": "<dependency>\n <groupId>org.springframework.boot</groupId>\n <artifactId>spring-boot-starter-thymeleaf</artifactId>\n</dependency>\n\n<dependency>\n <groupId>org.springframework.boot</groupId>\n <artifactId>spring-boot-starter-web</artifactId>\n</dependency>"
},
{
"code": null,
"e": 3786,
"s": 3711,
"text": "For Gradle users, add the below dependencies into your build.gradle file β"
},
{
"code": null,
"e": 3927,
"s": 3786,
"text": "compile group: βorg.springframework.bootβ, name: βspring-boot-starter-thymeleafβ\ncompile(βorg.springframework.boot:spring-boot-starter-webβ)"
},
{
"code": null,
"e": 3980,
"s": 3927,
"text": "The code for @Controller class file is given below β"
},
{
"code": null,
"e": 4024,
"s": 3980,
"text": "@Controller\npublic class ViewController {\n}"
},
{
"code": null,
"e": 4112,
"s": 4024,
"text": "You can define the Request URI methods to redirects into the HTML file as shown below β"
},
{
"code": null,
"e": 4297,
"s": 4112,
"text": "@RequestMapping(β/view-productsβ)\npublic String viewProducts() {\n return βview-productsβ;\n}\n@RequestMapping(β/add-productsβ)\npublic String addProducts() {\n return βadd-productsβ;\n}"
},
{
"code": null,
"e": 4395,
"s": 4297,
"text": "This API http://localhost:9090/products should return the below JSON in response as shown below β"
},
{
"code": null,
"e": 4499,
"s": 4395,
"text": "[\n {\n \"id\": \"1\",\n \"name\": \"Honey\"\n },\n {\n \"id\": \"2\",\n \"name\": \"Almond\"\n }\n]"
},
{
"code": null,
"e": 4585,
"s": 4499,
"text": "Now, create a view-products.html file under the templates directory in the classpath."
},
{
"code": null,
"e": 4701,
"s": 4585,
"text": "In the HTML file, we added the jQuery library and written the code to consume the RESTful web service on page load."
},
{
"code": null,
"e": 5037,
"s": 4701,
"text": "<script src = \"https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js\"></script>\n\n<script>\n$(document).ready(function(){\n $.getJSON(\"http://localhost:9090/products\", function(result){\n $.each(result, function(key,value) {\n $(\"#productsJson\").append(value.id+\" \"+value.name+\" \");\n }); \n });\n});\n</script>"
},
{
"code": null,
"e": 5155,
"s": 5037,
"text": "The POST method and this URL http://localhost:9090/products should contains the below Request Body and Response body."
},
{
"code": null,
"e": 5198,
"s": 5155,
"text": "The code for Request body is given below β"
},
{
"code": null,
"e": 5234,
"s": 5198,
"text": "{\n \"id\":\"3\",\n \"name\":\"Ginger\"\n}"
},
{
"code": null,
"e": 5278,
"s": 5234,
"text": "The code for Response body is given below β"
},
{
"code": null,
"e": 5311,
"s": 5278,
"text": "Product is created successfully\n"
},
{
"code": null,
"e": 5398,
"s": 5311,
"text": "Now, create the add-products.html file under the templates directory in the classpath."
},
{
"code": null,
"e": 5534,
"s": 5398,
"text": "In the HTML file, we added the jQuery library and written the code that submits the form to RESTful web service on clicking the button."
},
{
"code": null,
"e": 6246,
"s": 5534,
"text": "<script src = \"https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js\"></script>\n<script>\n $(document).ready(function() {\n $(\"button\").click(function() {\n var productmodel = {\n id : \"3\",\n name : \"Ginger\"\n };\n var requestJSON = JSON.stringify(productmodel);\n $.ajax({\n type : \"POST\",\n url : \"http://localhost:9090/products\",\n headers : {\n \"Content-Type\" : \"application/json\"\n },\n data : requestJSON,\n success : function(data) {\n alert(data);\n },\n error : function(data) {\n }\n });\n });\n });\n</script>"
},
{
"code": null,
"e": 6280,
"s": 6246,
"text": "The complete code is given below."
},
{
"code": null,
"e": 6301,
"s": 6280,
"text": "Maven β pom.xml file"
},
{
"code": null,
"e": 8005,
"s": 6301,
"text": "<?xml version = \"1.0\" encoding = \"UTF-8\"?>\n<project xmlns = \"http://maven.apache.org/POM/4.0.0\" \n xmlns:xsi = \"http://www.w3.org/2001/XMLSchema-instance\"\n xsi:schemaLocation = \"http://maven.apache.org/POM/4.0.0 \n http://maven.apache.org/xsd/maven-4.0.0.xsd\">\n \n <modelVersion>4.0.0</modelVersion>\n <groupId>com.tutorialspoint</groupId>\n <artifactId>demo</artifactId>\n <version>0.0.1-SNAPSHOT</version>\n <packaging>jar</packaging>\n <name>demo</name>\n <description>Demo project for Spring Boot</description>\n\n <parent>\n <groupId>org.springframework.boot</groupId>\n <artifactId>spring-boot-starter-parent</artifactId>\n <version>1.5.8.RELEASE</version>\n <relativePath />\n </parent>\n\n <properties>\n <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>\n <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>\n <java.version>1.8</java.version>\n </properties>\n\n <dependencies>\n <dependency>\n <groupId>org.springframework.boot</groupId>\n <artifactId>spring-boot-starter-web</artifactId>\n </dependency>\n\n <dependency>\n <groupId>org.springframework.boot</groupId>\n <artifactId>spring-boot-starter-test</artifactId>\n <scope>test</scope>\n </dependency>\n\n <dependency>\n <groupId>org.springframework.boot</groupId>\n <artifactId>spring-boot-starter-thymeleaf</artifactId>\n </dependency>\n </dependencies>\n\n <build>\n <plugins>\n <plugin>\n <groupId>org.springframework.boot</groupId>\n <artifactId>spring-boot-maven-plugin</artifactId>\n </plugin>\n </plugins>\n </build>\n \n</project>"
},
{
"code": null,
"e": 8057,
"s": 8005,
"text": "The code for Gradle β build.gradle is given below β"
},
{
"code": null,
"e": 8726,
"s": 8057,
"text": "buildscript {\n ext {\n springBootVersion = β1.5.8.RELEASEβ\n }\n repositories {\n mavenCentral()\n }\n dependencies {\n classpath(\"org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}\")\n }\n}\n\napply plugin: βjavaβ\napply plugin: βeclipseβ\napply plugin: βorg.springframework.bootβ\n\ngroup = βcom.tutorialspointβ\nversion = β0.0.1-SNAPSHOTβ\nsourceCompatibility = 1.8\n\nrepositories {\n mavenCentral()\n}\n\ndependencies {\n compile(βorg.springframework.boot:spring-boot-starter-webβ)\n compile group: βorg.springframework.bootβ, name: βspring-boot-starter-thymeleafβ\n testCompile(βorg.springframework.boot:spring-boot-starter-testβ)\n}"
},
{
"code": null,
"e": 8803,
"s": 8726,
"text": "The controller class file given below β ViewController.java is given below β"
},
{
"code": null,
"e": 9221,
"s": 8803,
"text": "package com.tutorialspoint.demo.controller;\n\nimport org.springframework.stereotype.Controller;\nimport org.springframework.web.bind.annotation.RequestMapping;\n\n@Controller\npublic class ViewController {\n @RequestMapping(β/view-productsβ)\n public String viewProducts() {\n return βview-productsβ;\n }\n @RequestMapping(β/add-productsβ)\n public String addProducts() {\n return βadd-productsβ; \n } \n}"
},
{
"code": null,
"e": 9266,
"s": 9221,
"text": "The view-products.html file is given below β"
},
{
"code": null,
"e": 9877,
"s": 9266,
"text": "<!DOCTYPE html>\n<html>\n <head>\n <meta charset = \"ISO-8859-1\"/>\n <title>View Products</title>\n <script src = \"https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js\"></script>\n \n <script>\n $(document).ready(function(){\n $.getJSON(\"http://localhost:9090/products\", function(result){\n $.each(result, function(key,value) {\n $(\"#productsJson\").append(value.id+\" \"+value.name+\" \");\n }); \n });\n });\n </script>\n </head>\n \n <body>\n <div id = \"productsJson\"> </div>\n </body>\n</html>"
},
{
"code": null,
"e": 9921,
"s": 9877,
"text": "The add-products.html file is given below β"
},
{
"code": null,
"e": 10992,
"s": 9921,
"text": "<!DOCTYPE html>\n<html>\n <head>\n <meta charset = \"ISO-8859-1\" />\n <title>Add Products</title>\n <script src = \"https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js\"></script>\n \n <script>\n $(document).ready(function() {\n $(\"button\").click(function() {\n var productmodel = {\n id : \"3\",\n name : \"Ginger\"\n };\n var requestJSON = JSON.stringify(productmodel);\n $.ajax({\n type : \"POST\",\n url : \"http://localhost:9090/products\",\n headers : {\n \"Content-Type\" : \"application/json\"\n },\n data : requestJSON,\n success : function(data) {\n alert(data);\n },\n error : function(data) {\n }\n });\n });\n });\n </script>\n </head>\n \n <body>\n <button>Click here to submit the form</button>\n </body>\n</html>"
},
{
"code": null,
"e": 11053,
"s": 10992,
"text": "The main Spring Boot Application class file is given below β"
},
{
"code": null,
"e": 11371,
"s": 11053,
"text": "package com.tutorialspoint.demo;\n\nimport org.springframework.boot.SpringApplication;\nimport org.springframework.boot.autoconfigure.SpringBootApplication;\n\n@SpringBootApplication\npublic class DemoApplication {\n public static void main(String[] args) {\n SpringApplication.run(DemoApplication.class, args);\n }\n}"
},
{
"code": null,
"e": 11500,
"s": 11371,
"text": "Now, you can create an executable JAR file, and run the Spring Boot application by using the following Maven or Gradle commands."
},
{
"code": null,
"e": 11544,
"s": 11500,
"text": "For Maven, use the command as given below β"
},
{
"code": null,
"e": 11563,
"s": 11544,
"text": "mvn clean install\n"
},
{
"code": null,
"e": 11640,
"s": 11563,
"text": "After βBUILD SUCCESSβ, you can find the JAR file under the target directory."
},
{
"code": null,
"e": 11685,
"s": 11640,
"text": "For Gradle, use the command as given below β"
},
{
"code": null,
"e": 11705,
"s": 11685,
"text": "gradle clean build\n"
},
{
"code": null,
"e": 11789,
"s": 11705,
"text": "After βBUILD SUCCESSFULβ, you can find the JAR file under the build/libs directory."
},
{
"code": null,
"e": 11839,
"s": 11789,
"text": "Run the JAR file by using the following command β"
},
{
"code": null,
"e": 11861,
"s": 11839,
"text": "java βjar <JARFILE> \n"
},
{
"code": null,
"e": 11919,
"s": 11861,
"text": "Now, the application has started on the Tomcat port 8080."
},
{
"code": null,
"e": 11993,
"s": 11919,
"text": "Now hit the URL in your web browser and you can see the output as shown β"
},
{
"code": null,
"e": 12030,
"s": 11993,
"text": "http://localhost:8080/view-products "
},
{
"code": null,
"e": 12066,
"s": 12030,
"text": "http://localhost:8080/add-products "
},
{
"code": null,
"e": 12156,
"s": 12066,
"text": "Now, click the button Click here to submit the form and you can see the result as shown β"
},
{
"code": null,
"e": 12216,
"s": 12156,
"text": "Now, hit the view products URL and see the created product."
},
{
"code": null,
"e": 12252,
"s": 12216,
"text": "http://localhost:8080/view-products"
},
{
"code": null,
"e": 12332,
"s": 12252,
"text": "To consume the APIs by using Angular JS, you can use the examples given below β"
},
{
"code": null,
"e": 12449,
"s": 12332,
"text": "Use the following code to create the Angular JS Controller to consume the GET API - http://localhost:9090/products β"
},
{
"code": null,
"e": 12650,
"s": 12449,
"text": "angular.module('demo', [])\n.controller('Hello', function($scope, $http) {\n $http.get('http://localhost:9090/products').\n then(function(response) {\n $scope.products = response.data;\n });\n});"
},
{
"code": null,
"e": 12768,
"s": 12650,
"text": "Use the following code to create the Angular JS Controller to consume the POST API - http://localhost:9090/products β"
},
{
"code": null,
"e": 12987,
"s": 12768,
"text": "angular.module('demo', [])\n.controller('Hello', function($scope, $http) {\n $http.post('http://localhost:9090/products',data).\n then(function(response) {\n console.log(\"Product created successfully\");\n });\n});"
},
{
"code": null,
"e": 13079,
"s": 12987,
"text": "Note β The Post method data represents the Request body in JSON format to create a product."
},
{
"code": null,
"e": 13113,
"s": 13079,
"text": "\n 102 Lectures \n 8 hours \n"
},
{
"code": null,
"e": 13127,
"s": 13113,
"text": " Karthikeya T"
},
{
"code": null,
"e": 13160,
"s": 13127,
"text": "\n 39 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 13175,
"s": 13160,
"text": " Chaand Sheikh"
},
{
"code": null,
"e": 13210,
"s": 13175,
"text": "\n 73 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 13222,
"s": 13210,
"text": " Senol Atac"
},
{
"code": null,
"e": 13257,
"s": 13222,
"text": "\n 62 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 13269,
"s": 13257,
"text": " Senol Atac"
},
{
"code": null,
"e": 13304,
"s": 13269,
"text": "\n 67 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 13316,
"s": 13304,
"text": " Senol Atac"
},
{
"code": null,
"e": 13349,
"s": 13316,
"text": "\n 69 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 13361,
"s": 13349,
"text": " Senol Atac"
},
{
"code": null,
"e": 13368,
"s": 13361,
"text": " Print"
},
{
"code": null,
"e": 13379,
"s": 13368,
"text": " Add Notes"
}
] |
Python program to find occurrence to each character in given string | In this article, we will learn about the solution to the problem statement given below.
Problem statement β We are given a string, we need to find the occurrence of each character in a given string.
Here we will be discussing 3 approaches as discussed below:L
Live Demo
test_str = "Tutorialspoint"
#count dictionary
count_dict = {}
for i in test_str:
#for existing characters in the dictionary
if i in count_dict:
count_dict[i] += 1
#for new characters to be added
else:
count_dict[i] = 1
print ("Count of all characters in Tutorialspoint is :\n "+
str(count_dict))
Count of all characters in Tutorialspoint is :
{'T': 1, 'u': 1, 't': 2, 'o': 2, 'r': 1, 'i': 2, 'a': 1, 'l': 1, 's': 1, 'p': 1, 'n': 1}
Live Demo
from collections import Counter
test_str = "Tutorialspoint"
# using collections.Counter() we generate a dictionary
res = Counter(test_str)
print ("Count of all characters in Tutorialspoint is :\n "+
str(dict(res)))
Count of all characters in Tutorialspoint is :
{'T': 1, 'u': 1, 't': 2, 'o': 2, 'r': 1, 'i': 2, 'a': 1, 'l': 1, 's': 1, 'p': 1, 'n': 1}
Live Demo
test_str = "Tutorialspoint"
# using set() to calculate unique characters in the given string
res = {i : test_str.count(i) for i in set(test_str)}
print ("Count of all characters in Tutorialspoint is :\n "+
str(dict(res)))
Count of all characters in Tutorialspoint is :
{'T': 1, 'u': 1, 't': 2, 'o': 2, 'r': 1, 'i': 2, 'a': 1, 'l': 1, 's': 1, 'p': 1, 'n': 1}
In this article, we have learned about how we can find the occurrence of each character in a given string. | [
{
"code": null,
"e": 1150,
"s": 1062,
"text": "In this article, we will learn about the solution to the problem statement given below."
},
{
"code": null,
"e": 1261,
"s": 1150,
"text": "Problem statement β We are given a string, we need to find the occurrence of each character in a given string."
},
{
"code": null,
"e": 1322,
"s": 1261,
"text": "Here we will be discussing 3 approaches as discussed below:L"
},
{
"code": null,
"e": 1333,
"s": 1322,
"text": " Live Demo"
},
{
"code": null,
"e": 1653,
"s": 1333,
"text": "test_str = \"Tutorialspoint\"\n#count dictionary\ncount_dict = {}\nfor i in test_str:\n #for existing characters in the dictionary\n if i in count_dict:\n count_dict[i] += 1\n #for new characters to be added\n else:\n count_dict[i] = 1\nprint (\"Count of all characters in Tutorialspoint is :\\n \"+\nstr(count_dict))"
},
{
"code": null,
"e": 1789,
"s": 1653,
"text": "Count of all characters in Tutorialspoint is :\n{'T': 1, 'u': 1, 't': 2, 'o': 2, 'r': 1, 'i': 2, 'a': 1, 'l': 1, 's': 1, 'p': 1, 'n': 1}"
},
{
"code": null,
"e": 1800,
"s": 1789,
"text": " Live Demo"
},
{
"code": null,
"e": 2015,
"s": 1800,
"text": "from collections import Counter\ntest_str = \"Tutorialspoint\"\n# using collections.Counter() we generate a dictionary\nres = Counter(test_str)\nprint (\"Count of all characters in Tutorialspoint is :\\n \"+\nstr(dict(res)))"
},
{
"code": null,
"e": 2151,
"s": 2015,
"text": "Count of all characters in Tutorialspoint is :\n{'T': 1, 'u': 1, 't': 2, 'o': 2, 'r': 1, 'i': 2, 'a': 1, 'l': 1, 's': 1, 'p': 1, 'n': 1}"
},
{
"code": null,
"e": 2162,
"s": 2151,
"text": " Live Demo"
},
{
"code": null,
"e": 2384,
"s": 2162,
"text": "test_str = \"Tutorialspoint\"\n# using set() to calculate unique characters in the given string\nres = {i : test_str.count(i) for i in set(test_str)}\nprint (\"Count of all characters in Tutorialspoint is :\\n \"+\nstr(dict(res)))"
},
{
"code": null,
"e": 2520,
"s": 2384,
"text": "Count of all characters in Tutorialspoint is :\n{'T': 1, 'u': 1, 't': 2, 'o': 2, 'r': 1, 'i': 2, 'a': 1, 'l': 1, 's': 1, 'p': 1, 'n': 1}"
},
{
"code": null,
"e": 2627,
"s": 2520,
"text": "In this article, we have learned about how we can find the occurrence of each character in a given string."
}
] |
Python | Numpy dstack() method | 19 Sep, 2019
With the help of numpy.dstack() method, we can get the combined array index by index and store like a stack by using numpy.dstack() method.
Syntax : numpy.dstack((array1, array2))
Return : Return combined array index by index.
Example #1 :In this example we can see that by using numpy.dstack() method, we are able to get the combined array in a stack index by index.
# import numpyimport numpy as np gfg1 = np.array([1, 2, 3])gfg2 = np.array([4, 5, 6]) # using numpy.dstack() methodprint(np.dstack((gfg1, gfg2)))
Output :
[[[1 4][2 5][3 6]]]
Example #2 :
# import numpyimport numpy as np gfg1 = np.array([[10], [2], [13]])gfg2 = np.array([[41], [55], [6]]) # using numpy.dstack() methodprint(np.dstack((gfg1, gfg2)))
Output :
[[[10 41]]
[[ 2 55]]
[[13 6]]]
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Introduction To PYTHON
Python | os.path.join() method
Python OOPs Concepts
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python - Pandas dataframe.append()
Create a directory in Python | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n19 Sep, 2019"
},
{
"code": null,
"e": 168,
"s": 28,
"text": "With the help of numpy.dstack() method, we can get the combined array index by index and store like a stack by using numpy.dstack() method."
},
{
"code": null,
"e": 208,
"s": 168,
"text": "Syntax : numpy.dstack((array1, array2))"
},
{
"code": null,
"e": 255,
"s": 208,
"text": "Return : Return combined array index by index."
},
{
"code": null,
"e": 396,
"s": 255,
"text": "Example #1 :In this example we can see that by using numpy.dstack() method, we are able to get the combined array in a stack index by index."
},
{
"code": "# import numpyimport numpy as np gfg1 = np.array([1, 2, 3])gfg2 = np.array([4, 5, 6]) # using numpy.dstack() methodprint(np.dstack((gfg1, gfg2)))",
"e": 544,
"s": 396,
"text": null
},
{
"code": null,
"e": 553,
"s": 544,
"text": "Output :"
},
{
"code": null,
"e": 573,
"s": 553,
"text": "[[[1 4][2 5][3 6]]]"
},
{
"code": null,
"e": 586,
"s": 573,
"text": "Example #2 :"
},
{
"code": "# import numpyimport numpy as np gfg1 = np.array([[10], [2], [13]])gfg2 = np.array([[41], [55], [6]]) # using numpy.dstack() methodprint(np.dstack((gfg1, gfg2)))",
"e": 750,
"s": 586,
"text": null
},
{
"code": null,
"e": 759,
"s": 750,
"text": "Output :"
},
{
"code": null,
"e": 770,
"s": 759,
"text": "[[[10 41]]"
},
{
"code": null,
"e": 780,
"s": 770,
"text": "[[ 2 55]]"
},
{
"code": null,
"e": 790,
"s": 780,
"text": "[[13 6]]]"
},
{
"code": null,
"e": 803,
"s": 790,
"text": "Python-numpy"
},
{
"code": null,
"e": 810,
"s": 803,
"text": "Python"
},
{
"code": null,
"e": 908,
"s": 810,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 940,
"s": 908,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 967,
"s": 940,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 990,
"s": 967,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 1021,
"s": 990,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 1042,
"s": 1021,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 1098,
"s": 1042,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 1140,
"s": 1098,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 1182,
"s": 1140,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 1217,
"s": 1182,
"text": "Python - Pandas dataframe.append()"
}
] |
How to create a Hotkey in Python? | 24 Jan, 2021
This article is about How to create a HotKey Using Python. But first, letβs discuss what is a Hotkey. A Hotkey is an assigned key or sequence of keys programmed to execute a command or perform a selected task during a software application: For instance, on Windows computers, the hotkey Ctrl+S are often wont to quickly save a file.
By reducing such sequences to a few keystrokes, can often save the user time, hence βshortcutβ and make computing a lot easier for people with disabilities.
Method 1: Using pynput (This library allows you to control and monitor input devices.)
Approach Used:
We import keyboard from pynputThen we create a set to keep track of which key inputs are currently pressedCreate a list of which Hotkey is needed to be pressed to perform the desired operation. Here we wanted the Hotkeys to be Shift+A and Shift+aWe create a function execute() that runs our desired program while pressing the Hotkey. Here we wished to print βDetected HotkeyβCreate a function on_press() that checks that any key pressed in under the given that we have. If yes, we need to add to the set and then look if all keys and particular combinations are in the current set. If yes, then we execute our operation.Create a function on_release() that checks that any key released under the given combinations that we have. If yes, we need to remove it from the current set.At last, run the program.
We import keyboard from pynput
Then we create a set to keep track of which key inputs are currently pressed
Create a list of which Hotkey is needed to be pressed to perform the desired operation. Here we wanted the Hotkeys to be Shift+A and Shift+a
We create a function execute() that runs our desired program while pressing the Hotkey. Here we wished to print βDetected Hotkeyβ
Create a function on_press() that checks that any key pressed in under the given that we have. If yes, we need to add to the set and then look if all keys and particular combinations are in the current set. If yes, then we execute our operation.
Create a function on_release() that checks that any key released under the given combinations that we have. If yes, we need to remove it from the current set.
At last, run the program.
Python3
from pynput import keyboard cmb = [{keyboard.Key.shift, keyboard.Key(char='a')},{keyboard.Key.shift, keyboard.Key(char='A')}] current = set() def execute(): print("Detected hotkey") def on_press(key): if any([key in z for z in cmb]): current.add(key) if any(all(k in current for k in z) for z in cmb): execute() def on_release(key): if any([key in z for z in cmb]): current.remove(key) with keyboard.Listener(on_press=on_press, on_release=on_release) as listener: listener.join()
Output :
Method 2: Using keyboard (Refer to the Article: Keyboard module in Python)
Python provides a library named keyboard which is employed to urge full control of the keyboard. Itβs a little Python library that may hook global events, register hotkeys, simulate key presses, and far more.
It helps to enter keys, record the keyboard activities and block the keys until a specified key is entered and simulate the keys.
It captures all keys, even onscreen keyboard events also are captured.
The keyboard module supports complex hotkeys.
Using this module we will listen and send keyboard events.,It works on both Windows and Linux operating systems.
Python3
# Keyboard module in Python import keyboard # press ctrl+shift+z to print "Hotkey Detected" keyboard.add_hotkey('ctrl + shift + z', print, args =('Hotkey', 'Detected')) keyboard.wait('esc')
Output:
Hotkey Detected
Picked
python-utility
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
Python | os.path.join() method
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | Get unique values from a list
Python | datetime.timedelta() function | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n24 Jan, 2021"
},
{
"code": null,
"e": 387,
"s": 54,
"text": "This article is about How to create a HotKey Using Python. But first, letβs discuss what is a Hotkey. A Hotkey is an assigned key or sequence of keys programmed to execute a command or perform a selected task during a software application: For instance, on Windows computers, the hotkey Ctrl+S are often wont to quickly save a file."
},
{
"code": null,
"e": 544,
"s": 387,
"text": "By reducing such sequences to a few keystrokes, can often save the user time, hence βshortcutβ and make computing a lot easier for people with disabilities."
},
{
"code": null,
"e": 631,
"s": 544,
"text": "Method 1: Using pynput (This library allows you to control and monitor input devices.)"
},
{
"code": null,
"e": 646,
"s": 631,
"text": "Approach Used:"
},
{
"code": null,
"e": 1450,
"s": 646,
"text": "We import keyboard from pynputThen we create a set to keep track of which key inputs are currently pressedCreate a list of which Hotkey is needed to be pressed to perform the desired operation. Here we wanted the Hotkeys to be Shift+A and Shift+aWe create a function execute() that runs our desired program while pressing the Hotkey. Here we wished to print βDetected HotkeyβCreate a function on_press() that checks that any key pressed in under the given that we have. If yes, we need to add to the set and then look if all keys and particular combinations are in the current set. If yes, then we execute our operation.Create a function on_release() that checks that any key released under the given combinations that we have. If yes, we need to remove it from the current set.At last, run the program."
},
{
"code": null,
"e": 1481,
"s": 1450,
"text": "We import keyboard from pynput"
},
{
"code": null,
"e": 1558,
"s": 1481,
"text": "Then we create a set to keep track of which key inputs are currently pressed"
},
{
"code": null,
"e": 1699,
"s": 1558,
"text": "Create a list of which Hotkey is needed to be pressed to perform the desired operation. Here we wanted the Hotkeys to be Shift+A and Shift+a"
},
{
"code": null,
"e": 1829,
"s": 1699,
"text": "We create a function execute() that runs our desired program while pressing the Hotkey. Here we wished to print βDetected Hotkeyβ"
},
{
"code": null,
"e": 2075,
"s": 1829,
"text": "Create a function on_press() that checks that any key pressed in under the given that we have. If yes, we need to add to the set and then look if all keys and particular combinations are in the current set. If yes, then we execute our operation."
},
{
"code": null,
"e": 2234,
"s": 2075,
"text": "Create a function on_release() that checks that any key released under the given combinations that we have. If yes, we need to remove it from the current set."
},
{
"code": null,
"e": 2260,
"s": 2234,
"text": "At last, run the program."
},
{
"code": null,
"e": 2268,
"s": 2260,
"text": "Python3"
},
{
"code": "from pynput import keyboard cmb = [{keyboard.Key.shift, keyboard.Key(char='a')},{keyboard.Key.shift, keyboard.Key(char='A')}] current = set() def execute(): print(\"Detected hotkey\") def on_press(key): if any([key in z for z in cmb]): current.add(key) if any(all(k in current for k in z) for z in cmb): execute() def on_release(key): if any([key in z for z in cmb]): current.remove(key) with keyboard.Listener(on_press=on_press, on_release=on_release) as listener: listener.join()",
"e": 2772,
"s": 2268,
"text": null
},
{
"code": null,
"e": 2781,
"s": 2772,
"text": "Output :"
},
{
"code": null,
"e": 2856,
"s": 2781,
"text": "Method 2: Using keyboard (Refer to the Article: Keyboard module in Python)"
},
{
"code": null,
"e": 3065,
"s": 2856,
"text": "Python provides a library named keyboard which is employed to urge full control of the keyboard. Itβs a little Python library that may hook global events, register hotkeys, simulate key presses, and far more."
},
{
"code": null,
"e": 3195,
"s": 3065,
"text": "It helps to enter keys, record the keyboard activities and block the keys until a specified key is entered and simulate the keys."
},
{
"code": null,
"e": 3266,
"s": 3195,
"text": "It captures all keys, even onscreen keyboard events also are captured."
},
{
"code": null,
"e": 3312,
"s": 3266,
"text": "The keyboard module supports complex hotkeys."
},
{
"code": null,
"e": 3425,
"s": 3312,
"text": "Using this module we will listen and send keyboard events.,It works on both Windows and Linux operating systems."
},
{
"code": null,
"e": 3433,
"s": 3425,
"text": "Python3"
},
{
"code": "# Keyboard module in Python import keyboard # press ctrl+shift+z to print \"Hotkey Detected\" keyboard.add_hotkey('ctrl + shift + z', print, args =('Hotkey', 'Detected')) keyboard.wait('esc') ",
"e": 3628,
"s": 3433,
"text": null
},
{
"code": null,
"e": 3636,
"s": 3628,
"text": "Output:"
},
{
"code": null,
"e": 3652,
"s": 3636,
"text": "Hotkey Detected"
},
{
"code": null,
"e": 3659,
"s": 3652,
"text": "Picked"
},
{
"code": null,
"e": 3674,
"s": 3659,
"text": "python-utility"
},
{
"code": null,
"e": 3681,
"s": 3674,
"text": "Python"
},
{
"code": null,
"e": 3779,
"s": 3681,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3811,
"s": 3779,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 3838,
"s": 3811,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 3859,
"s": 3838,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 3882,
"s": 3859,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 3913,
"s": 3882,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 3969,
"s": 3913,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 4011,
"s": 3969,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 4053,
"s": 4011,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 4092,
"s": 4053,
"text": "Python | Get unique values from a list"
}
] |
Python Program for Sieve of Eratosthenes | 22 Jun, 2022
Sieve of Eratosthenes is a method for finding all primes up to (and possibly including) a given natural. This method works well when is relatively small, allowing us to determine whether any natural number less than or equal to is prime or composite.
Implementation:
Given a number n, print all primes smaller than or equal to n. It is also given that n is a small number. For instance here if n is 10, the output should be β2, 3, 5, 7β. If n is 20, the output should be β2, 3, 5, 7, 11, 13, 17, 19β.
Example
Python3
# Python program to print all Primes Smaller# than or equal to N using Sieve of Eratosthenes def SieveOfEratosthenes(num): prime = [True for i in range(num+1)]# boolean array p = 2 while (p * p <= num): # If prime[p] is not # changed, then it is a prime if (prime[p] == True): # Updating all multiples of p for i in range(p * p, num+1, p): prime[i] = False p += 1 # Print all prime numbers for p in range(2, num+1): if prime[p]: print(p) # Driver codeif __name__ == '__main__': num = 50 print("Following are the prime numbers smaller"), print("than or equal to", num) SieveOfEratosthenes(num)
Output:
Chapters
descriptions off, selected
captions settings, opens captions settings dialog
captions off, selected
English
This is a modal window.
Beginning of dialog window. Escape will cancel and close the window.
End of dialog window.
Following are the prime numbers below 30
2 3 5 7 11 13 17 19 23 29
Time Complexity: O(n*log(log(n)))
Auxiliary Space: O(n)
Python Program for Sieve of Eratosthenes | GeeksforGeeks - YouTubeGeeksforGeeks530K subscribersPython Program for Sieve of Eratosthenes | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.More videosMore videosYou'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.CancelConfirmSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 2:02β’Liveβ’<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=Jm5aQoMmb1E" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
Please refer complete article on Sieve of Eratosthenes for more details!
SonalSrivastava02
itsmayank0
brendansport
amartyaghoshgfg
abhishek20b1531008
aryash747
chandramauliguptach
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python | Convert string dictionary to dictionary
Python program to add two numbers
Python Program for factorial of a number
Iterate over characters of a string in Python
Python program to find second largest number in a list
Python | Convert set into a list
Python | Convert a list into a tuple
Python Program for Bubble Sort
Python program to find sum of elements in list
Appending to list in Python dictionary | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n22 Jun, 2022"
},
{
"code": null,
"e": 306,
"s": 54,
"text": "Sieve of Eratosthenes is a method for finding all primes up to (and possibly including) a given natural. This method works well when is relatively small, allowing us to determine whether any natural number less than or equal to is prime or composite. "
},
{
"code": null,
"e": 322,
"s": 306,
"text": "Implementation:"
},
{
"code": null,
"e": 556,
"s": 322,
"text": "Given a number n, print all primes smaller than or equal to n. It is also given that n is a small number. For instance here if n is 10, the output should be β2, 3, 5, 7β. If n is 20, the output should be β2, 3, 5, 7, 11, 13, 17, 19β."
},
{
"code": null,
"e": 565,
"s": 556,
"text": "Example "
},
{
"code": null,
"e": 573,
"s": 565,
"text": "Python3"
},
{
"code": "# Python program to print all Primes Smaller# than or equal to N using Sieve of Eratosthenes def SieveOfEratosthenes(num): prime = [True for i in range(num+1)]# boolean array p = 2 while (p * p <= num): # If prime[p] is not # changed, then it is a prime if (prime[p] == True): # Updating all multiples of p for i in range(p * p, num+1, p): prime[i] = False p += 1 # Print all prime numbers for p in range(2, num+1): if prime[p]: print(p) # Driver codeif __name__ == '__main__': num = 50 print(\"Following are the prime numbers smaller\"), print(\"than or equal to\", num) SieveOfEratosthenes(num)",
"e": 1281,
"s": 573,
"text": null
},
{
"code": null,
"e": 1290,
"s": 1281,
"text": "Output: "
},
{
"code": null,
"e": 1299,
"s": 1290,
"text": "Chapters"
},
{
"code": null,
"e": 1326,
"s": 1299,
"text": "descriptions off, selected"
},
{
"code": null,
"e": 1376,
"s": 1326,
"text": "captions settings, opens captions settings dialog"
},
{
"code": null,
"e": 1399,
"s": 1376,
"text": "captions off, selected"
},
{
"code": null,
"e": 1407,
"s": 1399,
"text": "English"
},
{
"code": null,
"e": 1431,
"s": 1407,
"text": "This is a modal window."
},
{
"code": null,
"e": 1500,
"s": 1431,
"text": "Beginning of dialog window. Escape will cancel and close the window."
},
{
"code": null,
"e": 1522,
"s": 1500,
"text": "End of dialog window."
},
{
"code": null,
"e": 1589,
"s": 1522,
"text": "Following are the prime numbers below 30\n2 3 5 7 11 13 17 19 23 29"
},
{
"code": null,
"e": 1623,
"s": 1589,
"text": "Time Complexity: O(n*log(log(n)))"
},
{
"code": null,
"e": 1645,
"s": 1623,
"text": "Auxiliary Space: O(n)"
},
{
"code": null,
"e": 2543,
"s": 1645,
"text": "Python Program for Sieve of Eratosthenes | GeeksforGeeks - YouTubeGeeksforGeeks530K subscribersPython Program for Sieve of Eratosthenes | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.More videosMore videosYou'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.CancelConfirmSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 2:02β’Liveβ’<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=Jm5aQoMmb1E\" 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": 2617,
"s": 2543,
"text": "Please refer complete article on Sieve of Eratosthenes for more details! "
},
{
"code": null,
"e": 2635,
"s": 2617,
"text": "SonalSrivastava02"
},
{
"code": null,
"e": 2646,
"s": 2635,
"text": "itsmayank0"
},
{
"code": null,
"e": 2659,
"s": 2646,
"text": "brendansport"
},
{
"code": null,
"e": 2675,
"s": 2659,
"text": "amartyaghoshgfg"
},
{
"code": null,
"e": 2694,
"s": 2675,
"text": "abhishek20b1531008"
},
{
"code": null,
"e": 2704,
"s": 2694,
"text": "aryash747"
},
{
"code": null,
"e": 2724,
"s": 2704,
"text": "chandramauliguptach"
},
{
"code": null,
"e": 2740,
"s": 2724,
"text": "Python Programs"
},
{
"code": null,
"e": 2838,
"s": 2740,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2887,
"s": 2838,
"text": "Python | Convert string dictionary to dictionary"
},
{
"code": null,
"e": 2921,
"s": 2887,
"text": "Python program to add two numbers"
},
{
"code": null,
"e": 2962,
"s": 2921,
"text": "Python Program for factorial of a number"
},
{
"code": null,
"e": 3008,
"s": 2962,
"text": "Iterate over characters of a string in Python"
},
{
"code": null,
"e": 3063,
"s": 3008,
"text": "Python program to find second largest number in a list"
},
{
"code": null,
"e": 3096,
"s": 3063,
"text": "Python | Convert set into a list"
},
{
"code": null,
"e": 3133,
"s": 3096,
"text": "Python | Convert a list into a tuple"
},
{
"code": null,
"e": 3164,
"s": 3133,
"text": "Python Program for Bubble Sort"
},
{
"code": null,
"e": 3211,
"s": 3164,
"text": "Python program to find sum of elements in list"
}
] |
Octave β Basics of Plotting Data | 03 Nov, 2021
Octave has some in-built functions for visualizing the data. Few simple plots can give us a better way to understand our data. Whenever we perform a learning algorithm on an Octave environment, we can get a better sense of that algorithm and analyze it. Octave has lots of simple tools that we can use for a better understanding of our algorithm. In this tutorial, we are going to learn how to plot data for better visualization and understanding it in the Octave environment.Example 1 : Plotting a sine wave using the plot() and and sin() function:
MATLAB
% var_x for the y-axisvar_x = [0:0.01:1]; % var_y for the y-axisvar_y = sin(4 * pi * var); % plotting the graphplot(var_x, var_y);
Output :
Example 2 : Plotting a cosine wave using the plot() and and cos() function:
MATLAB
% var_x for the y-axisvar_x = [0:0.01:1]; % var_y for the y-axisvar_y = cos(3 * pi * var); % plotting the graphplot(var_x, var_y);
Output :
Example 3 : We can plot, one plot over another plot by holding the previous plot with the hold on command.
MATLAB
% declaring variable var_xvar_x = [0:0.01:1]; % declaring variable var_y1var_y1 = sin(4 * pi * var); % declaring variable var_y2var_y2 = cos(3 * pi * var); % plot var_x with var_y1plot(var_x, var_y1); % hold the above plot or figurehold on; % plot var with var_y2 with red colorplot(var_x, var_y2, 'r');
Output :
Example 4 : We can add labels for the x-axis and the y-axis along with the legends and title with the below code.
MATLAB
% declaring variable var_xvar_x = [0:0.01:1]; % declaring variable var_y1var_y1 = sin(4 * pi * var); % declaring variable var_y2var_y2 = cos(3 * pi * var); % plot var_x with var_y1plot(var_x, var_y1); % hold the above plot or figurehold on; % plot var with var_y2 with red colorplot(var_x, var_y2, 'r'); % adding label to the x-axisxlabel('time'); % adding label to the y-axisylabel('value'); % adding title for the plottitle('my first plot'); % add legends for these 2 curveslegend('sin', 'cos');
Output :
Example 5 : We can also plot data on different figures.
MATLAB
% declaring variable var_xvar_x = [0:0.01:1]; % declaring variable var_y1var_y1 = sin(4 * pi * var); % declaring variable var_y2var_y2 = cos(3 * pi * var); % plot var_x and var_y1 on figure 1figure(1);plot(var_x,var_y); % plot var_x and var_y2 on figure 2figure(2);plot(var_x,var_y2);
Output :
Example 6 : We can divide a figure into a m x n grid using the subplot() function. In the below code the first 2 parameter shows m and n and 3rd parameter is the grid count from top to left.
MATLAB
% var_x for the y-axisvar_x = [0:0.01:1]; % var_y for the y-axisvar_y = sin(4 * pi * var); % plot the var_x and var_y on a 3x3 grid% at 4 position counting from top to leftsubplot(3, 3, 4), plot(var_x, var_y);
Output :
Example 7 : We can change the axis values of any plot using the axis() function.
MATLAB
% declaring variable var_xvar_x = [0:0.01:1]; % declaring variable var_y1var_y1 = sin(4 * pi * var); % declaring variable var_y2var_y2 = cos(3 * pi * var); % plot var_x with var_y1plot(var_x, var_y1); % hold the above plot or figurehold on; % plot var with var_y2 with red colorplot(var_x, var_y2, 'r'); % adding label to the x-axisxlabel('time'); % adding label to the y-axisylabel('value'); % adding title for the plottitle('my first plot'); % add legends for these 2 curveslegend('sin', 'cos'); % first 2 parameter sets the x-axis% and next 2 will set the y-axisaxis([0.5 1 -1 1])
Here the first 2 parameters shows the range of the x-axis and the next 2 parameters shows the range of the y-axis. Output :
Example 8 : We can save our plots in our present working directory :
MATLAB
print -dpng 'plot.png'
In order to print this plot at our desired location, we can use cd with it as shown below :
MATLAB
cd '/home/dikshant/Documents'; print -dpng 'plot.png'
We can close a figure/plot using the close command.Example 9 : We can visualize a matrix using the imagesc() function.
MATLAB
% creating a 10x10 magic matrixmatrix = magic(10) % plot the matriximagesc(matrix)
Output :
matrix =
92 99 1 8 15 67 74 51 58 40
98 80 7 14 16 73 55 57 64 41
4 81 88 20 22 54 56 63 70 47
85 87 19 21 3 60 62 69 71 28
86 93 25 2 9 61 68 75 52 34
17 24 76 83 90 42 49 26 33 65
23 5 82 89 91 48 30 32 39 66
79 6 13 95 97 29 31 38 45 72
10 12 94 96 78 35 37 44 46 53
11 18 100 77 84 36 43 50 27 59
The above plot is of 10Γ10 grid, each grid represents a value with a color. The same color value results in the same color. We can also make a color bar with this plot to see which value corresponds to which color using the colorbar command. We can use multiple commands at a time by separating them with a comma(,) in Octave environment.
MATLAB
% creating a 10x10 magic matrixmatrix = magic(10) % plot this matrix with showing colorbar on the right of itimagesc(matrix), colorbar;
Output :
Drawing the magic square with a gray-scale colormap :
MATLAB
% creating a 10x10 magic matrixmatrix = magic(10) % plot this matrix with colorbar and gray colormapimagesc(matrix), colorbar, colormap gray;
Output :
anikakapoor
devanganuragi
Octave-GNU
Programming Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n03 Nov, 2021"
},
{
"code": null,
"e": 604,
"s": 52,
"text": "Octave has some in-built functions for visualizing the data. Few simple plots can give us a better way to understand our data. Whenever we perform a learning algorithm on an Octave environment, we can get a better sense of that algorithm and analyze it. Octave has lots of simple tools that we can use for a better understanding of our algorithm. In this tutorial, we are going to learn how to plot data for better visualization and understanding it in the Octave environment.Example 1 : Plotting a sine wave using the plot() and and sin() function: "
},
{
"code": null,
"e": 611,
"s": 604,
"text": "MATLAB"
},
{
"code": "% var_x for the y-axisvar_x = [0:0.01:1]; % var_y for the y-axisvar_y = sin(4 * pi * var); % plotting the graphplot(var_x, var_y);",
"e": 742,
"s": 611,
"text": null
},
{
"code": null,
"e": 753,
"s": 742,
"text": "Output : "
},
{
"code": null,
"e": 831,
"s": 753,
"text": "Example 2 : Plotting a cosine wave using the plot() and and cos() function: "
},
{
"code": null,
"e": 838,
"s": 831,
"text": "MATLAB"
},
{
"code": "% var_x for the y-axisvar_x = [0:0.01:1]; % var_y for the y-axisvar_y = cos(3 * pi * var); % plotting the graphplot(var_x, var_y);",
"e": 969,
"s": 838,
"text": null
},
{
"code": null,
"e": 980,
"s": 969,
"text": "Output : "
},
{
"code": null,
"e": 1089,
"s": 980,
"text": "Example 3 : We can plot, one plot over another plot by holding the previous plot with the hold on command. "
},
{
"code": null,
"e": 1096,
"s": 1089,
"text": "MATLAB"
},
{
"code": "% declaring variable var_xvar_x = [0:0.01:1]; % declaring variable var_y1var_y1 = sin(4 * pi * var); % declaring variable var_y2var_y2 = cos(3 * pi * var); % plot var_x with var_y1plot(var_x, var_y1); % hold the above plot or figurehold on; % plot var with var_y2 with red colorplot(var_x, var_y2, 'r');",
"e": 1400,
"s": 1096,
"text": null
},
{
"code": null,
"e": 1411,
"s": 1400,
"text": "Output : "
},
{
"code": null,
"e": 1527,
"s": 1411,
"text": "Example 4 : We can add labels for the x-axis and the y-axis along with the legends and title with the below code. "
},
{
"code": null,
"e": 1534,
"s": 1527,
"text": "MATLAB"
},
{
"code": "% declaring variable var_xvar_x = [0:0.01:1]; % declaring variable var_y1var_y1 = sin(4 * pi * var); % declaring variable var_y2var_y2 = cos(3 * pi * var); % plot var_x with var_y1plot(var_x, var_y1); % hold the above plot or figurehold on; % plot var with var_y2 with red colorplot(var_x, var_y2, 'r'); % adding label to the x-axisxlabel('time'); % adding label to the y-axisylabel('value'); % adding title for the plottitle('my first plot'); % add legends for these 2 curveslegend('sin', 'cos');",
"e": 2033,
"s": 1534,
"text": null
},
{
"code": null,
"e": 2044,
"s": 2033,
"text": "Output : "
},
{
"code": null,
"e": 2102,
"s": 2044,
"text": "Example 5 : We can also plot data on different figures. "
},
{
"code": null,
"e": 2109,
"s": 2102,
"text": "MATLAB"
},
{
"code": "% declaring variable var_xvar_x = [0:0.01:1]; % declaring variable var_y1var_y1 = sin(4 * pi * var); % declaring variable var_y2var_y2 = cos(3 * pi * var); % plot var_x and var_y1 on figure 1figure(1);plot(var_x,var_y); % plot var_x and var_y2 on figure 2figure(2);plot(var_x,var_y2);",
"e": 2396,
"s": 2109,
"text": null
},
{
"code": null,
"e": 2407,
"s": 2396,
"text": "Output : "
},
{
"code": null,
"e": 2600,
"s": 2407,
"text": "Example 6 : We can divide a figure into a m x n grid using the subplot() function. In the below code the first 2 parameter shows m and n and 3rd parameter is the grid count from top to left. "
},
{
"code": null,
"e": 2607,
"s": 2600,
"text": "MATLAB"
},
{
"code": "% var_x for the y-axisvar_x = [0:0.01:1]; % var_y for the y-axisvar_y = sin(4 * pi * var); % plot the var_x and var_y on a 3x3 grid% at 4 position counting from top to leftsubplot(3, 3, 4), plot(var_x, var_y);",
"e": 2818,
"s": 2607,
"text": null
},
{
"code": null,
"e": 2829,
"s": 2818,
"text": "Output : "
},
{
"code": null,
"e": 2911,
"s": 2829,
"text": "Example 7 : We can change the axis values of any plot using the axis() function. "
},
{
"code": null,
"e": 2918,
"s": 2911,
"text": "MATLAB"
},
{
"code": "% declaring variable var_xvar_x = [0:0.01:1]; % declaring variable var_y1var_y1 = sin(4 * pi * var); % declaring variable var_y2var_y2 = cos(3 * pi * var); % plot var_x with var_y1plot(var_x, var_y1); % hold the above plot or figurehold on; % plot var with var_y2 with red colorplot(var_x, var_y2, 'r'); % adding label to the x-axisxlabel('time'); % adding label to the y-axisylabel('value'); % adding title for the plottitle('my first plot'); % add legends for these 2 curveslegend('sin', 'cos'); % first 2 parameter sets the x-axis% and next 2 will set the y-axisaxis([0.5 1 -1 1])",
"e": 3509,
"s": 2918,
"text": null
},
{
"code": null,
"e": 3635,
"s": 3509,
"text": "Here the first 2 parameters shows the range of the x-axis and the next 2 parameters shows the range of the y-axis. Output : "
},
{
"code": null,
"e": 3706,
"s": 3635,
"text": "Example 8 : We can save our plots in our present working directory : "
},
{
"code": null,
"e": 3713,
"s": 3706,
"text": "MATLAB"
},
{
"code": "print -dpng 'plot.png'",
"e": 3736,
"s": 3713,
"text": null
},
{
"code": null,
"e": 3830,
"s": 3736,
"text": "In order to print this plot at our desired location, we can use cd with it as shown below : "
},
{
"code": null,
"e": 3837,
"s": 3830,
"text": "MATLAB"
},
{
"code": "cd '/home/dikshant/Documents'; print -dpng 'plot.png'",
"e": 3891,
"s": 3837,
"text": null
},
{
"code": null,
"e": 4012,
"s": 3891,
"text": "We can close a figure/plot using the close command.Example 9 : We can visualize a matrix using the imagesc() function. "
},
{
"code": null,
"e": 4019,
"s": 4012,
"text": "MATLAB"
},
{
"code": "% creating a 10x10 magic matrixmatrix = magic(10) % plot the matriximagesc(matrix)",
"e": 4102,
"s": 4019,
"text": null
},
{
"code": null,
"e": 4113,
"s": 4102,
"text": "Output : "
},
{
"code": null,
"e": 4733,
"s": 4113,
"text": "matrix =\n\n 92 99 1 8 15 67 74 51 58 40\n 98 80 7 14 16 73 55 57 64 41\n 4 81 88 20 22 54 56 63 70 47\n 85 87 19 21 3 60 62 69 71 28\n 86 93 25 2 9 61 68 75 52 34\n 17 24 76 83 90 42 49 26 33 65\n 23 5 82 89 91 48 30 32 39 66\n 79 6 13 95 97 29 31 38 45 72\n 10 12 94 96 78 35 37 44 46 53\n 11 18 100 77 84 36 43 50 27 59"
},
{
"code": null,
"e": 5076,
"s": 4735,
"text": "The above plot is of 10Γ10 grid, each grid represents a value with a color. The same color value results in the same color. We can also make a color bar with this plot to see which value corresponds to which color using the colorbar command. We can use multiple commands at a time by separating them with a comma(,) in Octave environment. "
},
{
"code": null,
"e": 5083,
"s": 5076,
"text": "MATLAB"
},
{
"code": "% creating a 10x10 magic matrixmatrix = magic(10) % plot this matrix with showing colorbar on the right of itimagesc(matrix), colorbar;",
"e": 5219,
"s": 5083,
"text": null
},
{
"code": null,
"e": 5230,
"s": 5219,
"text": "Output : "
},
{
"code": null,
"e": 5286,
"s": 5230,
"text": "Drawing the magic square with a gray-scale colormap : "
},
{
"code": null,
"e": 5293,
"s": 5286,
"text": "MATLAB"
},
{
"code": "% creating a 10x10 magic matrixmatrix = magic(10) % plot this matrix with colorbar and gray colormapimagesc(matrix), colorbar, colormap gray;",
"e": 5435,
"s": 5293,
"text": null
},
{
"code": null,
"e": 5446,
"s": 5435,
"text": "Output : "
},
{
"code": null,
"e": 5460,
"s": 5448,
"text": "anikakapoor"
},
{
"code": null,
"e": 5474,
"s": 5460,
"text": "devanganuragi"
},
{
"code": null,
"e": 5485,
"s": 5474,
"text": "Octave-GNU"
},
{
"code": null,
"e": 5506,
"s": 5485,
"text": "Programming Language"
}
] |
Tensorflow.js tf.losses.meanSquaredError() Function | 31 May, 2021
Tensorflow.js is an open-source JavaScript library developed by Google for running and training machine learning models and deep learning neural networks in browser and node.js environment.
Mean squared error is the average of squared differences between the predicted and the actual values. The result is always positive and 0.0 in case but never becomes negative. In tensorflow.js library, we use tf.losses.meanSquaredError() function to compute the mean squared error between two tensors.
Syntax:
tf.losses.meanSquaredError(labels, predictions, weights?, reduction?)
Parameters:
labels: This is the real output tensor with respect to which the difference in prediction is calculated. It can be tf.tensor, typedArray or a normal array.
predictions: This is the predicted output tensor with the same dimensions as labels. It is either tf.tensor or typedArray or normal array.
weights: This can be a tensor of rank either equal to that of labels so that it can be broadcastable or 0. It is optional.
reduction: Applying reduction to the loss. It is optional.
Return Value: tf.Tensor which is calculated by meansquaredError function.
Example 1: In this example we will take two 2 dimensional tensors on as label and the other as prediction and then find the mean squared error of these two.
Javascript
// Importing the tensorflow.js libraryconst tf = require("@tensorflow/tfjs"); // Defining label tensorconst y_true = tf.tensor2d([ [0., 1., 0.], [0., 0., 0.]]); // Defining prediction tensorconst y_pred = tf.tensor2d([ [1., 1., 0.], [1., 0., 0 ]]); // Calculating mean squared errorconst mse = tf.losses.meanSquaredError(y_true,y_pred) // Printing the outputmse.print()
Output:
Tensor
0.3333
Example 2: Similarly, we take another example in which we take the weights of rank as of labels in the meanSquaredError function and then calculate the mean squared error.
Javascript
// Importing the tensorflow.js libraryconst tf = require("@tensorflow/tfjs"); // Defining label tensorconst y_true = tf.tensor2d( [0., 1., 0., 0., 0., 0., 1., 0., 1., 1., 0., 1.], [4, 3]); // Defining predicted tensorconst y_pred = tf.tensor2d( [1., 1., 0., 1., 0., 0., 1., 1., 1., 0., 0., 1.], [4, 3]); // Calculating meansquared errorconst mse = tf.losses.meanSquaredError( y_true, y_pred, [0.7, 0.3, 0.2],) mse.print()
Output:
Tensor
0.2000
Example 3: In compile function of designing the model, we use βmean squared errorβ as the loss parameter. Following is a simple neural network where we do the computation.
Javascript
// Importing the tensorflow.js libraryconst tf = require("@tensorflow/tfjs"); // Define the modelconst model = tf.sequential({ layers: [tf.layers.dense({ units: 1, inputShape: [12] })],}); // In model compilation we pass// meanSquaredError as the parameter model.compile( { optimizer: "adam", loss: "meanSquaredError" }, (metrics = ["accuracy"])); // Evaluate the model which was compiled above// computation is done in batches of size 4const result = model.evaluate( tf.ones([10, 12]), tf.ones([10, 1]), { batchSize: 4, }); // Print the resultresult.print();
Output:
Tensor
0.4817
Reference: https://js.tensorflow.org/api/3.6.0/#metrics.meanSquaredError
Picked
Tensorflow.js
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n31 May, 2021"
},
{
"code": null,
"e": 218,
"s": 28,
"text": "Tensorflow.js is an open-source JavaScript library developed by Google for running and training machine learning models and deep learning neural networks in browser and node.js environment."
},
{
"code": null,
"e": 521,
"s": 218,
"text": "Mean squared error is the average of squared differences between the predicted and the actual values. The result is always positive and 0.0 in case but never becomes negative. In tensorflow.js library, we use tf.losses.meanSquaredError() function to compute the mean squared error between two tensors. "
},
{
"code": null,
"e": 530,
"s": 521,
"text": "Syntax: "
},
{
"code": null,
"e": 600,
"s": 530,
"text": "tf.losses.meanSquaredError(labels, predictions, weights?, reduction?)"
},
{
"code": null,
"e": 612,
"s": 600,
"text": "Parameters:"
},
{
"code": null,
"e": 768,
"s": 612,
"text": "labels: This is the real output tensor with respect to which the difference in prediction is calculated. It can be tf.tensor, typedArray or a normal array."
},
{
"code": null,
"e": 907,
"s": 768,
"text": "predictions: This is the predicted output tensor with the same dimensions as labels. It is either tf.tensor or typedArray or normal array."
},
{
"code": null,
"e": 1030,
"s": 907,
"text": "weights: This can be a tensor of rank either equal to that of labels so that it can be broadcastable or 0. It is optional."
},
{
"code": null,
"e": 1089,
"s": 1030,
"text": "reduction: Applying reduction to the loss. It is optional."
},
{
"code": null,
"e": 1163,
"s": 1089,
"text": "Return Value: tf.Tensor which is calculated by meansquaredError function."
},
{
"code": null,
"e": 1320,
"s": 1163,
"text": "Example 1: In this example we will take two 2 dimensional tensors on as label and the other as prediction and then find the mean squared error of these two."
},
{
"code": null,
"e": 1331,
"s": 1320,
"text": "Javascript"
},
{
"code": "// Importing the tensorflow.js libraryconst tf = require(\"@tensorflow/tfjs\"); // Defining label tensorconst y_true = tf.tensor2d([ [0., 1., 0.], [0., 0., 0.]]); // Defining prediction tensorconst y_pred = tf.tensor2d([ [1., 1., 0.], [1., 0., 0 ]]); // Calculating mean squared errorconst mse = tf.losses.meanSquaredError(y_true,y_pred) // Printing the outputmse.print()",
"e": 1719,
"s": 1331,
"text": null
},
{
"code": null,
"e": 1727,
"s": 1719,
"text": "Output:"
},
{
"code": null,
"e": 1745,
"s": 1727,
"text": "Tensor\n 0.3333"
},
{
"code": null,
"e": 1919,
"s": 1745,
"text": " Example 2: Similarly, we take another example in which we take the weights of rank as of labels in the meanSquaredError function and then calculate the mean squared error."
},
{
"code": null,
"e": 1930,
"s": 1919,
"text": "Javascript"
},
{
"code": "// Importing the tensorflow.js libraryconst tf = require(\"@tensorflow/tfjs\"); // Defining label tensorconst y_true = tf.tensor2d( [0., 1., 0., 0., 0., 0., 1., 0., 1., 1., 0., 1.], [4, 3]); // Defining predicted tensorconst y_pred = tf.tensor2d( [1., 1., 0., 1., 0., 0., 1., 1., 1., 0., 0., 1.], [4, 3]); // Calculating meansquared errorconst mse = tf.losses.meanSquaredError( y_true, y_pred, [0.7, 0.3, 0.2],) mse.print()",
"e": 2377,
"s": 1930,
"text": null
},
{
"code": null,
"e": 2385,
"s": 2377,
"text": "Output:"
},
{
"code": null,
"e": 2403,
"s": 2385,
"text": "Tensor\n 0.2000"
},
{
"code": null,
"e": 2575,
"s": 2403,
"text": "Example 3: In compile function of designing the model, we use βmean squared errorβ as the loss parameter. Following is a simple neural network where we do the computation."
},
{
"code": null,
"e": 2586,
"s": 2575,
"text": "Javascript"
},
{
"code": "// Importing the tensorflow.js libraryconst tf = require(\"@tensorflow/tfjs\"); // Define the modelconst model = tf.sequential({ layers: [tf.layers.dense({ units: 1, inputShape: [12] })],}); // In model compilation we pass// meanSquaredError as the parameter model.compile( { optimizer: \"adam\", loss: \"meanSquaredError\" }, (metrics = [\"accuracy\"])); // Evaluate the model which was compiled above// computation is done in batches of size 4const result = model.evaluate( tf.ones([10, 12]), tf.ones([10, 1]), { batchSize: 4, }); // Print the resultresult.print();",
"e": 3185,
"s": 2586,
"text": null
},
{
"code": null,
"e": 3193,
"s": 3185,
"text": "Output:"
},
{
"code": null,
"e": 3211,
"s": 3193,
"text": "Tensor\n 0.4817"
},
{
"code": null,
"e": 3285,
"s": 3211,
"text": " Reference: https://js.tensorflow.org/api/3.6.0/#metrics.meanSquaredError"
},
{
"code": null,
"e": 3292,
"s": 3285,
"text": "Picked"
},
{
"code": null,
"e": 3306,
"s": 3292,
"text": "Tensorflow.js"
},
{
"code": null,
"e": 3317,
"s": 3306,
"text": "JavaScript"
},
{
"code": null,
"e": 3334,
"s": 3317,
"text": "Web Technologies"
}
] |
Ruby For Beginners | 30 Jul, 2018
Ruby is a dynamic, reflective, object-oriented, general-purpose programming language. It was designed and developed in the mid-1990s by Yukihiro βMatzβ Matsumoto in Japan. This article will cover its basic syntax and some basic programs. This article is divided into various sections for various topics.1.SetUp : Letβs start by doing setup of the Ruby programming language.
For Linux Users, Go to terminal and type:
apt-get install ruby
Windows users, click here and install ruby on your windows.
And the Ruby will be installed to your system.
In order to compile the a ruby program, Open your text editor and save the program with β.rbβ extension. After this, go to terminal(or command prompt) and type : ruby βfile.rbβ where file is the name of the program you just made, and hence the program will be compiled.
2. A good first programputs is used to print something on the console in Ruby.For eg. A string
puts "Hello World"
puts "Hello Again"
3. Comments
# is called the pound character in ruby and it is used to add comments to your code.
=begin, =end are used for multi-line comments
Example:
# this is a comment and wont be executed
= begin
this is
a multi line
comment in ruby
= end
4. Maths: Simple mathematical functions can be carried out within the puts statements.Just as we use β%dβ or β%fβ and β&β in C,we will use β#{ } in Ruby to get our work done.
puts "Alok has #{25+30/6} Rupees in his pocket"
Output : Alok has 30 Rupees in his pocketThe use of #{ } is how you insert Ruby computations into text strings.
5. Variables and Names : Variables in ruby are the same as that of any other dynamic programming language. You just donβt need to mention its type and ruby will know its type automatically.Example:
cars = 100
drivers = 30
puts "There are #{cars} cars and #{drivers} drivers."
Output: There are 100 cars and 30 drivers.
6. Getting input
βgets.chompβ is used to take input from user.
βprintβ can be used instead for βputsβto print without a new line.
Example:
print "How old are you ? "
age = gets.chomp
print "How tall are you ?"
height = gets.chomp
puts " You are #{age} year old and your height is #{height} cms"
Run this code on your system as output will be given by the user
7. Prompting people for numbers
gets.chomp.to_i is used to get integer input from user.
gets.chomp.to_f is used to get float(decimal) input from user.
Example:
print "Give a number"
number = gets.chomp.to_i
puts "You just entered #{number}"
These are the most basic topics of Ruby that are essential for the beginner of Ruby programming language.We will cover more topics of Ruby in our upcoming articles.
This article is contributed by Harsh Wardhan Chaudhary (Intern). 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.
Ruby-Basics
Ruby
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 53,
"s": 25,
"text": "\n30 Jul, 2018"
},
{
"code": null,
"e": 427,
"s": 53,
"text": "Ruby is a dynamic, reflective, object-oriented, general-purpose programming language. It was designed and developed in the mid-1990s by Yukihiro βMatzβ Matsumoto in Japan. This article will cover its basic syntax and some basic programs. This article is divided into various sections for various topics.1.SetUp : Letβs start by doing setup of the Ruby programming language."
},
{
"code": null,
"e": 469,
"s": 427,
"text": "For Linux Users, Go to terminal and type:"
},
{
"code": null,
"e": 491,
"s": 469,
"text": " apt-get install ruby"
},
{
"code": null,
"e": 551,
"s": 491,
"text": "Windows users, click here and install ruby on your windows."
},
{
"code": null,
"e": 598,
"s": 551,
"text": "And the Ruby will be installed to your system."
},
{
"code": null,
"e": 868,
"s": 598,
"text": "In order to compile the a ruby program, Open your text editor and save the program with β.rbβ extension. After this, go to terminal(or command prompt) and type : ruby βfile.rbβ where file is the name of the program you just made, and hence the program will be compiled."
},
{
"code": null,
"e": 963,
"s": 868,
"text": "2. A good first programputs is used to print something on the console in Ruby.For eg. A string"
},
{
"code": null,
"e": 1002,
"s": 963,
"text": "puts \"Hello World\"\nputs \"Hello Again\"\n"
},
{
"code": null,
"e": 1014,
"s": 1002,
"text": "3. Comments"
},
{
"code": null,
"e": 1099,
"s": 1014,
"text": "# is called the pound character in ruby and it is used to add comments to your code."
},
{
"code": null,
"e": 1145,
"s": 1099,
"text": "=begin, =end are used for multi-line comments"
},
{
"code": null,
"e": 1154,
"s": 1145,
"text": "Example:"
},
{
"code": null,
"e": 1248,
"s": 1154,
"text": "# this is a comment and wont be executed\n= begin\nthis is \na multi line\ncomment in ruby\n= end\n"
},
{
"code": null,
"e": 1423,
"s": 1248,
"text": "4. Maths: Simple mathematical functions can be carried out within the puts statements.Just as we use β%dβ or β%fβ and β&β in C,we will use β#{ } in Ruby to get our work done."
},
{
"code": null,
"e": 1472,
"s": 1423,
"text": "puts \"Alok has #{25+30/6} Rupees in his pocket\"\n"
},
{
"code": null,
"e": 1584,
"s": 1472,
"text": "Output : Alok has 30 Rupees in his pocketThe use of #{ } is how you insert Ruby computations into text strings."
},
{
"code": null,
"e": 1782,
"s": 1584,
"text": "5. Variables and Names : Variables in ruby are the same as that of any other dynamic programming language. You just donβt need to mention its type and ruby will know its type automatically.Example:"
},
{
"code": null,
"e": 1860,
"s": 1782,
"text": "cars = 100\ndrivers = 30\nputs \"There are #{cars} cars and #{drivers} drivers.\""
},
{
"code": null,
"e": 1903,
"s": 1860,
"text": "Output: There are 100 cars and 30 drivers."
},
{
"code": null,
"e": 1920,
"s": 1903,
"text": "6. Getting input"
},
{
"code": null,
"e": 1966,
"s": 1920,
"text": "βgets.chompβ is used to take input from user."
},
{
"code": null,
"e": 2033,
"s": 1966,
"text": "βprintβ can be used instead for βputsβto print without a new line."
},
{
"code": null,
"e": 2042,
"s": 2033,
"text": "Example:"
},
{
"code": null,
"e": 2199,
"s": 2042,
"text": "print \"How old are you ? \"\nage = gets.chomp\nprint \"How tall are you ?\"\nheight = gets.chomp\nputs \" You are #{age} year old and your height is #{height} cms\"\n"
},
{
"code": null,
"e": 2264,
"s": 2199,
"text": "Run this code on your system as output will be given by the user"
},
{
"code": null,
"e": 2296,
"s": 2264,
"text": "7. Prompting people for numbers"
},
{
"code": null,
"e": 2352,
"s": 2296,
"text": "gets.chomp.to_i is used to get integer input from user."
},
{
"code": null,
"e": 2415,
"s": 2352,
"text": "gets.chomp.to_f is used to get float(decimal) input from user."
},
{
"code": null,
"e": 2424,
"s": 2415,
"text": "Example:"
},
{
"code": null,
"e": 2506,
"s": 2424,
"text": "print \"Give a number\"\nnumber = gets.chomp.to_i\nputs \"You just entered #{number}\"\n"
},
{
"code": null,
"e": 2671,
"s": 2506,
"text": "These are the most basic topics of Ruby that are essential for the beginner of Ruby programming language.We will cover more topics of Ruby in our upcoming articles."
},
{
"code": null,
"e": 2991,
"s": 2671,
"text": "This article is contributed by Harsh Wardhan Chaudhary (Intern). 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": 3003,
"s": 2991,
"text": "Ruby-Basics"
},
{
"code": null,
"e": 3008,
"s": 3003,
"text": "Ruby"
}
] |
Minimum Distance Between Words of a String | 15 Dec, 2021
Given a string s and two words w1 and w2 that are present in S. The task is to find the minimum distance between w1 and w2. Here, distance is the number of steps or words between the first and the second word.
Examples:
Input : s = βgeeks for geeks contribute practiceβ, w1 = βgeeksβ, w2 = βpracticeβ Output : 1 There is only one word between the closest occurrences of w1 and w2.
Input : s = βthe quick the brown quick brown the frogβ, w1 = βquickβ, w2 = βfrogβOutput : 2
A simple approach is to consider every occurrence of w1. For every occurrence of w1, find the closest w2 and keep track of the minimum distance.
C++
Java
Python3
C#
PHP
Javascript
// C++ program to find Minimum Distance// Between Words of a String#include <bits/stdc++.h>#include <sstream>using namespace std; // Function to implement split functionvoid split(const string &s, char delimiter, vector<string> &words){ string token; stringstream tokenStream(s); while (getline(tokenStream, token, delimiter)) words.push_back(token);} // Function to calculate the minimum// distance between w1 and w2 in sint distance(string s, string w1, string w2){ if (w1 == w2) return 0; // get individual words in a list vector<string> words; split(s, ' ', words); // assume total length of the string // as minimum distance int min_dist = words.size() + 1; // traverse through the entire string for (int index = 0; index < words.size(); index++) { if (words[index] == w1) { for (int search = 0; search < words.size(); search++) { if (words[search] == w2) { // the distance between the words is // the index of the first word - the // current word index int curr = abs(index - search) - 1; // comparing current distance with // the previously assumed distance if (curr < min_dist) min_dist = curr; } } } } // w1 and w2 are same and adjacent return min_dist;} // Driver Codeint main(int argc, char const *argv[]){ string s = "geeks for geeks contribute practice"; string w1 = "geeks"; string w2 = "practice"; cout << distance(s, w1, w2) << endl; return 0;} // This code is contributed by// sanjeev2552
// Java program to find Minimum Distance// Between Words of a String class solution { // Function to calculate the minimum// distance between w1 and w2 in sstatic int distance(String s,String w1,String w2){ if (w1 .equals( w2) ) return 0 ; // get individual words in a list String words[] = s.split(" "); // assume total length of the string // as minimum distance int min_dist = (words.length) + 1; // traverse through the entire string for (int index = 0; index < words.length ; index ++) { if (words[index] .equals( w1)) { for (int search = 0; search < words.length; search ++) { if (words[search] .equals(w2)) { // the distance between the words is // the index of the first word - the // current word index int curr = Math.abs(index - search) - 1; // comparing current distance with // the previously assumed distance if (curr < min_dist) { min_dist = curr ; } } } } } // w1 and w2 are same and adjacent return min_dist;} // Driver codepublic static void main(String args[]){ String s = "geeks for geeks contribute practice";String w1 = "geeks" ;String w2 = "practice" ; System.out.print( distance(s, w1, w2) ); }}//contributed by Arnab Kundu
# function to calculate the minimum# distance between w1 and w2 in s def distance(s, w1, w2): if w1 == w2 : return 0 # get individual words in a list words = s.split(" ") # assume total length of the string as # minimum distance min_dist = len(words)+1 # traverse through the entire string for index in range(len(words)): if words[index] == w1: for search in range(len(words)): if words[search] == w2: # the distance between the words is # the index of the first word - the # current word index curr = abs(index - search) - 1; # comparing current distance with # the previously assumed distance if curr < min_dist: min_dist = curr # w1 and w2 are same and adjacent return min_dist # Driver codes = "geeks for geeks contribute practice"w1 = "geeks"w2 = "practice"print(distance(s, w1, w2))
// C# program to find Minimum Distance// Between Words of a String using System; class solution { // Function to calculate the minimum// distance between w1 and w2 in sstatic int distance(string s,string w1,string w2){ if (w1 .Equals( w2) ) return 0 ; // get individual words in a list string[] words = s.Split(" "); // assume total length of the string // as minimum distance int min_dist = (words.Length) + 1; // traverse through the entire string for (int index = 0; index < words.Length ; index ++) { if (words[index] .Equals( w1)) { for (int search = 0; search < words.Length; search ++) { if (words[search] .Equals(w2)) { // the distance between the words is // the index of the first word - the // current word index int curr = Math.Abs(index - search) - 1; // comparing current distance with // the previously assumed distance if (curr < min_dist) { min_dist = curr ; } } } } } // w1 and w2 are same and adjacent return min_dist;} // Driver codepublic static void Main(){ string s = "geeks for geeks contribute practice";string w1 = "geeks" ;string w2 = "practice" ; Console.Write( distance(s, w1, w2) ); }}
<?php// PHP program to find Minimum Distance// Between Words of a String // Function to calculate the minimum// distance between w1 and w2 in sfunction distance($s, $w1, $w2){ if ($w1 == $w2 ) return 0 ; // get individual words in a list $words = explode(" ", $s); // assume total length of the string // as minimum distance $min_dist = sizeof($words) + 1; // traverse through the entire string for ($index = 0; $index < sizeof($words) ; $index ++) { if ($words[$index] == $w1) { for ($search = 0; $search < sizeof($words); $search ++) { if ($words[$search] == $w2) { // the distance between the words is // the index of the first word - the // current word index $curr = abs($index - $search) - 1; // comparing current distance with // the previously assumed distance if ($curr < $min_dist) { $min_dist = $curr ; } } } } } // w1 and w2 are same and adjacent return $min_dist;} // Driver code$s = "geeks for geeks contribute practice";$w1 = "geeks" ;$w2 = "practice" ; echo distance($s, $w1, $w2) ; // This code is contributed by Ryuga?>
<script>// Javascript program to find Minimum Distance// Between Words of a String // Function to calculate the minimum// distance between w1 and w2 in sfunction distance(s,w1,w2) { if (w1 ==( w2) ) return 0 ; // get individual words in a list let words = s.split(" "); // assume total length of the string // as minimum distance let min_dist = (words.length) + 1; // traverse through the entire string for (let index = 0; index < words.length ; index ++) { if (words[index] == ( w1)) { for (let search = 0; search < words.length; search ++) { if (words[search] == (w2)) { // the distance between the words is // the index of the first word - the // current word index let curr = Math.abs(index - search) - 1; // comparing current distance with // the previously assumed distance if (curr < min_dist) { min_dist = curr ; } } } } } // w1 and w2 are same and adjacent return min_dist;} // Driver code let s = "geeks for geeks contribute practice"; let w1 = "geeks" ; let w2 = "practice" ; document.write( distance(s, w1, w2) ); // This code is contributed by rag2127</script>
1
An efficient solution is to find the first occurrence of any element, then keep track of the previous element and current element. If they are different and the distance is less than the current minimum, update the minimum.
C++
Java
C#
Python3
Javascript
// C++ program to extract words from// a string using stringstream#include<bits/stdc++.h>using namespace std; int distance(string s, string w1, string w2){ if (w1 == w2) { return 0; } vector<string> words; // Used to split string around spaces. istringstream ss(s); string word; // for storing each word // Traverse through all words // while loop till we get // strings to store in string word while (ss >> word) { words.push_back(word); } int n = words.size(); // assume total length of the string as // minimum distance int min_dist = n + 1; // Find the first occurrence of any of the two // numbers (w1 or w2) and store the index of // this occurrence in prev int prev = 0, i = 0; for (i = 0; i < n; i++) { if (words[i] == w1 || (words[i] == w2)) { prev = i; break; } } // Traverse after the first occurrence while (i < n) { if (words[i] == w1 || (words[i] == w2)) { // If the current element matches with // any of the two then check if current // element and prev element are different // Also check if this value is smaller than // minimum distance so far if ((words[prev] != words[i]) && (i - prev) < min_dist) { min_dist = i - prev - 1; prev = i; } else { prev = i; } } i += 1; } return min_dist;} // Driver codeint main(){ string s = "geeks for geeks contribute practice"; string w1 = "geeks"; string w2 = "practice"; cout<<distance(s, w1, w2);} // This code is contributed by rutvik_56.
// Java program to extract words from// a string using stringstreamclass GFG { static int distance(String s, String w1, String w2) { if (w1.equals(w2)) { return 0; } // get individual words in a list String[] words = s.split(" "); int n = words.length; // assume total length of the string as // minimum distance int min_dist = n + 1; // Find the first occurrence of any of the two // numbers (w1 or w2) and store the index of // this occurrence in prev int prev = 0, i = 0; for (i = 0; i < n; i++) { if (words[i].equals(w1) || words[i].equals(w2)) { prev = i; break; } } // Traverse after the first occurrence while (i < n) { if (words[i].equals(w1) || words[i].equals(w2)) { // If the current element matches with // any of the two then check if current // element and prev element are different // Also check if this value is smaller than // minimum distance so far if ((!words[prev].equals(words[i])) && (i - prev) < min_dist) { min_dist = i - prev - 1; prev = i; } else { prev = i; } } i += 1; } return min_dist; }// Driver code public static void main(String[] args) { String s = "geeks for geeks contribute practice"; String w1 = "geeks"; String w2 = "practice"; System.out.println(distance(s, w1, w2));// This code is contributed by princiRaj1992 }}
// C# program to extract words from// a string using stringstreamusing System; class GFG{ static int distance(String s, String w1, String w2) { if (w1.Equals(w2)) { return 0; } // get individual words in a list String[] words = s.Split(" "); int n = words.Length; // assume total length of the string as // minimum distance int min_dist = n + 1; // Find the first occurrence of any of the two // numbers (w1 or w2) and store the index of // this occurrence in prev int prev = 0, i = 0; for (i = 0; i < n; i++) { if (words[i].Equals(w1) || words[i].Equals(w2)) { prev = i; break; } } // Traverse after the first occurrence while (i < n) { if (words[i].Equals(w1) || words[i].Equals(w2)) { // If the current element matches with // any of the two then check if current // element and prev element are different // Also check if this value is smaller than // minimum distance so far if ((!words[prev].Equals(words[i])) && (i - prev) < min_dist) { min_dist = i - prev - 1; prev = i; } else { prev = i; } } i += 1; } return min_dist; } // Driver code public static void Main(String[] args) { String s = "geeks for geeks contribute practice"; String w1 = "geeks"; String w2 = "practice"; Console.Write(distance(s, w1, w2)); }} // This code is contributed by Mohit kumar 29
# Python3 program to extract words from# a string using stringstream def distance(s, w1, w2): if w1 == w2 : return 0 # get individual words in a list words = s.split(" ") n = len(words) # assume total length of the string as # minimum distance min_dist = n+1 # Find the first occurrence of any of the two # numbers (w1 or w2) and store the index of # this occurrence in prev for i in range(n): if words[i] == w1 or words[i] == w2: prev = i break # Traverse after the first occurrence while i < n: if words[i] == w1 or words[i] == w2: # If the current element matches with # any of the two then check if current # element and prev element are different # Also check if this value is smaller than # minimum distance so far if words[prev] != words[i] and (i - prev) < min_dist : min_dist = i - prev - 1 prev = i else: prev = i i += 1 return min_dist # Driver codes = "geeks for geeks contribute practice"w1 = "geeks"w2 = "practice"print(distance(s, w1, w2))
<script> // Javascript program to extract words from// a string using stringstream function distance(s,w1,w2){ if (w1 == (w2)) { return 0; } // get individual words in a list let words = s.split(" "); let n = words.length; // assume total length of the string as // minimum distance let min_dist = n + 1; // Find the first occurrence of any of the two // numbers (w1 or w2) and store the index of // this occurrence in prev let prev = 0, i = 0; for (i = 0; i < n; i++) { if (words[i] == (w1) || words[i] == (w2)) { prev = i; break; } } // Traverse after the first occurrence while (i < n) { if (words[i] == (w1) || words[i] == (w2)) { // If the current element matches with // any of the two then check if current // element and prev element are different // Also check if this value is smaller than // minimum distance so far if ((words[prev] != (words[i])) && (i - prev) < min_dist) { min_dist = i - prev - 1; prev = i; } else { prev = i; } } i += 1; } return min_dist;} // Driver codelet s = "geeks for geeks contribute practice";let w1 = "geeks";let w2 = "practice";document.write(distance(s, w1, w2)); // This code is contributed by avanitrachhadiya2155</script>
1
An efficient solution is to store the index of word1 in (lastpos) variable if word1 occur again then we update (lastpos) if word1 not occur then simply find the difference of index of word1 and word2.
C++
// C++ program to find Minimum Distance// Between Words of a String#include <bits/stdc++.h>using namespace std; int shortestDistance(vector<string> &s, string word1, string word2) { if(word1==word2) return 0; int ans = INT_MAX; //To store the lastposition of word1 int lastPos = -1; for(int i = 0 ; i < s.size() ; i++) { if(s[i] == word1 || s[i] == word2) { //first occurrence of word1 if(lastPos == -1) lastPos = i; else { //if word1 repeated again we store the last position of word1 if(s[lastPos]==s[i]) lastPos = i; else { //find the difference of position of word1 and word2 ans = min(ans , (i-lastPos)-1); lastPos = i; } } } } return ans;}//Driver codeint main() { vector<string> s{"geeks", "for", "geeks", "contribute", "practice"}; string w1 = "geeks"; string w2 = "practice"; cout<<shortestDistance(s, w1, w2)<<"\n"; return 0;}
ankthon
andrew1234
ukasp
princiraj1992
mohit kumar 29
sanjeev2552
rutvik_56
rag2127
avanitrachhadiya2155
pushkar_s
sagar0719kumar
sweetyty
saurabh1990aror
Python Programs
Strings
Technical Scripter
Strings
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python program to find second largest number in a list
Python program to interchange first and last elements in a list
Python | Convert set into a list
Appending to list in Python dictionary
Python | Convert a list into a tuple
Write a program to reverse an array or string
Reverse a string in Java
Write a program to print all permutations of a given string
C++ Data Types
Different Methods to Reverse a String in C++ | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n15 Dec, 2021"
},
{
"code": null,
"e": 265,
"s": 54,
"text": "Given a string s and two words w1 and w2 that are present in S. The task is to find the minimum distance between w1 and w2. Here, distance is the number of steps or words between the first and the second word. "
},
{
"code": null,
"e": 276,
"s": 265,
"text": "Examples: "
},
{
"code": null,
"e": 437,
"s": 276,
"text": "Input : s = βgeeks for geeks contribute practiceβ, w1 = βgeeksβ, w2 = βpracticeβ Output : 1 There is only one word between the closest occurrences of w1 and w2."
},
{
"code": null,
"e": 529,
"s": 437,
"text": "Input : s = βthe quick the brown quick brown the frogβ, w1 = βquickβ, w2 = βfrogβOutput : 2"
},
{
"code": null,
"e": 675,
"s": 529,
"text": "A simple approach is to consider every occurrence of w1. For every occurrence of w1, find the closest w2 and keep track of the minimum distance. "
},
{
"code": null,
"e": 679,
"s": 675,
"text": "C++"
},
{
"code": null,
"e": 684,
"s": 679,
"text": "Java"
},
{
"code": null,
"e": 692,
"s": 684,
"text": "Python3"
},
{
"code": null,
"e": 695,
"s": 692,
"text": "C#"
},
{
"code": null,
"e": 699,
"s": 695,
"text": "PHP"
},
{
"code": null,
"e": 710,
"s": 699,
"text": "Javascript"
},
{
"code": "// C++ program to find Minimum Distance// Between Words of a String#include <bits/stdc++.h>#include <sstream>using namespace std; // Function to implement split functionvoid split(const string &s, char delimiter, vector<string> &words){ string token; stringstream tokenStream(s); while (getline(tokenStream, token, delimiter)) words.push_back(token);} // Function to calculate the minimum// distance between w1 and w2 in sint distance(string s, string w1, string w2){ if (w1 == w2) return 0; // get individual words in a list vector<string> words; split(s, ' ', words); // assume total length of the string // as minimum distance int min_dist = words.size() + 1; // traverse through the entire string for (int index = 0; index < words.size(); index++) { if (words[index] == w1) { for (int search = 0; search < words.size(); search++) { if (words[search] == w2) { // the distance between the words is // the index of the first word - the // current word index int curr = abs(index - search) - 1; // comparing current distance with // the previously assumed distance if (curr < min_dist) min_dist = curr; } } } } // w1 and w2 are same and adjacent return min_dist;} // Driver Codeint main(int argc, char const *argv[]){ string s = \"geeks for geeks contribute practice\"; string w1 = \"geeks\"; string w2 = \"practice\"; cout << distance(s, w1, w2) << endl; return 0;} // This code is contributed by// sanjeev2552",
"e": 2494,
"s": 710,
"text": null
},
{
"code": "// Java program to find Minimum Distance// Between Words of a String class solution { // Function to calculate the minimum// distance between w1 and w2 in sstatic int distance(String s,String w1,String w2){ if (w1 .equals( w2) ) return 0 ; // get individual words in a list String words[] = s.split(\" \"); // assume total length of the string // as minimum distance int min_dist = (words.length) + 1; // traverse through the entire string for (int index = 0; index < words.length ; index ++) { if (words[index] .equals( w1)) { for (int search = 0; search < words.length; search ++) { if (words[search] .equals(w2)) { // the distance between the words is // the index of the first word - the // current word index int curr = Math.abs(index - search) - 1; // comparing current distance with // the previously assumed distance if (curr < min_dist) { min_dist = curr ; } } } } } // w1 and w2 are same and adjacent return min_dist;} // Driver codepublic static void main(String args[]){ String s = \"geeks for geeks contribute practice\";String w1 = \"geeks\" ;String w2 = \"practice\" ; System.out.print( distance(s, w1, w2) ); }}//contributed by Arnab Kundu",
"e": 4031,
"s": 2494,
"text": null
},
{
"code": "# function to calculate the minimum# distance between w1 and w2 in s def distance(s, w1, w2): if w1 == w2 : return 0 # get individual words in a list words = s.split(\" \") # assume total length of the string as # minimum distance min_dist = len(words)+1 # traverse through the entire string for index in range(len(words)): if words[index] == w1: for search in range(len(words)): if words[search] == w2: # the distance between the words is # the index of the first word - the # current word index curr = abs(index - search) - 1; # comparing current distance with # the previously assumed distance if curr < min_dist: min_dist = curr # w1 and w2 are same and adjacent return min_dist # Driver codes = \"geeks for geeks contribute practice\"w1 = \"geeks\"w2 = \"practice\"print(distance(s, w1, w2))",
"e": 5063,
"s": 4031,
"text": null
},
{
"code": "// C# program to find Minimum Distance// Between Words of a String using System; class solution { // Function to calculate the minimum// distance between w1 and w2 in sstatic int distance(string s,string w1,string w2){ if (w1 .Equals( w2) ) return 0 ; // get individual words in a list string[] words = s.Split(\" \"); // assume total length of the string // as minimum distance int min_dist = (words.Length) + 1; // traverse through the entire string for (int index = 0; index < words.Length ; index ++) { if (words[index] .Equals( w1)) { for (int search = 0; search < words.Length; search ++) { if (words[search] .Equals(w2)) { // the distance between the words is // the index of the first word - the // current word index int curr = Math.Abs(index - search) - 1; // comparing current distance with // the previously assumed distance if (curr < min_dist) { min_dist = curr ; } } } } } // w1 and w2 are same and adjacent return min_dist;} // Driver codepublic static void Main(){ string s = \"geeks for geeks contribute practice\";string w1 = \"geeks\" ;string w2 = \"practice\" ; Console.Write( distance(s, w1, w2) ); }}",
"e": 6580,
"s": 5063,
"text": null
},
{
"code": "<?php// PHP program to find Minimum Distance// Between Words of a String // Function to calculate the minimum// distance between w1 and w2 in sfunction distance($s, $w1, $w2){ if ($w1 == $w2 ) return 0 ; // get individual words in a list $words = explode(\" \", $s); // assume total length of the string // as minimum distance $min_dist = sizeof($words) + 1; // traverse through the entire string for ($index = 0; $index < sizeof($words) ; $index ++) { if ($words[$index] == $w1) { for ($search = 0; $search < sizeof($words); $search ++) { if ($words[$search] == $w2) { // the distance between the words is // the index of the first word - the // current word index $curr = abs($index - $search) - 1; // comparing current distance with // the previously assumed distance if ($curr < $min_dist) { $min_dist = $curr ; } } } } } // w1 and w2 are same and adjacent return $min_dist;} // Driver code$s = \"geeks for geeks contribute practice\";$w1 = \"geeks\" ;$w2 = \"practice\" ; echo distance($s, $w1, $w2) ; // This code is contributed by Ryuga?>",
"e": 7993,
"s": 6580,
"text": null
},
{
"code": "<script>// Javascript program to find Minimum Distance// Between Words of a String // Function to calculate the minimum// distance between w1 and w2 in sfunction distance(s,w1,w2) { if (w1 ==( w2) ) return 0 ; // get individual words in a list let words = s.split(\" \"); // assume total length of the string // as minimum distance let min_dist = (words.length) + 1; // traverse through the entire string for (let index = 0; index < words.length ; index ++) { if (words[index] == ( w1)) { for (let search = 0; search < words.length; search ++) { if (words[search] == (w2)) { // the distance between the words is // the index of the first word - the // current word index let curr = Math.abs(index - search) - 1; // comparing current distance with // the previously assumed distance if (curr < min_dist) { min_dist = curr ; } } } } } // w1 and w2 are same and adjacent return min_dist;} // Driver code let s = \"geeks for geeks contribute practice\"; let w1 = \"geeks\" ; let w2 = \"practice\" ; document.write( distance(s, w1, w2) ); // This code is contributed by rag2127</script>",
"e": 9487,
"s": 7993,
"text": null
},
{
"code": null,
"e": 9489,
"s": 9487,
"text": "1"
},
{
"code": null,
"e": 9715,
"s": 9491,
"text": "An efficient solution is to find the first occurrence of any element, then keep track of the previous element and current element. If they are different and the distance is less than the current minimum, update the minimum."
},
{
"code": null,
"e": 9719,
"s": 9715,
"text": "C++"
},
{
"code": null,
"e": 9724,
"s": 9719,
"text": "Java"
},
{
"code": null,
"e": 9727,
"s": 9724,
"text": "C#"
},
{
"code": null,
"e": 9735,
"s": 9727,
"text": "Python3"
},
{
"code": null,
"e": 9746,
"s": 9735,
"text": "Javascript"
},
{
"code": "// C++ program to extract words from// a string using stringstream#include<bits/stdc++.h>using namespace std; int distance(string s, string w1, string w2){ if (w1 == w2) { return 0; } vector<string> words; // Used to split string around spaces. istringstream ss(s); string word; // for storing each word // Traverse through all words // while loop till we get // strings to store in string word while (ss >> word) { words.push_back(word); } int n = words.size(); // assume total length of the string as // minimum distance int min_dist = n + 1; // Find the first occurrence of any of the two // numbers (w1 or w2) and store the index of // this occurrence in prev int prev = 0, i = 0; for (i = 0; i < n; i++) { if (words[i] == w1 || (words[i] == w2)) { prev = i; break; } } // Traverse after the first occurrence while (i < n) { if (words[i] == w1 || (words[i] == w2)) { // If the current element matches with // any of the two then check if current // element and prev element are different // Also check if this value is smaller than // minimum distance so far if ((words[prev] != words[i]) && (i - prev) < min_dist) { min_dist = i - prev - 1; prev = i; } else { prev = i; } } i += 1; } return min_dist;} // Driver codeint main(){ string s = \"geeks for geeks contribute practice\"; string w1 = \"geeks\"; string w2 = \"practice\"; cout<<distance(s, w1, w2);} // This code is contributed by rutvik_56.",
"e": 11312,
"s": 9746,
"text": null
},
{
"code": "// Java program to extract words from// a string using stringstreamclass GFG { static int distance(String s, String w1, String w2) { if (w1.equals(w2)) { return 0; } // get individual words in a list String[] words = s.split(\" \"); int n = words.length; // assume total length of the string as // minimum distance int min_dist = n + 1; // Find the first occurrence of any of the two // numbers (w1 or w2) and store the index of // this occurrence in prev int prev = 0, i = 0; for (i = 0; i < n; i++) { if (words[i].equals(w1) || words[i].equals(w2)) { prev = i; break; } } // Traverse after the first occurrence while (i < n) { if (words[i].equals(w1) || words[i].equals(w2)) { // If the current element matches with // any of the two then check if current // element and prev element are different // Also check if this value is smaller than // minimum distance so far if ((!words[prev].equals(words[i])) && (i - prev) < min_dist) { min_dist = i - prev - 1; prev = i; } else { prev = i; } } i += 1; } return min_dist; }// Driver code public static void main(String[] args) { String s = \"geeks for geeks contribute practice\"; String w1 = \"geeks\"; String w2 = \"practice\"; System.out.println(distance(s, w1, w2));// This code is contributed by princiRaj1992 }}",
"e": 13018,
"s": 11312,
"text": null
},
{
"code": "// C# program to extract words from// a string using stringstreamusing System; class GFG{ static int distance(String s, String w1, String w2) { if (w1.Equals(w2)) { return 0; } // get individual words in a list String[] words = s.Split(\" \"); int n = words.Length; // assume total length of the string as // minimum distance int min_dist = n + 1; // Find the first occurrence of any of the two // numbers (w1 or w2) and store the index of // this occurrence in prev int prev = 0, i = 0; for (i = 0; i < n; i++) { if (words[i].Equals(w1) || words[i].Equals(w2)) { prev = i; break; } } // Traverse after the first occurrence while (i < n) { if (words[i].Equals(w1) || words[i].Equals(w2)) { // If the current element matches with // any of the two then check if current // element and prev element are different // Also check if this value is smaller than // minimum distance so far if ((!words[prev].Equals(words[i])) && (i - prev) < min_dist) { min_dist = i - prev - 1; prev = i; } else { prev = i; } } i += 1; } return min_dist; } // Driver code public static void Main(String[] args) { String s = \"geeks for geeks contribute practice\"; String w1 = \"geeks\"; String w2 = \"practice\"; Console.Write(distance(s, w1, w2)); }} // This code is contributed by Mohit kumar 29",
"e": 14874,
"s": 13018,
"text": null
},
{
"code": "# Python3 program to extract words from# a string using stringstream def distance(s, w1, w2): if w1 == w2 : return 0 # get individual words in a list words = s.split(\" \") n = len(words) # assume total length of the string as # minimum distance min_dist = n+1 # Find the first occurrence of any of the two # numbers (w1 or w2) and store the index of # this occurrence in prev for i in range(n): if words[i] == w1 or words[i] == w2: prev = i break # Traverse after the first occurrence while i < n: if words[i] == w1 or words[i] == w2: # If the current element matches with # any of the two then check if current # element and prev element are different # Also check if this value is smaller than # minimum distance so far if words[prev] != words[i] and (i - prev) < min_dist : min_dist = i - prev - 1 prev = i else: prev = i i += 1 return min_dist # Driver codes = \"geeks for geeks contribute practice\"w1 = \"geeks\"w2 = \"practice\"print(distance(s, w1, w2))",
"e": 16069,
"s": 14874,
"text": null
},
{
"code": "<script> // Javascript program to extract words from// a string using stringstream function distance(s,w1,w2){ if (w1 == (w2)) { return 0; } // get individual words in a list let words = s.split(\" \"); let n = words.length; // assume total length of the string as // minimum distance let min_dist = n + 1; // Find the first occurrence of any of the two // numbers (w1 or w2) and store the index of // this occurrence in prev let prev = 0, i = 0; for (i = 0; i < n; i++) { if (words[i] == (w1) || words[i] == (w2)) { prev = i; break; } } // Traverse after the first occurrence while (i < n) { if (words[i] == (w1) || words[i] == (w2)) { // If the current element matches with // any of the two then check if current // element and prev element are different // Also check if this value is smaller than // minimum distance so far if ((words[prev] != (words[i])) && (i - prev) < min_dist) { min_dist = i - prev - 1; prev = i; } else { prev = i; } } i += 1; } return min_dist;} // Driver codelet s = \"geeks for geeks contribute practice\";let w1 = \"geeks\";let w2 = \"practice\";document.write(distance(s, w1, w2)); // This code is contributed by avanitrachhadiya2155</script>",
"e": 17686,
"s": 16069,
"text": null
},
{
"code": null,
"e": 17688,
"s": 17686,
"text": "1"
},
{
"code": null,
"e": 17891,
"s": 17690,
"text": "An efficient solution is to store the index of word1 in (lastpos) variable if word1 occur again then we update (lastpos) if word1 not occur then simply find the difference of index of word1 and word2."
},
{
"code": null,
"e": 17895,
"s": 17891,
"text": "C++"
},
{
"code": "// C++ program to find Minimum Distance// Between Words of a String#include <bits/stdc++.h>using namespace std; int shortestDistance(vector<string> &s, string word1, string word2) { if(word1==word2) return 0; int ans = INT_MAX; //To store the lastposition of word1 int lastPos = -1; for(int i = 0 ; i < s.size() ; i++) { if(s[i] == word1 || s[i] == word2) { //first occurrence of word1 if(lastPos == -1) lastPos = i; else { //if word1 repeated again we store the last position of word1 if(s[lastPos]==s[i]) lastPos = i; else { //find the difference of position of word1 and word2 ans = min(ans , (i-lastPos)-1); lastPos = i; } } } } return ans;}//Driver codeint main() { vector<string> s{\"geeks\", \"for\", \"geeks\", \"contribute\", \"practice\"}; string w1 = \"geeks\"; string w2 = \"practice\"; cout<<shortestDistance(s, w1, w2)<<\"\\n\"; return 0;} ",
"e": 19134,
"s": 17895,
"text": null
},
{
"code": null,
"e": 19142,
"s": 19134,
"text": "ankthon"
},
{
"code": null,
"e": 19153,
"s": 19142,
"text": "andrew1234"
},
{
"code": null,
"e": 19159,
"s": 19153,
"text": "ukasp"
},
{
"code": null,
"e": 19173,
"s": 19159,
"text": "princiraj1992"
},
{
"code": null,
"e": 19188,
"s": 19173,
"text": "mohit kumar 29"
},
{
"code": null,
"e": 19200,
"s": 19188,
"text": "sanjeev2552"
},
{
"code": null,
"e": 19210,
"s": 19200,
"text": "rutvik_56"
},
{
"code": null,
"e": 19218,
"s": 19210,
"text": "rag2127"
},
{
"code": null,
"e": 19239,
"s": 19218,
"text": "avanitrachhadiya2155"
},
{
"code": null,
"e": 19249,
"s": 19239,
"text": "pushkar_s"
},
{
"code": null,
"e": 19264,
"s": 19249,
"text": "sagar0719kumar"
},
{
"code": null,
"e": 19273,
"s": 19264,
"text": "sweetyty"
},
{
"code": null,
"e": 19289,
"s": 19273,
"text": "saurabh1990aror"
},
{
"code": null,
"e": 19305,
"s": 19289,
"text": "Python Programs"
},
{
"code": null,
"e": 19313,
"s": 19305,
"text": "Strings"
},
{
"code": null,
"e": 19332,
"s": 19313,
"text": "Technical Scripter"
},
{
"code": null,
"e": 19340,
"s": 19332,
"text": "Strings"
},
{
"code": null,
"e": 19438,
"s": 19340,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 19493,
"s": 19438,
"text": "Python program to find second largest number in a list"
},
{
"code": null,
"e": 19557,
"s": 19493,
"text": "Python program to interchange first and last elements in a list"
},
{
"code": null,
"e": 19590,
"s": 19557,
"text": "Python | Convert set into a list"
},
{
"code": null,
"e": 19629,
"s": 19590,
"text": "Appending to list in Python dictionary"
},
{
"code": null,
"e": 19666,
"s": 19629,
"text": "Python | Convert a list into a tuple"
},
{
"code": null,
"e": 19712,
"s": 19666,
"text": "Write a program to reverse an array or string"
},
{
"code": null,
"e": 19737,
"s": 19712,
"text": "Reverse a string in Java"
},
{
"code": null,
"e": 19797,
"s": 19737,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 19812,
"s": 19797,
"text": "C++ Data Types"
}
] |
Python PIL | ImageOps.flip() method | 11 Jul, 2019
PIL is the Python Imaging Library which provides the python interpreter with image editing capabilities. The ImageOps module contains a number of βready-madeβ image processing operations. This module is somewhat experimental, and most operators only work on L and RGB images.
ImageOps.flip() Flip the image vertically (top to bottom).
Syntax: PIL.ImageOps.flip(image)
Parameters:image β The image to flip. The image will be flip vertically.
Returns: An image.
Image Used:
# Importing Image and ImageOps module from PIL package from PIL import Image, ImageOps # creating a image1 object im1 = Image.open(r"C:\Users\System-Pc\Desktop\a.JPG") # applying flip method im2 = ImageOps.flip(im1) im2.show()
Output:
Python-pil
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n11 Jul, 2019"
},
{
"code": null,
"e": 304,
"s": 28,
"text": "PIL is the Python Imaging Library which provides the python interpreter with image editing capabilities. The ImageOps module contains a number of βready-madeβ image processing operations. This module is somewhat experimental, and most operators only work on L and RGB images."
},
{
"code": null,
"e": 363,
"s": 304,
"text": "ImageOps.flip() Flip the image vertically (top to bottom)."
},
{
"code": null,
"e": 396,
"s": 363,
"text": "Syntax: PIL.ImageOps.flip(image)"
},
{
"code": null,
"e": 469,
"s": 396,
"text": "Parameters:image β The image to flip. The image will be flip vertically."
},
{
"code": null,
"e": 488,
"s": 469,
"text": "Returns: An image."
},
{
"code": null,
"e": 500,
"s": 488,
"text": "Image Used:"
},
{
"code": "# Importing Image and ImageOps module from PIL package from PIL import Image, ImageOps # creating a image1 object im1 = Image.open(r\"C:\\Users\\System-Pc\\Desktop\\a.JPG\") # applying flip method im2 = ImageOps.flip(im1) im2.show()",
"e": 737,
"s": 500,
"text": null
},
{
"code": null,
"e": 745,
"s": 737,
"text": "Output:"
},
{
"code": null,
"e": 756,
"s": 745,
"text": "Python-pil"
},
{
"code": null,
"e": 763,
"s": 756,
"text": "Python"
}
] |
Frameless Window in ElectronJS | 12 Dec, 2021
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.
In a complex desktop application, a situation might occur wherein the developers may have to carry out additional background processes and computational tasks in parallel frames without interrupting the user experience. These background processes running within parallel frames should not be visible to the user as additional GUI windows but should be activated accordingly whenever the need arises. We can see this behavior in many modern desktop applications such as the Google Chrome web browser. Additionally, the developers might want to restrict the user to a specific frame with limited functionality such as when displaying a License Agreement or Terms & Conditions window. In such windows, the Title Bar, Navigational Bar, Context Menus are disabled and the user should not be able to close/skip/minimize the window frame. Electron provides us with a way by which we can open a window without toolbars, borders, or any other graphical components or make the entire window transparent using the properties in options of a new BrowserWindow object. Such windows are known as Frameless windows in Electron. This tutorial will demonstrate how to create and features of a Frameless window in Electron.
We assume that you are familiar with the prerequisites as covered in the above-mentioned link. For Electron to work, node and npm need to be pre-installed in the system.
Project Structure:
Example: Follow the Steps given in Dynamic Styling in ElectronJS to set up the basic Electron Application. Copy the Boilerplate code for the main.js file and the index.html file as provided in the article. Also, perform the necessary changes mentioned for the package.json file to launch the Electron Application. We will continue building our application using the same code base. The basic steps required to set up the Electron application remain the same. package.json:
{
"name": "electron-frameless",
"version": "1.0.0",
"description": "Frameless Window in Electron",
"main": "main.js",
"scripts": {
"start": "electron ."
},
"keywords": [
"electron"
],
"author": "Radhesh Khanna",
"license": "ISC",
"dependencies": {
"electron": "^8.3.0"
}
}
Output:
Frameless Window in Electron: The BrowserWindow Instance is part of the Main Process. To import and use BrowserWindow in the Renderer Process, we will be using Electron remote module. A frameless window is a window that has no chrome. Chrome is any visible aspect of a window aside from the webpages themselves (e.g., toolbars, menu bar, borders, etc). We can define a BrowserWindow Instance as a Frameless or a Transparent window by specifying the properties of the BrowserWindow object.
index.html: Add the following snippet in that file.
html
<body style="-webkit-app-region: drag"> <h3>Frameless Window in Electron</h3> <button id="frame" style="-webkit-app-region: no-drag;"> Create a Frameless Window </button> <br><br> <button id="frameless" style="-webkit-app-region: no-drag;"> Create a Frameless Draggable Window </button> <br><br><!-- Adding Individual Renderer Process JS File --><script src="index.js"></script></body>
index.js: The Create a Frameless Window and Create a Frameless Draggable Window buttons do not have any functionality associated with them yet. To change this, add the following code in the index.js file.
javascript
const electron = require('electron')// Import BrowserWindow using Electron remoteconst BrowserWindow = electron.remote.BrowserWindow;// let win = BrowserWindow.getAllWindows()[0]; var frame = document.getElementById('frame');frame.addEventListener('click', (event) => { const win = new BrowserWindow({ width: 800, height: 600, // Creating a Frameless Window frame: false, webPreferences: { nodeIntegration: true } }); win.loadURL('https://www.google.com/');}); var frameless = document.getElementById('frameless');frameless.addEventListener('click', (event) => { const win = new BrowserWindow({ width: 800, height: 600, frame: false, webPreferences: { nodeIntegration: true } }); win.loadFile('src/index.html'); win.show();});
To create a Frameless window in Electron, the frame: false property is set in the options of the BrowserWindow Instance. By setting this property, only the webpage itself will be visible to the user without any additional chrome or GUI components. Refer to the output for a better understanding. By default, the frameless window is non-draggable. Applications need to specify the -webkit-app-region: drag CSS property to tell Electron which regions are draggable. To make the whole window draggable, this CSS property is set to the style of the body tag in HTML. Applications can also use -webkit-app-region: no-drag CSS property to indicate the non-draggable area. Once we have defined a frameless window, we can customize it to our look and feel and provide a custom titlebar along with custom window controls. Note β When the -webkit-app-region: drag CSS property is set to the body tag, we need to set -webkit-app-region: no-drag CSS property to the Buttons or any clickable components within the window. Else, we will not be able to click on those clickable components.
Note: Sometimes in Frameless windows, the dragging behavior may conflict with the text selection. For example, when dragging a window via the title bar, we may accidentally select the text on the title bar. This occurs when the size of the custom title bar is especially small. To prevent this we need to disable the text selection by using the -webkit-user-select: none; CSS property.
Note: As of v8.3.0 of Electron, only rectangular shapes are currently supported for draggable regions. Also, -webkit-app-region: drag CSS property is known to have problems while the Chrome Dev tools are open. Note β In some environments, the draggable region within a window can be treated as a non-client frame. This means that whenever we right-click on the draggable region, the system context menu may open. To make the context menu behave correctly, we should never use a custom context menu on draggable regions. The frame: false property of the BrowserWindow Instance is supported on all OS platforms. Additionally, in macOS, we have some more properties to define chromeless windows instead of the frame property. If we use the frame property in macOS, it disables the titlebar and the windows controls (a.k.a traffic lights in macOS). Instead, we can use the titleBarStyle property in the options of the BrowserWindow Instance to hide the titlebar and make the content extend the entire window size while still preserving the window controls.
titleBarStyle: βhiddenβ This property hides the titlebar, makes the content extend the full size of the window, yet still displays the windows controls in the top-left corner of the chromeless window.
titleBarStyle: βhiddenInsetβ This property hides the titlebar but provides an alternative look wherein the windows controls are slightly more inset from the edge of the chromeless window.
titleBarStyle: βcustomButtonsOnHoverβ This property uses miniature buttons as windows controls and displays a custom drawer on hover near the top-left of the chromeless window. This property can only be used together with the frame: false property.
At this point, upon launching the Electron application, we should be able to activate a Frameless window and a Frameless draggable window in the application. In this tutorial, we have loaded an external website in the frameless window and the index.html file once again in the frameless draggable window respectively for demonstration purposes. Output:
index.html: Now we will see how to make a frameless window completely transparent in the application and see some of the features and limitations of a Transparent window in Electron.
html
<body style="-webkit-app-region: drag"> <h3>Frameless Window in Electron</h3><button id="transparent" style="-webkit-app-region: no-drag;"> Create a Frameless Transparent Window</button><!-- Adding Individual Renderer Process JS File --><script src="index.js"></script></body>
index.js: The Create a Frameless Transparent Window button does not have any functionality associated with it yet. To change this, add the following code in the index.js file.
javascript
const electron = require('electron')// Import BrowserWindow using Electron remoteconst BrowserWindow = electron.remote.BrowserWindow;// let win = BrowserWindow.getAllWindows()[0]; var transparent = document.getElementById('transparent');transparent.addEventListener('click', (event) => { const win = new BrowserWindow({ width: 800, height: 600, frame: false, webPreferences: { nodeIntegration: true }, transparent: true, }); win.show();});
Explanation: To create a Transparent window in Electron, the transparent: true property is set in the options of the BrowserWindow Instance. These transparent windows can be used for loading external scripts, perform background processes, and additional computation tasks. However, as of v8.3.0 of Electron, there are certain limitations that are associated with transparent windows. Some of the more important limitations are listed below:
We cannot click through transparent windows.
Transparent windows are not resizable. Setting the resizable: true property in the options of the BrowserWindow Instance makes the transparent windows stop working on some OS environments.
We cannot apply the blur filter to the contents below the Transparent window since it can only be applied to the webpage itself and hence the contents below the transparent window will be clearly visible. As mentioned above, we will not be able to click through the transparent window as well. This has been demonstrated in the output as well.
To get the current BrowserWindow Instance in the Renderer Process, we can use some Static Methods provided by the BrowserWindow object.
BrowserWindow.getAllWindows(): This method returns an Array of active/opened BrowserWindow Instances. In this application, we have only one active BrowserWindow Instance and it can be directly referred from the Array as shown in the code.
BrowserWindow.getFocusedWindow(): This method returns the BrowserWindow Instance which is focused in the Application. If no current BrowserWindow Instance is found, it returns null. In this application, we only have one active BrowserWindow Instance and it can be directly referred to using this method as shown in the code.
At this point, upon launching the Electron application, we should be able to activate a Transparent window in the application. Output:
Note: While creating Transparent windows, when we specify the transparent: true property in the options but also at the same time use the win.loadFile(filepath) or win.loadURL(url) Instance methods of the BrowserWindow object, the Instance methods take precendence and the respective windows with the content are loaded into the application. However, in the case of the win.loadFile(filepath) Instance method, only the content of the file without any background is loaded into the application. This can also be used to enhance the GUI of the application. Refer the Output below for a better understanding. Output:
anikaseth98
ElectronJS
HTML
JavaScript
Node.js
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to update Node.js and NPM to next version ?
REST API (Introduction)
CSS to put icon inside an input element in a form
Types of CSS (Cascading Style Sheet)
Design a Tribute Page using HTML & CSS
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
Difference Between PUT and PATCH Request
How to append HTML code to a div using JavaScript ? | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n12 Dec, 2021"
},
{
"code": null,
"e": 328,
"s": 28,
"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": 1535,
"s": 328,
"text": "In a complex desktop application, a situation might occur wherein the developers may have to carry out additional background processes and computational tasks in parallel frames without interrupting the user experience. These background processes running within parallel frames should not be visible to the user as additional GUI windows but should be activated accordingly whenever the need arises. We can see this behavior in many modern desktop applications such as the Google Chrome web browser. Additionally, the developers might want to restrict the user to a specific frame with limited functionality such as when displaying a License Agreement or Terms & Conditions window. In such windows, the Title Bar, Navigational Bar, Context Menus are disabled and the user should not be able to close/skip/minimize the window frame. Electron provides us with a way by which we can open a window without toolbars, borders, or any other graphical components or make the entire window transparent using the properties in options of a new BrowserWindow object. Such windows are known as Frameless windows in Electron. This tutorial will demonstrate how to create and features of a Frameless window in Electron. "
},
{
"code": null,
"e": 1705,
"s": 1535,
"text": "We assume that you are familiar with the prerequisites as covered in the above-mentioned link. For Electron to work, node and npm need to be pre-installed in the system."
},
{
"code": null,
"e": 1726,
"s": 1705,
"text": "Project Structure: "
},
{
"code": null,
"e": 2200,
"s": 1726,
"text": "Example: Follow the Steps given in Dynamic Styling in ElectronJS to set up the basic Electron Application. Copy the Boilerplate code for the main.js file and the index.html file as provided in the article. Also, perform the necessary changes mentioned for the package.json file to launch the Electron Application. We will continue building our application using the same code base. The basic steps required to set up the Electron application remain the same. package.json: "
},
{
"code": null,
"e": 2509,
"s": 2200,
"text": "{\n \"name\": \"electron-frameless\",\n \"version\": \"1.0.0\",\n \"description\": \"Frameless Window in Electron\",\n \"main\": \"main.js\",\n \"scripts\": {\n \"start\": \"electron .\"\n },\n \"keywords\": [\n \"electron\"\n ],\n \"author\": \"Radhesh Khanna\",\n \"license\": \"ISC\",\n \"dependencies\": {\n \"electron\": \"^8.3.0\"\n }\n}"
},
{
"code": null,
"e": 2518,
"s": 2509,
"text": "Output: "
},
{
"code": null,
"e": 3009,
"s": 2518,
"text": "Frameless Window in Electron: The BrowserWindow Instance is part of the Main Process. To import and use BrowserWindow in the Renderer Process, we will be using Electron remote module. A frameless window is a window that has no chrome. Chrome is any visible aspect of a window aside from the webpages themselves (e.g., toolbars, menu bar, borders, etc). We can define a BrowserWindow Instance as a Frameless or a Transparent window by specifying the properties of the BrowserWindow object. "
},
{
"code": null,
"e": 3061,
"s": 3009,
"text": "index.html: Add the following snippet in that file."
},
{
"code": null,
"e": 3066,
"s": 3061,
"text": "html"
},
{
"code": "<body style=\"-webkit-app-region: drag\"> <h3>Frameless Window in Electron</h3> <button id=\"frame\" style=\"-webkit-app-region: no-drag;\"> Create a Frameless Window </button> <br><br> <button id=\"frameless\" style=\"-webkit-app-region: no-drag;\"> Create a Frameless Draggable Window </button> <br><br><!-- Adding Individual Renderer Process JS File --><script src=\"index.js\"></script></body>",
"e": 3468,
"s": 3066,
"text": null
},
{
"code": null,
"e": 3674,
"s": 3468,
"text": "index.js: The Create a Frameless Window and Create a Frameless Draggable Window buttons do not have any functionality associated with them yet. To change this, add the following code in the index.js file."
},
{
"code": null,
"e": 3685,
"s": 3674,
"text": "javascript"
},
{
"code": "const electron = require('electron')// Import BrowserWindow using Electron remoteconst BrowserWindow = electron.remote.BrowserWindow;// let win = BrowserWindow.getAllWindows()[0]; var frame = document.getElementById('frame');frame.addEventListener('click', (event) => { const win = new BrowserWindow({ width: 800, height: 600, // Creating a Frameless Window frame: false, webPreferences: { nodeIntegration: true } }); win.loadURL('https://www.google.com/');}); var frameless = document.getElementById('frameless');frameless.addEventListener('click', (event) => { const win = new BrowserWindow({ width: 800, height: 600, frame: false, webPreferences: { nodeIntegration: true } }); win.loadFile('src/index.html'); win.show();});",
"e": 4532,
"s": 3685,
"text": null
},
{
"code": null,
"e": 5608,
"s": 4532,
"text": "To create a Frameless window in Electron, the frame: false property is set in the options of the BrowserWindow Instance. By setting this property, only the webpage itself will be visible to the user without any additional chrome or GUI components. Refer to the output for a better understanding. By default, the frameless window is non-draggable. Applications need to specify the -webkit-app-region: drag CSS property to tell Electron which regions are draggable. To make the whole window draggable, this CSS property is set to the style of the body tag in HTML. Applications can also use -webkit-app-region: no-drag CSS property to indicate the non-draggable area. Once we have defined a frameless window, we can customize it to our look and feel and provide a custom titlebar along with custom window controls. Note β When the -webkit-app-region: drag CSS property is set to the body tag, we need to set -webkit-app-region: no-drag CSS property to the Buttons or any clickable components within the window. Else, we will not be able to click on those clickable components. "
},
{
"code": null,
"e": 5995,
"s": 5608,
"text": "Note: Sometimes in Frameless windows, the dragging behavior may conflict with the text selection. For example, when dragging a window via the title bar, we may accidentally select the text on the title bar. This occurs when the size of the custom title bar is especially small. To prevent this we need to disable the text selection by using the -webkit-user-select: none; CSS property. "
},
{
"code": null,
"e": 7049,
"s": 5995,
"text": "Note: As of v8.3.0 of Electron, only rectangular shapes are currently supported for draggable regions. Also, -webkit-app-region: drag CSS property is known to have problems while the Chrome Dev tools are open. Note β In some environments, the draggable region within a window can be treated as a non-client frame. This means that whenever we right-click on the draggable region, the system context menu may open. To make the context menu behave correctly, we should never use a custom context menu on draggable regions. The frame: false property of the BrowserWindow Instance is supported on all OS platforms. Additionally, in macOS, we have some more properties to define chromeless windows instead of the frame property. If we use the frame property in macOS, it disables the titlebar and the windows controls (a.k.a traffic lights in macOS). Instead, we can use the titleBarStyle property in the options of the BrowserWindow Instance to hide the titlebar and make the content extend the entire window size while still preserving the window controls. "
},
{
"code": null,
"e": 7250,
"s": 7049,
"text": "titleBarStyle: βhiddenβ This property hides the titlebar, makes the content extend the full size of the window, yet still displays the windows controls in the top-left corner of the chromeless window."
},
{
"code": null,
"e": 7438,
"s": 7250,
"text": "titleBarStyle: βhiddenInsetβ This property hides the titlebar but provides an alternative look wherein the windows controls are slightly more inset from the edge of the chromeless window."
},
{
"code": null,
"e": 7687,
"s": 7438,
"text": "titleBarStyle: βcustomButtonsOnHoverβ This property uses miniature buttons as windows controls and displays a custom drawer on hover near the top-left of the chromeless window. This property can only be used together with the frame: false property."
},
{
"code": null,
"e": 8041,
"s": 7687,
"text": "At this point, upon launching the Electron application, we should be able to activate a Frameless window and a Frameless draggable window in the application. In this tutorial, we have loaded an external website in the frameless window and the index.html file once again in the frameless draggable window respectively for demonstration purposes. Output: "
},
{
"code": null,
"e": 8224,
"s": 8041,
"text": "index.html: Now we will see how to make a frameless window completely transparent in the application and see some of the features and limitations of a Transparent window in Electron."
},
{
"code": null,
"e": 8229,
"s": 8224,
"text": "html"
},
{
"code": "<body style=\"-webkit-app-region: drag\"> <h3>Frameless Window in Electron</h3><button id=\"transparent\" style=\"-webkit-app-region: no-drag;\"> Create a Frameless Transparent Window</button><!-- Adding Individual Renderer Process JS File --><script src=\"index.js\"></script></body>",
"e": 8509,
"s": 8229,
"text": null
},
{
"code": null,
"e": 8685,
"s": 8509,
"text": "index.js: The Create a Frameless Transparent Window button does not have any functionality associated with it yet. To change this, add the following code in the index.js file."
},
{
"code": null,
"e": 8696,
"s": 8685,
"text": "javascript"
},
{
"code": "const electron = require('electron')// Import BrowserWindow using Electron remoteconst BrowserWindow = electron.remote.BrowserWindow;// let win = BrowserWindow.getAllWindows()[0]; var transparent = document.getElementById('transparent');transparent.addEventListener('click', (event) => { const win = new BrowserWindow({ width: 800, height: 600, frame: false, webPreferences: { nodeIntegration: true }, transparent: true, }); win.show();});",
"e": 9198,
"s": 8696,
"text": null
},
{
"code": null,
"e": 9642,
"s": 9198,
"text": "Explanation: To create a Transparent window in Electron, the transparent: true property is set in the options of the BrowserWindow Instance. These transparent windows can be used for loading external scripts, perform background processes, and additional computation tasks. However, as of v8.3.0 of Electron, there are certain limitations that are associated with transparent windows. Some of the more important limitations are listed below: "
},
{
"code": null,
"e": 9687,
"s": 9642,
"text": "We cannot click through transparent windows."
},
{
"code": null,
"e": 9876,
"s": 9687,
"text": "Transparent windows are not resizable. Setting the resizable: true property in the options of the BrowserWindow Instance makes the transparent windows stop working on some OS environments."
},
{
"code": null,
"e": 10220,
"s": 9876,
"text": "We cannot apply the blur filter to the contents below the Transparent window since it can only be applied to the webpage itself and hence the contents below the transparent window will be clearly visible. As mentioned above, we will not be able to click through the transparent window as well. This has been demonstrated in the output as well."
},
{
"code": null,
"e": 10357,
"s": 10220,
"text": "To get the current BrowserWindow Instance in the Renderer Process, we can use some Static Methods provided by the BrowserWindow object. "
},
{
"code": null,
"e": 10596,
"s": 10357,
"text": "BrowserWindow.getAllWindows(): This method returns an Array of active/opened BrowserWindow Instances. In this application, we have only one active BrowserWindow Instance and it can be directly referred from the Array as shown in the code."
},
{
"code": null,
"e": 10923,
"s": 10596,
"text": "BrowserWindow.getFocusedWindow(): This method returns the BrowserWindow Instance which is focused in the Application. If no current BrowserWindow Instance is found, it returns null. In this application, we only have one active BrowserWindow Instance and it can be directly referred to using this method as shown in the code. "
},
{
"code": null,
"e": 11059,
"s": 10923,
"text": "At this point, upon launching the Electron application, we should be able to activate a Transparent window in the application. Output: "
},
{
"code": null,
"e": 11674,
"s": 11059,
"text": "Note: While creating Transparent windows, when we specify the transparent: true property in the options but also at the same time use the win.loadFile(filepath) or win.loadURL(url) Instance methods of the BrowserWindow object, the Instance methods take precendence and the respective windows with the content are loaded into the application. However, in the case of the win.loadFile(filepath) Instance method, only the content of the file without any background is loaded into the application. This can also be used to enhance the GUI of the application. Refer the Output below for a better understanding. Output: "
},
{
"code": null,
"e": 11688,
"s": 11676,
"text": "anikaseth98"
},
{
"code": null,
"e": 11699,
"s": 11688,
"text": "ElectronJS"
},
{
"code": null,
"e": 11704,
"s": 11699,
"text": "HTML"
},
{
"code": null,
"e": 11715,
"s": 11704,
"text": "JavaScript"
},
{
"code": null,
"e": 11723,
"s": 11715,
"text": "Node.js"
},
{
"code": null,
"e": 11740,
"s": 11723,
"text": "Web Technologies"
},
{
"code": null,
"e": 11745,
"s": 11740,
"text": "HTML"
},
{
"code": null,
"e": 11843,
"s": 11745,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 11891,
"s": 11843,
"text": "How to update Node.js and NPM to next version ?"
},
{
"code": null,
"e": 11915,
"s": 11891,
"text": "REST API (Introduction)"
},
{
"code": null,
"e": 11965,
"s": 11915,
"text": "CSS to put icon inside an input element in a form"
},
{
"code": null,
"e": 12002,
"s": 11965,
"text": "Types of CSS (Cascading Style Sheet)"
},
{
"code": null,
"e": 12041,
"s": 12002,
"text": "Design a Tribute Page using HTML & CSS"
},
{
"code": null,
"e": 12102,
"s": 12041,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 12174,
"s": 12102,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 12214,
"s": 12174,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 12255,
"s": 12214,
"text": "Difference Between PUT and PATCH Request"
}
] |
pthread_cancel() in C with example | 06 Sep, 2017
prerequisite: Multithreading, pthread_self() in C with Example
pthread_cancel() = This function cancel a particular thread using thread id. This function send a cancellation request to the thread.
Syntax : β int pthread_cancel(pthread_t thread);
First Program : β Cancel self thread
// C program to demonstrates cancellation of self thread // using thread id#include <stdio.h>#include <stdlib.h>#include <pthread.h> void* calls(void* ptr){ printf("GeeksForGeeks"); // To exit the current thread // pthread_self() return the particular thread id pthread_cancel(pthread_self()); return NULL;} int main(){ // NULL when no attribute pthread_t thread; // calls is a function name pthread_create(&thread, NULL, calls, NULL); // Waiting for when thread is completed pthread_join(thread, NULL); return 0;}
Output:
GeeksForGeeks
If you use Linux then compile this program gcc program_name.c -lpthread
Second Program : β Cancel other thread
// C program to demonstrates cancellation of another thread // using thread id#include <stdio.h>#include <unistd.h>#include <sys/types.h>#include <pthread.h> // To Countint counter = 0; // for temporary thread which will be // store thread id of second threadpthread_t tmp_thread; // thread_one call funcvoid* func(void* p) { while (1) { printf("thread number one\n"); sleep(1); // sleep 1 second counter++; // for exiting if counter = = 5 if (counter = = 2) { // for cancel thread_two pthread_cancel(tmp_thread); // for exit from thread_one pthread_exit(NULL); } }} // thread_two call func2void* func2(void* p) { // store thread_two id to tmp_thread tmp_thread = pthread_self(); while (1) { printf("thread Number two"); sleep(1); // sleep 1 second }} // Driver codeint main(){ // declare two thread pthread_t thread_one, thread_two; // create thread_one pthread_create(&thread_one, NULL, func, NULL); // create thread_two pthread_create(&thread_two, NULL, func2, NULL); // waiting for when thread_one is completed pthread_join(thread_one, NULL); // waiting for when thread_two is completed pthread_join(thread_two, NULL); }
Output:
thread number one
thread number two
thread number one
thread number two
If you use Linux then compile this program gcc program_name.c -lpthread
This article is contributed by Devanshu Agarwal. 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.
C-Library
C Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Substring in C++
Function Pointer in C
Multidimensional Arrays in C / C++
Left Shift and Right Shift Operators in C/C++
Different Methods to Reverse a String in C++
std::string class in C++
Unordered Sets in C++ Standard Template Library
rand() and srand() in C/C++
Enumeration (or enum) in C
What is the purpose of a function prototype? | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n06 Sep, 2017"
},
{
"code": null,
"e": 117,
"s": 54,
"text": "prerequisite: Multithreading, pthread_self() in C with Example"
},
{
"code": null,
"e": 251,
"s": 117,
"text": "pthread_cancel() = This function cancel a particular thread using thread id. This function send a cancellation request to the thread."
},
{
"code": null,
"e": 300,
"s": 251,
"text": "Syntax : β int pthread_cancel(pthread_t thread);"
},
{
"code": null,
"e": 337,
"s": 300,
"text": "First Program : β Cancel self thread"
},
{
"code": "// C program to demonstrates cancellation of self thread // using thread id#include <stdio.h>#include <stdlib.h>#include <pthread.h> void* calls(void* ptr){ printf(\"GeeksForGeeks\"); // To exit the current thread // pthread_self() return the particular thread id pthread_cancel(pthread_self()); return NULL;} int main(){ // NULL when no attribute pthread_t thread; // calls is a function name pthread_create(&thread, NULL, calls, NULL); // Waiting for when thread is completed pthread_join(thread, NULL); return 0;}",
"e": 909,
"s": 339,
"text": null
},
{
"code": null,
"e": 917,
"s": 909,
"text": "Output:"
},
{
"code": null,
"e": 932,
"s": 917,
"text": "GeeksForGeeks\n"
},
{
"code": null,
"e": 1006,
"s": 934,
"text": "If you use Linux then compile this program gcc program_name.c -lpthread"
},
{
"code": null,
"e": 1045,
"s": 1006,
"text": "Second Program : β Cancel other thread"
},
{
"code": "// C program to demonstrates cancellation of another thread // using thread id#include <stdio.h>#include <unistd.h>#include <sys/types.h>#include <pthread.h> // To Countint counter = 0; // for temporary thread which will be // store thread id of second threadpthread_t tmp_thread; // thread_one call funcvoid* func(void* p) { while (1) { printf(\"thread number one\\n\"); sleep(1); // sleep 1 second counter++; // for exiting if counter = = 5 if (counter = = 2) { // for cancel thread_two pthread_cancel(tmp_thread); // for exit from thread_one pthread_exit(NULL); } }} // thread_two call func2void* func2(void* p) { // store thread_two id to tmp_thread tmp_thread = pthread_self(); while (1) { printf(\"thread Number two\"); sleep(1); // sleep 1 second }} // Driver codeint main(){ // declare two thread pthread_t thread_one, thread_two; // create thread_one pthread_create(&thread_one, NULL, func, NULL); // create thread_two pthread_create(&thread_two, NULL, func2, NULL); // waiting for when thread_one is completed pthread_join(thread_one, NULL); // waiting for when thread_two is completed pthread_join(thread_two, NULL); }",
"e": 2371,
"s": 1047,
"text": null
},
{
"code": null,
"e": 2379,
"s": 2371,
"text": "Output:"
},
{
"code": null,
"e": 2453,
"s": 2379,
"text": "thread number one\nthread number two\nthread number one \nthread number two\n"
},
{
"code": null,
"e": 2527,
"s": 2455,
"text": "If you use Linux then compile this program gcc program_name.c -lpthread"
},
{
"code": null,
"e": 2831,
"s": 2527,
"text": "This article is contributed by Devanshu Agarwal. 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": 2956,
"s": 2831,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 2966,
"s": 2956,
"text": "C-Library"
},
{
"code": null,
"e": 2977,
"s": 2966,
"text": "C Language"
},
{
"code": null,
"e": 3075,
"s": 2977,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3092,
"s": 3075,
"text": "Substring in C++"
},
{
"code": null,
"e": 3114,
"s": 3092,
"text": "Function Pointer in C"
},
{
"code": null,
"e": 3149,
"s": 3114,
"text": "Multidimensional Arrays in C / C++"
},
{
"code": null,
"e": 3195,
"s": 3149,
"text": "Left Shift and Right Shift Operators in C/C++"
},
{
"code": null,
"e": 3240,
"s": 3195,
"text": "Different Methods to Reverse a String in C++"
},
{
"code": null,
"e": 3265,
"s": 3240,
"text": "std::string class in C++"
},
{
"code": null,
"e": 3313,
"s": 3265,
"text": "Unordered Sets in C++ Standard Template Library"
},
{
"code": null,
"e": 3341,
"s": 3313,
"text": "rand() and srand() in C/C++"
},
{
"code": null,
"e": 3368,
"s": 3341,
"text": "Enumeration (or enum) in C"
}
] |
Program for Next Fit algorithm in Memory Management | 25 Apr, 2022
Prerequisite: Partition allocation methods What is Next Fit ? Next fit is a modified version of βfirst fitβ. It begins as the first fit to find a free partition but when called next time it starts searching from where it left off, not from the beginning. This policy makes use of a roving pointer. The pointer moves along the memory chain to search for a next fit. This helps in, to avoid the usage of memory always from the head (beginning) of the free block chain. What are its advantage over first fit ?
First fit is a straight and fast algorithm, but tends to cut large portion of free parts into small pieces due to which, processes that need a large portion of memory block would not get anything even if the sum of all small pieces is greater than it required which is so-called external fragmentation problem.
Another problem of the first fit is that it tends to allocate memory parts at the beginning of the memory, which may lead to more internal fragments at the beginning. Next fit tries to address this problem by starting the search for the free portion of parts not from the start of the memory, but from where it ends last time.
Next fit is a very fast searching algorithm and is also comparatively faster than First Fit and Best Fit Memory Management Algorithms.
Example:
Input : blockSize[] = {5, 10, 20};
processSize[] = {10, 20, 30};
Output:
Process No. Process Size Block no.
1 10 2
2 20 3
3 30 Not Allocated
Algorithm:
Input the number of memory blocks and their sizes and initializes all the blocks as free.Input the number of processes and their sizes.Start by picking each process and check if it can be assigned to the current block, if yes, allocate it the required memory and check for next process but from the block where we left not from starting.If the current block size is smaller then keep checking the further blocks.
Input the number of memory blocks and their sizes and initializes all the blocks as free.
Input the number of processes and their sizes.
Start by picking each process and check if it can be assigned to the current block, if yes, allocate it the required memory and check for next process but from the block where we left not from starting.
If the current block size is smaller then keep checking the further blocks.
C++
Java
Python3
C#
PHP
Javascript
// C/C++ program for next fit// memory management algorithm#include <bits/stdc++.h>using namespace std; // Function to allocate memory to blocks as per Next fit// algorithmvoid NextFit(int blockSize[], int m, int processSize[], int n){ // Stores block id of the block allocated to a // process int allocation[n], j = 0; // Initially no block is assigned to any process memset(allocation, -1, sizeof(allocation)); // pick each process and find suitable blocks // according to its size ad assign to it for (int i = 0; i < n; i++) { // Do not start from beginning while (j < m) { if (blockSize[j] >= processSize[i]) { // allocate block j to p[i] process allocation[i] = j; // Reduce available memory in this block. blockSize[j] -= processSize[i]; break; } // mod m will help in traversing the blocks from // starting block after we reach the end. j = (j + 1) % m; } } cout << "\nProcess No.\tProcess Size\tBlock no.\n"; for (int i = 0; i < n; i++) { cout << " " << i + 1 << "\t\t" << processSize[i] << "\t\t"; if (allocation[i] != -1) cout << allocation[i] + 1; else cout << "Not Allocated"; cout << endl; }} // Driver programint main(){ int blockSize[] = { 5, 10, 20 }; int processSize[] = { 10, 20, 5 }; int m = sizeof(blockSize) / sizeof(blockSize[0]); int n = sizeof(processSize) / sizeof(processSize[0]); NextFit(blockSize, m, processSize, n); return 0;}
// Java program for next fit// memory management algorithmimport java.util.Arrays; public class GFG { // Function to allocate memory to blocks as per Next fit// algorithm static void NextFit(int blockSize[], int m, int processSize[], int n) { // Stores block id of the block allocated to a // process int allocation[] = new int[n], j = 0; // Initially no block is assigned to any process Arrays.fill(allocation, -1); // pick each process and find suitable blocks // according to its size ad assign to it for (int i = 0; i < n; i++) { // Do not start from beginning int count =0; while (j < m) { count++; //makes sure that for every process we traverse through entire array maximum once only.This avoids the problem of going into infinite loop if memory is not available if (blockSize[j] >= processSize[i]) { // allocate block j to p[i] process allocation[i] = j; // Reduce available memory in this block. blockSize[j] -= processSize[i]; break; } // mod m will help in traversing the blocks from // starting block after we reach the end. j = (j + 1) % m; } } System.out.print("\nProcess No.\tProcess Size\tBlock no.\n"); for (int i = 0; i < n; i++) { System.out.print( i + 1 + "\t\t" + processSize[i] + "\t\t"); if (allocation[i] != -1) { System.out.print(allocation[i] + 1); } else { System.out.print("Not Allocated"); } System.out.println(""); } } // Driver program static public void main(String[] args) { int blockSize[] = {5, 10, 20}; int processSize[] = {10, 20, 5}; int m = blockSize.length; int n = processSize.length; NextFit(blockSize, m, processSize, n); }} // This code is contributed by Rajput-Ji
# Python3 program for next fit# memory management algorithm # Function to allocate memory to# blocks as per Next fit algorithmdef NextFit(blockSize, m, processSize, n): # Stores block id of the block # allocated to a process # Initially no block is assigned # to any process allocation = [-1] * n j = 0 t = m-1 # pick each process and find suitable blocks # according to its size ad assign to it for i in range(n): # Do not start from beginning while j < m: if blockSize[j] >= processSize[i]: # allocate block j to p[i] process allocation[i] = j # Reduce available memory in this block. blockSize[j] -= processSize[i] # sets a new end point t = (j - 1) % m break if t == j: # sets a new end point t = (j - 1) % m # breaks the loop after going through all memory block break # mod m will help in traversing the # blocks from starting block after # we reach the end. j = (j + 1) % m print("Process No. Process Size Block no.") for i in range(n): print(i + 1, " ", processSize[i],end = " ") if allocation[i] != -1: print(allocation[i] + 1) else: print("Not Allocated") # Driver Codeif __name__ == '__main__': blockSize = [5, 10, 20] processSize = [10, 20, 5] m = len(blockSize) n = len(processSize) NextFit(blockSize, m, processSize, n)
// C# program for next fit// memory management algorithmusing System;using System.Linq;public class GFG { // Function to allocate memory to blocks as per Next fit// algorithm static void NextFit(int []blockSize, int m, int []processSize, int n) { // Stores block id of the block allocated to a // process int []allocation = new int[n]; int j = 0; // Initially no block is assigned to any process Enumerable.Repeat(-1, n).ToArray(); // pick each process and find suitable blocks // according to its size ad assign to it for (int i = 0; i < n; i++) { // Do not start from beginning while (j < m) { if (blockSize[j] >= processSize[i]) { // allocate block j to p[i] process allocation[i] = j; // Reduce available memory in this block. blockSize[j] -= processSize[i]; break; } // mod m will help in traversing the blocks from // starting block after we reach the end. j = (j + 1) % m; } } Console.Write("\nProcess No.\tProcess Size\tBlock no.\n"); for (int i = 0; i < n; i++) { Console.Write( i + 1 + "\t\t" + processSize[i] + "\t\t"); if (allocation[i] != -1) { Console.Write(allocation[i] + 1); } else { Console.Write("Not Allocated"); } Console.WriteLine(""); } } // Driver program static public void Main() { int []blockSize = {5, 10, 20}; int []processSize = {10, 20, 5}; int m = blockSize.Length; int n = processSize.Length; NextFit(blockSize, m, processSize, n); }} /*This code is contributed by Rajput-Ji*/
<?php// PHP program for next fit// memory management algorithm // Function to allocate memory to blocks as per Next fit// algorithmfunction NextFit($blockSize, $m, $processSize, $n){ // Stores block id of the block allocated to a // process $allocation = array_fill(0, $n, -1); $j = 0; // Initially no block is assigned to any process above // pick each process and find suitable blocks // according to its size ad assign to it for ($i = 0; $i < $n; $i++) { // Do not start from beginning while ($j < $m) { if ($blockSize[$j] >= $processSize[$i]) { // allocate block j to p[i] process $allocation[$i] = $j; // Reduce available memory in this block. $blockSize[$j] -= $processSize[$i]; break; } // mod m will help in traversing the blocks from // starting block after we reach the end. $j = ($j + 1) % $m; } } echo "\nProcess No.\tProcess Size\tBlock no.\n"; for ($i = 0; $i < $n; $i++) { echo " ".($i + 1)."\t\t".$processSize[$i]."\t\t"; if ($allocation[$i] != -1) echo ($allocation[$i] + 1); else echo "Not Allocated"; echo "\n"; }} // Driver program $blockSize = array( 5, 10, 20 ); $processSize = array( 10, 20, 5 ); $m = count($blockSize); $n = count($processSize); NextFit($blockSize, $m, $processSize, $n); // This code is contributed by mits?>
<script> // JavaScript program for next fit// memory management algorithm // Function to allocate memory to blocks as per Next fit// algorithm function NextFit(blockSize, m, processSize, n) { // Stores block id of the block allocated to a // process let allocation = Array.from({length: n}, (_, i) => -1), j = 0; // pick each process and find suitable blocks // according to its size ad assign to it for (let i = 0; i < n; i++) { // Do not start from beginning while (j < m) { if (blockSize[j] >= processSize[i]) { // allocate block j to p[i] process allocation[i] = j; // Reduce available memory in this block. blockSize[j] -= processSize[i]; break; } // mod m will help in traversing the blocks from // starting block after we reach the end. j = (j + 1) % m; } } document.write("\nProcess No. Process Size. Block no." + "<br/>"); for (let i = 0; i < n; i++) { document.write( i + 1 + Array(20).fill('\xa0').join('') + processSize[i] + Array(20).fill('\xa0').join('')); if (allocation[i] != -1) { document.write(allocation[i] + 1); } else { document.write("Not Allocated"); } document.write("<br/>"); } } // Driver Code let blockSize = [5, 10, 20]; let processSize = [10, 20, 5]; let m = blockSize.length; let n = processSize.length; NextFit(blockSize, m, processSize, n); // This code is contributed by susmitakundugoaldanga.</script>
Process No. Process Size Block no.
1 10 2
2 20 3
3 5 1
This article is contributed by Akash Gupta. 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.
ishita_thakkar
Rajput-Ji
PranchalKatiyar
Akanksha_Rai
Mithun Kumar
susmitakundugoaldanga
vidulamagdum12
dhruvmillu
Greedy
Operating Systems
Operating Systems
Greedy
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Huffman Coding | Greedy Algo-3
Coin Change | DP-7
Activity Selection Problem | Greedy Algo-1
Fractional Knapsack Problem
Job Sequencing Problem
Types of Operating Systems
Banker's Algorithm in Operating System
Disk Scheduling Algorithms
Introduction of Deadlock in Operating System
Inter Process Communication (IPC) | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n25 Apr, 2022"
},
{
"code": null,
"e": 563,
"s": 54,
"text": "Prerequisite: Partition allocation methods What is Next Fit ? Next fit is a modified version of βfirst fitβ. It begins as the first fit to find a free partition but when called next time it starts searching from where it left off, not from the beginning. This policy makes use of a roving pointer. The pointer moves along the memory chain to search for a next fit. This helps in, to avoid the usage of memory always from the head (beginning) of the free block chain. What are its advantage over first fit ? "
},
{
"code": null,
"e": 874,
"s": 563,
"text": "First fit is a straight and fast algorithm, but tends to cut large portion of free parts into small pieces due to which, processes that need a large portion of memory block would not get anything even if the sum of all small pieces is greater than it required which is so-called external fragmentation problem."
},
{
"code": null,
"e": 1201,
"s": 874,
"text": "Another problem of the first fit is that it tends to allocate memory parts at the beginning of the memory, which may lead to more internal fragments at the beginning. Next fit tries to address this problem by starting the search for the free portion of parts not from the start of the memory, but from where it ends last time."
},
{
"code": null,
"e": 1336,
"s": 1201,
"text": "Next fit is a very fast searching algorithm and is also comparatively faster than First Fit and Best Fit Memory Management Algorithms."
},
{
"code": null,
"e": 1582,
"s": 1338,
"text": "Example:\nInput : blockSize[] = {5, 10, 20};\n processSize[] = {10, 20, 30};\nOutput:\nProcess No. Process Size Block no.\n 1 10 2\n 2 20 3\n 3 30 Not Allocated"
},
{
"code": null,
"e": 1597,
"s": 1584,
"text": "Algorithm: "
},
{
"code": null,
"e": 2010,
"s": 1597,
"text": "Input the number of memory blocks and their sizes and initializes all the blocks as free.Input the number of processes and their sizes.Start by picking each process and check if it can be assigned to the current block, if yes, allocate it the required memory and check for next process but from the block where we left not from starting.If the current block size is smaller then keep checking the further blocks."
},
{
"code": null,
"e": 2100,
"s": 2010,
"text": "Input the number of memory blocks and their sizes and initializes all the blocks as free."
},
{
"code": null,
"e": 2147,
"s": 2100,
"text": "Input the number of processes and their sizes."
},
{
"code": null,
"e": 2350,
"s": 2147,
"text": "Start by picking each process and check if it can be assigned to the current block, if yes, allocate it the required memory and check for next process but from the block where we left not from starting."
},
{
"code": null,
"e": 2426,
"s": 2350,
"text": "If the current block size is smaller then keep checking the further blocks."
},
{
"code": null,
"e": 2434,
"s": 2430,
"text": "C++"
},
{
"code": null,
"e": 2439,
"s": 2434,
"text": "Java"
},
{
"code": null,
"e": 2447,
"s": 2439,
"text": "Python3"
},
{
"code": null,
"e": 2450,
"s": 2447,
"text": "C#"
},
{
"code": null,
"e": 2454,
"s": 2450,
"text": "PHP"
},
{
"code": null,
"e": 2465,
"s": 2454,
"text": "Javascript"
},
{
"code": "// C/C++ program for next fit// memory management algorithm#include <bits/stdc++.h>using namespace std; // Function to allocate memory to blocks as per Next fit// algorithmvoid NextFit(int blockSize[], int m, int processSize[], int n){ // Stores block id of the block allocated to a // process int allocation[n], j = 0; // Initially no block is assigned to any process memset(allocation, -1, sizeof(allocation)); // pick each process and find suitable blocks // according to its size ad assign to it for (int i = 0; i < n; i++) { // Do not start from beginning while (j < m) { if (blockSize[j] >= processSize[i]) { // allocate block j to p[i] process allocation[i] = j; // Reduce available memory in this block. blockSize[j] -= processSize[i]; break; } // mod m will help in traversing the blocks from // starting block after we reach the end. j = (j + 1) % m; } } cout << \"\\nProcess No.\\tProcess Size\\tBlock no.\\n\"; for (int i = 0; i < n; i++) { cout << \" \" << i + 1 << \"\\t\\t\" << processSize[i] << \"\\t\\t\"; if (allocation[i] != -1) cout << allocation[i] + 1; else cout << \"Not Allocated\"; cout << endl; }} // Driver programint main(){ int blockSize[] = { 5, 10, 20 }; int processSize[] = { 10, 20, 5 }; int m = sizeof(blockSize) / sizeof(blockSize[0]); int n = sizeof(processSize) / sizeof(processSize[0]); NextFit(blockSize, m, processSize, n); return 0;}",
"e": 4100,
"s": 2465,
"text": null
},
{
"code": "// Java program for next fit// memory management algorithmimport java.util.Arrays; public class GFG { // Function to allocate memory to blocks as per Next fit// algorithm static void NextFit(int blockSize[], int m, int processSize[], int n) { // Stores block id of the block allocated to a // process int allocation[] = new int[n], j = 0; // Initially no block is assigned to any process Arrays.fill(allocation, -1); // pick each process and find suitable blocks // according to its size ad assign to it for (int i = 0; i < n; i++) { // Do not start from beginning int count =0; while (j < m) { count++; //makes sure that for every process we traverse through entire array maximum once only.This avoids the problem of going into infinite loop if memory is not available if (blockSize[j] >= processSize[i]) { // allocate block j to p[i] process allocation[i] = j; // Reduce available memory in this block. blockSize[j] -= processSize[i]; break; } // mod m will help in traversing the blocks from // starting block after we reach the end. j = (j + 1) % m; } } System.out.print(\"\\nProcess No.\\tProcess Size\\tBlock no.\\n\"); for (int i = 0; i < n; i++) { System.out.print( i + 1 + \"\\t\\t\" + processSize[i] + \"\\t\\t\"); if (allocation[i] != -1) { System.out.print(allocation[i] + 1); } else { System.out.print(\"Not Allocated\"); } System.out.println(\"\"); } } // Driver program static public void main(String[] args) { int blockSize[] = {5, 10, 20}; int processSize[] = {10, 20, 5}; int m = blockSize.length; int n = processSize.length; NextFit(blockSize, m, processSize, n); }} // This code is contributed by Rajput-Ji",
"e": 6184,
"s": 4100,
"text": null
},
{
"code": "# Python3 program for next fit# memory management algorithm # Function to allocate memory to# blocks as per Next fit algorithmdef NextFit(blockSize, m, processSize, n): # Stores block id of the block # allocated to a process # Initially no block is assigned # to any process allocation = [-1] * n j = 0 t = m-1 # pick each process and find suitable blocks # according to its size ad assign to it for i in range(n): # Do not start from beginning while j < m: if blockSize[j] >= processSize[i]: # allocate block j to p[i] process allocation[i] = j # Reduce available memory in this block. blockSize[j] -= processSize[i] # sets a new end point t = (j - 1) % m break if t == j: # sets a new end point t = (j - 1) % m # breaks the loop after going through all memory block break # mod m will help in traversing the # blocks from starting block after # we reach the end. j = (j + 1) % m print(\"Process No. Process Size Block no.\") for i in range(n): print(i + 1, \" \", processSize[i],end = \" \") if allocation[i] != -1: print(allocation[i] + 1) else: print(\"Not Allocated\") # Driver Codeif __name__ == '__main__': blockSize = [5, 10, 20] processSize = [10, 20, 5] m = len(blockSize) n = len(processSize) NextFit(blockSize, m, processSize, n)",
"e": 7864,
"s": 6184,
"text": null
},
{
"code": "// C# program for next fit// memory management algorithmusing System;using System.Linq;public class GFG { // Function to allocate memory to blocks as per Next fit// algorithm static void NextFit(int []blockSize, int m, int []processSize, int n) { // Stores block id of the block allocated to a // process int []allocation = new int[n]; int j = 0; // Initially no block is assigned to any process Enumerable.Repeat(-1, n).ToArray(); // pick each process and find suitable blocks // according to its size ad assign to it for (int i = 0; i < n; i++) { // Do not start from beginning while (j < m) { if (blockSize[j] >= processSize[i]) { // allocate block j to p[i] process allocation[i] = j; // Reduce available memory in this block. blockSize[j] -= processSize[i]; break; } // mod m will help in traversing the blocks from // starting block after we reach the end. j = (j + 1) % m; } } Console.Write(\"\\nProcess No.\\tProcess Size\\tBlock no.\\n\"); for (int i = 0; i < n; i++) { Console.Write( i + 1 + \"\\t\\t\" + processSize[i] + \"\\t\\t\"); if (allocation[i] != -1) { Console.Write(allocation[i] + 1); } else { Console.Write(\"Not Allocated\"); } Console.WriteLine(\"\"); } } // Driver program static public void Main() { int []blockSize = {5, 10, 20}; int []processSize = {10, 20, 5}; int m = blockSize.Length; int n = processSize.Length; NextFit(blockSize, m, processSize, n); }} /*This code is contributed by Rajput-Ji*/",
"e": 9755,
"s": 7864,
"text": null
},
{
"code": "<?php// PHP program for next fit// memory management algorithm // Function to allocate memory to blocks as per Next fit// algorithmfunction NextFit($blockSize, $m, $processSize, $n){ // Stores block id of the block allocated to a // process $allocation = array_fill(0, $n, -1); $j = 0; // Initially no block is assigned to any process above // pick each process and find suitable blocks // according to its size ad assign to it for ($i = 0; $i < $n; $i++) { // Do not start from beginning while ($j < $m) { if ($blockSize[$j] >= $processSize[$i]) { // allocate block j to p[i] process $allocation[$i] = $j; // Reduce available memory in this block. $blockSize[$j] -= $processSize[$i]; break; } // mod m will help in traversing the blocks from // starting block after we reach the end. $j = ($j + 1) % $m; } } echo \"\\nProcess No.\\tProcess Size\\tBlock no.\\n\"; for ($i = 0; $i < $n; $i++) { echo \" \".($i + 1).\"\\t\\t\".$processSize[$i].\"\\t\\t\"; if ($allocation[$i] != -1) echo ($allocation[$i] + 1); else echo \"Not Allocated\"; echo \"\\n\"; }} // Driver program $blockSize = array( 5, 10, 20 ); $processSize = array( 10, 20, 5 ); $m = count($blockSize); $n = count($processSize); NextFit($blockSize, $m, $processSize, $n); // This code is contributed by mits?>",
"e": 11297,
"s": 9755,
"text": null
},
{
"code": "<script> // JavaScript program for next fit// memory management algorithm // Function to allocate memory to blocks as per Next fit// algorithm function NextFit(blockSize, m, processSize, n) { // Stores block id of the block allocated to a // process let allocation = Array.from({length: n}, (_, i) => -1), j = 0; // pick each process and find suitable blocks // according to its size ad assign to it for (let i = 0; i < n; i++) { // Do not start from beginning while (j < m) { if (blockSize[j] >= processSize[i]) { // allocate block j to p[i] process allocation[i] = j; // Reduce available memory in this block. blockSize[j] -= processSize[i]; break; } // mod m will help in traversing the blocks from // starting block after we reach the end. j = (j + 1) % m; } } document.write(\"\\nProcess No. Process Size. Block no.\" + \"<br/>\"); for (let i = 0; i < n; i++) { document.write( i + 1 + Array(20).fill('\\xa0').join('') + processSize[i] + Array(20).fill('\\xa0').join('')); if (allocation[i] != -1) { document.write(allocation[i] + 1); } else { document.write(\"Not Allocated\"); } document.write(\"<br/>\"); } } // Driver Code let blockSize = [5, 10, 20]; let processSize = [10, 20, 5]; let m = blockSize.length; let n = processSize.length; NextFit(blockSize, m, processSize, n); // This code is contributed by susmitakundugoaldanga.</script>",
"e": 13077,
"s": 11297,
"text": null
},
{
"code": null,
"e": 13223,
"s": 13077,
"text": "Process No. Process Size Block no.\n 1 10 2\n 2 20 3\n 3 5 1"
},
{
"code": null,
"e": 13645,
"s": 13225,
"text": "This article is contributed by Akash Gupta. 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": 13660,
"s": 13645,
"text": "ishita_thakkar"
},
{
"code": null,
"e": 13670,
"s": 13660,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 13686,
"s": 13670,
"text": "PranchalKatiyar"
},
{
"code": null,
"e": 13699,
"s": 13686,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 13712,
"s": 13699,
"text": "Mithun Kumar"
},
{
"code": null,
"e": 13734,
"s": 13712,
"text": "susmitakundugoaldanga"
},
{
"code": null,
"e": 13749,
"s": 13734,
"text": "vidulamagdum12"
},
{
"code": null,
"e": 13760,
"s": 13749,
"text": "dhruvmillu"
},
{
"code": null,
"e": 13767,
"s": 13760,
"text": "Greedy"
},
{
"code": null,
"e": 13785,
"s": 13767,
"text": "Operating Systems"
},
{
"code": null,
"e": 13803,
"s": 13785,
"text": "Operating Systems"
},
{
"code": null,
"e": 13810,
"s": 13803,
"text": "Greedy"
},
{
"code": null,
"e": 13908,
"s": 13810,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 13939,
"s": 13908,
"text": "Huffman Coding | Greedy Algo-3"
},
{
"code": null,
"e": 13958,
"s": 13939,
"text": "Coin Change | DP-7"
},
{
"code": null,
"e": 14001,
"s": 13958,
"text": "Activity Selection Problem | Greedy Algo-1"
},
{
"code": null,
"e": 14029,
"s": 14001,
"text": "Fractional Knapsack Problem"
},
{
"code": null,
"e": 14052,
"s": 14029,
"text": "Job Sequencing Problem"
},
{
"code": null,
"e": 14079,
"s": 14052,
"text": "Types of Operating Systems"
},
{
"code": null,
"e": 14118,
"s": 14079,
"text": "Banker's Algorithm in Operating System"
},
{
"code": null,
"e": 14145,
"s": 14118,
"text": "Disk Scheduling Algorithms"
},
{
"code": null,
"e": 14190,
"s": 14145,
"text": "Introduction of Deadlock in Operating System"
}
] |
Text detection using Python | 14 Sep, 2021
Python language is widely used for modern machine learning and data analysis. One can detect an image, speech, can even detect an object through Python. For now, we will detect whether the text from the user gives a positive feeling or negative feeling by classifying the text as positive, negative, or neutral. In the code, Vader sentiment analysis and Tkinter are used. Tkinter is a standard GUI library for creating the GUI application.
Required Installations in Anaconda:
tkinter: This module is used for creating a simple GUI application. This module generally comes pre-installed with Python but to install it externally type the below command in the terminal. Using conda command.
conda install -c anaconda tk
Linux users can also use the below command.
sudo apt-get install python3-tk
nltk: This module is used for making computers understand the natural language. To install it type the below command in the terminal.Using conda.
conda install -c anaconda nltk
Using pip.
pip install nltk
numpy: This module is the fundamental package for scientific computing with Python. To install it type the below command in the terminal.Using conda.
conda install -c conda-forge numpy
Using pip.
pip install numpy
pandas: This module is used for data analysis. It provides highly optimized performance with back-end source code is purely written in C or Python. To install it type the below command in the terminal.Using conda
conda install -c anaconda pandas
Using pip.
pip install pandas
matplotlib: This module is an amazing visualization library in Python for 2D plots of arrays. Matplotlib is a multi-platform data visualization library built on NumPy arrays. To install it type the below command in the terminal.Using conda.
conda install -c conda-forge matplotlib
Using pip.
pip install matplotlib
VADER (Valence Aware Dictionary and sEntiment Reasoner) is a lexicon and rule-based sentiment analysis tool that is specifically attuned to sentiments expressed in social media. VADER uses a combination of A sentiment lexicon is a list of lexical features (e.g., words) which are generally labeled according to their semantic orientation as either positive or negative. VADER not only tells about the Positivity and Negativity score but also tells us about how positive or negative a sentiment is.
Note: For more information, refer to Python | Sentiment Analysis using VADER.
Below is the implementation.
Python3
import timeimport pandas as pdimport numpy as npimport matplotlib.pyplot as pltfrom tkinter import *import tkinter.messageboxfrom nltk.sentiment.vader import SentimentIntensityAnalyzer class analysis_text(): # Main function in program def center(self, toplevel): toplevel.update_idletasks() w = toplevel.winfo_screenwidth() h = toplevel.winfo_screenheight() size = tuple(int(_) for _ in toplevel.geometry().split('+')[0].split('x')) x = w/2 - size[0]/2 y = h/2 - size[1]/2 toplevel.geometry("%dx%d+%d+%d" % (size + (x, y))) def callback(self): if tkinter.messagebox.askokcancel("Quit", "Do you want to leave?"): self.main.destroy() def setResult(self, type, res): #calculated comments in vader analysis if (type == "neg"): self.negativeLabel.configure(text = "you typed negative comment : " + str(res) + " % \n") elif (type == "neu"): self.neutralLabel.configure( text = "you typed comment : " + str(res) + " % \n") elif (type == "pos"): self.positiveLabel.configure(text = "you typed positive comment: " + str(res) + " % \n") def runAnalysis(self): sentences = [] sentences.append(self.line.get()) sid = SentimentIntensityAnalyzer() for sentence in sentences: # print(sentence) ss = sid.polarity_scores(sentence) if ss['compound'] >= 0.05 : self.normalLabel.configure(text = " you typed positive statement: ") elif ss['compound'] <= - 0.05 : self.normalLabel.configure(text = " you typed negative statement") else : self.normalLabel.configure(text = " you normal typed statement: ") for k in sorted(ss): self.setResult(k, ss[k]) print() def editedText(self, event): self.typedText.configure(text = self.line.get() + event.char) def runByEnter(self, event): self.runAnalysis() def __init__(self): # Create main window self.main = Tk() self.main.title("Text Detector system") self.main.geometry("600x600") self.main.resizable(width=FALSE, height=FALSE) self.main.protocol("WM_DELETE_WINDOW", self.callback) self.main.focus() self.center(self.main) # addition item on window self.label1 = Label(text = "type a text here :") self.label1.pack() # Add a hidden button Enter self.line = Entry(self.main, width=70) self.line.pack() self.textLabel = Label(text = "\n", font=("Helvetica", 15)) self.textLabel.pack() self.typedText = Label(text = "", fg = "blue", font=("Helvetica", 20)) self.typedText.pack() self.line.bind("<Key>",self.editedText) self.line.bind("<Return>",self.runByEnter) self.result = Label(text = "\n", font=("Helvetica", 15)) self.result.pack() self.negativeLabel = Label(text = "", fg = "red", font=("Helvetica", 20)) self.negativeLabel.pack() self.neutralLabel = Label(text = "", font=("Helvetica", 20)) self.neutralLabel.pack() self.positiveLabel = Label(text = "", fg = "green", font=("Helvetica", 20)) self.positiveLabel.pack() self.normalLabel =Label (text ="", fg ="red", font=("Helvetica", 20)) self.normalLabel.pack() # Driver codemyanalysis = analysis_text()mainloop()
Output:
surindertarika1234
rajeev0719singh
Python Tkinter-exercises
Python-nltk
Python-tkinter
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Iterate over a list in Python
Python OOPs Concepts | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n14 Sep, 2021"
},
{
"code": null,
"e": 468,
"s": 28,
"text": "Python language is widely used for modern machine learning and data analysis. One can detect an image, speech, can even detect an object through Python. For now, we will detect whether the text from the user gives a positive feeling or negative feeling by classifying the text as positive, negative, or neutral. In the code, Vader sentiment analysis and Tkinter are used. Tkinter is a standard GUI library for creating the GUI application."
},
{
"code": null,
"e": 505,
"s": 468,
"text": "Required Installations in Anaconda: "
},
{
"code": null,
"e": 717,
"s": 505,
"text": "tkinter: This module is used for creating a simple GUI application. This module generally comes pre-installed with Python but to install it externally type the below command in the terminal. Using conda command."
},
{
"code": null,
"e": 746,
"s": 717,
"text": "conda install -c anaconda tk"
},
{
"code": null,
"e": 791,
"s": 746,
"text": "Linux users can also use the below command. "
},
{
"code": null,
"e": 823,
"s": 791,
"text": "sudo apt-get install python3-tk"
},
{
"code": null,
"e": 969,
"s": 823,
"text": "nltk: This module is used for making computers understand the natural language. To install it type the below command in the terminal.Using conda."
},
{
"code": null,
"e": 1000,
"s": 969,
"text": "conda install -c anaconda nltk"
},
{
"code": null,
"e": 1012,
"s": 1000,
"text": "Using pip. "
},
{
"code": null,
"e": 1029,
"s": 1012,
"text": "pip install nltk"
},
{
"code": null,
"e": 1179,
"s": 1029,
"text": "numpy: This module is the fundamental package for scientific computing with Python. To install it type the below command in the terminal.Using conda."
},
{
"code": null,
"e": 1214,
"s": 1179,
"text": "conda install -c conda-forge numpy"
},
{
"code": null,
"e": 1226,
"s": 1214,
"text": "Using pip. "
},
{
"code": null,
"e": 1244,
"s": 1226,
"text": "pip install numpy"
},
{
"code": null,
"e": 1457,
"s": 1244,
"text": "pandas: This module is used for data analysis. It provides highly optimized performance with back-end source code is purely written in C or Python. To install it type the below command in the terminal.Using conda"
},
{
"code": null,
"e": 1490,
"s": 1457,
"text": "conda install -c anaconda pandas"
},
{
"code": null,
"e": 1502,
"s": 1490,
"text": "Using pip. "
},
{
"code": null,
"e": 1521,
"s": 1502,
"text": "pip install pandas"
},
{
"code": null,
"e": 1762,
"s": 1521,
"text": "matplotlib: This module is an amazing visualization library in Python for 2D plots of arrays. Matplotlib is a multi-platform data visualization library built on NumPy arrays. To install it type the below command in the terminal.Using conda."
},
{
"code": null,
"e": 1802,
"s": 1762,
"text": "conda install -c conda-forge matplotlib"
},
{
"code": null,
"e": 1814,
"s": 1802,
"text": "Using pip. "
},
{
"code": null,
"e": 1837,
"s": 1814,
"text": "pip install matplotlib"
},
{
"code": null,
"e": 2335,
"s": 1837,
"text": "VADER (Valence Aware Dictionary and sEntiment Reasoner) is a lexicon and rule-based sentiment analysis tool that is specifically attuned to sentiments expressed in social media. VADER uses a combination of A sentiment lexicon is a list of lexical features (e.g., words) which are generally labeled according to their semantic orientation as either positive or negative. VADER not only tells about the Positivity and Negativity score but also tells us about how positive or negative a sentiment is."
},
{
"code": null,
"e": 2413,
"s": 2335,
"text": "Note: For more information, refer to Python | Sentiment Analysis using VADER."
},
{
"code": null,
"e": 2442,
"s": 2413,
"text": "Below is the implementation."
},
{
"code": null,
"e": 2450,
"s": 2442,
"text": "Python3"
},
{
"code": "import timeimport pandas as pdimport numpy as npimport matplotlib.pyplot as pltfrom tkinter import *import tkinter.messageboxfrom nltk.sentiment.vader import SentimentIntensityAnalyzer class analysis_text(): # Main function in program def center(self, toplevel): toplevel.update_idletasks() w = toplevel.winfo_screenwidth() h = toplevel.winfo_screenheight() size = tuple(int(_) for _ in toplevel.geometry().split('+')[0].split('x')) x = w/2 - size[0]/2 y = h/2 - size[1]/2 toplevel.geometry(\"%dx%d+%d+%d\" % (size + (x, y))) def callback(self): if tkinter.messagebox.askokcancel(\"Quit\", \"Do you want to leave?\"): self.main.destroy() def setResult(self, type, res): #calculated comments in vader analysis if (type == \"neg\"): self.negativeLabel.configure(text = \"you typed negative comment : \" + str(res) + \" % \\n\") elif (type == \"neu\"): self.neutralLabel.configure( text = \"you typed comment : \" + str(res) + \" % \\n\") elif (type == \"pos\"): self.positiveLabel.configure(text = \"you typed positive comment: \" + str(res) + \" % \\n\") def runAnalysis(self): sentences = [] sentences.append(self.line.get()) sid = SentimentIntensityAnalyzer() for sentence in sentences: # print(sentence) ss = sid.polarity_scores(sentence) if ss['compound'] >= 0.05 : self.normalLabel.configure(text = \" you typed positive statement: \") elif ss['compound'] <= - 0.05 : self.normalLabel.configure(text = \" you typed negative statement\") else : self.normalLabel.configure(text = \" you normal typed statement: \") for k in sorted(ss): self.setResult(k, ss[k]) print() def editedText(self, event): self.typedText.configure(text = self.line.get() + event.char) def runByEnter(self, event): self.runAnalysis() def __init__(self): # Create main window self.main = Tk() self.main.title(\"Text Detector system\") self.main.geometry(\"600x600\") self.main.resizable(width=FALSE, height=FALSE) self.main.protocol(\"WM_DELETE_WINDOW\", self.callback) self.main.focus() self.center(self.main) # addition item on window self.label1 = Label(text = \"type a text here :\") self.label1.pack() # Add a hidden button Enter self.line = Entry(self.main, width=70) self.line.pack() self.textLabel = Label(text = \"\\n\", font=(\"Helvetica\", 15)) self.textLabel.pack() self.typedText = Label(text = \"\", fg = \"blue\", font=(\"Helvetica\", 20)) self.typedText.pack() self.line.bind(\"<Key>\",self.editedText) self.line.bind(\"<Return>\",self.runByEnter) self.result = Label(text = \"\\n\", font=(\"Helvetica\", 15)) self.result.pack() self.negativeLabel = Label(text = \"\", fg = \"red\", font=(\"Helvetica\", 20)) self.negativeLabel.pack() self.neutralLabel = Label(text = \"\", font=(\"Helvetica\", 20)) self.neutralLabel.pack() self.positiveLabel = Label(text = \"\", fg = \"green\", font=(\"Helvetica\", 20)) self.positiveLabel.pack() self.normalLabel =Label (text =\"\", fg =\"red\", font=(\"Helvetica\", 20)) self.normalLabel.pack() # Driver codemyanalysis = analysis_text()mainloop()",
"e": 6802,
"s": 2450,
"text": null
},
{
"code": null,
"e": 6810,
"s": 6802,
"text": "Output:"
},
{
"code": null,
"e": 6831,
"s": 6812,
"text": "surindertarika1234"
},
{
"code": null,
"e": 6847,
"s": 6831,
"text": "rajeev0719singh"
},
{
"code": null,
"e": 6872,
"s": 6847,
"text": "Python Tkinter-exercises"
},
{
"code": null,
"e": 6884,
"s": 6872,
"text": "Python-nltk"
},
{
"code": null,
"e": 6899,
"s": 6884,
"text": "Python-tkinter"
},
{
"code": null,
"e": 6906,
"s": 6899,
"text": "Python"
},
{
"code": null,
"e": 7004,
"s": 6906,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 7022,
"s": 7004,
"text": "Python Dictionary"
},
{
"code": null,
"e": 7064,
"s": 7022,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 7086,
"s": 7064,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 7121,
"s": 7086,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 7147,
"s": 7121,
"text": "Python String | replace()"
},
{
"code": null,
"e": 7179,
"s": 7147,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 7208,
"s": 7179,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 7235,
"s": 7208,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 7265,
"s": 7235,
"text": "Iterate over a list in Python"
}
] |
Fermatβs Factorization Method | 10 Jun, 2021
Fermatβs Factorization method is based on the representation of an odd integer as the difference of two squares. For an integer n, we want a and b such as:
n = a2 - b2 = (a+b)(a-b)
where (a+b) and (a-b) are
the factors of the number n
Example:
Input: n = 6557
Output: [79,83]
Explanation:
For the above value,
the first try for a is ceil value
of square root of 6557, which is 81.
Then,
b2 = 812 - 6557 = 4,
as it is a perfect square.
So, b = 2
So, the factors of 6557 are:
(a - b) = 81 -2 = 79 &
(a + b) = 81 + 2 = 83.
Approach :
If n = pq is a factorization of n into two positive integers, Then, since n is odd, so p and q are both odd.Let, a = 1/2 * (p+q) and b = 1/2 * (q-p).Since a and b are both integers, then p = (a β b) and q = (a + b).So, n = pq = (a β b)(a + b) = a2 β b2In case of prime number, we go back until b = 1 in as one factor is 1 for a prime number.A while loop ensures this operation
If n = pq is a factorization of n into two positive integers, Then, since n is odd, so p and q are both odd.
Let, a = 1/2 * (p+q) and b = 1/2 * (q-p).
Since a and b are both integers, then p = (a β b) and q = (a + b).
So, n = pq = (a β b)(a + b) = a2 β b2
In case of prime number, we go back until b = 1 in as one factor is 1 for a prime number.
A while loop ensures this operation
Below is the implementation of the above approach
C++
Java
Python3
C#
Javascript
// C++ implementation of fermat's factorization#include<bits/stdc++.h> using namespace std; // This function finds the value of a and b // and returns a+b and a-b void FermatFactors(int n) { // since fermat's factorization applicable // for odd positive integers only if(n <= 0) { cout << "[" << n << "]"; return; } // check if n is a even number if((n & 1) == 0) { cout << "[" << n / 2.0 << "," << 2 << "]"; return; } int a = ceil(sqrt(n)) ; // if n is a perfect root, // then both its square roots are its factors if(a * a == n) { cout << "[" << a << "," << a << "]"; return; } int b; while(true) { int b1 = a * a - n ; b = (int)sqrt(b1) ; if(b * b == b1) break; else a += 1; } cout << "[" << (a - b) << "," << (a + b) << "]" ; return; } // Driver Code int main() { FermatFactors(6557); return 0; } // This code is contributed by AnkitRai01
// Java implementation of fermat's factorizationclass GFG{ // This function finds the value of a and b // and returns a+b and a-b static void FermatFactors(int n) { // since fermat's factorization applicable // for odd positive integers only if(n <= 0) { System.out.print("["+ n + "]"); return; } // check if n is a even number if((n & 1) == 0) { System.out.print("[" + n / 2.0 + "," + 2 + "]"); return; } int a = (int)Math.ceil(Math.sqrt(n)) ; // if n is a perfect root, // then both its square roots are its factors if(a * a == n) { System.out.print("[" + a + "," + a + "]"); return; } int b; while(true) { int b1 = a * a - n ; b = (int)(Math.sqrt(b1)) ; if(b * b == b1) break; else a += 1; } System.out.print("[" + (a - b) +"," + (a + b) + "]" ); return; } // Driver Code public static void main (String[] args) { FermatFactors(6557); }} // This code is contributed by AnkitRai01
# Python 3 implementation of fermat's factorization from math import ceil, sqrt #This function finds the value of a and b#and returns a+b and a-bdef FermatFactors(n): # since fermat's factorization applicable # for odd positive integers only if(n<= 0): return [n] # check if n is a even number if(n & 1) == 0: return [n / 2, 2] a = ceil(sqrt(n)) #if n is a perfect root, #then both its square roots are its factors if(a * a == n): return [a, a] while(True): b1 = a * a - n b = int(sqrt(b1)) if(b * b == b1): break else: a += 1 return [a-b, a + b] # Driver Codeprint(FermatFactors(6557))
// C# implementation of fermat's factorizationusing System; class GFG{ // This function finds the value of a and b // and returns a+b and a-b static void FermatFactors(int n) { // since fermat's factorization applicable // for odd positive integers only if(n <= 0) { Console.Write("["+ n + "]"); return; } // check if n is a even number if((n & 1) == 0) { Console.Write("[" + n / 2.0 + "," + 2 + "]"); return; } int a = (int)Math.Ceiling(Math.Sqrt(n)) ; // if n is a perfect root, // then both its square roots are its factors if(a * a == n) { Console.Write("[" + a + "," + a + "]"); return; } int b; while(true) { int b1 = a * a - n ; b = (int)(Math.Sqrt(b1)) ; if(b * b == b1) break; else a += 1; } Console.Write("[" + (a - b) +"," + (a + b) + "]" ); return; } // Driver Code public static void Main () { FermatFactors(6557); }} // This code is contributed by AnkitRai01
<script> // JavaScript implementation of fermat's factorization // This function finds the value of a and b // and returns a+b and a-b function FermatFactors(n) { // since fermat's factorization applicable // for odd positive integers only if(n <= 0) { document.write("["+ n + "]"); return; } // check if n is a even number if((n & 1) == 0) { document.write("[" + (n / 2.0) + "," + (2) + "]"); return; } let a = Math.ceil(Math.sqrt(n)) ; // if n is a perfect root, // then both its square roots are its factors if(a * a == n) { document.write("[" + a + "," + a + "]"); return; } let b; while(true) { let b1 = a * a - n ; b = parseInt(Math.sqrt(b1), 10); if(b * b == b1) break; else a += 1; } document.write("[" + (a - b) +", " + (a + b) + "]"); return; } FermatFactors(6557); </script>
[79, 83]
ankthon
suresh07
number-theory
Mathematical
number-theory
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Merge two sorted arrays
Operators in C / C++
Prime Numbers
Minimum number of jumps to reach end
The Knight's tour problem | Backtracking-1
Find minimum number of coins that make a given value
Algorithm to solve Rubik's Cube
Modulo 10^9+7 (1000000007)
Modulo Operator (%) in C/C++ with Examples
Program for factorial of a number | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n10 Jun, 2021"
},
{
"code": null,
"e": 212,
"s": 54,
"text": "Fermatβs Factorization method is based on the representation of an odd integer as the difference of two squares. For an integer n, we want a and b such as: "
},
{
"code": null,
"e": 293,
"s": 212,
"text": "n = a2 - b2 = (a+b)(a-b) \n\nwhere (a+b) and (a-b) are\nthe factors of the number n"
},
{
"code": null,
"e": 304,
"s": 293,
"text": "Example: "
},
{
"code": null,
"e": 590,
"s": 304,
"text": "Input: n = 6557\nOutput: [79,83]\nExplanation: \nFor the above value, \nthe first try for a is ceil value \nof square root of 6557, which is 81.\n\nThen, \nb2 = 812 - 6557 = 4,\nas it is a perfect square.\nSo, b = 2\n\nSo, the factors of 6557 are: \n(a - b) = 81 -2 = 79 & \n(a + b) = 81 + 2 = 83."
},
{
"code": null,
"e": 605,
"s": 592,
"text": "Approach : "
},
{
"code": null,
"e": 982,
"s": 605,
"text": "If n = pq is a factorization of n into two positive integers, Then, since n is odd, so p and q are both odd.Let, a = 1/2 * (p+q) and b = 1/2 * (q-p).Since a and b are both integers, then p = (a β b) and q = (a + b).So, n = pq = (a β b)(a + b) = a2 β b2In case of prime number, we go back until b = 1 in as one factor is 1 for a prime number.A while loop ensures this operation"
},
{
"code": null,
"e": 1091,
"s": 982,
"text": "If n = pq is a factorization of n into two positive integers, Then, since n is odd, so p and q are both odd."
},
{
"code": null,
"e": 1133,
"s": 1091,
"text": "Let, a = 1/2 * (p+q) and b = 1/2 * (q-p)."
},
{
"code": null,
"e": 1200,
"s": 1133,
"text": "Since a and b are both integers, then p = (a β b) and q = (a + b)."
},
{
"code": null,
"e": 1238,
"s": 1200,
"text": "So, n = pq = (a β b)(a + b) = a2 β b2"
},
{
"code": null,
"e": 1328,
"s": 1238,
"text": "In case of prime number, we go back until b = 1 in as one factor is 1 for a prime number."
},
{
"code": null,
"e": 1364,
"s": 1328,
"text": "A while loop ensures this operation"
},
{
"code": null,
"e": 1415,
"s": 1364,
"text": "Below is the implementation of the above approach "
},
{
"code": null,
"e": 1419,
"s": 1415,
"text": "C++"
},
{
"code": null,
"e": 1424,
"s": 1419,
"text": "Java"
},
{
"code": null,
"e": 1432,
"s": 1424,
"text": "Python3"
},
{
"code": null,
"e": 1435,
"s": 1432,
"text": "C#"
},
{
"code": null,
"e": 1446,
"s": 1435,
"text": "Javascript"
},
{
"code": "// C++ implementation of fermat's factorization#include<bits/stdc++.h> using namespace std; // This function finds the value of a and b // and returns a+b and a-b void FermatFactors(int n) { // since fermat's factorization applicable // for odd positive integers only if(n <= 0) { cout << \"[\" << n << \"]\"; return; } // check if n is a even number if((n & 1) == 0) { cout << \"[\" << n / 2.0 << \",\" << 2 << \"]\"; return; } int a = ceil(sqrt(n)) ; // if n is a perfect root, // then both its square roots are its factors if(a * a == n) { cout << \"[\" << a << \",\" << a << \"]\"; return; } int b; while(true) { int b1 = a * a - n ; b = (int)sqrt(b1) ; if(b * b == b1) break; else a += 1; } cout << \"[\" << (a - b) << \",\" << (a + b) << \"]\" ; return; } // Driver Code int main() { FermatFactors(6557); return 0; } // This code is contributed by AnkitRai01",
"e": 2672,
"s": 1446,
"text": null
},
{
"code": "// Java implementation of fermat's factorizationclass GFG{ // This function finds the value of a and b // and returns a+b and a-b static void FermatFactors(int n) { // since fermat's factorization applicable // for odd positive integers only if(n <= 0) { System.out.print(\"[\"+ n + \"]\"); return; } // check if n is a even number if((n & 1) == 0) { System.out.print(\"[\" + n / 2.0 + \",\" + 2 + \"]\"); return; } int a = (int)Math.ceil(Math.sqrt(n)) ; // if n is a perfect root, // then both its square roots are its factors if(a * a == n) { System.out.print(\"[\" + a + \",\" + a + \"]\"); return; } int b; while(true) { int b1 = a * a - n ; b = (int)(Math.sqrt(b1)) ; if(b * b == b1) break; else a += 1; } System.out.print(\"[\" + (a - b) +\",\" + (a + b) + \"]\" ); return; } // Driver Code public static void main (String[] args) { FermatFactors(6557); }} // This code is contributed by AnkitRai01",
"e": 3935,
"s": 2672,
"text": null
},
{
"code": "# Python 3 implementation of fermat's factorization from math import ceil, sqrt #This function finds the value of a and b#and returns a+b and a-bdef FermatFactors(n): # since fermat's factorization applicable # for odd positive integers only if(n<= 0): return [n] # check if n is a even number if(n & 1) == 0: return [n / 2, 2] a = ceil(sqrt(n)) #if n is a perfect root, #then both its square roots are its factors if(a * a == n): return [a, a] while(True): b1 = a * a - n b = int(sqrt(b1)) if(b * b == b1): break else: a += 1 return [a-b, a + b] # Driver Codeprint(FermatFactors(6557))",
"e": 4644,
"s": 3935,
"text": null
},
{
"code": "// C# implementation of fermat's factorizationusing System; class GFG{ // This function finds the value of a and b // and returns a+b and a-b static void FermatFactors(int n) { // since fermat's factorization applicable // for odd positive integers only if(n <= 0) { Console.Write(\"[\"+ n + \"]\"); return; } // check if n is a even number if((n & 1) == 0) { Console.Write(\"[\" + n / 2.0 + \",\" + 2 + \"]\"); return; } int a = (int)Math.Ceiling(Math.Sqrt(n)) ; // if n is a perfect root, // then both its square roots are its factors if(a * a == n) { Console.Write(\"[\" + a + \",\" + a + \"]\"); return; } int b; while(true) { int b1 = a * a - n ; b = (int)(Math.Sqrt(b1)) ; if(b * b == b1) break; else a += 1; } Console.Write(\"[\" + (a - b) +\",\" + (a + b) + \"]\" ); return; } // Driver Code public static void Main () { FermatFactors(6557); }} // This code is contributed by AnkitRai01",
"e": 5897,
"s": 4644,
"text": null
},
{
"code": "<script> // JavaScript implementation of fermat's factorization // This function finds the value of a and b // and returns a+b and a-b function FermatFactors(n) { // since fermat's factorization applicable // for odd positive integers only if(n <= 0) { document.write(\"[\"+ n + \"]\"); return; } // check if n is a even number if((n & 1) == 0) { document.write(\"[\" + (n / 2.0) + \",\" + (2) + \"]\"); return; } let a = Math.ceil(Math.sqrt(n)) ; // if n is a perfect root, // then both its square roots are its factors if(a * a == n) { document.write(\"[\" + a + \",\" + a + \"]\"); return; } let b; while(true) { let b1 = a * a - n ; b = parseInt(Math.sqrt(b1), 10); if(b * b == b1) break; else a += 1; } document.write(\"[\" + (a - b) +\", \" + (a + b) + \"]\"); return; } FermatFactors(6557); </script>",
"e": 7061,
"s": 5897,
"text": null
},
{
"code": null,
"e": 7070,
"s": 7061,
"text": "[79, 83]"
},
{
"code": null,
"e": 7080,
"s": 7072,
"text": "ankthon"
},
{
"code": null,
"e": 7089,
"s": 7080,
"text": "suresh07"
},
{
"code": null,
"e": 7103,
"s": 7089,
"text": "number-theory"
},
{
"code": null,
"e": 7116,
"s": 7103,
"text": "Mathematical"
},
{
"code": null,
"e": 7130,
"s": 7116,
"text": "number-theory"
},
{
"code": null,
"e": 7143,
"s": 7130,
"text": "Mathematical"
},
{
"code": null,
"e": 7241,
"s": 7143,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 7265,
"s": 7241,
"text": "Merge two sorted arrays"
},
{
"code": null,
"e": 7286,
"s": 7265,
"text": "Operators in C / C++"
},
{
"code": null,
"e": 7300,
"s": 7286,
"text": "Prime Numbers"
},
{
"code": null,
"e": 7337,
"s": 7300,
"text": "Minimum number of jumps to reach end"
},
{
"code": null,
"e": 7380,
"s": 7337,
"text": "The Knight's tour problem | Backtracking-1"
},
{
"code": null,
"e": 7433,
"s": 7380,
"text": "Find minimum number of coins that make a given value"
},
{
"code": null,
"e": 7465,
"s": 7433,
"text": "Algorithm to solve Rubik's Cube"
},
{
"code": null,
"e": 7492,
"s": 7465,
"text": "Modulo 10^9+7 (1000000007)"
},
{
"code": null,
"e": 7535,
"s": 7492,
"text": "Modulo Operator (%) in C/C++ with Examples"
}
] |
Rust - Ownership | The memory for a program can be allocated in the following β
Stack
Heap
A stack follows a last in first out order. Stack stores data values for which the size is known at compile time. For example, a variable of fixed size i32 is a candidate for stack allocation. Its size is known at compile time. All scalar types can be stored in stack as the size is fixed.
Consider an example of a string, which is assigned a value at runtime. The exact size of such a string cannot be determined at compile time. So it is not a candidate for stack allocation but for heap allocation.
The heap memory stores data values the size of which is unknown at compile time. It is used to store dynamic data. Simply put, a heap memory is allocated to data values that may change throughout the life cycle of the program. The heap is an area in the memory which is less organized when compared to stack.
Each value in Rust has a variable that is called owner of the value. Every data stored in Rust will have an owner associated with it. For example, in the syntax β let age = 30, age is the owner of the value 30.
Each data can have only one owner at a time.
Each data can have only one owner at a time.
Two variables cannot point to the same memory location. The variables will always be pointing to different memory locations.
Two variables cannot point to the same memory location. The variables will always be pointing to different memory locations.
The ownership of value can be transferred by β
Assigning value of one variable to another variable.
Assigning value of one variable to another variable.
Passing value to a function.
Passing value to a function.
Returning value from a function.
Returning value from a function.
The key selling point of Rust as a language is its memory safety. Memory safety is achieved by tight control on who can use what and when restrictions.
Consider the following snippet β
fn main(){
let v = vec![1,2,3];
// vector v owns the object in heap
//only a single variable owns the heap memory at any given time
let v2 = v;
// here two variables owns heap value,
//two pointers to the same content is not allowed in rust
//Rust is very smart in terms of memory access ,so it detects a race condition
//as two variables point to same heap
println!("{:?}",v);
}
The above example declares a vector v. The idea of ownership is that only one variable binds to a resource, either v binds to resource or v2 binds to the resource. The above example throws an error β use of moved value: `v`. This is because the ownership of the resource is transferred to v2. It means the ownership is moved from v to v2 (v2=v) and v is invalidated after the move.
The ownership of a value also changes when we pass an object in the heap to a closure or function.
fn main(){
let v = vec![1,2,3]; // vector v owns the object in heap
let v2 = v; // moves ownership to v2
display(v2); // v2 is moved to display and v2 is invalidated
println!("In main {:?}",v2); //v2 is No longer usable here
}
fn display(v:Vec<i32>){
println!("inside display {:?}",v);
}
Ownership passed to the function will be invalidated as function execution completes. One work around for this is let the function return the owned object back to the caller.
fn main(){
let v = vec![1,2,3]; // vector v owns the object in heap
let v2 = v; // moves ownership to v2
let v2_return = display(v2);
println!("In main {:?}",v2_return);
}
fn display(v:Vec<i32>)->Vec<i32> {
// returning same vector
println!("inside display {:?}",v);
}
In case of primitive types, contents from one variable is copied to another. So, there is no ownership move happening. This is because a primitive variable needs less resources than an object. Consider the following example β
fn main(){
let u1 = 10;
let u2 = u1; // u1 value copied(not moved) to u2
println!("u1 = {}",u1);
}
The output will be β 10. | [
{
"code": null,
"e": 2282,
"s": 2221,
"text": "The memory for a program can be allocated in the following β"
},
{
"code": null,
"e": 2288,
"s": 2282,
"text": "Stack"
},
{
"code": null,
"e": 2293,
"s": 2288,
"text": "Heap"
},
{
"code": null,
"e": 2582,
"s": 2293,
"text": "A stack follows a last in first out order. Stack stores data values for which the size is known at compile time. For example, a variable of fixed size i32 is a candidate for stack allocation. Its size is known at compile time. All scalar types can be stored in stack as the size is fixed."
},
{
"code": null,
"e": 2794,
"s": 2582,
"text": "Consider an example of a string, which is assigned a value at runtime. The exact size of such a string cannot be determined at compile time. So it is not a candidate for stack allocation but for heap allocation."
},
{
"code": null,
"e": 3103,
"s": 2794,
"text": "The heap memory stores data values the size of which is unknown at compile time. It is used to store dynamic data. Simply put, a heap memory is allocated to data values that may change throughout the life cycle of the program. The heap is an area in the memory which is less organized when compared to stack."
},
{
"code": null,
"e": 3314,
"s": 3103,
"text": "Each value in Rust has a variable that is called owner of the value. Every data stored in Rust will have an owner associated with it. For example, in the syntax β let age = 30, age is the owner of the value 30."
},
{
"code": null,
"e": 3359,
"s": 3314,
"text": "Each data can have only one owner at a time."
},
{
"code": null,
"e": 3404,
"s": 3359,
"text": "Each data can have only one owner at a time."
},
{
"code": null,
"e": 3529,
"s": 3404,
"text": "Two variables cannot point to the same memory location. The variables will always be pointing to different memory locations."
},
{
"code": null,
"e": 3654,
"s": 3529,
"text": "Two variables cannot point to the same memory location. The variables will always be pointing to different memory locations."
},
{
"code": null,
"e": 3701,
"s": 3654,
"text": "The ownership of value can be transferred by β"
},
{
"code": null,
"e": 3754,
"s": 3701,
"text": "Assigning value of one variable to another variable."
},
{
"code": null,
"e": 3807,
"s": 3754,
"text": "Assigning value of one variable to another variable."
},
{
"code": null,
"e": 3836,
"s": 3807,
"text": "Passing value to a function."
},
{
"code": null,
"e": 3865,
"s": 3836,
"text": "Passing value to a function."
},
{
"code": null,
"e": 3898,
"s": 3865,
"text": "Returning value from a function."
},
{
"code": null,
"e": 3931,
"s": 3898,
"text": "Returning value from a function."
},
{
"code": null,
"e": 4083,
"s": 3931,
"text": "The key selling point of Rust as a language is its memory safety. Memory safety is achieved by tight control on who can use what and when restrictions."
},
{
"code": null,
"e": 4116,
"s": 4083,
"text": "Consider the following snippet β"
},
{
"code": null,
"e": 4528,
"s": 4116,
"text": "fn main(){\n let v = vec![1,2,3]; \n // vector v owns the object in heap\n\n //only a single variable owns the heap memory at any given time\n let v2 = v; \n // here two variables owns heap value,\n //two pointers to the same content is not allowed in rust\n\n //Rust is very smart in terms of memory access ,so it detects a race condition\n //as two variables point to same heap\n\n println!(\"{:?}\",v);\n}"
},
{
"code": null,
"e": 4910,
"s": 4528,
"text": "The above example declares a vector v. The idea of ownership is that only one variable binds to a resource, either v binds to resource or v2 binds to the resource. The above example throws an error β use of moved value: `v`. This is because the ownership of the resource is transferred to v2. It means the ownership is moved from v to v2 (v2=v) and v is invalidated after the move."
},
{
"code": null,
"e": 5009,
"s": 4910,
"text": "The ownership of a value also changes when we pass an object in the heap to a closure or function."
},
{
"code": null,
"e": 5344,
"s": 5009,
"text": "fn main(){\n let v = vec![1,2,3]; // vector v owns the object in heap\n let v2 = v; // moves ownership to v2\n display(v2); // v2 is moved to display and v2 is invalidated\n println!(\"In main {:?}\",v2); //v2 is No longer usable here\n}\nfn display(v:Vec<i32>){\n println!(\"inside display {:?}\",v);\n}"
},
{
"code": null,
"e": 5519,
"s": 5344,
"text": "Ownership passed to the function will be invalidated as function execution completes. One work around for this is let the function return the owned object back to the caller."
},
{
"code": null,
"e": 5832,
"s": 5519,
"text": "fn main(){\n let v = vec![1,2,3]; // vector v owns the object in heap\n let v2 = v; // moves ownership to v2\n let v2_return = display(v2); \n println!(\"In main {:?}\",v2_return);\n}\nfn display(v:Vec<i32>)->Vec<i32> { \n // returning same vector\n println!(\"inside display {:?}\",v);\n}"
},
{
"code": null,
"e": 6058,
"s": 5832,
"text": "In case of primitive types, contents from one variable is copied to another. So, there is no ownership move happening. This is because a primitive variable needs less resources than an object. Consider the following example β"
},
{
"code": null,
"e": 6168,
"s": 6058,
"text": "fn main(){\n let u1 = 10;\n let u2 = u1; // u1 value copied(not moved) to u2\n\n println!(\"u1 = {}\",u1);\n}"
}
] |
What does the β+β (plus sign) CSS selector mean? | 04 Dec, 2018
The β+β sign selector is used to select the elements that are placed immediately after the specified element but not inside the particular elements.
Note: The IE8 and earlier versions </DOCTYPE> must be declared to work element + element selector.
Syntax:
element + element {
// CSS property
}
Example:
<!DOCTYPE html><html> <head> <title>+ sign selector</title> <style> h2 + div { font-size:20px; font-weight:bold; display:inline; background-color: yellow; color:green; } h1 { color:green; } body { text-align:center; } </style> </head> <body> <h1>GeeksforGeeks</h1> <h2>+ sign Selector</h2> <div>A computer science portal for geeks</div> </body></html>
Output:
Supported Browsers: The browser supported by β+β selector are listed below:
Apple Safari
Google Chrome
Firefox
Opera
Internet Explorer 7.0
CSS-Misc
Picked
CSS
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to update Node.js and NPM to next version ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
How to create footer to stay at the bottom of a Web page?
CSS to put icon inside an input element in a form
How to update Node.js and NPM to next version ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
REST API (Introduction)
Hide or show elements in HTML using display property | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n04 Dec, 2018"
},
{
"code": null,
"e": 177,
"s": 28,
"text": "The β+β sign selector is used to select the elements that are placed immediately after the specified element but not inside the particular elements."
},
{
"code": null,
"e": 276,
"s": 177,
"text": "Note: The IE8 and earlier versions </DOCTYPE> must be declared to work element + element selector."
},
{
"code": null,
"e": 284,
"s": 276,
"text": "Syntax:"
},
{
"code": null,
"e": 328,
"s": 284,
"text": "element + element {\n // CSS property\n} \n"
},
{
"code": null,
"e": 337,
"s": 328,
"text": "Example:"
},
{
"code": "<!DOCTYPE html><html> <head> <title>+ sign selector</title> <style> h2 + div { font-size:20px; font-weight:bold; display:inline; background-color: yellow; color:green; } h1 { color:green; } body { text-align:center; } </style> </head> <body> <h1>GeeksforGeeks</h1> <h2>+ sign Selector</h2> <div>A computer science portal for geeks</div> </body></html> ",
"e": 930,
"s": 337,
"text": null
},
{
"code": null,
"e": 938,
"s": 930,
"text": "Output:"
},
{
"code": null,
"e": 1014,
"s": 938,
"text": "Supported Browsers: The browser supported by β+β selector are listed below:"
},
{
"code": null,
"e": 1027,
"s": 1014,
"text": "Apple Safari"
},
{
"code": null,
"e": 1041,
"s": 1027,
"text": "Google Chrome"
},
{
"code": null,
"e": 1049,
"s": 1041,
"text": "Firefox"
},
{
"code": null,
"e": 1055,
"s": 1049,
"text": "Opera"
},
{
"code": null,
"e": 1077,
"s": 1055,
"text": "Internet Explorer 7.0"
},
{
"code": null,
"e": 1086,
"s": 1077,
"text": "CSS-Misc"
},
{
"code": null,
"e": 1093,
"s": 1086,
"text": "Picked"
},
{
"code": null,
"e": 1097,
"s": 1093,
"text": "CSS"
},
{
"code": null,
"e": 1102,
"s": 1097,
"text": "HTML"
},
{
"code": null,
"e": 1119,
"s": 1102,
"text": "Web Technologies"
},
{
"code": null,
"e": 1124,
"s": 1119,
"text": "HTML"
},
{
"code": null,
"e": 1222,
"s": 1124,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1270,
"s": 1222,
"text": "How to update Node.js and NPM to next version ?"
},
{
"code": null,
"e": 1332,
"s": 1270,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 1382,
"s": 1332,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
},
{
"code": null,
"e": 1440,
"s": 1382,
"text": "How to create footer to stay at the bottom of a Web page?"
},
{
"code": null,
"e": 1490,
"s": 1440,
"text": "CSS to put icon inside an input element in a form"
},
{
"code": null,
"e": 1538,
"s": 1490,
"text": "How to update Node.js and NPM to next version ?"
},
{
"code": null,
"e": 1600,
"s": 1538,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 1650,
"s": 1600,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
},
{
"code": null,
"e": 1674,
"s": 1650,
"text": "REST API (Introduction)"
}
] |
OpenCV - Filter2D | The Filter2D operation convolves an image with the kernel. You can perform this operation on an image using the Filter2D() method of the imgproc class. Following is the syntax of this method β
filter2D(src, dst, ddepth, kernel)
This method accepts the following parameters β
src β A Mat object representing the source (input image) for this operation.
src β A Mat object representing the source (input image) for this operation.
dst β A Mat object representing the destination (output image) for this operation.
dst β A Mat object representing the destination (output image) for this operation.
ddepth β A variable of the type integer representing the depth of the output image.
ddepth β A variable of the type integer representing the depth of the output image.
kernel β A Mat object representing the convolution kernel.
kernel β A Mat object representing the convolution kernel.
The following program demonstrates how to perform the Filter2D operation on an image.
import org.opencv.core.Core;
import org.opencv.core.CvType;
import org.opencv.core.Mat;
import org.opencv.imgcodecs.Imgcodecs;
import org.opencv.imgproc.Imgproc;
public class Filter2D {
public static void main( String[] args ) {
//Loading the OpenCV core library
System.loadLibrary( Core.NATIVE_LIBRARY_NAME );
//Reading the Image from the file and storing it in to a Matrix object
String file ="E:/OpenCV/chap11/filter_input.jpg";
Mat src = Imgcodecs.imread(file);
//Creating an empty matrix to store the result
Mat dst = new Mat();
// Creating kernel matrix
Mat kernel = Mat.ones(2,2, CvType.CV_32F);
for(int i = 0; i<kernel.rows(); i++) {
for(int j = 0; j<kernel.cols(); j++) {
double[] m = kernel.get(i, j);
for(int k = 1; k<m.length; k++) {
m[k] = m[k]/(2 * 2);
}
kernel.put(i,j, m);
}
}
Imgproc.filter2D(src, dst, -1, kernel);
Imgcodecs.imwrite("E:/OpenCV/chap11/filter2d.jpg", dst);
System.out.println("Image Processed");
}
}
Assume that following is the input image filter_input.jpg specified in the above program.
On executing the program, you will get the following output β
Image Processed
If you open the specified path, you can observe the output image as follows β | [
{
"code": null,
"e": 3331,
"s": 3138,
"text": "The Filter2D operation convolves an image with the kernel. You can perform this operation on an image using the Filter2D() method of the imgproc class. Following is the syntax of this method β"
},
{
"code": null,
"e": 3367,
"s": 3331,
"text": "filter2D(src, dst, ddepth, kernel)\n"
},
{
"code": null,
"e": 3414,
"s": 3367,
"text": "This method accepts the following parameters β"
},
{
"code": null,
"e": 3491,
"s": 3414,
"text": "src β A Mat object representing the source (input image) for this operation."
},
{
"code": null,
"e": 3568,
"s": 3491,
"text": "src β A Mat object representing the source (input image) for this operation."
},
{
"code": null,
"e": 3651,
"s": 3568,
"text": "dst β A Mat object representing the destination (output image) for this operation."
},
{
"code": null,
"e": 3734,
"s": 3651,
"text": "dst β A Mat object representing the destination (output image) for this operation."
},
{
"code": null,
"e": 3818,
"s": 3734,
"text": "ddepth β A variable of the type integer representing the depth of the output image."
},
{
"code": null,
"e": 3902,
"s": 3818,
"text": "ddepth β A variable of the type integer representing the depth of the output image."
},
{
"code": null,
"e": 3961,
"s": 3902,
"text": "kernel β A Mat object representing the convolution kernel."
},
{
"code": null,
"e": 4020,
"s": 3961,
"text": "kernel β A Mat object representing the convolution kernel."
},
{
"code": null,
"e": 4106,
"s": 4020,
"text": "The following program demonstrates how to perform the Filter2D operation on an image."
},
{
"code": null,
"e": 5224,
"s": 4106,
"text": "import org.opencv.core.Core;\nimport org.opencv.core.CvType;\nimport org.opencv.core.Mat;\nimport org.opencv.imgcodecs.Imgcodecs;\nimport org.opencv.imgproc.Imgproc;\n\npublic class Filter2D {\n public static void main( String[] args ) {\n //Loading the OpenCV core library \n System.loadLibrary( Core.NATIVE_LIBRARY_NAME );\n\n //Reading the Image from the file and storing it in to a Matrix object\n String file =\"E:/OpenCV/chap11/filter_input.jpg\";\n Mat src = Imgcodecs.imread(file);\n\n //Creating an empty matrix to store the result\n Mat dst = new Mat();\n\n // Creating kernel matrix\n Mat kernel = Mat.ones(2,2, CvType.CV_32F);\n \n for(int i = 0; i<kernel.rows(); i++) {\n for(int j = 0; j<kernel.cols(); j++) {\n double[] m = kernel.get(i, j);\n\n for(int k = 1; k<m.length; k++) {\n m[k] = m[k]/(2 * 2);\n }\n kernel.put(i,j, m);\n }\n }\n Imgproc.filter2D(src, dst, -1, kernel);\n Imgcodecs.imwrite(\"E:/OpenCV/chap11/filter2d.jpg\", dst);\n System.out.println(\"Image Processed\");\n }\n}"
},
{
"code": null,
"e": 5314,
"s": 5224,
"text": "Assume that following is the input image filter_input.jpg specified in the above program."
},
{
"code": null,
"e": 5376,
"s": 5314,
"text": "On executing the program, you will get the following output β"
},
{
"code": null,
"e": 5393,
"s": 5376,
"text": "Image Processed\n"
}
] |
How to Create Gradient Background Animation using HTML and CSS ? | 12 Jun, 2020
Gradient animation can be added to the background of your websites by using simple HTML and CSS @keyframes rule that generate the desired animation.
HTML Code: In the following example, the basic structure of the HTML page is implemented.
<!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content= "width=device-width, initial-scale=1.0"> <title>Gradient Background Animation</title></head> <body> <section> <div> <h2>GeeksforGeeks</h2> <p>Gradient background Animation</p> </div> </section></body> </html>
CSS Code: In the following section, designing of the background is implemented using simple CSS @keyframes rule that provide the animation feature. Providing different gradient colors is done using linear-gradient() function.
<style> body { margin: 0; padding: 0; animation: effect 3s linear infinite; } section { width: 100%; height: 100vh; } div { position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); font-size: 3em; } h2 { text-align: center; } @keyframes effect { 0% { background: linear-gradient(#008000, #00FF00); } 50% { background: linear-gradient(#220080, #0084ff); } 100% { background: linear-gradient(#e78f3c, #ff4800); } }</style>
Complete Code: It is the combination of the above two code sections.
<!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content= "width=device-width, initial-scale=1.0"> <title>Gradient Background Animation</title></head> <style> body { margin: 0; padding: 0; animation: effect 3s linear infinite; } section { width: 100%; height: 100vh; } div { position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); font-size: 3em; } h2 { text-align: center; } @keyframes effect { 0% { background: linear-gradient(#008000, #00FF00); } 50% { background: linear-gradient(#220080, #0084ff); } 100% { background: linear-gradient(#e78f3c, #ff4800); } }</style> <body> <section> <div> <h2>GeeksforGeeks</h2> <p>Gradient background Animation</p> </div> </section></body> </html>
Output:
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. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n12 Jun, 2020"
},
{
"code": null,
"e": 177,
"s": 28,
"text": "Gradient animation can be added to the background of your websites by using simple HTML and CSS @keyframes rule that generate the desired animation."
},
{
"code": null,
"e": 267,
"s": 177,
"text": "HTML Code: In the following example, the basic structure of the HTML page is implemented."
},
{
"code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\"> <meta name=\"viewport\" content= \"width=device-width, initial-scale=1.0\"> <title>Gradient Background Animation</title></head> <body> <section> <div> <h2>GeeksforGeeks</h2> <p>Gradient background Animation</p> </div> </section></body> </html>",
"e": 630,
"s": 267,
"text": null
},
{
"code": null,
"e": 856,
"s": 630,
"text": "CSS Code: In the following section, designing of the background is implemented using simple CSS @keyframes rule that provide the animation feature. Providing different gradient colors is done using linear-gradient() function."
},
{
"code": "<style> body { margin: 0; padding: 0; animation: effect 3s linear infinite; } section { width: 100%; height: 100vh; } div { position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); font-size: 3em; } h2 { text-align: center; } @keyframes effect { 0% { background: linear-gradient(#008000, #00FF00); } 50% { background: linear-gradient(#220080, #0084ff); } 100% { background: linear-gradient(#e78f3c, #ff4800); } }</style>",
"e": 1489,
"s": 856,
"text": null
},
{
"code": null,
"e": 1558,
"s": 1489,
"text": "Complete Code: It is the combination of the above two code sections."
},
{
"code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\"> <meta name=\"viewport\" content= \"width=device-width, initial-scale=1.0\"> <title>Gradient Background Animation</title></head> <style> body { margin: 0; padding: 0; animation: effect 3s linear infinite; } section { width: 100%; height: 100vh; } div { position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); font-size: 3em; } h2 { text-align: center; } @keyframes effect { 0% { background: linear-gradient(#008000, #00FF00); } 50% { background: linear-gradient(#220080, #0084ff); } 100% { background: linear-gradient(#e78f3c, #ff4800); } }</style> <body> <section> <div> <h2>GeeksforGeeks</h2> <p>Gradient background Animation</p> </div> </section></body> </html>",
"e": 2555,
"s": 1558,
"text": null
},
{
"code": null,
"e": 2563,
"s": 2555,
"text": "Output:"
},
{
"code": null,
"e": 2572,
"s": 2563,
"text": "CSS-Misc"
},
{
"code": null,
"e": 2582,
"s": 2572,
"text": "HTML-Misc"
},
{
"code": null,
"e": 2586,
"s": 2582,
"text": "CSS"
},
{
"code": null,
"e": 2591,
"s": 2586,
"text": "HTML"
},
{
"code": null,
"e": 2608,
"s": 2591,
"text": "Web Technologies"
},
{
"code": null,
"e": 2635,
"s": 2608,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 2640,
"s": 2635,
"text": "HTML"
}
] |
PHP - Logical Operators Example | Try following example to understand all the logical operators. Copy and paste following PHP program in test.php file and keep it in your PHP Server's document root and browse it using any browser.
<html>
<head>
<title>Logical Operators</title>
</head>
<body>
<?php
$a = 42;
$b = 0;
if( $a && $b ) {
echo "TEST1 : Both a and b are true<br/>";
}else{
echo "TEST1 : Either a or b is false<br/>";
}
if( $a and $b ) {
echo "TEST2 : Both a and b are true<br/>";
}else{
echo "TEST2 : Either a or b is false<br/>";
}
if( $a || $b ) {
echo "TEST3 : Either a or b is true<br/>";
}else{
echo "TEST3 : Both a and b are false<br/>";
}
if( $a or $b ) {
echo "TEST4 : Either a or b is true<br/>";
}else {
echo "TEST4 : Both a and b are false<br/>";
}
$a = 10;
$b = 20;
if( $a ) {
echo "TEST5 : a is true <br/>";
}else {
echo "TEST5 : a is false<br/>";
}
if( $b ) {
echo "TEST6 : b is true <br/>";
}else {
echo "TEST6 : b is false<br/>";
}
if( !$a ) {
echo "TEST7 : a is true <br/>";
}else {
echo "TEST7 : a is false<br/>";
}
if( !$b ) {
echo "TEST8 : b is true <br/>";
}else {
echo "TEST8 : b is false<br/>";
}
?>
</body>
</html>
This will produce the following result β
TEST1 : Either a or b is false
TEST2 : Either a or b is false
TEST3 : Either a or b is true
TEST4 : Either a or b is true
TEST5 : a is true
TEST6 : b is true
TEST7 : a is false
TEST8 : b is false | [
{
"code": null,
"e": 3088,
"s": 2891,
"text": "Try following example to understand all the logical operators. Copy and paste following PHP program in test.php file and keep it in your PHP Server's document root and browse it using any browser."
},
{
"code": null,
"e": 4596,
"s": 3088,
"text": "<html>\n \n <head>\n <title>Logical Operators</title>\n </head>\n \n <body>\n \n <?php\n $a = 42;\n $b = 0;\n \n if( $a && $b ) {\n echo \"TEST1 : Both a and b are true<br/>\";\n }else{\n echo \"TEST1 : Either a or b is false<br/>\";\n }\n \n if( $a and $b ) {\n echo \"TEST2 : Both a and b are true<br/>\";\n }else{\n echo \"TEST2 : Either a or b is false<br/>\";\n }\n \n if( $a || $b ) {\n echo \"TEST3 : Either a or b is true<br/>\";\n }else{\n echo \"TEST3 : Both a and b are false<br/>\";\n }\n \n if( $a or $b ) {\n echo \"TEST4 : Either a or b is true<br/>\";\n }else {\n echo \"TEST4 : Both a and b are false<br/>\";\n }\n \n $a = 10;\n $b = 20;\n \n if( $a ) {\n echo \"TEST5 : a is true <br/>\";\n }else {\n echo \"TEST5 : a is false<br/>\";\n }\n \n if( $b ) {\n echo \"TEST6 : b is true <br/>\";\n }else {\n echo \"TEST6 : b is false<br/>\";\n }\n \n if( !$a ) {\n echo \"TEST7 : a is true <br/>\";\n }else {\n echo \"TEST7 : a is false<br/>\";\n }\n \n if( !$b ) {\n echo \"TEST8 : b is true <br/>\";\n }else {\n echo \"TEST8 : b is false<br/>\";\n }\n ?>\n \n </body>\n</html>"
},
{
"code": null,
"e": 4637,
"s": 4596,
"text": "This will produce the following result β"
}
] |
SVG path attribute | 31 Mar, 2022
The path attribute defines a text path or the motion path along with the characters of a text are displayed or a referenced element is animated respectively. The elements that are using this attribute includes: <animateMotion> and <textPath>.
Syntax:
path = path-data
Attribute Values: The path attribute accepts the values mentioned above and described below
path-data: It has two different value i.e. it can either define a text path or the motion path along with the glyphs are to be rendered or animated respectively.
Note: Its default value is considered as normal.
Below examples illustrate the use of path attribute.
Example 1:
HTML
<!DOCTYPE html><html> <body> <h1 style="color: green; margin-left: 10px;"> GeeksforGeeks </h1> <svg viewBox="0 10 500 100" xmlns="http://www.w3.org/2000/svg"> <path fill="green" d = "M10, 90 Q90, 90 90, 45 Q90, 10 50, 10 Q10, 10 10, 40 Q10, 70 45, 70 Q70, 70 75, 50" /> <text> <textPath path = "M10, 90 Q90, 90 90, 45 Q90, 10 50, 10 Q10, 10 10, 40 Q10, 70 45, 70 Q70, 70 75, 50"> It is a Compute Science Portal </textPath> </text> </svg></body> </html>
Output:
Example 2:
HTML
<!DOCTYPE html><html> <body> <h1 style="color: green; margin-left: 80px;"> GeeksforGeeks </h1> <svg viewBox="0 15 700 200" xmlns="http://www.w3.org/2000/svg"> <path fill="none" stroke="green" d = "M 100, 100 m -75, 0 a 75, 75 0 1, 0 150, 0 a 75, 75 0 1, 0 -150, 0" /> <circle r="5" fill="green"> <animateMotion dur="5s" repeatCount="indefinite" path="M 100, 100 m -75, 0 a 75, 75 0 1, 0 150, 0 a 75, 75 0 1, 0 -150,0" /> </circle> </svg></body> </html>
Output:
HTML-SVG
SVG-Attribute
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": "\n31 Mar, 2022"
},
{
"code": null,
"e": 271,
"s": 28,
"text": "The path attribute defines a text path or the motion path along with the characters of a text are displayed or a referenced element is animated respectively. The elements that are using this attribute includes: <animateMotion> and <textPath>."
},
{
"code": null,
"e": 279,
"s": 271,
"text": "Syntax:"
},
{
"code": null,
"e": 297,
"s": 279,
"text": "path = path-data\n"
},
{
"code": null,
"e": 389,
"s": 297,
"text": "Attribute Values: The path attribute accepts the values mentioned above and described below"
},
{
"code": null,
"e": 551,
"s": 389,
"text": "path-data: It has two different value i.e. it can either define a text path or the motion path along with the glyphs are to be rendered or animated respectively."
},
{
"code": null,
"e": 600,
"s": 551,
"text": "Note: Its default value is considered as normal."
},
{
"code": null,
"e": 653,
"s": 600,
"text": "Below examples illustrate the use of path attribute."
},
{
"code": null,
"e": 664,
"s": 653,
"text": "Example 1:"
},
{
"code": null,
"e": 669,
"s": 664,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <body> <h1 style=\"color: green; margin-left: 10px;\"> GeeksforGeeks </h1> <svg viewBox=\"0 10 500 100\" xmlns=\"http://www.w3.org/2000/svg\"> <path fill=\"green\" d = \"M10, 90 Q90, 90 90, 45 Q90, 10 50, 10 Q10, 10 10, 40 Q10, 70 45, 70 Q70, 70 75, 50\" /> <text> <textPath path = \"M10, 90 Q90, 90 90, 45 Q90, 10 50, 10 Q10, 10 10, 40 Q10, 70 45, 70 Q70, 70 75, 50\"> It is a Compute Science Portal </textPath> </text> </svg></body> </html>",
"e": 1362,
"s": 669,
"text": null
},
{
"code": null,
"e": 1370,
"s": 1362,
"text": "Output:"
},
{
"code": null,
"e": 1381,
"s": 1370,
"text": "Example 2:"
},
{
"code": null,
"e": 1386,
"s": 1381,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <body> <h1 style=\"color: green; margin-left: 80px;\"> GeeksforGeeks </h1> <svg viewBox=\"0 15 700 200\" xmlns=\"http://www.w3.org/2000/svg\"> <path fill=\"none\" stroke=\"green\" d = \"M 100, 100 m -75, 0 a 75, 75 0 1, 0 150, 0 a 75, 75 0 1, 0 -150, 0\" /> <circle r=\"5\" fill=\"green\"> <animateMotion dur=\"5s\" repeatCount=\"indefinite\" path=\"M 100, 100 m -75, 0 a 75, 75 0 1, 0 150, 0 a 75, 75 0 1, 0 -150,0\" /> </circle> </svg></body> </html>",
"e": 2025,
"s": 1386,
"text": null
},
{
"code": null,
"e": 2033,
"s": 2025,
"text": "Output:"
},
{
"code": null,
"e": 2042,
"s": 2033,
"text": "HTML-SVG"
},
{
"code": null,
"e": 2056,
"s": 2042,
"text": "SVG-Attribute"
},
{
"code": null,
"e": 2061,
"s": 2056,
"text": "HTML"
},
{
"code": null,
"e": 2078,
"s": 2061,
"text": "Web Technologies"
},
{
"code": null,
"e": 2083,
"s": 2078,
"text": "HTML"
}
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.