title
stringlengths 3
221
| text
stringlengths 17
477k
| parsed
listlengths 0
3.17k
|
|---|---|---|
Java Program to Sort Objects in ArrayList by Date
|
21 Feb, 2022
The foremost tool that strikes is the sort() method to be used for the comparator mechanism of the Collections class which sorts in the decreasing order. Yes if in generic we want to achieve the goal considering the boundary condition where objects to sorted are user-defined then blindly do with Comparator. Both approaches are discussed below where the object is also created of the user-defined type.
Methods:
In Java, we have multiple methods to sort objects in ArrayList by Date. This can be done by using the Comparable<> interface or by the Collections.sort() method, to accomplish this task you can use any one of them.
Using Comparator interfaceUsing Collections.sort() method
Using Comparator interface
Using Collections.sort() method
Now let’s discuss all of them one by one.
Method 1: Using Comparator interface
The Java Comparator interface is used to order the objects of the user-defined class. By using the Comparator<> interface you can sort the elements on the basis of any data member defined in the user-defined class. The java.util package contains this interface. We can do this task by using methods compare() and compareTo() which will be used for comparing the objects of our DateItem class.
Approach:
Create a new class and name that class as DateItem and create a variable of type String, then create a constructor of class DateItem and pass that String type variable here.
In the main method create an ArrayList of type DateItem.
Store the objects of DateItem in the ArrayList.
Create another class called sortItems which implements Comparator and pass our DateItem class to a comparator.
Now in the Comparator class create a compare method that returns an integer and takes two parameters of the ‘DateItem‘ object as compare(Object obj1, Object obj2).
Inside the compare method for return value use the compareTo() method which will return the specified value by comparing the DateItem objects.
Now in the main method use Collections.sort() method and pass the ArrayList and ‘SortItem‘ class object to it, it will sort the dates, and output will be generated.
Example 1
Java
// Java Program to Sort Objects in ArrayList by Date// Using Comparator interface // Importing required classesimport java.util.*; // Class 1// helper class for DateItemclass DateItem { // Member variable of this class String date; // Constructor of this class DateItem(String date) { // This keyword refers to current object itself this.date = date; }} // Class 2// Helper class implementing Comparator// from the Comparable interfaceclass sortItems implements Comparator<DateItem> { // Method of this class // @Override public int compare(DateItem a, DateItem b) { // Returning the value after comparing the objects // this will sort the data in Ascending order return a.date.compareTo(b.date); }} // Class 3// Main classpublic class GFG { // Main driver method public static void main(String args[]) { // Creating ArrayList class object // Declaring object of type-DateItem // class(user-defined) ArrayList<DateItem> dateList = new ArrayList<>(); // Adding data to the ArrayList // using standard add() method dateList.add(new DateItem("2020-03-25")); dateList.add(new DateItem("2019-01-27")); dateList.add(new DateItem("1998-01-27")); dateList.add(new DateItem("1998-02-26")); // Sorting the ArrayList // using Collections.sort() method Collections.sort(dateList, new sortItems()); // Display message System.out.println("Sorted in Ascending Order"); // Iterating the list using for-each loop for (DateItem d : dateList) { // Printing the sorted items from the List System.out.println(d.date); } }}
Sorted in Ascending Order
1998-01-27
1998-02-26
2019-01-27
2020-03-25
Note : This code will sort the dates in Ascending order. If you want to change the order of sorting you can refer to the program below:
Example 2
Java
// Java Program to Sort Objects in ArrayList by Date// Using Comparator interface // Importing required classesimport java.util.*; // Class 1// Helper classclass DateItem { // Member variable String date; // Constructor of this class DateItem(String date) { // this keyword refers to current instance itself this.date = date; }} // Class 2// Helper class implementing Comparable interfaceclass sortItems implements Comparator<DateItem> { // @Override // Method of this class // To compare datetime objects public int compare(DateItem a, DateItem b) { // Returning the value after comparing the objects // this will sort the data in Descending order return b.date.compareTo(a.date); }} // Class 3// Main classpublic class GFG { // Main driver method public static void main(String args[]) { // Creating an ArrayList of DateItem class // (user-defined) ArrayList<DateItem> dateList = new ArrayList<>(); // Adding data to the ArrayList // using standard add() method dateList.add(new DateItem("2020-03-25")); dateList.add(new DateItem("2019-01-27")); dateList.add(new DateItem("1998-01-27")); dateList.add(new DateItem("1998-02-26")); // Sorting the elements on ArrayList object above Collections.sort(dateList, new sortItems()); // Display message only System.out.println("Sorted in Descending Order"); // Iterating the List // using for-each loop for (DateItem d : dateList) { // Printing the sorted items from the List System.out.println(d.date); } }}
Sorted in Descending Order
2020-03-25
2019-01-27
1998-02-26
1998-01-27
Method 2: Using Collections.sort() method
The Collections.sort() method can be used to sort the ArrayList of custom objects. We can use this method to sort the Objects in ArrayList by the Date. java.util.Collections.sort() method is present in java.util.Collections class. It is used to sort the elements present in the specified list of Collections in ascending order. It works similar to java.util.Arrays.sort() method, but it is better than it as it can sort the elements of Array as well as a linked list, queue, and many more presents in it.
Example
Java
// Java Program to Sort Objects in ArrayList by Date// Using Collections.sort() method // Importing required classesimport java.util.*; // Main classpublic class GFG { // Main driver method public static void main(String[] args) { // Creating an ArrayList of String to // store the Dates ArrayList<String> datesList = new ArrayList<>(); // Adding date to ArrayList // using standard add() method datesList.add("2020-03-25"); datesList.add("2019-01-27"); datesList.add("2020-03-26"); datesList.add("2020-02-26"); // Display message only System.out.println( "Dates Object before sorting : "); // Iterating in the ArrayList // using for each loop for (String dates : datesList) { // Printing the data from the list System.out.println(dates); } // Sorting the ArrayList // using Collections.sort() method Collections.sort(datesList); // Display message only System.out.println("Dates Object after sorting : "); // Iterating in the ArrayList // using for-each loop for (String dates : datesList) { // Printing the data from the list System.out.println(dates); } }}
Dates Object before sorting :
2020-03-25
2019-01-27
2020-03-26
2020-02-26
Dates Object after sorting :
2019-01-27
2020-02-26
2020-03-25
2020-03-26
surindertarika1234
germanshephered48
Java-ArrayList
Java-Collections
Picked
Java
Java Programs
Java
Java-Collections
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n21 Feb, 2022"
},
{
"code": null,
"e": 433,
"s": 28,
"text": "The foremost tool that strikes is the sort() method to be used for the comparator mechanism of the Collections class which sorts in the decreasing order. Yes if in generic we want to achieve the goal considering the boundary condition where objects to sorted are user-defined then blindly do with Comparator. Both approaches are discussed below where the object is also created of the user-defined type. "
},
{
"code": null,
"e": 442,
"s": 433,
"text": "Methods:"
},
{
"code": null,
"e": 658,
"s": 442,
"text": "In Java, we have multiple methods to sort objects in ArrayList by Date. This can be done by using the Comparable<> interface or by the Collections.sort() method, to accomplish this task you can use any one of them. "
},
{
"code": null,
"e": 716,
"s": 658,
"text": "Using Comparator interfaceUsing Collections.sort() method"
},
{
"code": null,
"e": 743,
"s": 716,
"text": "Using Comparator interface"
},
{
"code": null,
"e": 775,
"s": 743,
"text": "Using Collections.sort() method"
},
{
"code": null,
"e": 818,
"s": 775,
"text": "Now let’s discuss all of them one by one. "
},
{
"code": null,
"e": 855,
"s": 818,
"text": "Method 1: Using Comparator interface"
},
{
"code": null,
"e": 1248,
"s": 855,
"text": "The Java Comparator interface is used to order the objects of the user-defined class. By using the Comparator<> interface you can sort the elements on the basis of any data member defined in the user-defined class. The java.util package contains this interface. We can do this task by using methods compare() and compareTo() which will be used for comparing the objects of our DateItem class."
},
{
"code": null,
"e": 1259,
"s": 1248,
"text": "Approach: "
},
{
"code": null,
"e": 1433,
"s": 1259,
"text": "Create a new class and name that class as DateItem and create a variable of type String, then create a constructor of class DateItem and pass that String type variable here."
},
{
"code": null,
"e": 1490,
"s": 1433,
"text": "In the main method create an ArrayList of type DateItem."
},
{
"code": null,
"e": 1538,
"s": 1490,
"text": "Store the objects of DateItem in the ArrayList."
},
{
"code": null,
"e": 1649,
"s": 1538,
"text": "Create another class called sortItems which implements Comparator and pass our DateItem class to a comparator."
},
{
"code": null,
"e": 1813,
"s": 1649,
"text": "Now in the Comparator class create a compare method that returns an integer and takes two parameters of the ‘DateItem‘ object as compare(Object obj1, Object obj2)."
},
{
"code": null,
"e": 1956,
"s": 1813,
"text": "Inside the compare method for return value use the compareTo() method which will return the specified value by comparing the DateItem objects."
},
{
"code": null,
"e": 2121,
"s": 1956,
"text": "Now in the main method use Collections.sort() method and pass the ArrayList and ‘SortItem‘ class object to it, it will sort the dates, and output will be generated."
},
{
"code": null,
"e": 2131,
"s": 2121,
"text": "Example 1"
},
{
"code": null,
"e": 2136,
"s": 2131,
"text": "Java"
},
{
"code": "// Java Program to Sort Objects in ArrayList by Date// Using Comparator interface // Importing required classesimport java.util.*; // Class 1// helper class for DateItemclass DateItem { // Member variable of this class String date; // Constructor of this class DateItem(String date) { // This keyword refers to current object itself this.date = date; }} // Class 2// Helper class implementing Comparator// from the Comparable interfaceclass sortItems implements Comparator<DateItem> { // Method of this class // @Override public int compare(DateItem a, DateItem b) { // Returning the value after comparing the objects // this will sort the data in Ascending order return a.date.compareTo(b.date); }} // Class 3// Main classpublic class GFG { // Main driver method public static void main(String args[]) { // Creating ArrayList class object // Declaring object of type-DateItem // class(user-defined) ArrayList<DateItem> dateList = new ArrayList<>(); // Adding data to the ArrayList // using standard add() method dateList.add(new DateItem(\"2020-03-25\")); dateList.add(new DateItem(\"2019-01-27\")); dateList.add(new DateItem(\"1998-01-27\")); dateList.add(new DateItem(\"1998-02-26\")); // Sorting the ArrayList // using Collections.sort() method Collections.sort(dateList, new sortItems()); // Display message System.out.println(\"Sorted in Ascending Order\"); // Iterating the list using for-each loop for (DateItem d : dateList) { // Printing the sorted items from the List System.out.println(d.date); } }}",
"e": 3878,
"s": 2136,
"text": null
},
{
"code": null,
"e": 3951,
"s": 3881,
"text": "Sorted in Ascending Order\n1998-01-27\n1998-02-26\n2019-01-27\n2020-03-25"
},
{
"code": null,
"e": 4087,
"s": 3951,
"text": "Note : This code will sort the dates in Ascending order. If you want to change the order of sorting you can refer to the program below:"
},
{
"code": null,
"e": 4099,
"s": 4089,
"text": "Example 2"
},
{
"code": null,
"e": 4106,
"s": 4101,
"text": "Java"
},
{
"code": "// Java Program to Sort Objects in ArrayList by Date// Using Comparator interface // Importing required classesimport java.util.*; // Class 1// Helper classclass DateItem { // Member variable String date; // Constructor of this class DateItem(String date) { // this keyword refers to current instance itself this.date = date; }} // Class 2// Helper class implementing Comparable interfaceclass sortItems implements Comparator<DateItem> { // @Override // Method of this class // To compare datetime objects public int compare(DateItem a, DateItem b) { // Returning the value after comparing the objects // this will sort the data in Descending order return b.date.compareTo(a.date); }} // Class 3// Main classpublic class GFG { // Main driver method public static void main(String args[]) { // Creating an ArrayList of DateItem class // (user-defined) ArrayList<DateItem> dateList = new ArrayList<>(); // Adding data to the ArrayList // using standard add() method dateList.add(new DateItem(\"2020-03-25\")); dateList.add(new DateItem(\"2019-01-27\")); dateList.add(new DateItem(\"1998-01-27\")); dateList.add(new DateItem(\"1998-02-26\")); // Sorting the elements on ArrayList object above Collections.sort(dateList, new sortItems()); // Display message only System.out.println(\"Sorted in Descending Order\"); // Iterating the List // using for-each loop for (DateItem d : dateList) { // Printing the sorted items from the List System.out.println(d.date); } }}",
"e": 5794,
"s": 4106,
"text": null
},
{
"code": null,
"e": 5868,
"s": 5797,
"text": "Sorted in Descending Order\n2020-03-25\n2019-01-27\n1998-02-26\n1998-01-27"
},
{
"code": null,
"e": 5912,
"s": 5870,
"text": "Method 2: Using Collections.sort() method"
},
{
"code": null,
"e": 6419,
"s": 5914,
"text": "The Collections.sort() method can be used to sort the ArrayList of custom objects. We can use this method to sort the Objects in ArrayList by the Date. java.util.Collections.sort() method is present in java.util.Collections class. It is used to sort the elements present in the specified list of Collections in ascending order. It works similar to java.util.Arrays.sort() method, but it is better than it as it can sort the elements of Array as well as a linked list, queue, and many more presents in it."
},
{
"code": null,
"e": 6430,
"s": 6421,
"text": "Example "
},
{
"code": null,
"e": 6437,
"s": 6432,
"text": "Java"
},
{
"code": "// Java Program to Sort Objects in ArrayList by Date// Using Collections.sort() method // Importing required classesimport java.util.*; // Main classpublic class GFG { // Main driver method public static void main(String[] args) { // Creating an ArrayList of String to // store the Dates ArrayList<String> datesList = new ArrayList<>(); // Adding date to ArrayList // using standard add() method datesList.add(\"2020-03-25\"); datesList.add(\"2019-01-27\"); datesList.add(\"2020-03-26\"); datesList.add(\"2020-02-26\"); // Display message only System.out.println( \"Dates Object before sorting : \"); // Iterating in the ArrayList // using for each loop for (String dates : datesList) { // Printing the data from the list System.out.println(dates); } // Sorting the ArrayList // using Collections.sort() method Collections.sort(datesList); // Display message only System.out.println(\"Dates Object after sorting : \"); // Iterating in the ArrayList // using for-each loop for (String dates : datesList) { // Printing the data from the list System.out.println(dates); } }}",
"e": 7742,
"s": 6437,
"text": null
},
{
"code": null,
"e": 7894,
"s": 7745,
"text": "Dates Object before sorting : \n2020-03-25\n2019-01-27\n2020-03-26\n2020-02-26\nDates Object after sorting : \n2019-01-27\n2020-02-26\n2020-03-25\n2020-03-26"
},
{
"code": null,
"e": 7915,
"s": 7896,
"text": "surindertarika1234"
},
{
"code": null,
"e": 7933,
"s": 7915,
"text": "germanshephered48"
},
{
"code": null,
"e": 7948,
"s": 7933,
"text": "Java-ArrayList"
},
{
"code": null,
"e": 7965,
"s": 7948,
"text": "Java-Collections"
},
{
"code": null,
"e": 7972,
"s": 7965,
"text": "Picked"
},
{
"code": null,
"e": 7977,
"s": 7972,
"text": "Java"
},
{
"code": null,
"e": 7991,
"s": 7977,
"text": "Java Programs"
},
{
"code": null,
"e": 7996,
"s": 7991,
"text": "Java"
},
{
"code": null,
"e": 8013,
"s": 7996,
"text": "Java-Collections"
}
] |
Sum and Product of Array elements using JavaScript
|
12 Sep, 2019
Given an array and is the task to find the Sum and Product of the values of an Array using JavaScript.
Simple method: It uses a simple method to access the array elements by an index number and use the loop to find the sum and product of values of an Array using JavaScript.
Example 1: This example uses a simple method to find the sum of Array elements using JavaScript.
<!DOCTYPE html><html> <head> <title> How to Find the sum of Values of an Array in JavaScript? </title></head> <body style="text-align:center;"> <h1 style = "color:green;" > GeeksForGeeks </h1> <h3> How to Find the sum of Values of an Array in JavaScript? </h3> <h4> ----Given Array----<br> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11] </h4> <button onclick="myFunction()">Click</button> <p id="gfg"></p> <script> $(document).ready(function() { $("button").click(function() { function sum(input) { if (toString.call(input) !== "[object Array]") return false; var total = 0; for(var i=0;i<input.length;i++) { if(isNaN(input[i])) { continue; } total += Number(input[i]); } return total; } document.getElementById("gfg").innerHTML = "----Sum of Array----" + "<br>" + sum([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]); }); }); </script></body> </html>
Output:
Before click on the Button:
After Click on the Button:
Example 2: This example uses a simple method to find the product of Array elements using JavaScript.
<!DOCTYPE html><html> <head> <title> How to Find the product of Values of an Array in JavaScript? </title></head> <body style="text-align:center;"> <h1 style = "color:green;" > GeeksForGeeks </h1> <h3> How to Find the product of Values of an Array in JavaScript? </h3> <h4> ----Given Array----<br> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11] </h4> <button onclick="myFunction()">Click</button> <p id="gfg"></p> <script> $(document).ready(function(){ $("button").click(function(){ function product(input) { if (toString.call(input) !== "[object Array]") return false; var total = 1; for(var i=0;i<input.length;i++) { if(isNaN(input[i])){ continue; } total *= Number(input[i]); } return total; } document.getElementById("gfg").innerHTML = "----product of Array----" + "<br>" + product([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]); }); }); </script></body> </html>
Output:
Before click on the Button:
After Click on the Button:
Using reduce() method: The array reduce() method in JavaScript is used to reduce the array to a single value and executes a provided function for each value of the array (from left-to-right) and the return value of the function is stored in an accumulator.
Syntax:
array.reduce( function( total, currentValue, currentIndex, arr ), initialValue )
Example 1: This example uses array reduce() method to find the sum of values of an Array using JavaScript.
<!DOCTYPE html><html> <head> <title> How to Find the sum of Values of an Array in JavaScript? </title></head> <body style="text-align:center;"> <h1 style = "color:green;" > GeeksForGeeks </h1> <h3> How to Find the sum of Values of an Array in JavaScript? </h3> <h4> ----Given Array----<br> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11] </h4> <button onclick="myGeeks()"> Click Here! </button> <br><br> Sum: <span id="GFG"></span> <script> var arr=[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]; function sumofArray(sum, num) { return sum + num; } function myGeeks(item) { document.getElementById("GFG").innerHTML = arr.reduce(sumofArray); } </script></body> </html>
Output:
Before click on the Button:
After Click on the Button:
Example 2: This example uses array reduce() method to find the product of values of an Array using JavaScript.
<!DOCTYPE html><html> <head> <title> How to Find the product of Values of an Array in JavaScript? </title></head> <body style="text-align:center;"> <h1 style = "color:green;" > GeeksForGeeks </h1> <h3> How to Find the product of Values of an Array in JavaScript? </h3> <h4> ----Given Array----<br> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11] </h4> <button onclick="myGeeks()"> Click Here! </button> <br><br> Product: <span id="GFG"></span> <script> var arr=[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]; function productofArray(product, num) { return product * num; } function myGeeks(item) { document.getElementById("GFG").innerHTML = arr.reduce(productofArray); } </script></body> </html>
Output:
Before click on the Button:
After Click on the Button:
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
Remove elements from a JavaScript Array
Roadmap to Learn JavaScript For Beginners
Difference Between PUT and PATCH Request
JavaScript | Promises
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": "\n12 Sep, 2019"
},
{
"code": null,
"e": 131,
"s": 28,
"text": "Given an array and is the task to find the Sum and Product of the values of an Array using JavaScript."
},
{
"code": null,
"e": 303,
"s": 131,
"text": "Simple method: It uses a simple method to access the array elements by an index number and use the loop to find the sum and product of values of an Array using JavaScript."
},
{
"code": null,
"e": 400,
"s": 303,
"text": "Example 1: This example uses a simple method to find the sum of Array elements using JavaScript."
},
{
"code": "<!DOCTYPE html><html> <head> <title> How to Find the sum of Values of an Array in JavaScript? </title></head> <body style=\"text-align:center;\"> <h1 style = \"color:green;\" > GeeksForGeeks </h1> <h3> How to Find the sum of Values of an Array in JavaScript? </h3> <h4> ----Given Array----<br> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11] </h4> <button onclick=\"myFunction()\">Click</button> <p id=\"gfg\"></p> <script> $(document).ready(function() { $(\"button\").click(function() { function sum(input) { if (toString.call(input) !== \"[object Array]\") return false; var total = 0; for(var i=0;i<input.length;i++) { if(isNaN(input[i])) { continue; } total += Number(input[i]); } return total; } document.getElementById(\"gfg\").innerHTML = \"----Sum of Array----\" + \"<br>\" + sum([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]); }); }); </script></body> </html> ",
"e": 1772,
"s": 400,
"text": null
},
{
"code": null,
"e": 1780,
"s": 1772,
"text": "Output:"
},
{
"code": null,
"e": 1808,
"s": 1780,
"text": "Before click on the Button:"
},
{
"code": null,
"e": 1835,
"s": 1808,
"text": "After Click on the Button:"
},
{
"code": null,
"e": 1936,
"s": 1835,
"text": "Example 2: This example uses a simple method to find the product of Array elements using JavaScript."
},
{
"code": "<!DOCTYPE html><html> <head> <title> How to Find the product of Values of an Array in JavaScript? </title></head> <body style=\"text-align:center;\"> <h1 style = \"color:green;\" > GeeksForGeeks </h1> <h3> How to Find the product of Values of an Array in JavaScript? </h3> <h4> ----Given Array----<br> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11] </h4> <button onclick=\"myFunction()\">Click</button> <p id=\"gfg\"></p> <script> $(document).ready(function(){ $(\"button\").click(function(){ function product(input) { if (toString.call(input) !== \"[object Array]\") return false; var total = 1; for(var i=0;i<input.length;i++) { if(isNaN(input[i])){ continue; } total *= Number(input[i]); } return total; } document.getElementById(\"gfg\").innerHTML = \"----product of Array----\" + \"<br>\" + product([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]); }); }); </script></body> </html> ",
"e": 3302,
"s": 1936,
"text": null
},
{
"code": null,
"e": 3310,
"s": 3302,
"text": "Output:"
},
{
"code": null,
"e": 3338,
"s": 3310,
"text": "Before click on the Button:"
},
{
"code": null,
"e": 3365,
"s": 3338,
"text": "After Click on the Button:"
},
{
"code": null,
"e": 3622,
"s": 3365,
"text": "Using reduce() method: The array reduce() method in JavaScript is used to reduce the array to a single value and executes a provided function for each value of the array (from left-to-right) and the return value of the function is stored in an accumulator."
},
{
"code": null,
"e": 3630,
"s": 3622,
"text": "Syntax:"
},
{
"code": null,
"e": 3711,
"s": 3630,
"text": "array.reduce( function( total, currentValue, currentIndex, arr ), initialValue )"
},
{
"code": null,
"e": 3818,
"s": 3711,
"text": "Example 1: This example uses array reduce() method to find the sum of values of an Array using JavaScript."
},
{
"code": "<!DOCTYPE html><html> <head> <title> How to Find the sum of Values of an Array in JavaScript? </title></head> <body style=\"text-align:center;\"> <h1 style = \"color:green;\" > GeeksForGeeks </h1> <h3> How to Find the sum of Values of an Array in JavaScript? </h3> <h4> ----Given Array----<br> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11] </h4> <button onclick=\"myGeeks()\"> Click Here! </button> <br><br> Sum: <span id=\"GFG\"></span> <script> var arr=[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]; function sumofArray(sum, num) { return sum + num; } function myGeeks(item) { document.getElementById(\"GFG\").innerHTML = arr.reduce(sumofArray); } </script></body> </html> ",
"e": 4709,
"s": 3818,
"text": null
},
{
"code": null,
"e": 4717,
"s": 4709,
"text": "Output:"
},
{
"code": null,
"e": 4745,
"s": 4717,
"text": "Before click on the Button:"
},
{
"code": null,
"e": 4772,
"s": 4745,
"text": "After Click on the Button:"
},
{
"code": null,
"e": 4883,
"s": 4772,
"text": "Example 2: This example uses array reduce() method to find the product of values of an Array using JavaScript."
},
{
"code": "<!DOCTYPE html><html> <head> <title> How to Find the product of Values of an Array in JavaScript? </title></head> <body style=\"text-align:center;\"> <h1 style = \"color:green;\" > GeeksForGeeks </h1> <h3> How to Find the product of Values of an Array in JavaScript? </h3> <h4> ----Given Array----<br> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11] </h4> <button onclick=\"myGeeks()\"> Click Here! </button> <br><br> Product: <span id=\"GFG\"></span> <script> var arr=[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]; function productofArray(product, num) { return product * num; } function myGeeks(item) { document.getElementById(\"GFG\").innerHTML = arr.reduce(productofArray); } </script></body> </html> ",
"e": 5807,
"s": 4883,
"text": null
},
{
"code": null,
"e": 5815,
"s": 5807,
"text": "Output:"
},
{
"code": null,
"e": 5843,
"s": 5815,
"text": "Before click on the Button:"
},
{
"code": null,
"e": 5870,
"s": 5843,
"text": "After Click on the Button:"
},
{
"code": null,
"e": 5881,
"s": 5870,
"text": "JavaScript"
},
{
"code": null,
"e": 5898,
"s": 5881,
"text": "Web Technologies"
},
{
"code": null,
"e": 5925,
"s": 5898,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 6023,
"s": 5925,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 6084,
"s": 6023,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 6124,
"s": 6084,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 6166,
"s": 6124,
"text": "Roadmap to Learn JavaScript For Beginners"
},
{
"code": null,
"e": 6207,
"s": 6166,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 6229,
"s": 6207,
"text": "JavaScript | Promises"
},
{
"code": null,
"e": 6262,
"s": 6229,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 6324,
"s": 6262,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 6385,
"s": 6324,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 6435,
"s": 6385,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
mktime() function in C++ STL
|
20 Jul, 2021
The mktime() is an inbuilt C++ function which converts the local calendar time to the time since epoch and returns the value as an object of type time_t.
Syntax :
time_t mktime( struct tm *time_ptr )
Parameters: The function accepts a mandatory parameter pointer time_ptr that points to a tm object structure that contains a calendar time which is to be converted.
Return Value: The function returns two type of values as described below:
It returns the time since epoch as an object of type time_t if the parameter passed is a success.
It returns -1 on failure.
Below program illustrates the mktime() function:
C++
// C++ program to demonstrate the// mktime() function #include <bits/stdc++.h>using namespace std; int main(){ time_t tim; tm* time_ptr; char weekday[7][20] = { "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" }; // Date int year = 2018; int month = 6; int day = 18; time(&tim); time_ptr = localtime(&tim); // tm_year is time since 1900 time_ptr->tm_year = year - 1900; // Months calculated since January time_ptr->tm_mon = month - 1; // Day calculated in the month time_ptr->tm_mday = day; // time_ptr pointer to be pass mktime(time_ptr); cout << "The Day on 18th June 2018 was " << weekday[time_ptr->tm_wday]; return 0;}
The Day on 18th June 2018 was Monday
manikarora059
CPP-Functions
CPP-Library
date-time-program
STL
C++
STL
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n20 Jul, 2021"
},
{
"code": null,
"e": 182,
"s": 28,
"text": "The mktime() is an inbuilt C++ function which converts the local calendar time to the time since epoch and returns the value as an object of type time_t."
},
{
"code": null,
"e": 192,
"s": 182,
"text": "Syntax : "
},
{
"code": null,
"e": 231,
"s": 192,
"text": "time_t mktime( struct tm *time_ptr )"
},
{
"code": null,
"e": 397,
"s": 231,
"text": "Parameters: The function accepts a mandatory parameter pointer time_ptr that points to a tm object structure that contains a calendar time which is to be converted. "
},
{
"code": null,
"e": 472,
"s": 397,
"text": "Return Value: The function returns two type of values as described below: "
},
{
"code": null,
"e": 570,
"s": 472,
"text": "It returns the time since epoch as an object of type time_t if the parameter passed is a success."
},
{
"code": null,
"e": 596,
"s": 570,
"text": "It returns -1 on failure."
},
{
"code": null,
"e": 646,
"s": 596,
"text": "Below program illustrates the mktime() function: "
},
{
"code": null,
"e": 650,
"s": 646,
"text": "C++"
},
{
"code": "// C++ program to demonstrate the// mktime() function #include <bits/stdc++.h>using namespace std; int main(){ time_t tim; tm* time_ptr; char weekday[7][20] = { \"Sunday\", \"Monday\", \"Tuesday\", \"Wednesday\", \"Thursday\", \"Friday\", \"Saturday\" }; // Date int year = 2018; int month = 6; int day = 18; time(&tim); time_ptr = localtime(&tim); // tm_year is time since 1900 time_ptr->tm_year = year - 1900; // Months calculated since January time_ptr->tm_mon = month - 1; // Day calculated in the month time_ptr->tm_mday = day; // time_ptr pointer to be pass mktime(time_ptr); cout << \"The Day on 18th June 2018 was \" << weekday[time_ptr->tm_wday]; return 0;}",
"e": 1536,
"s": 650,
"text": null
},
{
"code": null,
"e": 1573,
"s": 1536,
"text": "The Day on 18th June 2018 was Monday"
},
{
"code": null,
"e": 1587,
"s": 1573,
"text": "manikarora059"
},
{
"code": null,
"e": 1601,
"s": 1587,
"text": "CPP-Functions"
},
{
"code": null,
"e": 1613,
"s": 1601,
"text": "CPP-Library"
},
{
"code": null,
"e": 1631,
"s": 1613,
"text": "date-time-program"
},
{
"code": null,
"e": 1635,
"s": 1631,
"text": "STL"
},
{
"code": null,
"e": 1639,
"s": 1635,
"text": "C++"
},
{
"code": null,
"e": 1643,
"s": 1639,
"text": "STL"
},
{
"code": null,
"e": 1647,
"s": 1643,
"text": "CPP"
}
] |
Unsupervised Anomaly Detection in Python | by Edwin Tan | Towards Data Science
|
Anomaly detection also known as outlier detection is the process of finding data points within a dataset that differs from the rest. Common applications of anomaly detection includes fraud detection in financial transactions, fault detection and predictive maintenance.
Broadly speaking, anomaly detection can be categorized into supervised and unsupervised realm. Supervised anomaly detection requires labelled dataset that indicates if a record is “normal” or “abnormal”. Unsupervised anomaly detection involves an unlabeled dataset. It assumes that the majority data points in the unlabeled dataset are “normal” and it looks for data points that differs from the “normal” data points.
In this article, we will be using Pycaret for detecting anomalies. Pycaret is an Automated Machine Learning (AutoML) tool that can be used for both supervised and unsupervised learning.
Let’s start by installing PyCaret.
pip install pycaret==2.3.5pip install scipy==1.4.1
Import the necessary modules
from pycaret.anomaly import *from sklearn.datasets import load_breast_cancer
Load the dataset
We will be using the Wisconsin Breast Cancer (Diagnostic) dataset[1] from UCI Machine Learning Repository[2] which contains features computed digitized image of a fine needle aspirate of a breast mass and the diagnosis if the mass is benign (B) or malignant (M). This dataset commonly used for demonstrating supervised machine learning where a model is trained to predict the diagnosis. For the purpose of demonstrating unsupervised anomaly detection, we will ignore the diagnosis.
We split the data into the training set reserve a small “unseen” set for scoring.
df = load_breast_cancer(as_frame=True)['data']df_train = df.iloc[:-10]df_unseen = df.tail(10)
Set up Pycaret
anom = setup(data = df_train, silent = True)
Setting the silent parameter to True automatically confirms the input of data types when setup is executed. If silent is set to False, Pycaret requires the user to do manual confirmation of the input data types as shown in the image below.
Pycaret will infer the data type if they are not explicitly defined. We can also define which columns contain categorical, numeric, ordinal and date features using the categorical_features ,numeric_features ,ordinal_features parameters. Defining the different data type will affect how the column is being pre-processed. For example, the categorical_imputation parameter determines how missing categorical values are being handled with. The available options are constant and mode. Similarly for numeric features, the numeric_imputation parameter determines how missing numeric values are being handled. The available options are mean, medianor zero.
There is a wide range of other pre-processing options such as normalization, dimension reduction and even custom transformation. Check out the documentation for more details.
Check available models
Let’s check what anomaly detection models are available in Pycaret.
models()
The reference column indicates which source package the model was built from. PyOD (Python Outlier Detection) is a package that offers wide variety of outlier detection models.
Train the anomaly detection model
anom_model = create_model(model = 'iforest', fraction = 0.05)
We train an anomaly detection model by defining the model’s ID. The fraction parameter indicates indicates the amount of outliers present in the dataset. The default value is 0.05 which indicates that the dataset has 5% of outliers.
Score the dataset
results = assign_model(anom_model)
assign_model scores the training dataset using the trained model and returns the prediction of the model, concatenated with the training data. The Anomaly column is binary where 1 indicates that the record is anomalous and 0 indicates that it is normal. The Anomaly_Score column gives the raw score for the record, where negative indicates that the record is normal.
Plot model
The plot_model function helps to visualize high dimension data using TSNE or UMAP.
plot_model(anom_model, plot = 'tsne')
plot_model(anom_model, plot = 'umap')
Save the model
save_model saves the transformation pipeline and the trained model as a pickle file. The pickle file contains a scikit-learn pipeline object.
save_model(model = anom_model, model_name = 'iforest_model')
Load the model
load_model loads the saved transformation pipeline and trained model as a scikit-learn pipeline object.
loaded_model = load_model('iforest_model')type(loaded_model)>> sklearn.pipeline.Pipeline
Score on unseen data
The predict method will get us the a binary output of 1 or 0 where 1 represents an abnormal record and 0 represents a normal record.
loaded_model.predict(df_unseen)>> array([0, 0, 0, 0, 0, 1, 0, 0, 1, 0])
The predict_proba method will get us the probability of a record being classified as 0 or 1 .
loaded_model.predict_proba(df_unseen)>> array([[0.81527091, 0.18472909], [0.88219213, 0.11780787], [0.4789605 , 0.5210395 ], [0.46277058, 0.53722942], [0.47638085, 0.52361915], [0.4421625 , 0.5578375 ], [0.68153289, 0.31846711], [0.75207438, 0.24792562], [0.27120702, 0.72879298], [0.54821746, 0.45178254]])
The decision_function method will return us the anomaly score
loaded_model.decision_function(df_unseen)>> array([-0.11826784, -0.14024322, -0.00783128, -0.00251488, -0.00698418, 0.00425233, -0.07435137, -0.09751556, 0.06039016, -0.03057366])
In this article we explored how to quickly train an unsupervised anomaly detection model using Pycaret, visualize the high dimension features using TSNE or UMAP and use the trained model to predict on unseen data.
Join Medium to read more stories like this.
[1] Breast Cancer Wisconsin (Diagnostic) Data Set
Creators:
1. Dr. William H. Wolberg, General Surgery Dept.University of Wisconsin, Clinical Sciences CenterMadison, WI 53792wolberg ‘@’ eagle.surgery.wisc.edu
2. W. Nick Street, Computer Sciences Dept.University of Wisconsin, 1210 West Dayton St., Madison, WI 53706street ‘@’ cs.wisc.edu 608–262–6619
3. Olvi L. Mangasarian, Computer Sciences Dept.University of Wisconsin, 1210 West Dayton St., Madison, WI 53706olvi ‘@’ cs.wisc.edu
Donor: Nick Street
License: CC BY 4.0
[2] Dua, D. and Graff, C. (2019). UCI Machine Learning Repository [http://archive.ics.uci.edu/ml]. Irvine, CA: University of California, School of Information and Computer Science.
|
[
{
"code": null,
"e": 442,
"s": 172,
"text": "Anomaly detection also known as outlier detection is the process of finding data points within a dataset that differs from the rest. Common applications of anomaly detection includes fraud detection in financial transactions, fault detection and predictive maintenance."
},
{
"code": null,
"e": 860,
"s": 442,
"text": "Broadly speaking, anomaly detection can be categorized into supervised and unsupervised realm. Supervised anomaly detection requires labelled dataset that indicates if a record is “normal” or “abnormal”. Unsupervised anomaly detection involves an unlabeled dataset. It assumes that the majority data points in the unlabeled dataset are “normal” and it looks for data points that differs from the “normal” data points."
},
{
"code": null,
"e": 1046,
"s": 860,
"text": "In this article, we will be using Pycaret for detecting anomalies. Pycaret is an Automated Machine Learning (AutoML) tool that can be used for both supervised and unsupervised learning."
},
{
"code": null,
"e": 1081,
"s": 1046,
"text": "Let’s start by installing PyCaret."
},
{
"code": null,
"e": 1132,
"s": 1081,
"text": "pip install pycaret==2.3.5pip install scipy==1.4.1"
},
{
"code": null,
"e": 1161,
"s": 1132,
"text": "Import the necessary modules"
},
{
"code": null,
"e": 1238,
"s": 1161,
"text": "from pycaret.anomaly import *from sklearn.datasets import load_breast_cancer"
},
{
"code": null,
"e": 1255,
"s": 1238,
"text": "Load the dataset"
},
{
"code": null,
"e": 1737,
"s": 1255,
"text": "We will be using the Wisconsin Breast Cancer (Diagnostic) dataset[1] from UCI Machine Learning Repository[2] which contains features computed digitized image of a fine needle aspirate of a breast mass and the diagnosis if the mass is benign (B) or malignant (M). This dataset commonly used for demonstrating supervised machine learning where a model is trained to predict the diagnosis. For the purpose of demonstrating unsupervised anomaly detection, we will ignore the diagnosis."
},
{
"code": null,
"e": 1819,
"s": 1737,
"text": "We split the data into the training set reserve a small “unseen” set for scoring."
},
{
"code": null,
"e": 1913,
"s": 1819,
"text": "df = load_breast_cancer(as_frame=True)['data']df_train = df.iloc[:-10]df_unseen = df.tail(10)"
},
{
"code": null,
"e": 1928,
"s": 1913,
"text": "Set up Pycaret"
},
{
"code": null,
"e": 1986,
"s": 1928,
"text": "anom = setup(data = df_train, silent = True)"
},
{
"code": null,
"e": 2226,
"s": 1986,
"text": "Setting the silent parameter to True automatically confirms the input of data types when setup is executed. If silent is set to False, Pycaret requires the user to do manual confirmation of the input data types as shown in the image below."
},
{
"code": null,
"e": 2877,
"s": 2226,
"text": "Pycaret will infer the data type if they are not explicitly defined. We can also define which columns contain categorical, numeric, ordinal and date features using the categorical_features ,numeric_features ,ordinal_features parameters. Defining the different data type will affect how the column is being pre-processed. For example, the categorical_imputation parameter determines how missing categorical values are being handled with. The available options are constant and mode. Similarly for numeric features, the numeric_imputation parameter determines how missing numeric values are being handled. The available options are mean, medianor zero."
},
{
"code": null,
"e": 3052,
"s": 2877,
"text": "There is a wide range of other pre-processing options such as normalization, dimension reduction and even custom transformation. Check out the documentation for more details."
},
{
"code": null,
"e": 3075,
"s": 3052,
"text": "Check available models"
},
{
"code": null,
"e": 3143,
"s": 3075,
"text": "Let’s check what anomaly detection models are available in Pycaret."
},
{
"code": null,
"e": 3152,
"s": 3143,
"text": "models()"
},
{
"code": null,
"e": 3329,
"s": 3152,
"text": "The reference column indicates which source package the model was built from. PyOD (Python Outlier Detection) is a package that offers wide variety of outlier detection models."
},
{
"code": null,
"e": 3363,
"s": 3329,
"text": "Train the anomaly detection model"
},
{
"code": null,
"e": 3425,
"s": 3363,
"text": "anom_model = create_model(model = 'iforest', fraction = 0.05)"
},
{
"code": null,
"e": 3658,
"s": 3425,
"text": "We train an anomaly detection model by defining the model’s ID. The fraction parameter indicates indicates the amount of outliers present in the dataset. The default value is 0.05 which indicates that the dataset has 5% of outliers."
},
{
"code": null,
"e": 3676,
"s": 3658,
"text": "Score the dataset"
},
{
"code": null,
"e": 3711,
"s": 3676,
"text": "results = assign_model(anom_model)"
},
{
"code": null,
"e": 4078,
"s": 3711,
"text": "assign_model scores the training dataset using the trained model and returns the prediction of the model, concatenated with the training data. The Anomaly column is binary where 1 indicates that the record is anomalous and 0 indicates that it is normal. The Anomaly_Score column gives the raw score for the record, where negative indicates that the record is normal."
},
{
"code": null,
"e": 4089,
"s": 4078,
"text": "Plot model"
},
{
"code": null,
"e": 4172,
"s": 4089,
"text": "The plot_model function helps to visualize high dimension data using TSNE or UMAP."
},
{
"code": null,
"e": 4210,
"s": 4172,
"text": "plot_model(anom_model, plot = 'tsne')"
},
{
"code": null,
"e": 4248,
"s": 4210,
"text": "plot_model(anom_model, plot = 'umap')"
},
{
"code": null,
"e": 4263,
"s": 4248,
"text": "Save the model"
},
{
"code": null,
"e": 4405,
"s": 4263,
"text": "save_model saves the transformation pipeline and the trained model as a pickle file. The pickle file contains a scikit-learn pipeline object."
},
{
"code": null,
"e": 4466,
"s": 4405,
"text": "save_model(model = anom_model, model_name = 'iforest_model')"
},
{
"code": null,
"e": 4481,
"s": 4466,
"text": "Load the model"
},
{
"code": null,
"e": 4585,
"s": 4481,
"text": "load_model loads the saved transformation pipeline and trained model as a scikit-learn pipeline object."
},
{
"code": null,
"e": 4674,
"s": 4585,
"text": "loaded_model = load_model('iforest_model')type(loaded_model)>> sklearn.pipeline.Pipeline"
},
{
"code": null,
"e": 4695,
"s": 4674,
"text": "Score on unseen data"
},
{
"code": null,
"e": 4828,
"s": 4695,
"text": "The predict method will get us the a binary output of 1 or 0 where 1 represents an abnormal record and 0 represents a normal record."
},
{
"code": null,
"e": 4900,
"s": 4828,
"text": "loaded_model.predict(df_unseen)>> array([0, 0, 0, 0, 0, 1, 0, 0, 1, 0])"
},
{
"code": null,
"e": 4994,
"s": 4900,
"text": "The predict_proba method will get us the probability of a record being classified as 0 or 1 ."
},
{
"code": null,
"e": 5356,
"s": 4994,
"text": "loaded_model.predict_proba(df_unseen)>> array([[0.81527091, 0.18472909], [0.88219213, 0.11780787], [0.4789605 , 0.5210395 ], [0.46277058, 0.53722942], [0.47638085, 0.52361915], [0.4421625 , 0.5578375 ], [0.68153289, 0.31846711], [0.75207438, 0.24792562], [0.27120702, 0.72879298], [0.54821746, 0.45178254]])"
},
{
"code": null,
"e": 5418,
"s": 5356,
"text": "The decision_function method will return us the anomaly score"
},
{
"code": null,
"e": 5606,
"s": 5418,
"text": "loaded_model.decision_function(df_unseen)>> array([-0.11826784, -0.14024322, -0.00783128, -0.00251488, -0.00698418, 0.00425233, -0.07435137, -0.09751556, 0.06039016, -0.03057366])"
},
{
"code": null,
"e": 5820,
"s": 5606,
"text": "In this article we explored how to quickly train an unsupervised anomaly detection model using Pycaret, visualize the high dimension features using TSNE or UMAP and use the trained model to predict on unseen data."
},
{
"code": null,
"e": 5864,
"s": 5820,
"text": "Join Medium to read more stories like this."
},
{
"code": null,
"e": 5914,
"s": 5864,
"text": "[1] Breast Cancer Wisconsin (Diagnostic) Data Set"
},
{
"code": null,
"e": 5924,
"s": 5914,
"text": "Creators:"
},
{
"code": null,
"e": 6073,
"s": 5924,
"text": "1. Dr. William H. Wolberg, General Surgery Dept.University of Wisconsin, Clinical Sciences CenterMadison, WI 53792wolberg ‘@’ eagle.surgery.wisc.edu"
},
{
"code": null,
"e": 6215,
"s": 6073,
"text": "2. W. Nick Street, Computer Sciences Dept.University of Wisconsin, 1210 West Dayton St., Madison, WI 53706street ‘@’ cs.wisc.edu 608–262–6619"
},
{
"code": null,
"e": 6347,
"s": 6215,
"text": "3. Olvi L. Mangasarian, Computer Sciences Dept.University of Wisconsin, 1210 West Dayton St., Madison, WI 53706olvi ‘@’ cs.wisc.edu"
},
{
"code": null,
"e": 6366,
"s": 6347,
"text": "Donor: Nick Street"
},
{
"code": null,
"e": 6385,
"s": 6366,
"text": "License: CC BY 4.0"
}
] |
process.cpuUsage() Method in Node.js
|
The process.argv() method is used for getting the user and its cpu usage for the current running process. The data is returned in an object with the properties user and system. The values obtained are in microseconds,i.e.10^-6 seconds. The values returned may be greater than the actual elapsed time if multiple cores are performing work for the running process.
process.cpuUsage([previousValue])
The method only accepts a single parameter which is defined below −
previousValue – This is an optional parameter. This is the previous return value by calling the process.cpuUsage() method.
previousValue – This is an optional parameter. This is the previous return value by calling the process.cpuUsage() method.
Create a file with name – cpuUsage.js and copy the below code snippet. After creating file, use the following command to run this code as shown in the example below −
node cpuUsage.js
cpuUsage.js
Live Demo
// Node.js program to demonstrate the use of process.argv
// Importing the process module
const process = require('process');
// Getting the cpu usage details by calling the below method
const usage = process.cpuUsage();
// Printing the cpu usage values
console.log(usage);
admin@root:~/node/test$ node cpuUsage.js
{ user: 352914, system: 19826 }
Let's take a look at one more example.
Live Demo
// Node.js program to demonstrate the use of process.argv
// Importing the process module
const process = require('process');
// Getting the cpu usage details by calling the below method
var usage = process.cpuUsage();
// Printing the cpu usage values
console.log("cpu usage before: ", usage);
// Printing the current time stamp
const now = Date.now();
// Looping to delay the process for 100 milliseconds
while (Date.now() - now < 100);
// After using the cpu for nearly 100ms
// calling the process.cpuUsage() method again...
usage = process.cpuUsage(usage);
// Printing the new cpu usage values
console.log("Cpu usage by this process: ", usage);
admin@root:~/node/test$ node cpuUsage.js
cpu usage before: { user: 357675, system: 32150 }
Cpu usage by this process: { user: 93760, system: 95 }
|
[
{
"code": null,
"e": 1425,
"s": 1062,
"text": "The process.argv() method is used for getting the user and its cpu usage for the current running process. The data is returned in an object with the properties user and system. The values obtained are in microseconds,i.e.10^-6 seconds. The values returned may be greater than the actual elapsed time if multiple cores are performing work for the running process."
},
{
"code": null,
"e": 1459,
"s": 1425,
"text": "process.cpuUsage([previousValue])"
},
{
"code": null,
"e": 1527,
"s": 1459,
"text": "The method only accepts a single parameter which is defined below −"
},
{
"code": null,
"e": 1650,
"s": 1527,
"text": "previousValue – This is an optional parameter. This is the previous return value by calling the process.cpuUsage() method."
},
{
"code": null,
"e": 1773,
"s": 1650,
"text": "previousValue – This is an optional parameter. This is the previous return value by calling the process.cpuUsage() method."
},
{
"code": null,
"e": 1940,
"s": 1773,
"text": "Create a file with name – cpuUsage.js and copy the below code snippet. After creating file, use the following command to run this code as shown in the example below −"
},
{
"code": null,
"e": 1957,
"s": 1940,
"text": "node cpuUsage.js"
},
{
"code": null,
"e": 1969,
"s": 1957,
"text": "cpuUsage.js"
},
{
"code": null,
"e": 1980,
"s": 1969,
"text": " Live Demo"
},
{
"code": null,
"e": 2257,
"s": 1980,
"text": "// Node.js program to demonstrate the use of process.argv\n\n// Importing the process module\nconst process = require('process');\n\n// Getting the cpu usage details by calling the below method\nconst usage = process.cpuUsage();\n\n// Printing the cpu usage values\nconsole.log(usage);"
},
{
"code": null,
"e": 2330,
"s": 2257,
"text": "admin@root:~/node/test$ node cpuUsage.js\n{ user: 352914, system: 19826 }"
},
{
"code": null,
"e": 2369,
"s": 2330,
"text": "Let's take a look at one more example."
},
{
"code": null,
"e": 2380,
"s": 2369,
"text": " Live Demo"
},
{
"code": null,
"e": 3035,
"s": 2380,
"text": "// Node.js program to demonstrate the use of process.argv\n\n// Importing the process module\nconst process = require('process');\n\n// Getting the cpu usage details by calling the below method\nvar usage = process.cpuUsage();\n// Printing the cpu usage values\nconsole.log(\"cpu usage before: \", usage);\n\n// Printing the current time stamp\nconst now = Date.now();\n\n// Looping to delay the process for 100 milliseconds\nwhile (Date.now() - now < 100);\n\n// After using the cpu for nearly 100ms\n// calling the process.cpuUsage() method again...\nusage = process.cpuUsage(usage);\n\n// Printing the new cpu usage values\nconsole.log(\"Cpu usage by this process: \", usage);"
},
{
"code": null,
"e": 3181,
"s": 3035,
"text": "admin@root:~/node/test$ node cpuUsage.js\ncpu usage before: { user: 357675, system: 32150 }\nCpu usage by this process: { user: 93760, system: 95 }"
}
] |
JavaScript Prompt Example
|
The prompt dialog box is very useful when you want to pop-up a text box to get user input. Thus, it enables you to interact with the user. The user needs to fill in the field and then click OK. This dialog box is displayed using a method called prompt()
Following is the code for showing prompt in JavaScript −
Live Demo
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
body {
font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
}
.result {
font-size: 18px;
font-weight: 500;
color: blueviolet;
}
</style>
</head>
<body>
<h1>JavaScript Prompt() method</h1>
<div class="result"></div>
<button class="Btn">CLICK HERE</button>
<h3>Click on the above button to get the prompt dialogue box</h3>
<script>
let resultEle = document.querySelector(".result");
document.querySelector(".Btn").addEventListener("click", () => {
let res = prompt("Are you sure");
if (res === null) {
resultEle.innerHTML = "You pressed cancel";
} else {
resultEle.innerHTML = "You entered " + res + " in the prompt box";
}
});
</script>
</body>
</html>
On clicking on ‘CLICK HERE’ button and typing something in the promt box −
On clicking OK on the prompt box −
|
[
{
"code": null,
"e": 1316,
"s": 1062,
"text": "The prompt dialog box is very useful when you want to pop-up a text box to get user input. Thus, it enables you to interact with the user. The user needs to fill in the field and then click OK. This dialog box is displayed using a method called prompt()"
},
{
"code": null,
"e": 1373,
"s": 1316,
"text": "Following is the code for showing prompt in JavaScript −"
},
{
"code": null,
"e": 1384,
"s": 1373,
"text": " Live Demo"
},
{
"code": null,
"e": 2251,
"s": 1384,
"text": "<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n<meta charset=\"UTF-8\" />\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" />\n<title>Document</title>\n<style>\nbody {\n font-family: \"Segoe UI\", Tahoma, Geneva, Verdana, sans-serif;\n}\n.result {\n font-size: 18px;\n font-weight: 500;\n color: blueviolet;\n}\n</style>\n</head>\n<body>\n<h1>JavaScript Prompt() method</h1>\n<div class=\"result\"></div>\n<button class=\"Btn\">CLICK HERE</button>\n<h3>Click on the above button to get the prompt dialogue box</h3>\n<script>\nlet resultEle = document.querySelector(\".result\");\ndocument.querySelector(\".Btn\").addEventListener(\"click\", () => {\n let res = prompt(\"Are you sure\");\n if (res === null) {\n resultEle.innerHTML = \"You pressed cancel\";\n } else {\n resultEle.innerHTML = \"You entered \" + res + \" in the prompt box\";\n }\n});\n</script>\n</body>\n</html>"
},
{
"code": null,
"e": 2326,
"s": 2251,
"text": "On clicking on ‘CLICK HERE’ button and typing something in the promt box −"
},
{
"code": null,
"e": 2361,
"s": 2326,
"text": "On clicking OK on the prompt box −"
}
] |
Detecting knee- / elbow points in a graph | by Daniel Kleine | Towards Data Science
|
When working with data, it is sometimes important to know where a data point’s “relative costs to increase some tunable parameter is no longer worth the corresponding performance benefit” (Satopää, Albrecht, Irwin, and Raghavan, 2011, [2], p.1 ). The algorithm “Kneedle” detects those beneficial data points showing the best balance inherent tradeoffs — called “knees” (curves that have negative concavity) or sometimes “elbows” (curves that have positive concavity) — in discrete data sets based on the mathematical definition of curvature for continuous functions. With this article, I want to summarize the steps “Kneedle” goes through, demonstrate the benefits of this algorithm and show applications with the Python package “kneed”.
The “Kneedle” algorithm has been published by Satopää, Albrecht, Irwin, and Raghavan (2011, [2]) using the concept of curvature as a mathematical measure of much a function differs from a straight line. Satopää et al. (2011, [2], p. 2) conclude that “as a result, the maximum curvature captures the leveling off effects operators use to identify knees”.
ieeexplore.ieee.org
For continuous functions, the curvature is described as shown here:
en.wikipedia.org
Let’s create for instance N = 10,000 random standard normal distributed data points and display them in a histogram:
Now we can sort the values in an ascending order to get a cumulative distribution function (CDF) showing each x-value on the x-axis and its probability of occurrence on the y-axis:
Satopää et al. (2011, [2], p. 2) point out that “curvature is well-defined for continuous functions”, but there is no clear definition of curvature for discrete data. In this instance, the curvature can be fitted to a continuous function — but when the data is noisy, this fitting can become even more difficult. This is where the “Kneedle” algorithm comes into play.
Let’s take a deeper look how this algorithm works. For this, I have used the original discrete data from Figure 2 in the conference paper published by Satopää et alia (2011, [2]). It’s provided by the Python package “kneed”:
import kneedkneed.DataGenerator.figure2()
This is the raw data being plotted:
Let’s get through the steps the “Kneedle” algorithm follows:
1. Normalizing to the unit square
Using a spline to “smooth” the shape of the raw data.
2. Normalizing to the unit square
Range of x- and y-values will be normalized to 0 to 1 (see axes).
3. Calculating the difference curve changes
Calculating perpendicular distances (Euclidean distances from the data points to diagonal given line from first to last data point)...
... and rotating them by 45 degrees counter clockwise. The magnitude of these rotated perpendicular lines indicates the difference values.
4. Calculating the local maxima of the difference curve
Finding the “knee” points at the local maxima of the difference curve in the normalized curve (for detecting elbow points, the graph will be inverted).
5. Calculating threshold for each local maximum in the difference curve
For each local maximum in the difference curve, there is a unique threshold value that is based on the average difference between the x-values and a sensitivity parameter (please see Satopää et al., 2011 [2], p. 4 for further reference how this threshold is computed in detail). This sensitivity parameter measures how many “flat” points are expected to be seen in the original unmodified data before declaring a “knee” and can be adjusted: A small sensitivity value detects knees quicker, whereas a larger one is more conservative.
6. Each difference value is compared with threshold
If a difference value drops below the threshold before the local maximum is reached, the algorithm is declaring a “knee”. Conversely, the threshold value is reset to zero.
Now let’s take a deeper look into the Python package “kneed” written by Kevin Arvai that uses the “Kneedle" algorithm:
pypi.org
With this, we can for instance directly plot the normalized difference curve including the “knee” point:
kneed.readthedocs.io
We can use the function KneedLocator() in order to find a knee/elbow in our data:
# calculate and show knee/elbowkneedle = kneed.KneeLocator(...)knee_point = kneedle.knee #elbow_point = kneedle.elbowprint('Knee: ', knee_point) #print('Elbow: ', elbow_point)kneedle.plot_knee()
These are the most important parameters for KneedLocator():
curve: ”concave” for a “knee”, convex for an “elbow” — based on the negative/positive concavity of the function
direction: “increasing” for a positive slope, “decreasing” for a negative slope of the function
online: Knee as first element detected (False) or correcting “old” knee values if necessary if points are received (True)
S: Sensitivity for knee detection (S=0 or bigger); Satopää et alia [2] state that “kneedle” has perfect information in offline setting when sensitivity is 0 whereas in online settings, overall a sensitivity of 1 shows the best overall performance, but it can vary from the data points received.
Detecting elbows with the “kneedle” algorithm becomes super handy for clustering algorithms:
a) K-Means
With the elbow method, you can calculate the within-cluster sum of squares as a measure of the within-cluster variance and detect the best value for the number of clusters to form (k):
b) DBSCAN
When calculating the distance metric (usually Euclidean distance) for each data point and sorting them in an ascending order, they can be plotted in a k-distances graph to a find a threshold value for defining a cluster:
Even for classification, “Kneedle” becomes extremely useful when looking at the True Positive Rate as well as the False Positive Rate. Both their trade-offs are represented in a receiver operating characteristic curve . The “knee” in a ROC curve can provide a good measure for a threshold value as the TPR’s increase slows down and the FPR starts increasing faster at this point:
“kneed” also provides an interactive API called “ikneed” on Streamlit, where you can test (small) data sets for “knees” respectively “elbows”. There you can also play around with the parameters (please see link to see their impacts directly):
https://share.streamlit.io/arvkevi/ikneed/main/ikneed.py
github.com
In my opinion, “kneed” is currently the most powerful Python package for knee detection as it provides a lot of useful functions. Nevertheless, there are other similar Python packages provided for finding knees of a curve, such as “kneebow”:
pypi.org
[1] Photo by Lucaxx Freire on Unsplash
[2] V. Satopää, J. Albrecht, D. Irwin and B. Raghavan, “Finding a “Kneedle” in a Haystack: Detecting Knee Points in System Behavior” (2011), 31st International Conference on Distributed Computing Systems Workshops, 2011, pp. 166–171, doi: 10.1109/ICDCSW.2011.20.
|
[
{
"code": null,
"e": 912,
"s": 172,
"text": "When working with data, it is sometimes important to know where a data point’s “relative costs to increase some tunable parameter is no longer worth the corresponding performance benefit” (Satopää, Albrecht, Irwin, and Raghavan, 2011, [2], p.1 ). The algorithm “Kneedle” detects those beneficial data points showing the best balance inherent tradeoffs — called “knees” (curves that have negative concavity) or sometimes “elbows” (curves that have positive concavity) — in discrete data sets based on the mathematical definition of curvature for continuous functions. With this article, I want to summarize the steps “Kneedle” goes through, demonstrate the benefits of this algorithm and show applications with the Python package “kneed”."
},
{
"code": null,
"e": 1270,
"s": 912,
"text": "The “Kneedle” algorithm has been published by Satopää, Albrecht, Irwin, and Raghavan (2011, [2]) using the concept of curvature as a mathematical measure of much a function differs from a straight line. Satopää et al. (2011, [2], p. 2) conclude that “as a result, the maximum curvature captures the leveling off effects operators use to identify knees”."
},
{
"code": null,
"e": 1290,
"s": 1270,
"text": "ieeexplore.ieee.org"
},
{
"code": null,
"e": 1358,
"s": 1290,
"text": "For continuous functions, the curvature is described as shown here:"
},
{
"code": null,
"e": 1375,
"s": 1358,
"text": "en.wikipedia.org"
},
{
"code": null,
"e": 1492,
"s": 1375,
"text": "Let’s create for instance N = 10,000 random standard normal distributed data points and display them in a histogram:"
},
{
"code": null,
"e": 1673,
"s": 1492,
"text": "Now we can sort the values in an ascending order to get a cumulative distribution function (CDF) showing each x-value on the x-axis and its probability of occurrence on the y-axis:"
},
{
"code": null,
"e": 2043,
"s": 1673,
"text": "Satopää et al. (2011, [2], p. 2) point out that “curvature is well-defined for continuous functions”, but there is no clear definition of curvature for discrete data. In this instance, the curvature can be fitted to a continuous function — but when the data is noisy, this fitting can become even more difficult. This is where the “Kneedle” algorithm comes into play."
},
{
"code": null,
"e": 2270,
"s": 2043,
"text": "Let’s take a deeper look how this algorithm works. For this, I have used the original discrete data from Figure 2 in the conference paper published by Satopää et alia (2011, [2]). It’s provided by the Python package “kneed”:"
},
{
"code": null,
"e": 2312,
"s": 2270,
"text": "import kneedkneed.DataGenerator.figure2()"
},
{
"code": null,
"e": 2348,
"s": 2312,
"text": "This is the raw data being plotted:"
},
{
"code": null,
"e": 2409,
"s": 2348,
"text": "Let’s get through the steps the “Kneedle” algorithm follows:"
},
{
"code": null,
"e": 2443,
"s": 2409,
"text": "1. Normalizing to the unit square"
},
{
"code": null,
"e": 2497,
"s": 2443,
"text": "Using a spline to “smooth” the shape of the raw data."
},
{
"code": null,
"e": 2531,
"s": 2497,
"text": "2. Normalizing to the unit square"
},
{
"code": null,
"e": 2597,
"s": 2531,
"text": "Range of x- and y-values will be normalized to 0 to 1 (see axes)."
},
{
"code": null,
"e": 2641,
"s": 2597,
"text": "3. Calculating the difference curve changes"
},
{
"code": null,
"e": 2776,
"s": 2641,
"text": "Calculating perpendicular distances (Euclidean distances from the data points to diagonal given line from first to last data point)..."
},
{
"code": null,
"e": 2915,
"s": 2776,
"text": "... and rotating them by 45 degrees counter clockwise. The magnitude of these rotated perpendicular lines indicates the difference values."
},
{
"code": null,
"e": 2971,
"s": 2915,
"text": "4. Calculating the local maxima of the difference curve"
},
{
"code": null,
"e": 3123,
"s": 2971,
"text": "Finding the “knee” points at the local maxima of the difference curve in the normalized curve (for detecting elbow points, the graph will be inverted)."
},
{
"code": null,
"e": 3195,
"s": 3123,
"text": "5. Calculating threshold for each local maximum in the difference curve"
},
{
"code": null,
"e": 3730,
"s": 3195,
"text": "For each local maximum in the difference curve, there is a unique threshold value that is based on the average difference between the x-values and a sensitivity parameter (please see Satopää et al., 2011 [2], p. 4 for further reference how this threshold is computed in detail). This sensitivity parameter measures how many “flat” points are expected to be seen in the original unmodified data before declaring a “knee” and can be adjusted: A small sensitivity value detects knees quicker, whereas a larger one is more conservative."
},
{
"code": null,
"e": 3782,
"s": 3730,
"text": "6. Each difference value is compared with threshold"
},
{
"code": null,
"e": 3954,
"s": 3782,
"text": "If a difference value drops below the threshold before the local maximum is reached, the algorithm is declaring a “knee”. Conversely, the threshold value is reset to zero."
},
{
"code": null,
"e": 4073,
"s": 3954,
"text": "Now let’s take a deeper look into the Python package “kneed” written by Kevin Arvai that uses the “Kneedle\" algorithm:"
},
{
"code": null,
"e": 4082,
"s": 4073,
"text": "pypi.org"
},
{
"code": null,
"e": 4187,
"s": 4082,
"text": "With this, we can for instance directly plot the normalized difference curve including the “knee” point:"
},
{
"code": null,
"e": 4208,
"s": 4187,
"text": "kneed.readthedocs.io"
},
{
"code": null,
"e": 4290,
"s": 4208,
"text": "We can use the function KneedLocator() in order to find a knee/elbow in our data:"
},
{
"code": null,
"e": 4485,
"s": 4290,
"text": "# calculate and show knee/elbowkneedle = kneed.KneeLocator(...)knee_point = kneedle.knee #elbow_point = kneedle.elbowprint('Knee: ', knee_point) #print('Elbow: ', elbow_point)kneedle.plot_knee()"
},
{
"code": null,
"e": 4545,
"s": 4485,
"text": "These are the most important parameters for KneedLocator():"
},
{
"code": null,
"e": 4657,
"s": 4545,
"text": "curve: ”concave” for a “knee”, convex for an “elbow” — based on the negative/positive concavity of the function"
},
{
"code": null,
"e": 4753,
"s": 4657,
"text": "direction: “increasing” for a positive slope, “decreasing” for a negative slope of the function"
},
{
"code": null,
"e": 4875,
"s": 4753,
"text": "online: Knee as first element detected (False) or correcting “old” knee values if necessary if points are received (True)"
},
{
"code": null,
"e": 5172,
"s": 4875,
"text": "S: Sensitivity for knee detection (S=0 or bigger); Satopää et alia [2] state that “kneedle” has perfect information in offline setting when sensitivity is 0 whereas in online settings, overall a sensitivity of 1 shows the best overall performance, but it can vary from the data points received."
},
{
"code": null,
"e": 5265,
"s": 5172,
"text": "Detecting elbows with the “kneedle” algorithm becomes super handy for clustering algorithms:"
},
{
"code": null,
"e": 5276,
"s": 5265,
"text": "a) K-Means"
},
{
"code": null,
"e": 5461,
"s": 5276,
"text": "With the elbow method, you can calculate the within-cluster sum of squares as a measure of the within-cluster variance and detect the best value for the number of clusters to form (k):"
},
{
"code": null,
"e": 5471,
"s": 5461,
"text": "b) DBSCAN"
},
{
"code": null,
"e": 5692,
"s": 5471,
"text": "When calculating the distance metric (usually Euclidean distance) for each data point and sorting them in an ascending order, they can be plotted in a k-distances graph to a find a threshold value for defining a cluster:"
},
{
"code": null,
"e": 6072,
"s": 5692,
"text": "Even for classification, “Kneedle” becomes extremely useful when looking at the True Positive Rate as well as the False Positive Rate. Both their trade-offs are represented in a receiver operating characteristic curve . The “knee” in a ROC curve can provide a good measure for a threshold value as the TPR’s increase slows down and the FPR starts increasing faster at this point:"
},
{
"code": null,
"e": 6315,
"s": 6072,
"text": "“kneed” also provides an interactive API called “ikneed” on Streamlit, where you can test (small) data sets for “knees” respectively “elbows”. There you can also play around with the parameters (please see link to see their impacts directly):"
},
{
"code": null,
"e": 6372,
"s": 6315,
"text": "https://share.streamlit.io/arvkevi/ikneed/main/ikneed.py"
},
{
"code": null,
"e": 6383,
"s": 6372,
"text": "github.com"
},
{
"code": null,
"e": 6625,
"s": 6383,
"text": "In my opinion, “kneed” is currently the most powerful Python package for knee detection as it provides a lot of useful functions. Nevertheless, there are other similar Python packages provided for finding knees of a curve, such as “kneebow”:"
},
{
"code": null,
"e": 6634,
"s": 6625,
"text": "pypi.org"
},
{
"code": null,
"e": 6673,
"s": 6634,
"text": "[1] Photo by Lucaxx Freire on Unsplash"
}
] |
Sorting an associative array in ascending order - JavaScript
|
Suppose, we have an array of objects like this −
const people = [
{"id":1, "name":"Andrew", "age":30, "gender":"m", "category":"G"},
{"id":2, "name":"Brandon", "age":25, "gender":"m", "category":"G"},
{"id":3, "name":"Christine", "age":20, "gender":"m", "category":"G"},
{"id":4, "name":"Elena", "age":29, "gender":"W", "category":"M"}
];
We are required to write a JavaScript function that takes in one such array and sorts the array in place, according to the age property of each object in increasing order.
Therefore, the output should look something like this −
const output = [
{"id":3, "name":"Christine", "age":20, "gender":"m", "category":"G"},
{"id":2, "name":"Brandon", "age":25, "gender":"m", "category":"G"},
{"id":4, "name":"Elena", "age":29, "gender":"W", "category":"M"},
{"id":1, "name":"Andrew", "age":30, "gender":"m", "category":"G"}
];
Following is the complete code −
const people = [
{"id":1, "name":"Andrew", "age":30, "gender":"m", "category":"G"},
{"id":2, "name":"Brandon", "age":25, "gender":"m", "category":"G"},
{"id":3, "name":"Christine", "age":20, "gender":"m", "category":"G"},
{"id":4, "name":"Elena", "age":29, "gender":"W", "category":"M"}
];
const sorter = (a, b) => {
return a.age - b.age;
};
const sortByAge = arr => {
arr.sort(sorter);
};
sortByAge(people);
console.log(people);
This will produce the following output in console −
[
{ id: 3, name: 'Christine', age: 20, gender: 'm', category: 'G' },
{ id: 2, name: 'Brandon', age: 25, gender: 'm', category: 'G' },
{ id: 4, name: 'Elena', age: 29, gender: 'W', category: 'M' },
{ id: 1, name: 'Andrew', age: 30, gender: 'm', category: 'G' }
]
|
[
{
"code": null,
"e": 1111,
"s": 1062,
"text": "Suppose, we have an array of objects like this −"
},
{
"code": null,
"e": 1415,
"s": 1111,
"text": "const people = [\n {\"id\":1, \"name\":\"Andrew\", \"age\":30, \"gender\":\"m\", \"category\":\"G\"},\n {\"id\":2, \"name\":\"Brandon\", \"age\":25, \"gender\":\"m\", \"category\":\"G\"},\n {\"id\":3, \"name\":\"Christine\", \"age\":20, \"gender\":\"m\", \"category\":\"G\"},\n {\"id\":4, \"name\":\"Elena\", \"age\":29, \"gender\":\"W\", \"category\":\"M\"} \n];"
},
{
"code": null,
"e": 1587,
"s": 1415,
"text": "We are required to write a JavaScript function that takes in one such array and sorts the array in place, according to the age property of each object in increasing order."
},
{
"code": null,
"e": 1643,
"s": 1587,
"text": "Therefore, the output should look something like this −"
},
{
"code": null,
"e": 1945,
"s": 1643,
"text": "const output = [\n {\"id\":3, \"name\":\"Christine\", \"age\":20, \"gender\":\"m\", \"category\":\"G\"},\n {\"id\":2, \"name\":\"Brandon\", \"age\":25, \"gender\":\"m\", \"category\":\"G\"},\n {\"id\":4, \"name\":\"Elena\", \"age\":29, \"gender\":\"W\", \"category\":\"M\"},\n {\"id\":1, \"name\":\"Andrew\", \"age\":30, \"gender\":\"m\", \"category\":\"G\"}\n];"
},
{
"code": null,
"e": 1978,
"s": 1945,
"text": "Following is the complete code −"
},
{
"code": null,
"e": 2426,
"s": 1978,
"text": "const people = [\n {\"id\":1, \"name\":\"Andrew\", \"age\":30, \"gender\":\"m\", \"category\":\"G\"},\n {\"id\":2, \"name\":\"Brandon\", \"age\":25, \"gender\":\"m\", \"category\":\"G\"},\n {\"id\":3, \"name\":\"Christine\", \"age\":20, \"gender\":\"m\", \"category\":\"G\"},\n {\"id\":4, \"name\":\"Elena\", \"age\":29, \"gender\":\"W\", \"category\":\"M\"}\n];\nconst sorter = (a, b) => {\n return a.age - b.age;\n};\nconst sortByAge = arr => {\n arr.sort(sorter);\n};\nsortByAge(people);\nconsole.log(people);"
},
{
"code": null,
"e": 2478,
"s": 2426,
"text": "This will produce the following output in console −"
},
{
"code": null,
"e": 2752,
"s": 2478,
"text": "[\n { id: 3, name: 'Christine', age: 20, gender: 'm', category: 'G' },\n { id: 2, name: 'Brandon', age: 25, gender: 'm', category: 'G' },\n { id: 4, name: 'Elena', age: 29, gender: 'W', category: 'M' },\n { id: 1, name: 'Andrew', age: 30, gender: 'm', category: 'G' }\n]"
}
] |
Gradient Descent animation: 1. Simple linear Regression | by Tobias Roeschl | Towards Data Science
|
The Gradient Descent method is one of the most widely used parameter optimization algorithms in machine learning today. Python’s celluloid-module enables us to create vivid animations of model parameters and costs during gradient descent.
In this article, I exemplarily want to use simple linear regression to visualize batch gradient descent. The goal is to build a linear regression model and train it on some data points we made up. For every training round (‘epoch’), we intend to store current model parameters and costs. Finally, we aim to create some animations with our stored values.
There are various articles on how to set up and fit a linear regression model on Medium alone. In theory, we are trying to find the best fitting, straight line for our data. Mathematically, a straight line in two-dimensional space can be described with the following function: y= w*x+b, with w representing the slope (or “weight) and b representing the y-intercept (or “bias”) of our line. There are numerous methods on how to determine the optimal values for w and b given our n data points. The gradient descent algorithm aims to minimize the mean squared error between observed data points (y) and points we predicted with our regression line (ŷ). The mean squared error is also being referred to as ‘cost function’ (or ‘costs’) usually denoted as J.
With our data points fixed, the cost function is only dependent on the parameters w and b. We aim to adjust our parameters until the cost function reaches its minimum. To get a glimpse on how to adjust (decrease vs. increase) the parameters we introduce the gradient of our cost function ∇J(w,b):
with δJ/δw and δJ/δb being the partial derivatives of J with respect to w and b respectively. By constantly moving our parameters in the opposite direction of the current gradient ∇J, we can stepwise reduce the costs J. The size of the steps we take to reach the (local/global) minimum of J is usually denoted as α and is also referred to as ‘learning rate’. When training our model, our objective is to repeat the following for each epoch until we reach convergence:
Metaphorically speaking, the cost function can be imagined as some mountainous terrain, where beginning from a certain starting point, we want to head downhill until we reach a valley. Analogously, the gradient is giving us the ‘multidimensional slope’ i.e. the direction of where ‘uphill’ is on the mountain surface. That’s why we intend to constantly adjust our parameters in the opposite direction of the gradient.
Gradient descent algorithm can be sub-classified according to how much of the training data is being used simultaneously to compute the gradient of our cost function. In the following example, we use the entire dataset for every update respectively, which is also referred to as batch gradient descent. In Python we import some useful libraries and set up our simple linear regression model:
We then want to introduce our training data, define the learning rate (α=0.001), initialize our starting parameters (w=3, b=-1), and finally train our model. For every epoch, we store the updated values of our parameters, the costs, and some particular predicted y-values in lists. List items are then being stored in numpy arrays where they serve as raw data for our animated plots.
# Introduce training data
x_train = np.array([
[1],
[2],
[4],
[5],
[6],
[7]
])
y_train = np.array([
[4],
[-12],
[3],
[-11],
[-5],
[-17]
])
# Introduce lists where data points are being stored:
w_list=[] # list contains weights
b_list=[] # list contains biases
c_list=[] # list contains costs
ys_list=[] # store arrays of predicted y-values for xs ( -> plot regression line!)
cl_list = [] # list contains predicted y-values for x_train ( -> plot connecting lines!)
xs= np.array([ # set x-values for regression line plot
[-3],
[10]
])
# Train model:
model=LinearRegression(w=3,b=-1,lr=0.001) # set initial parameters and learning rate
for i in range(60000): # set number of epochs
w_list.append(model.params()[0]) # append weights (=slopes) to list
b_list.append(model.params()[1]) # append biases (=y-intercepts) to list
c_list.append(model.cost(x_train,y_train)) # append costs to list
ys_list.append(model.predict(xs).T) # append pairs of predicted y-values for xs
cl_list.append(model.predict(x_train).T) # append predicted y-values for x_train to list
model.fit(x_train, y_train) # fit model
# print parameters and costs after all epochs
print("weight: " + str( model.params()[0]) )
print("y-intercept: " + str( model.params()[1]) )
print("costs: "+ str(model.cost(x_train, y_train)))
weight: [[-2.]]
y-intercept: [2.]
costs: 42.66666666666668
Note that the particularly small learning rate of 0.001 was chosen on purpose to prevent overly large steps during the first epochs of gradient descent. A larger learning rate (e.g. α=0.1) usually results in faster model convergence requiring fewer epochs. However, overly large steps during the first epochs of gradient descent tend to result in less appealing animations or even failure to converge. Just to make sure our fitted parameters converged to their true values, we verify our results with sklearn’s inborn linear regression model.
import sklearn
from sklearn.linear_model import LinearRegression
reg = LinearRegression().fit(x_train, y_train)
print(reg.coef_)
print(reg.intercept_)
[[-2.]]
[2.]
Since we are now confident that our gradient descent algorithm worked out as planned, we can move on to the animations.
With our data points being generated and stored, we can now start to build some animations. We could, for example, plot the values our cost function and parameters take on with respect to the epoch while plotting the corresponding regression line simultaneously:
These rather basic plots reveal a very important characteristic of gradient descent: if set up correctly, costs drop rapidly and parameter values change noticeably at the beginning of gradient descent. With rising epochs, only minor changes to costs and parameter values can be observed. Therefore, plotting all values we initially stored seems unfavorable. While predominantly focusing on the first epochs of the fitting process we can visualize most of the ‘action’ without crashing Python while generating these resource-intensive animations. After trying out some different selections of points to plot, I decided to utilize the first 50 epochs of the fitting process continuously, followed by plotting only every 5th or 200th data point until the number of epochs reaches 12,000. In the following piece of code, we define the epochs we intend to incorporate in our plots and create the animation above through snapshots after each for-loop. By calling Camera’s animate-function we can turn our snapshots into animations.
In my opinion, it makes sense to return the final values of J, w and b being plotted, so that we can make sure we roughly visualized model convergence in our animation despite not using all the points we stored during the fitting process. Especially in 3D-animations, it can sometimes be difficult to confirm the former just by looking at the graph.
A more intriguing way of visualizing gradient descent can be obtained if we plot the cost function with respect to the parameters w and b, since this is closer to the actual concept of J being a function of w and b. In addition, we seek to introduce connection lines (dashed) between the regression line and our training data to portray the respective residuals.
Some minor changes to our previous piece of code get us the animation above:
Referring to the aforementioned ‘mountain’-analogy, creating a 3D visualization of gradient descent seems desirable. However, this requires some preliminary work since we have to create some data points we never encountered during the fitting process. In other words, we need to compute costs for every possible pair of w and b over a predefined range of parameter values to obtain a surface plot. Fortunately, numpy has a built-in function called meshgrid, which enables us to create coordinate grids for our three-dimensional plots.
With the following code, we can now visualize gradient descent in three dimensions.
I hope you enjoyed this article. If anything is unclear or if you have noticed any mistakes, please feel free to leave a comment. In the next article, I will address animations of gradient descent using the example of multilinear regression. The complete notebook can be found on my GitHub. Thank you for your interest!
|
[
{
"code": null,
"e": 411,
"s": 172,
"text": "The Gradient Descent method is one of the most widely used parameter optimization algorithms in machine learning today. Python’s celluloid-module enables us to create vivid animations of model parameters and costs during gradient descent."
},
{
"code": null,
"e": 765,
"s": 411,
"text": "In this article, I exemplarily want to use simple linear regression to visualize batch gradient descent. The goal is to build a linear regression model and train it on some data points we made up. For every training round (‘epoch’), we intend to store current model parameters and costs. Finally, we aim to create some animations with our stored values."
},
{
"code": null,
"e": 1520,
"s": 765,
"text": "There are various articles on how to set up and fit a linear regression model on Medium alone. In theory, we are trying to find the best fitting, straight line for our data. Mathematically, a straight line in two-dimensional space can be described with the following function: y= w*x+b, with w representing the slope (or “weight) and b representing the y-intercept (or “bias”) of our line. There are numerous methods on how to determine the optimal values for w and b given our n data points. The gradient descent algorithm aims to minimize the mean squared error between observed data points (y) and points we predicted with our regression line (ŷ). The mean squared error is also being referred to as ‘cost function’ (or ‘costs’) usually denoted as J."
},
{
"code": null,
"e": 1817,
"s": 1520,
"text": "With our data points fixed, the cost function is only dependent on the parameters w and b. We aim to adjust our parameters until the cost function reaches its minimum. To get a glimpse on how to adjust (decrease vs. increase) the parameters we introduce the gradient of our cost function ∇J(w,b):"
},
{
"code": null,
"e": 2285,
"s": 1817,
"text": "with δJ/δw and δJ/δb being the partial derivatives of J with respect to w and b respectively. By constantly moving our parameters in the opposite direction of the current gradient ∇J, we can stepwise reduce the costs J. The size of the steps we take to reach the (local/global) minimum of J is usually denoted as α and is also referred to as ‘learning rate’. When training our model, our objective is to repeat the following for each epoch until we reach convergence:"
},
{
"code": null,
"e": 2703,
"s": 2285,
"text": "Metaphorically speaking, the cost function can be imagined as some mountainous terrain, where beginning from a certain starting point, we want to head downhill until we reach a valley. Analogously, the gradient is giving us the ‘multidimensional slope’ i.e. the direction of where ‘uphill’ is on the mountain surface. That’s why we intend to constantly adjust our parameters in the opposite direction of the gradient."
},
{
"code": null,
"e": 3095,
"s": 2703,
"text": "Gradient descent algorithm can be sub-classified according to how much of the training data is being used simultaneously to compute the gradient of our cost function. In the following example, we use the entire dataset for every update respectively, which is also referred to as batch gradient descent. In Python we import some useful libraries and set up our simple linear regression model:"
},
{
"code": null,
"e": 3479,
"s": 3095,
"text": "We then want to introduce our training data, define the learning rate (α=0.001), initialize our starting parameters (w=3, b=-1), and finally train our model. For every epoch, we store the updated values of our parameters, the costs, and some particular predicted y-values in lists. List items are then being stored in numpy arrays where they serve as raw data for our animated plots."
},
{
"code": null,
"e": 4948,
"s": 3479,
"text": "# Introduce training data\nx_train = np.array([ \n [1],\n [2],\n [4],\n [5],\n [6],\n [7]\n])\n\ny_train = np.array([ \n [4],\n [-12],\n [3],\n [-11],\n [-5],\n [-17]\n])\n\n\n# Introduce lists where data points are being stored: \nw_list=[] # list contains weights\nb_list=[] # list contains biases\nc_list=[] # list contains costs \nys_list=[] # store arrays of predicted y-values for xs ( -> plot regression line!) \ncl_list = [] # list contains predicted y-values for x_train ( -> plot connecting lines!) \n\nxs= np.array([ # set x-values for regression line plot \n [-3],\n [10]\n ])\n\n# Train model: \nmodel=LinearRegression(w=3,b=-1,lr=0.001) # set initial parameters and learning rate \n\nfor i in range(60000): # set number of epochs\n w_list.append(model.params()[0]) # append weights (=slopes) to list\n b_list.append(model.params()[1]) # append biases (=y-intercepts) to list\n c_list.append(model.cost(x_train,y_train)) # append costs to list\n ys_list.append(model.predict(xs).T) # append pairs of predicted y-values for xs \n cl_list.append(model.predict(x_train).T) # append predicted y-values for x_train to list\n model.fit(x_train, y_train) # fit model\n\n\n# print parameters and costs after all epochs\nprint(\"weight: \" + str( model.params()[0]) ) \nprint(\"y-intercept: \" + str( model.params()[1]) )\nprint(\"costs: \"+ str(model.cost(x_train, y_train))) \n"
},
{
"code": null,
"e": 5008,
"s": 4948,
"text": "weight: [[-2.]]\ny-intercept: [2.]\ncosts: 42.66666666666668\n"
},
{
"code": null,
"e": 5551,
"s": 5008,
"text": "Note that the particularly small learning rate of 0.001 was chosen on purpose to prevent overly large steps during the first epochs of gradient descent. A larger learning rate (e.g. α=0.1) usually results in faster model convergence requiring fewer epochs. However, overly large steps during the first epochs of gradient descent tend to result in less appealing animations or even failure to converge. Just to make sure our fitted parameters converged to their true values, we verify our results with sklearn’s inborn linear regression model."
},
{
"code": null,
"e": 5704,
"s": 5551,
"text": "import sklearn\nfrom sklearn.linear_model import LinearRegression\n\nreg = LinearRegression().fit(x_train, y_train)\nprint(reg.coef_)\nprint(reg.intercept_)\n"
},
{
"code": null,
"e": 5718,
"s": 5704,
"text": "[[-2.]]\n[2.]\n"
},
{
"code": null,
"e": 5838,
"s": 5718,
"text": "Since we are now confident that our gradient descent algorithm worked out as planned, we can move on to the animations."
},
{
"code": null,
"e": 6101,
"s": 5838,
"text": "With our data points being generated and stored, we can now start to build some animations. We could, for example, plot the values our cost function and parameters take on with respect to the epoch while plotting the corresponding regression line simultaneously:"
},
{
"code": null,
"e": 7127,
"s": 6101,
"text": "These rather basic plots reveal a very important characteristic of gradient descent: if set up correctly, costs drop rapidly and parameter values change noticeably at the beginning of gradient descent. With rising epochs, only minor changes to costs and parameter values can be observed. Therefore, plotting all values we initially stored seems unfavorable. While predominantly focusing on the first epochs of the fitting process we can visualize most of the ‘action’ without crashing Python while generating these resource-intensive animations. After trying out some different selections of points to plot, I decided to utilize the first 50 epochs of the fitting process continuously, followed by plotting only every 5th or 200th data point until the number of epochs reaches 12,000. In the following piece of code, we define the epochs we intend to incorporate in our plots and create the animation above through snapshots after each for-loop. By calling Camera’s animate-function we can turn our snapshots into animations."
},
{
"code": null,
"e": 7477,
"s": 7127,
"text": "In my opinion, it makes sense to return the final values of J, w and b being plotted, so that we can make sure we roughly visualized model convergence in our animation despite not using all the points we stored during the fitting process. Especially in 3D-animations, it can sometimes be difficult to confirm the former just by looking at the graph."
},
{
"code": null,
"e": 7840,
"s": 7477,
"text": "A more intriguing way of visualizing gradient descent can be obtained if we plot the cost function with respect to the parameters w and b, since this is closer to the actual concept of J being a function of w and b. In addition, we seek to introduce connection lines (dashed) between the regression line and our training data to portray the respective residuals."
},
{
"code": null,
"e": 7917,
"s": 7840,
"text": "Some minor changes to our previous piece of code get us the animation above:"
},
{
"code": null,
"e": 8452,
"s": 7917,
"text": "Referring to the aforementioned ‘mountain’-analogy, creating a 3D visualization of gradient descent seems desirable. However, this requires some preliminary work since we have to create some data points we never encountered during the fitting process. In other words, we need to compute costs for every possible pair of w and b over a predefined range of parameter values to obtain a surface plot. Fortunately, numpy has a built-in function called meshgrid, which enables us to create coordinate grids for our three-dimensional plots."
},
{
"code": null,
"e": 8536,
"s": 8452,
"text": "With the following code, we can now visualize gradient descent in three dimensions."
}
] |
Count maximum number of cars parked at the same time - GeeksforGeeks
|
23 Aug, 2021
Given a 2d array arr[][] with each row representing a pair representing entry and exit time of a car in a parking lot, the task is to calculate the maximum number of cars that can be parked at the same time.
Examples:
Input: arr[][] = {{1012, 1136}, {1317, 1417}, {1015, 1020}}Output: 2Explanation:1st car entered at 10:12 and exits at 11:36 and 3rd car entered at 10:15 and exits at 10:20.Therefore, 1st and 3rd car are present at the same time.
Input: arr[][] = {{1120, 1159}, {1508, 1529}, {1508, 1527}, {1503, 1600}, {1458, 1629}, {1224, 1313}}Output: 4Explanation: 2nd, 3rd, 4th and 5th cars are present at the same time.
Approach: The idea is to use Kadane’s algorithm to solve this problem. Follow the steps below to solve the problem:
Initialize a vector of pairs to store the entry or exit time as the first element of a pair and true as the second element of a pair, if corresponding time stored is entry time. Otherwise, store as false.
Sort the vector in non-decreasing order of time.
Initialize two variables, say curMax, to look for all true contiguous segments of the array, and maxFinal, to keep track of longest true contiguous segment among all true segments.
Iterate over the range [0, 2*N – 1]:If a car entered, increment curMax by 1.Otherwise:If curMax > maxFinal, update maxFinal = curMax.Whenever a car exits, subtract curMax by 1.
If a car entered, increment curMax by 1.
Otherwise:If curMax > maxFinal, update maxFinal = curMax.Whenever a car exits, subtract curMax by 1.
If curMax > maxFinal, update maxFinal = curMax.
Whenever a car exits, subtract curMax by 1.
Print maxFinal as the answer.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program for the above approach #include <bits/stdc++.h>using namespace std; // Function to count maximum number// of cars parked at the sameint maxCars(int arr[][2], int N){ // Stores info about // entry and exit times pair<int, bool> a[2 * N]; // Convert given array to new array for (int i = 0; i < N; i++) { a[2 * i] = { arr[i][0], true }; a[2 * i + 1] = { arr[i][1], false }; } // Sort array in ascending // order of time sort(a, a + 2 * N); // Stores current maximum // at every iteration int curMax = 0; // Stores final maximum number // of cars parked at any time int maxFinal = 0; // Traverse the array for (int i = 0; i < 2 * N; ++i) { // When car entered if (a[i].second) { curMax++; } // When car exits else { if (curMax > maxFinal) { maxFinal = curMax; } curMax--; } } // Print the answer cout << maxFinal;} // Driver Codeint main(){ // Given array int arr[][2] = { { 1012, 1136 }, { 1317, 1412 }, { 1015, 1020 } }; // Size of the array int N = sizeof(arr) / sizeof(arr[0]); // Function Call maxCars(arr, N); return 0;}
// Java program for the above approachimport java.io.*;import java.lang.*;import java.util.*; class GFG{ // Pair classstatic class pair{ int first; boolean second; pair(int first, boolean second) { this.first = first; this.second = second; }} // Function to count maximum number// of cars parked at the samestatic void maxCars(int arr[][], int N){ // Stores info about // entry and exit times pair a[] = new pair[2 * N]; // Convert given array to new array for(int i = 0; i < N; i++) { a[2 * i] = new pair(arr[i][0], true); a[2 * i + 1] = new pair(arr[i][1], false); } // Sort array in ascending // order of time Arrays.sort(a, (p1, p2) -> p1.first - p2.first); // Stores current maximum // at every iteration int curMax = 0; // Stores final maximum number // of cars parked at any time int maxFinal = 0; // Traverse the array for(int i = 0; i < 2 * N; ++i) { // When car entered if (a[i].second) { curMax++; } // When car exits else { if (curMax > maxFinal) { maxFinal = curMax; } curMax--; } } // Print the answer System.out.println(maxFinal);} // Driver Codepublic static void main(String[] args){ // Given array int arr[][] = { { 1012, 1136 }, { 1317, 1412 }, { 1015, 1020 } }; // Size of the array int N = arr.length; // Function Call maxCars(arr, N);}} // This code is contributed by Kingash
# Python3 program for the above approach # Function to count maximum number# of cars parked at the samedef maxCars(arr, N): # Stores info about # entry and exit times a = [[0,True] for i in range(2 * N)] # Convert given array to new array for i in range(N): a[2 * i] = [arr[i][0], True] a[2 * i + 1] = [arr[i][1], False] # Sort array in ascending # order of time a = sorted(a) # Stores current maximum # at every iteration curMax = 0 # Stores final maximum number # of cars parked at any time maxFinal = 0 # Traverse the array for i in range(2*N): # When car entered if (a[i][1]): curMax += 1 # When car exits else: if (curMax > maxFinal): maxFinal = curMax curMax -= 1 # Print answer print (maxFinal) # Driver Codeif __name__ == '__main__': # Given array arr= [ [ 1012, 1136 ], [ 1317, 1412 ], [ 1015, 1020 ]] # Size of the array N = len(arr) # Function Call maxCars(arr, N) # This code is contributed by mohit kumar 29.
// C# program for the above approachusing System;class GFG{ // Function to count maximum number // of cars parked at the same static void maxCars(int[,] arr, int N) { // Stores info about // entry and exit times Tuple<int, bool>[] a = new Tuple<int, bool>[2 * N]; // Convert given array to new array for (int i = 0; i < N; i++) { a[2 * i] = new Tuple<int, bool>(arr[i,0], true); a[2 * i + 1] = new Tuple<int, bool>(arr[i,1], false); } // Stores current maximum // at every iteration int curMax = 1; // Stores final maximum number // of cars parked at any time int maxFinal = 0; // Traverse the array for (int i = 0; i < 2 * N; ++i) { // When car entered if (a[i].Item2) { curMax++; } // When car exits else { if (curMax > maxFinal) { maxFinal = curMax; } curMax--; } } // Print the answer Console.WriteLine(maxFinal); } static void Main () { // Given array int[,] arr = { { 1012, 1136 }, { 1317, 1412 }, { 1015, 1020 } }; // Size of the array int N = 2; // Function Call maxCars(arr, N); }} // This code is contributed by suresh07.
<script> // JavaScript program for the above approach // Pair classclass pair{ constructor(first,second) { this.first = first; this.second = second; }} // Function to count maximum number// of cars parked at the samefunction maxCars(arr,N){ // Stores info about // entry and exit times let a = new Array(2 * N); // Convert given array to new array for(let i = 0; i < N; i++) { a[2 * i] = new pair(arr[i][0], true); a[2 * i + 1] = new pair(arr[i][1], false); } // Sort array in ascending // order of time a.sort(function(p1, p2){return p1.first - p2.first}); // Stores current maximum // at every iteration let curMax = 0; // Stores final maximum number // of cars parked at any time let maxFinal = 0; // Traverse the array for(let i = 0; i < 2 * N; ++i) { // When car entered if (a[i].second) { curMax++; } // When car exits else { if (curMax > maxFinal) { maxFinal = curMax; } curMax--; } } // Print the answer document.write(maxFinal+"<br>");} // Driver Codelet arr=[[ 1012, 1136 ], [ 1317, 1412 ], [ 1015, 1020 ]];// Size of the arraylet N = arr.length; // Function CallmaxCars(arr, N); // This code is contributed by unknown2108 </script>
2
Time Complexity: O(N)Auxiliary Space: O(N)
mohit kumar 29
Kingash
unknown2108
suresh07
khushboogoyal499
Kadane
Arrays
Mathematical
Technical Scripter
Arrays
Mathematical
Kadane
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Stack Data Structure (Introduction and Program)
Top 50 Array Coding Problems for Interviews
Introduction to Arrays
Multidimensional Arrays in Java
Linear Search
Program for Fibonacci numbers
Write a program to print all permutations of a given string
C++ Data Types
Set in C++ Standard Template Library (STL)
Coin Change | DP-7
|
[
{
"code": null,
"e": 25141,
"s": 25113,
"text": "\n23 Aug, 2021"
},
{
"code": null,
"e": 25349,
"s": 25141,
"text": "Given a 2d array arr[][] with each row representing a pair representing entry and exit time of a car in a parking lot, the task is to calculate the maximum number of cars that can be parked at the same time."
},
{
"code": null,
"e": 25359,
"s": 25349,
"text": "Examples:"
},
{
"code": null,
"e": 25588,
"s": 25359,
"text": "Input: arr[][] = {{1012, 1136}, {1317, 1417}, {1015, 1020}}Output: 2Explanation:1st car entered at 10:12 and exits at 11:36 and 3rd car entered at 10:15 and exits at 10:20.Therefore, 1st and 3rd car are present at the same time."
},
{
"code": null,
"e": 25768,
"s": 25588,
"text": "Input: arr[][] = {{1120, 1159}, {1508, 1529}, {1508, 1527}, {1503, 1600}, {1458, 1629}, {1224, 1313}}Output: 4Explanation: 2nd, 3rd, 4th and 5th cars are present at the same time."
},
{
"code": null,
"e": 25884,
"s": 25768,
"text": "Approach: The idea is to use Kadane’s algorithm to solve this problem. Follow the steps below to solve the problem:"
},
{
"code": null,
"e": 26089,
"s": 25884,
"text": "Initialize a vector of pairs to store the entry or exit time as the first element of a pair and true as the second element of a pair, if corresponding time stored is entry time. Otherwise, store as false."
},
{
"code": null,
"e": 26138,
"s": 26089,
"text": "Sort the vector in non-decreasing order of time."
},
{
"code": null,
"e": 26319,
"s": 26138,
"text": "Initialize two variables, say curMax, to look for all true contiguous segments of the array, and maxFinal, to keep track of longest true contiguous segment among all true segments."
},
{
"code": null,
"e": 26496,
"s": 26319,
"text": "Iterate over the range [0, 2*N – 1]:If a car entered, increment curMax by 1.Otherwise:If curMax > maxFinal, update maxFinal = curMax.Whenever a car exits, subtract curMax by 1."
},
{
"code": null,
"e": 26537,
"s": 26496,
"text": "If a car entered, increment curMax by 1."
},
{
"code": null,
"e": 26638,
"s": 26537,
"text": "Otherwise:If curMax > maxFinal, update maxFinal = curMax.Whenever a car exits, subtract curMax by 1."
},
{
"code": null,
"e": 26686,
"s": 26638,
"text": "If curMax > maxFinal, update maxFinal = curMax."
},
{
"code": null,
"e": 26730,
"s": 26686,
"text": "Whenever a car exits, subtract curMax by 1."
},
{
"code": null,
"e": 26760,
"s": 26730,
"text": "Print maxFinal as the answer."
},
{
"code": null,
"e": 26811,
"s": 26760,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 26815,
"s": 26811,
"text": "C++"
},
{
"code": null,
"e": 26820,
"s": 26815,
"text": "Java"
},
{
"code": null,
"e": 26828,
"s": 26820,
"text": "Python3"
},
{
"code": null,
"e": 26831,
"s": 26828,
"text": "C#"
},
{
"code": null,
"e": 26842,
"s": 26831,
"text": "Javascript"
},
{
"code": "// C++ program for the above approach #include <bits/stdc++.h>using namespace std; // Function to count maximum number// of cars parked at the sameint maxCars(int arr[][2], int N){ // Stores info about // entry and exit times pair<int, bool> a[2 * N]; // Convert given array to new array for (int i = 0; i < N; i++) { a[2 * i] = { arr[i][0], true }; a[2 * i + 1] = { arr[i][1], false }; } // Sort array in ascending // order of time sort(a, a + 2 * N); // Stores current maximum // at every iteration int curMax = 0; // Stores final maximum number // of cars parked at any time int maxFinal = 0; // Traverse the array for (int i = 0; i < 2 * N; ++i) { // When car entered if (a[i].second) { curMax++; } // When car exits else { if (curMax > maxFinal) { maxFinal = curMax; } curMax--; } } // Print the answer cout << maxFinal;} // Driver Codeint main(){ // Given array int arr[][2] = { { 1012, 1136 }, { 1317, 1412 }, { 1015, 1020 } }; // Size of the array int N = sizeof(arr) / sizeof(arr[0]); // Function Call maxCars(arr, N); return 0;}",
"e": 28128,
"s": 26842,
"text": null
},
{
"code": "// Java program for the above approachimport java.io.*;import java.lang.*;import java.util.*; class GFG{ // Pair classstatic class pair{ int first; boolean second; pair(int first, boolean second) { this.first = first; this.second = second; }} // Function to count maximum number// of cars parked at the samestatic void maxCars(int arr[][], int N){ // Stores info about // entry and exit times pair a[] = new pair[2 * N]; // Convert given array to new array for(int i = 0; i < N; i++) { a[2 * i] = new pair(arr[i][0], true); a[2 * i + 1] = new pair(arr[i][1], false); } // Sort array in ascending // order of time Arrays.sort(a, (p1, p2) -> p1.first - p2.first); // Stores current maximum // at every iteration int curMax = 0; // Stores final maximum number // of cars parked at any time int maxFinal = 0; // Traverse the array for(int i = 0; i < 2 * N; ++i) { // When car entered if (a[i].second) { curMax++; } // When car exits else { if (curMax > maxFinal) { maxFinal = curMax; } curMax--; } } // Print the answer System.out.println(maxFinal);} // Driver Codepublic static void main(String[] args){ // Given array int arr[][] = { { 1012, 1136 }, { 1317, 1412 }, { 1015, 1020 } }; // Size of the array int N = arr.length; // Function Call maxCars(arr, N);}} // This code is contributed by Kingash",
"e": 29746,
"s": 28128,
"text": null
},
{
"code": "# Python3 program for the above approach # Function to count maximum number# of cars parked at the samedef maxCars(arr, N): # Stores info about # entry and exit times a = [[0,True] for i in range(2 * N)] # Convert given array to new array for i in range(N): a[2 * i] = [arr[i][0], True] a[2 * i + 1] = [arr[i][1], False] # Sort array in ascending # order of time a = sorted(a) # Stores current maximum # at every iteration curMax = 0 # Stores final maximum number # of cars parked at any time maxFinal = 0 # Traverse the array for i in range(2*N): # When car entered if (a[i][1]): curMax += 1 # When car exits else: if (curMax > maxFinal): maxFinal = curMax curMax -= 1 # Print answer print (maxFinal) # Driver Codeif __name__ == '__main__': # Given array arr= [ [ 1012, 1136 ], [ 1317, 1412 ], [ 1015, 1020 ]] # Size of the array N = len(arr) # Function Call maxCars(arr, N) # This code is contributed by mohit kumar 29.",
"e": 30858,
"s": 29746,
"text": null
},
{
"code": "// C# program for the above approachusing System;class GFG{ // Function to count maximum number // of cars parked at the same static void maxCars(int[,] arr, int N) { // Stores info about // entry and exit times Tuple<int, bool>[] a = new Tuple<int, bool>[2 * N]; // Convert given array to new array for (int i = 0; i < N; i++) { a[2 * i] = new Tuple<int, bool>(arr[i,0], true); a[2 * i + 1] = new Tuple<int, bool>(arr[i,1], false); } // Stores current maximum // at every iteration int curMax = 1; // Stores final maximum number // of cars parked at any time int maxFinal = 0; // Traverse the array for (int i = 0; i < 2 * N; ++i) { // When car entered if (a[i].Item2) { curMax++; } // When car exits else { if (curMax > maxFinal) { maxFinal = curMax; } curMax--; } } // Print the answer Console.WriteLine(maxFinal); } static void Main () { // Given array int[,] arr = { { 1012, 1136 }, { 1317, 1412 }, { 1015, 1020 } }; // Size of the array int N = 2; // Function Call maxCars(arr, N); }} // This code is contributed by suresh07.",
"e": 32304,
"s": 30858,
"text": null
},
{
"code": "<script> // JavaScript program for the above approach // Pair classclass pair{ constructor(first,second) { this.first = first; this.second = second; }} // Function to count maximum number// of cars parked at the samefunction maxCars(arr,N){ // Stores info about // entry and exit times let a = new Array(2 * N); // Convert given array to new array for(let i = 0; i < N; i++) { a[2 * i] = new pair(arr[i][0], true); a[2 * i + 1] = new pair(arr[i][1], false); } // Sort array in ascending // order of time a.sort(function(p1, p2){return p1.first - p2.first}); // Stores current maximum // at every iteration let curMax = 0; // Stores final maximum number // of cars parked at any time let maxFinal = 0; // Traverse the array for(let i = 0; i < 2 * N; ++i) { // When car entered if (a[i].second) { curMax++; } // When car exits else { if (curMax > maxFinal) { maxFinal = curMax; } curMax--; } } // Print the answer document.write(maxFinal+\"<br>\");} // Driver Codelet arr=[[ 1012, 1136 ], [ 1317, 1412 ], [ 1015, 1020 ]];// Size of the arraylet N = arr.length; // Function CallmaxCars(arr, N); // This code is contributed by unknown2108 </script>",
"e": 33739,
"s": 32304,
"text": null
},
{
"code": null,
"e": 33741,
"s": 33739,
"text": "2"
},
{
"code": null,
"e": 33786,
"s": 33743,
"text": "Time Complexity: O(N)Auxiliary Space: O(N)"
},
{
"code": null,
"e": 33803,
"s": 33788,
"text": "mohit kumar 29"
},
{
"code": null,
"e": 33811,
"s": 33803,
"text": "Kingash"
},
{
"code": null,
"e": 33823,
"s": 33811,
"text": "unknown2108"
},
{
"code": null,
"e": 33832,
"s": 33823,
"text": "suresh07"
},
{
"code": null,
"e": 33849,
"s": 33832,
"text": "khushboogoyal499"
},
{
"code": null,
"e": 33856,
"s": 33849,
"text": "Kadane"
},
{
"code": null,
"e": 33863,
"s": 33856,
"text": "Arrays"
},
{
"code": null,
"e": 33876,
"s": 33863,
"text": "Mathematical"
},
{
"code": null,
"e": 33895,
"s": 33876,
"text": "Technical Scripter"
},
{
"code": null,
"e": 33902,
"s": 33895,
"text": "Arrays"
},
{
"code": null,
"e": 33915,
"s": 33902,
"text": "Mathematical"
},
{
"code": null,
"e": 33922,
"s": 33915,
"text": "Kadane"
},
{
"code": null,
"e": 34020,
"s": 33922,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 34029,
"s": 34020,
"text": "Comments"
},
{
"code": null,
"e": 34042,
"s": 34029,
"text": "Old Comments"
},
{
"code": null,
"e": 34090,
"s": 34042,
"text": "Stack Data Structure (Introduction and Program)"
},
{
"code": null,
"e": 34134,
"s": 34090,
"text": "Top 50 Array Coding Problems for Interviews"
},
{
"code": null,
"e": 34157,
"s": 34134,
"text": "Introduction to Arrays"
},
{
"code": null,
"e": 34189,
"s": 34157,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 34203,
"s": 34189,
"text": "Linear Search"
},
{
"code": null,
"e": 34233,
"s": 34203,
"text": "Program for Fibonacci numbers"
},
{
"code": null,
"e": 34293,
"s": 34233,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 34308,
"s": 34293,
"text": "C++ Data Types"
},
{
"code": null,
"e": 34351,
"s": 34308,
"text": "Set in C++ Standard Template Library (STL)"
}
] |
java.lang.reflect.Field.get() Method Example
|
The java.lang.reflect.Field.get(Object obj) method returns the value of the field represented by this Field, on the specified object. The value is automatically wrapped in an object if it has a primitive type.
Following is the declaration for java.lang.reflect.Field.get(Object obj) method.
public Object get(Object obj)
throws IllegalArgumentException, IllegalAccessException
obj − object from which the represented field's value is to be extracted.
the value of the represented field in object obj; primitive values are wrapped in an appropriate object before being returned.
IllegalAccessException − if this Field object is enforcing Java language access control and the underlying field is inaccessible.
IllegalAccessException − if this Field object is enforcing Java language access control and the underlying field is inaccessible.
IllegalArgumentException − if the specified object is not an instance of the class or interface declaring the underlying field (or a subclass or implementor thereof).
IllegalArgumentException − if the specified object is not an instance of the class or interface declaring the underlying field (or a subclass or implementor thereof).
NullPointerException − if the specified object is null and the field is an instance field.
NullPointerException − if the specified object is null and the field is an instance field.
ExceptionInInitializerError − if the initialization provoked by this method fails.
ExceptionInInitializerError − if the initialization provoked by this method fails.
The following example shows the usage of java.lang.reflect.Field.get(Object obj) method.
package com.tutorialspoint;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.reflect.Field;
public class FieldDemo {
public static void main(String[] args) throws NoSuchFieldException,
SecurityException, IllegalArgumentException, IllegalAccessException {
SampleClass sampleObject = new SampleClass();
sampleObject.setSampleField("data");
Field field = SampleClass.class.getField("sampleField");
System.out.println(field.get(sampleObject));
}
}
@CustomAnnotation(name = "SampleClass", value = "Sample Class Annotation")
class SampleClass {
@CustomAnnotation(name="sampleClassField", value = "Sample Field Annotation")
public String sampleField;
public String getSampleField() {
return sampleField;
}
public void setSampleField(String sampleField) {
this.sampleField = sampleField;
}
}
@Retention(RetentionPolicy.RUNTIME)
@interface CustomAnnotation {
public String name();
public String value();
}
Let us compile and run the above program, this will produce the following result −
data
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 1664,
"s": 1454,
"text": "The java.lang.reflect.Field.get(Object obj) method returns the value of the field represented by this Field, on the specified object. The value is automatically wrapped in an object if it has a primitive type."
},
{
"code": null,
"e": 1745,
"s": 1664,
"text": "Following is the declaration for java.lang.reflect.Field.get(Object obj) method."
},
{
"code": null,
"e": 1835,
"s": 1745,
"text": "public Object get(Object obj)\n throws IllegalArgumentException, IllegalAccessException\n"
},
{
"code": null,
"e": 1909,
"s": 1835,
"text": "obj − object from which the represented field's value is to be extracted."
},
{
"code": null,
"e": 2036,
"s": 1909,
"text": "the value of the represented field in object obj; primitive values are wrapped in an appropriate object before being returned."
},
{
"code": null,
"e": 2166,
"s": 2036,
"text": "IllegalAccessException − if this Field object is enforcing Java language access control and the underlying field is inaccessible."
},
{
"code": null,
"e": 2296,
"s": 2166,
"text": "IllegalAccessException − if this Field object is enforcing Java language access control and the underlying field is inaccessible."
},
{
"code": null,
"e": 2463,
"s": 2296,
"text": "IllegalArgumentException − if the specified object is not an instance of the class or interface declaring the underlying field (or a subclass or implementor thereof)."
},
{
"code": null,
"e": 2630,
"s": 2463,
"text": "IllegalArgumentException − if the specified object is not an instance of the class or interface declaring the underlying field (or a subclass or implementor thereof)."
},
{
"code": null,
"e": 2721,
"s": 2630,
"text": "NullPointerException − if the specified object is null and the field is an instance field."
},
{
"code": null,
"e": 2812,
"s": 2721,
"text": "NullPointerException − if the specified object is null and the field is an instance field."
},
{
"code": null,
"e": 2895,
"s": 2812,
"text": "ExceptionInInitializerError − if the initialization provoked by this method fails."
},
{
"code": null,
"e": 2978,
"s": 2895,
"text": "ExceptionInInitializerError − if the initialization provoked by this method fails."
},
{
"code": null,
"e": 3067,
"s": 2978,
"text": "The following example shows the usage of java.lang.reflect.Field.get(Object obj) method."
},
{
"code": null,
"e": 4121,
"s": 3067,
"text": "package com.tutorialspoint;\n\nimport java.lang.annotation.Retention;\nimport java.lang.annotation.RetentionPolicy;\nimport java.lang.reflect.Field;\n\npublic class FieldDemo {\n\n public static void main(String[] args) throws NoSuchFieldException, \n SecurityException, IllegalArgumentException, IllegalAccessException {\n \n SampleClass sampleObject = new SampleClass();\n sampleObject.setSampleField(\"data\");\n \n Field field = SampleClass.class.getField(\"sampleField\");\n System.out.println(field.get(sampleObject));\n }\n}\n\n@CustomAnnotation(name = \"SampleClass\", value = \"Sample Class Annotation\")\nclass SampleClass {\n\n @CustomAnnotation(name=\"sampleClassField\", value = \"Sample Field Annotation\")\n public String sampleField;\n \n public String getSampleField() {\n return sampleField;\n }\n\n public void setSampleField(String sampleField) {\n this.sampleField = sampleField;\n }\n}\n\n@Retention(RetentionPolicy.RUNTIME)\n@interface CustomAnnotation {\n public String name();\n public String value();\n}"
},
{
"code": null,
"e": 4204,
"s": 4121,
"text": "Let us compile and run the above program, this will produce the following result −"
},
{
"code": null,
"e": 4210,
"s": 4204,
"text": "data\n"
},
{
"code": null,
"e": 4217,
"s": 4210,
"text": " Print"
},
{
"code": null,
"e": 4228,
"s": 4217,
"text": " Add Notes"
}
] |
Python Stock Analysis — Candlestick Chart with Python and Plotly | by Jose Manu (CodingFun) | Towards Data Science
|
A candlestick chart is a very common and useful representation of stock prices. By looking into a candlestick chart, we can visually see the open, close, low and high price for any given stock.
In this article, I would like to show you how to use Python, Pandas and Plotly to build your own candlestick chart.
We will start by importing all the required packages. We will need Pandas, Plotly, Json and requests. Requests and Json are needed to retrieve stock information from a free financial API Financialmodelingprep.
import plotly.express as pximport plotly.graph_objects as goimport pandas as pdimport requestsimport jsonquote = 'AAPL'days = 300def candlestick(quote,days): r = requests.get(f'https://financialmodelingprep.com/api/v3/historical- price-full/{quote}?timeseries={days}') r = r.json() return r
We pass as an argument of the get function the API endpoint url that we store in a variable named r. Then, we convert the API response to Json so that we Python can easily manipulate it with Python. The variable r will contain historical price data for any stock that we passed to our candlestick function. In above example, we have passed as parameters of our function ‘AAPL’ (i.e. Apple) and 300 days. Therefore, as a result, we get a list representing 300 data points. Each element in the list is a dictionary containing the information needed for our candlestick chart, that is, the open, high, low and close for each of the dates.
“symbol” : “AAPL”, “historical” : [ { “date” : “2015–01–20”, “open” : 107.84, “high” : 108.97, “low” : 106.5, “close” : 108.72, “volume” : 4.98999E7, “unadjustedVolume” : 4.98999E7, “change” : -0.88, “changePercent” : -0.816,....
When possible, I always like to convert my data into a Pandas DataFrame since it let me handle, operate and clean my data on a very easy and convenient manner. That is what we achieve with below two lines of code.
First, we parse our variable r to extract the value associated to the historical key and store it in a variable called stockdata. This way, we keep a list of dictionaries. Each dictionary contains stock price data for a single day. Then, we can simply convert the stockdata list to a Pandas DataFrame.
stockdata = r[‘historical’]stockdata_df = pd.DataFrame(stockdata)
If we print out our Pandas Dataframe stockdata_df, we get something similar to below where each row represents a day and each column is giving us stock price information:
So far so good. Now, let’s move to the fun part. We can start building our chart with Plotly. Plotly is a very powerful graphing library. Very easy to use with Python and Pandas.
First of all, we need to create a fig object which will contain our data points. Within our Figure, we define our date, open, high, low and close. Each of the data points will be a column from our stockdata_df Pandas DataFrame. For example, open will contain the open price for each of the dates included in our Pandas DataFrame. Since, we passed in our function 300 days, open will contain the open stock price of Apple for the last 300 days.
Let’s also update the layout of our figure by using the Plotly fig.update_layout command to give some nice title to our chart, change the font and ensure that the the text is well positioned in the top center of the chart area.
Finally, we can use fig.show() to display the candlestick chart:
fig = go.Figure(data=[go.Candlestick(x=stockdata_df['date'], open=stockdata_df['open'], high=stockdata_df['high'], low=stockdata_df['low'], close=stockdata_df['close'])])fig.update_layout( title= { 'text': quote, 'y':0.9, 'x':0.5, 'xanchor': 'center', 'yanchor': 'top'}, font=dict( family="Courier New, monospace", size=20, color="#7f7f7f" ) )fig.show()
And now magically, or rather because our coding skills, an impressive candlestick chart is displayed in front of us, including a slider to zoom in and out for any particular period of time. Try it out by your own!
I have included the whole script below for your reference. Just replace quote and days variables to select the desired stock and the number of days that you want to display in the chart.
Note: If you have any problems while running below code, ensure that you have all required libraries installed.
import plotly.express as pximport plotly.graph_objects as goimport pandas as pdimport requestsimport jsonquote = ‘AAPL’days = 300def candlestick(quote,days): r = requests.get(f’https://financialmodelingprep.com/api/v3/historical-price-full/{quote}?timeseries={days}') r = r.json() stockdata = r[‘historical’] stockdata_df = pd.DataFrame(stockdata) fig = go.Figure(data=[go.Candlestick(x=stockdata_df[‘date’], open=stockdata_df[‘open’], high=stockdata_df[‘high’], low=stockdata_df[‘low’], close=stockdata_df[‘close’])]) fig.update_layout( title= { ‘text’: quote, ‘y’:0.9, ‘x’:0.5, ‘xanchor’: ‘center’, ‘yanchor’: ‘top’}, font=dict( family=”Courier New, monospace”, size=20, color=”#7f7f7f” )) fig.show() candlestick(quote,days)
|
[
{
"code": null,
"e": 366,
"s": 172,
"text": "A candlestick chart is a very common and useful representation of stock prices. By looking into a candlestick chart, we can visually see the open, close, low and high price for any given stock."
},
{
"code": null,
"e": 482,
"s": 366,
"text": "In this article, I would like to show you how to use Python, Pandas and Plotly to build your own candlestick chart."
},
{
"code": null,
"e": 692,
"s": 482,
"text": "We will start by importing all the required packages. We will need Pandas, Plotly, Json and requests. Requests and Json are needed to retrieve stock information from a free financial API Financialmodelingprep."
},
{
"code": null,
"e": 997,
"s": 692,
"text": "import plotly.express as pximport plotly.graph_objects as goimport pandas as pdimport requestsimport jsonquote = 'AAPL'days = 300def candlestick(quote,days): r = requests.get(f'https://financialmodelingprep.com/api/v3/historical- price-full/{quote}?timeseries={days}') r = r.json() return r"
},
{
"code": null,
"e": 1633,
"s": 997,
"text": "We pass as an argument of the get function the API endpoint url that we store in a variable named r. Then, we convert the API response to Json so that we Python can easily manipulate it with Python. The variable r will contain historical price data for any stock that we passed to our candlestick function. In above example, we have passed as parameters of our function ‘AAPL’ (i.e. Apple) and 300 days. Therefore, as a result, we get a list representing 300 data points. Each element in the list is a dictionary containing the information needed for our candlestick chart, that is, the open, high, low and close for each of the dates."
},
{
"code": null,
"e": 1863,
"s": 1633,
"text": "“symbol” : “AAPL”, “historical” : [ { “date” : “2015–01–20”, “open” : 107.84, “high” : 108.97, “low” : 106.5, “close” : 108.72, “volume” : 4.98999E7, “unadjustedVolume” : 4.98999E7, “change” : -0.88, “changePercent” : -0.816,...."
},
{
"code": null,
"e": 2077,
"s": 1863,
"text": "When possible, I always like to convert my data into a Pandas DataFrame since it let me handle, operate and clean my data on a very easy and convenient manner. That is what we achieve with below two lines of code."
},
{
"code": null,
"e": 2379,
"s": 2077,
"text": "First, we parse our variable r to extract the value associated to the historical key and store it in a variable called stockdata. This way, we keep a list of dictionaries. Each dictionary contains stock price data for a single day. Then, we can simply convert the stockdata list to a Pandas DataFrame."
},
{
"code": null,
"e": 2445,
"s": 2379,
"text": "stockdata = r[‘historical’]stockdata_df = pd.DataFrame(stockdata)"
},
{
"code": null,
"e": 2616,
"s": 2445,
"text": "If we print out our Pandas Dataframe stockdata_df, we get something similar to below where each row represents a day and each column is giving us stock price information:"
},
{
"code": null,
"e": 2795,
"s": 2616,
"text": "So far so good. Now, let’s move to the fun part. We can start building our chart with Plotly. Plotly is a very powerful graphing library. Very easy to use with Python and Pandas."
},
{
"code": null,
"e": 3239,
"s": 2795,
"text": "First of all, we need to create a fig object which will contain our data points. Within our Figure, we define our date, open, high, low and close. Each of the data points will be a column from our stockdata_df Pandas DataFrame. For example, open will contain the open price for each of the dates included in our Pandas DataFrame. Since, we passed in our function 300 days, open will contain the open stock price of Apple for the last 300 days."
},
{
"code": null,
"e": 3467,
"s": 3239,
"text": "Let’s also update the layout of our figure by using the Plotly fig.update_layout command to give some nice title to our chart, change the font and ensure that the the text is well positioned in the top center of the chart area."
},
{
"code": null,
"e": 3532,
"s": 3467,
"text": "Finally, we can use fig.show() to display the candlestick chart:"
},
{
"code": null,
"e": 4014,
"s": 3532,
"text": "fig = go.Figure(data=[go.Candlestick(x=stockdata_df['date'], open=stockdata_df['open'], high=stockdata_df['high'], low=stockdata_df['low'], close=stockdata_df['close'])])fig.update_layout( title= { 'text': quote, 'y':0.9, 'x':0.5, 'xanchor': 'center', 'yanchor': 'top'}, font=dict( family=\"Courier New, monospace\", size=20, color=\"#7f7f7f\" ) )fig.show()"
},
{
"code": null,
"e": 4228,
"s": 4014,
"text": "And now magically, or rather because our coding skills, an impressive candlestick chart is displayed in front of us, including a slider to zoom in and out for any particular period of time. Try it out by your own!"
},
{
"code": null,
"e": 4415,
"s": 4228,
"text": "I have included the whole script below for your reference. Just replace quote and days variables to select the desired stock and the number of days that you want to display in the chart."
},
{
"code": null,
"e": 4527,
"s": 4415,
"text": "Note: If you have any problems while running below code, ensure that you have all required libraries installed."
}
] |
How to split last n digits of each value in the array with JavaScript?
|
We have an array of literals like this −
const arr = ["", 20191219, 20191220, 20191221, 20191222, 20191223, 20191224, 20191225];
We are required to write a JavaScript function that takes in this array and a number n and if the
corresponding element contains more than or equal to n characters, then the new element
should contain only the last n characters otherwise the element should be left as it is.
Let's write the code for this function −
const arr = ["", 20191219, 20191220, 20191221, 20191222, 20191223,
20191224, 20191225];
const splitElement = (arr, num) => {
return arr.map(el => {
if(String(el).length <= num){
return el;
};
const part = String(el).substr(String(el).length - num, num);
return +part || part;
});
};
console.log(splitElement(arr, 2));
console.log(splitElement(arr, 1));
console.log(splitElement(arr, 4));
The output in the console will be −
[
'', 19, 20, 21,
22, 23, 24, 25
]
[
'', 9, '0', 1,
2, 3, 4, 5
]
[
'', 1219, 1220,
1221, 1222, 1223,
1224, 1225
]
|
[
{
"code": null,
"e": 1103,
"s": 1062,
"text": "We have an array of literals like this −"
},
{
"code": null,
"e": 1191,
"s": 1103,
"text": "const arr = [\"\", 20191219, 20191220, 20191221, 20191222, 20191223, 20191224, 20191225];"
},
{
"code": null,
"e": 1466,
"s": 1191,
"text": "We are required to write a JavaScript function that takes in this array and a number n and if the\ncorresponding element contains more than or equal to n characters, then the new element\nshould contain only the last n characters otherwise the element should be left as it is."
},
{
"code": null,
"e": 1507,
"s": 1466,
"text": "Let's write the code for this function −"
},
{
"code": null,
"e": 1934,
"s": 1507,
"text": "const arr = [\"\", 20191219, 20191220, 20191221, 20191222, 20191223,\n20191224, 20191225];\nconst splitElement = (arr, num) => {\n return arr.map(el => {\n if(String(el).length <= num){\n return el;\n };\n const part = String(el).substr(String(el).length - num, num);\n return +part || part;\n });\n};\nconsole.log(splitElement(arr, 2));\nconsole.log(splitElement(arr, 1));\nconsole.log(splitElement(arr, 4));"
},
{
"code": null,
"e": 1970,
"s": 1934,
"text": "The output in the console will be −"
},
{
"code": null,
"e": 2105,
"s": 1970,
"text": "[\n '', 19, 20, 21,\n 22, 23, 24, 25\n]\n[\n '', 9, '0', 1,\n 2, 3, 4, 5\n]\n[\n '', 1219, 1220,\n 1221, 1222, 1223,\n 1224, 1225\n]"
}
] |
Python - WebForm Submission
|
Often the interaction with a webpage needs some data to be submitted to the server through the forms present in the html page. These webforms are typically used
for processes like signing up for a new account or supplying some information like name or roll number to retrieve the result of an examination. The requests module
handles this gracefully using the POST method with the required parameters.
In the below example we use the sign up form of a website by supplying the userid and password value. After the submission of the values we print the response.
import requests
ID_USERNAME = 'signup-user-name'
ID_PASSWORD = 'signup-user-password'
USERNAME = 'username'
PASSWORD = 'yourpassword'
SIGNUP_URL = 'http://codepad.org/login'
def submit_form():
"""Submit a form"""
payload = {ID_USERNAME : USERNAME, ID_PASSWORD : PASSWORD,}
resp = requests.get(SIGNUP_URL)
print "Response to GET request: %s" %resp.content
resp = requests.post(SIGNUP_URL, payload)
print "Headers from a POST request response: %s" %resp.headers
#print "HTML Response: %s" %resp.read()
if __name__ == '__main__':
submit_form()
When we run the above program, we get the following output −
Response to GET request: <!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<meta HTTP-EQUIV="Pragma" CONTENT="no-cache">
<meta HTTP-EQUIV="Expires" CONTENT="-1">
<title>Login - codepad</title>
<link href="/main.css" media="screen" rel="stylesheet" type="text/css" />
<style type="text/css">
</style>
<script src='https://www.google.com/recaptcha/api.js'></script>
<script>
function onRecaptcha(token) {
document.getElementById("editor-form").submit();
}
</script>
</head>
<body >
.....................
.....................
187 Lectures
17.5 hours
Malhar Lathkar
55 Lectures
8 hours
Arnab Chakraborty
136 Lectures
11 hours
In28Minutes Official
75 Lectures
13 hours
Eduonix Learning Solutions
70 Lectures
8.5 hours
Lets Kode It
63 Lectures
6 hours
Abhilash Nelson
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2729,
"s": 2326,
"text": "Often the interaction with a webpage needs some data to be submitted to the server through the forms present in the html page. These webforms are typically used \nfor processes like signing up for a new account or supplying some information like name or roll number to retrieve the result of an examination. The requests module\nhandles this gracefully using the POST method with the required parameters."
},
{
"code": null,
"e": 2889,
"s": 2729,
"text": "In the below example we use the sign up form of a website by supplying the userid and password value. After the submission of the values we print the response."
},
{
"code": null,
"e": 3462,
"s": 2889,
"text": "import requests\n\nID_USERNAME = 'signup-user-name'\nID_PASSWORD = 'signup-user-password'\nUSERNAME = 'username'\nPASSWORD = 'yourpassword'\nSIGNUP_URL = 'http://codepad.org/login'\ndef submit_form():\n \"\"\"Submit a form\"\"\"\n payload = {ID_USERNAME : USERNAME, ID_PASSWORD : PASSWORD,}\n\n resp = requests.get(SIGNUP_URL)\n print \"Response to GET request: %s\" %resp.content\n\n resp = requests.post(SIGNUP_URL, payload)\n print \"Headers from a POST request response: %s\" %resp.headers\n#print \"HTML Response: %s\" %resp.read()\n\nif __name__ == '__main__':\n submit_form()"
},
{
"code": null,
"e": 3523,
"s": 3462,
"text": "When we run the above program, we get the following output −"
},
{
"code": null,
"e": 4185,
"s": 3523,
"text": "Response to GET request: <!DOCTYPE html>\n<html>\n\n<head>\n\n <meta http-equiv=\"content-type\" content=\"text/html; charset=UTF-8\">\n <meta HTTP-EQUIV=\"Pragma\" CONTENT=\"no-cache\">\n <meta HTTP-EQUIV=\"Expires\" CONTENT=\"-1\">\n\n <title>Login - codepad</title>\n\n \n\n <link href=\"/main.css\" media=\"screen\" rel=\"stylesheet\" type=\"text/css\" />\n <style type=\"text/css\">\n \n\n </style>\n <script src='https://www.google.com/recaptcha/api.js'></script>\n <script>\n function onRecaptcha(token) {\n document.getElementById(\"editor-form\").submit();\n }\n </script>\n</head>\n\n\n <body >\n\n\t.....................\n\t.....................\n\n"
},
{
"code": null,
"e": 4222,
"s": 4185,
"text": "\n 187 Lectures \n 17.5 hours \n"
},
{
"code": null,
"e": 4238,
"s": 4222,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 4271,
"s": 4238,
"text": "\n 55 Lectures \n 8 hours \n"
},
{
"code": null,
"e": 4290,
"s": 4271,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 4325,
"s": 4290,
"text": "\n 136 Lectures \n 11 hours \n"
},
{
"code": null,
"e": 4347,
"s": 4325,
"text": " In28Minutes Official"
},
{
"code": null,
"e": 4381,
"s": 4347,
"text": "\n 75 Lectures \n 13 hours \n"
},
{
"code": null,
"e": 4409,
"s": 4381,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 4444,
"s": 4409,
"text": "\n 70 Lectures \n 8.5 hours \n"
},
{
"code": null,
"e": 4458,
"s": 4444,
"text": " Lets Kode It"
},
{
"code": null,
"e": 4491,
"s": 4458,
"text": "\n 63 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 4508,
"s": 4491,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 4515,
"s": 4508,
"text": " Print"
},
{
"code": null,
"e": 4526,
"s": 4515,
"text": " Add Notes"
}
] |
Count the number of occurrences of a string in a VARCHAR field in MySQL?
|
To count the number of occurrences of a string in a VARCHAR, we can use the logic of subtraction with length. First, we will create a table with the help of create command.
mysql> create table StringOccurrenceDemo
-> (
-> Cases varchar(100),
-> StringValue varchar(500)
-> );
Query OK, 0 rows affected (0.56 sec)
After executing the above table, we will insert records into the table. The query is as follows −
mysql> insert into StringOccurrenceDemo values('First','This is MySQL Demo and MySQL is an open source RDBMS');
Query OK, 1 row affected (0.07 sec)
mysql> insert into StringOccurrenceDemo values('Second','There is no');
Query OK, 1 row affected (0.20 sec)
mysql> insert into StringOccurrenceDemo values('Third','There is MySQL,Hi MySQL,Hello MySQL');
Query OK, 1 row affected (0.17 sec)
Display all records with the help of select statement.
mysql> select *From StringOccurrenceDemo;
The following is the output.
+--------+------------------------------------------------------+
| Cases | StringValue |
+--------+------------------------------------------------------+
| First | This is MySQL Demo and MySQL is an open source RDBMS |
| Second | There is no |
| Third | There is MySQL,Hi MySQL,Hello MySQL |
+--------+------------------------------------------------------+
3 rows in set (0.00 sec)
The following is the query to count the occurrences of string “MySQL”. The result will get displayed in the column ‘NumberOfOccurrenceOfMySQL’
mysql> SELECT Cases,StringValue,
-> ROUND (
-> (
-> LENGTH(StringValue)- LENGTH( REPLACE (StringValue, "MySQL", "") )
-> ) / LENGTH("MySQL")
-> ) AS NumberOfOccurrenceOfMySQL
-> from StringOccurrenceDemo;
Here is the output.
+--------+------------------------------------------------------+---------------------------+
| Cases | StringValue | NumberOfOccurrenceOfMySQL|
+--------+------------------------------------------------------+---------------------------+
| First | This is MySQL Demo and MySQL is an open source RDBMS | 2 |
| Second | There is | 0 |
| Third | There is MySQL,Hi MySQL,Hello MySQL | 3 |
+--------+------------------------------------------------------+---------------------------+
3 rows in set (0.05 sec)
The above output shows that we have found the count for occurrences of string ‘MySQL’.
|
[
{
"code": null,
"e": 1235,
"s": 1062,
"text": "To count the number of occurrences of a string in a VARCHAR, we can use the logic of subtraction with length. First, we will create a table with the help of create command."
},
{
"code": null,
"e": 1388,
"s": 1235,
"text": "mysql> create table StringOccurrenceDemo\n -> (\n -> Cases varchar(100),\n -> StringValue varchar(500)\n -> );\nQuery OK, 0 rows affected (0.56 sec) "
},
{
"code": null,
"e": 1486,
"s": 1388,
"text": "After executing the above table, we will insert records into the table. The query is as follows −"
},
{
"code": null,
"e": 1875,
"s": 1486,
"text": "mysql> insert into StringOccurrenceDemo values('First','This is MySQL Demo and MySQL is an open source RDBMS');\nQuery OK, 1 row affected (0.07 sec)\n\nmysql> insert into StringOccurrenceDemo values('Second','There is no');\nQuery OK, 1 row affected (0.20 sec)\n\nmysql> insert into StringOccurrenceDemo values('Third','There is MySQL,Hi MySQL,Hello MySQL');\nQuery OK, 1 row affected (0.17 sec)"
},
{
"code": null,
"e": 1930,
"s": 1875,
"text": "Display all records with the help of select statement."
},
{
"code": null,
"e": 1972,
"s": 1930,
"text": "mysql> select *From StringOccurrenceDemo;"
},
{
"code": null,
"e": 2001,
"s": 1972,
"text": "The following is the output."
},
{
"code": null,
"e": 2489,
"s": 2001,
"text": "+--------+------------------------------------------------------+\n| Cases | StringValue |\n+--------+------------------------------------------------------+\n| First | This is MySQL Demo and MySQL is an open source RDBMS |\n| Second | There is no |\n| Third | There is MySQL,Hi MySQL,Hello MySQL |\n+--------+------------------------------------------------------+\n3 rows in set (0.00 sec)\n"
},
{
"code": null,
"e": 2633,
"s": 2489,
"text": "The following is the query to count the occurrences of string “MySQL”. The result will get displayed in the column ‘NumberOfOccurrenceOfMySQL’"
},
{
"code": null,
"e": 2857,
"s": 2633,
"text": "mysql> SELECT Cases,StringValue,\n -> ROUND (\n -> (\n -> LENGTH(StringValue)- LENGTH( REPLACE (StringValue, \"MySQL\", \"\") )\n -> ) / LENGTH(\"MySQL\")\n -> ) AS NumberOfOccurrenceOfMySQL\n -> from StringOccurrenceDemo;"
},
{
"code": null,
"e": 2877,
"s": 2857,
"text": "Here is the output."
},
{
"code": null,
"e": 3561,
"s": 2877,
"text": "+--------+------------------------------------------------------+---------------------------+\n| Cases | StringValue | NumberOfOccurrenceOfMySQL|\n+--------+------------------------------------------------------+---------------------------+\n| First | This is MySQL Demo and MySQL is an open source RDBMS | 2 |\n| Second | There is | 0 |\n| Third | There is MySQL,Hi MySQL,Hello MySQL | 3 |\n+--------+------------------------------------------------------+---------------------------+\n3 rows in set (0.05 sec)\n"
},
{
"code": null,
"e": 3648,
"s": 3561,
"text": "The above output shows that we have found the count for occurrences of string ‘MySQL’."
}
] |
Microsoft Azure - Find Orphaned Disks - GeeksforGeeks
|
16 Dec, 2021
In this article, you will see that how to find the unattached disks also known as orphaned disks in Azure. The main objective or purpose of deleting the orphaned resources is to save the cost of unused resources. When you delete a VM in Azure, the disks will not be deleted automatically and they will be left as orphaned disks.
Follow the below steps to find orphaned disks in Azure:
Step 1: Login to Azure Portal.
Step 2: Go to Azure Resource Graph Explorer >> select the Resource Graph Explorer
Step 3: Select Scope >> Subscription >> Select your subscriptions (You can select single or multiple subscriptions of your choice at once)
For Example: Here, I have selected 8 Subscriptions from Scope.
Step 4: Paste the below query in the query box and click on the Run query to get the list/report of unattached disks.
Example:
Resources
| where type has "microsoft.compute/disks"
| extend diskState = tostring(properties.diskState)
| where diskState == 'Unattached' or managedBy == ""
| project name, diskState, managedBy, subscriptionId, resourceGroup, location
Output:
Example 1: If you have selected multiple subscriptions in scope then you will be getting many results >> In this case, you can add where subscriptionId has “_SubscriptionId_Value” to get the results in a particular select subscription.
Resources
| where type has "microsoft.compute/disks"
| extend diskState = tostring(properties.diskState)
| where diskState == 'Unattached' or managedBy == ""
| where subscriptionId has ""
| project name, diskState, managedBy, subscriptionId, resourceGroup, location
Output:
Example 2: If you want results of tagged values to that orphaned disks then you can use the following kql command.
Resources
| where type has "microsoft.compute/disks"
| extend diskState = tostring(properties.diskState)
| where diskState == 'Unattached' or managedBy == ""
| where subscriptionId == ""
| where tags.Environment == "Production" // "Dev", "Prod", "Test",...etc.
| project name, diskState, managedBy, subscriptionId, resourceGroup, location, tags
Output:
That’s it you are done.
azure-virtual-machine
Cloud-Computing
Microsoft Azure
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Microsoft Azure - Azure VM Disk Space in Percentage using Azure KQL
Microsoft Azure - Rebooting an Application Gateway
Microsoft Azure - Installation of Service Bus Explorer
Microsoft Azure - Handling Orphaned NSGs
Microsoft Azure - Check Resource Owner in Azure using KQL
Microsoft Azure - Query System Event Log Data Using Azure KQL
Microsoft Azure - Get Azure VM Properties using Azure PowerShell
Microsoft Azure - KQL Query to Get the VM Computer Properties
Microsoft Azure - Graph Query to Get Properties of Azure VM Resource
Microsoft Azure - Mount Azure Storage in Container App In App Service
|
[
{
"code": null,
"e": 25772,
"s": 25744,
"text": "\n16 Dec, 2021"
},
{
"code": null,
"e": 26101,
"s": 25772,
"text": "In this article, you will see that how to find the unattached disks also known as orphaned disks in Azure. The main objective or purpose of deleting the orphaned resources is to save the cost of unused resources. When you delete a VM in Azure, the disks will not be deleted automatically and they will be left as orphaned disks."
},
{
"code": null,
"e": 26157,
"s": 26101,
"text": "Follow the below steps to find orphaned disks in Azure:"
},
{
"code": null,
"e": 26188,
"s": 26157,
"text": "Step 1: Login to Azure Portal."
},
{
"code": null,
"e": 26270,
"s": 26188,
"text": "Step 2: Go to Azure Resource Graph Explorer >> select the Resource Graph Explorer"
},
{
"code": null,
"e": 26409,
"s": 26270,
"text": "Step 3: Select Scope >> Subscription >> Select your subscriptions (You can select single or multiple subscriptions of your choice at once)"
},
{
"code": null,
"e": 26472,
"s": 26409,
"text": "For Example: Here, I have selected 8 Subscriptions from Scope."
},
{
"code": null,
"e": 26590,
"s": 26472,
"text": "Step 4: Paste the below query in the query box and click on the Run query to get the list/report of unattached disks."
},
{
"code": null,
"e": 26599,
"s": 26590,
"text": "Example:"
},
{
"code": null,
"e": 26836,
"s": 26599,
"text": "Resources\n| where type has \"microsoft.compute/disks\"\n| extend diskState = tostring(properties.diskState)\n| where diskState == 'Unattached' or managedBy == \"\"\n| project name, diskState, managedBy, subscriptionId, resourceGroup, location"
},
{
"code": null,
"e": 26844,
"s": 26836,
"text": "Output:"
},
{
"code": null,
"e": 27080,
"s": 26844,
"text": "Example 1: If you have selected multiple subscriptions in scope then you will be getting many results >> In this case, you can add where subscriptionId has “_SubscriptionId_Value” to get the results in a particular select subscription."
},
{
"code": null,
"e": 27349,
"s": 27080,
"text": "Resources\n| where type has \"microsoft.compute/disks\"\n| extend diskState = tostring(properties.diskState)\n| where diskState == 'Unattached' or managedBy == \"\"\n| where subscriptionId has \"\" \n| project name, diskState, managedBy, subscriptionId, resourceGroup, location"
},
{
"code": null,
"e": 27357,
"s": 27349,
"text": "Output:"
},
{
"code": null,
"e": 27472,
"s": 27357,
"text": "Example 2: If you want results of tagged values to that orphaned disks then you can use the following kql command."
},
{
"code": null,
"e": 27819,
"s": 27472,
"text": "Resources\n| where type has \"microsoft.compute/disks\"\n| extend diskState = tostring(properties.diskState)\n| where diskState == 'Unattached' or managedBy == \"\"\n| where subscriptionId == \"\" \n| where tags.Environment == \"Production\" // \"Dev\", \"Prod\", \"Test\",...etc.\n| project name, diskState, managedBy, subscriptionId, resourceGroup, location, tags"
},
{
"code": null,
"e": 27827,
"s": 27819,
"text": "Output:"
},
{
"code": null,
"e": 27851,
"s": 27827,
"text": "That’s it you are done."
},
{
"code": null,
"e": 27873,
"s": 27851,
"text": "azure-virtual-machine"
},
{
"code": null,
"e": 27889,
"s": 27873,
"text": "Cloud-Computing"
},
{
"code": null,
"e": 27905,
"s": 27889,
"text": "Microsoft Azure"
},
{
"code": null,
"e": 28003,
"s": 27905,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28012,
"s": 28003,
"text": "Comments"
},
{
"code": null,
"e": 28025,
"s": 28012,
"text": "Old Comments"
},
{
"code": null,
"e": 28093,
"s": 28025,
"text": "Microsoft Azure - Azure VM Disk Space in Percentage using Azure KQL"
},
{
"code": null,
"e": 28144,
"s": 28093,
"text": "Microsoft Azure - Rebooting an Application Gateway"
},
{
"code": null,
"e": 28199,
"s": 28144,
"text": "Microsoft Azure - Installation of Service Bus Explorer"
},
{
"code": null,
"e": 28240,
"s": 28199,
"text": "Microsoft Azure - Handling Orphaned NSGs"
},
{
"code": null,
"e": 28298,
"s": 28240,
"text": "Microsoft Azure - Check Resource Owner in Azure using KQL"
},
{
"code": null,
"e": 28360,
"s": 28298,
"text": "Microsoft Azure - Query System Event Log Data Using Azure KQL"
},
{
"code": null,
"e": 28425,
"s": 28360,
"text": "Microsoft Azure - Get Azure VM Properties using Azure PowerShell"
},
{
"code": null,
"e": 28487,
"s": 28425,
"text": "Microsoft Azure - KQL Query to Get the VM Computer Properties"
},
{
"code": null,
"e": 28556,
"s": 28487,
"text": "Microsoft Azure - Graph Query to Get Properties of Azure VM Resource"
}
] |
How to parse JSON input using Python?
|
You can parse JSON files using the JSON module in Python. This module parses the json and puts it in a dict. You can then get the values from this like a normal dict. For example, if you have a json with the following content −
{
"id": "file",
"value": "File",
"popup": {
"menuitem": [
{"value": "New", "onclick": "CreateNewDoc()"},
{"value": "Open", "onclick": "OpenDoc()"},
{"value": "Close", "onclick": "CloseDoc()"}
]
}
}
You can load it in your python program and loop over its keys in the following way −
import json
f = open('data.json')
data = json.load(f)
f.close()
# Now you can use data as a normal dict −
for (k, v) in data.items():
print("Key: " + k)
print("Value: " + str(v))
This will give the output −
Key: id
Value: file
Key: value
Value: File
Key: popup
Value: {'menuitem': [{'value': 'New', 'onclick': 'CreateNewDoc()'}, {'value': 'Open', 'onclick': 'OpenDoc()'}, {'value': 'Close', 'onclick': 'CloseDoc()'}]}
|
[
{
"code": null,
"e": 1290,
"s": 1062,
"text": "You can parse JSON files using the JSON module in Python. This module parses the json and puts it in a dict. You can then get the values from this like a normal dict. For example, if you have a json with the following content −"
},
{
"code": null,
"e": 1539,
"s": 1290,
"text": "{\n \"id\": \"file\",\n \"value\": \"File\",\n \"popup\": {\n \"menuitem\": [\n {\"value\": \"New\", \"onclick\": \"CreateNewDoc()\"},\n {\"value\": \"Open\", \"onclick\": \"OpenDoc()\"},\n {\"value\": \"Close\", \"onclick\": \"CloseDoc()\"}\n ]\n }\n}"
},
{
"code": null,
"e": 1624,
"s": 1539,
"text": "You can load it in your python program and loop over its keys in the following way −"
},
{
"code": null,
"e": 1688,
"s": 1624,
"text": "import json\nf = open('data.json')\ndata = json.load(f)\nf.close()"
},
{
"code": null,
"e": 1730,
"s": 1688,
"text": "# Now you can use data as a normal dict −"
},
{
"code": null,
"e": 1809,
"s": 1730,
"text": "for (k, v) in data.items():\n print(\"Key: \" + k)\n print(\"Value: \" + str(v))"
},
{
"code": null,
"e": 1837,
"s": 1809,
"text": "This will give the output −"
},
{
"code": null,
"e": 2048,
"s": 1837,
"text": "Key: id\nValue: file\nKey: value\nValue: File\nKey: popup\nValue: {'menuitem': [{'value': 'New', 'onclick': 'CreateNewDoc()'}, {'value': 'Open', 'onclick': 'OpenDoc()'}, {'value': 'Close', 'onclick': 'CloseDoc()'}]}"
}
] |
How to use custom headers in the PowerShell output table?
|
If you want the specific properties in PowerShell, you need to use the Select-Object (Alias − Select) as a pipeline.
In the below example, we will retrieve the specific properties of the Spooler service.
Get-Service Spooler | Select Name, DisplayName, Starttype, Status
Name DisplayName StartType Status
---- ----------- --------- ------
Spooler Print Spooler Automatic Running
Now we will customize the header by renaming the “Name” property to the “Alias Name” by the Name and the Expression syntax inside the Select-object.
Get-
Service Spooler | Select @{N='Alias Name';E={$_.Name}}, DisplayName, Starttype, Status
You can also use other commands as well inside the expression.
Get-ComputerInfo | Select Csname, WindowsProductName, Csworkgroup
CsName WindowsProductName CsWorkgroup
------ ------------------ -----------
DESKTOP-9435KM9 Windows 10 Pro WORKGROUP
In the above example, we need to add property “Computer Uptime” and for that, we need to add new command to the existing command using Expression syntax.
Get-
ComputerInfo | Select Csname, WindowsProductName, Csworkgroup, @{N='Days Uptime';E={((Get-Date) - (gcim Win32_OperatingSystem).LastBootUpTime).Days}}
CsName WindowsProductName CsWorkgroup Days Uptime
------ ------------------ ----------- -----------
DESKTOP-9435KM9 Windows 10 Pro WORKGROUP 1
|
[
{
"code": null,
"e": 1179,
"s": 1062,
"text": "If you want the specific properties in PowerShell, you need to use the Select-Object (Alias − Select) as a pipeline."
},
{
"code": null,
"e": 1266,
"s": 1179,
"text": "In the below example, we will retrieve the specific properties of the Spooler service."
},
{
"code": null,
"e": 1332,
"s": 1266,
"text": "Get-Service Spooler | Select Name, DisplayName, Starttype, Status"
},
{
"code": null,
"e": 1471,
"s": 1332,
"text": "Name DisplayName StartType Status\n---- ----------- --------- ------\nSpooler Print Spooler Automatic Running"
},
{
"code": null,
"e": 1620,
"s": 1471,
"text": "Now we will customize the header by renaming the “Name” property to the “Alias Name” by the Name and the Expression syntax inside the Select-object."
},
{
"code": null,
"e": 1712,
"s": 1620,
"text": "Get-\nService Spooler | Select @{N='Alias Name';E={$_.Name}}, DisplayName, Starttype, Status"
},
{
"code": null,
"e": 1775,
"s": 1712,
"text": "You can also use other commands as well inside the expression."
},
{
"code": null,
"e": 1841,
"s": 1775,
"text": "Get-ComputerInfo | Select Csname, WindowsProductName, Csworkgroup"
},
{
"code": null,
"e": 2007,
"s": 1841,
"text": "CsName WindowsProductName CsWorkgroup\n------ ------------------ -----------\nDESKTOP-9435KM9 Windows 10 Pro WORKGROUP"
},
{
"code": null,
"e": 2161,
"s": 2007,
"text": "In the above example, we need to add property “Computer Uptime” and for that, we need to add new command to the existing command using Expression syntax."
},
{
"code": null,
"e": 2316,
"s": 2161,
"text": "Get-\nComputerInfo | Select Csname, WindowsProductName, Csworkgroup, @{N='Days Uptime';E={((Get-Date) - (gcim Win32_OperatingSystem).LastBootUpTime).Days}}"
},
{
"code": null,
"e": 2550,
"s": 2316,
"text": "CsName WindowsProductName CsWorkgroup Days Uptime\n------ ------------------ ----------- -----------\nDESKTOP-9435KM9 Windows 10 Pro WORKGROUP 1"
}
] |
Data Preprocessing with scikit-learn — Missing Values | by Angelica Lo Duca | Towards Data Science
|
By popular demand from my previous article, in this tutorial I illustrate how to preprocess data using scikit-learn, a Python library for machine learning.
Data preprocessing transforms data into a format which is more suitable for estimators. Data preprocessing involves the following operations:
dealing with missing values
normalization
standardization
formatting
binning
In my previous articles I illustrated how to deal with missing values, normalization, standardization, formatting and binning with Python pandas. In this tutorial I show you how to deal with mising values with scikit-learn. For the other preprocessing techniques in scikit-learn, I will write other posts.
All the scikit-learn operations described in this tutorial follow the following steps:
select a preprocessing methodology
fit it through the fit() function
apply it to data through the transform() function.
The scikit-learn library works only with arrays, thus when performing every operation, a dataframe column must be converted to an array. This can be achieved through the numpy.array() function, which receives the dataframe column as input. In addition, the fit() function receives as input an array of arrays, each representing a sample of the dataset. Thus the reshape() function could be used to convert a standard array to an array of arrays.
You can download the full code from my Github repository.
In this tutorial we exploit the cupcake.csv dataset, which contains the trend search of the word cupcake on Google Trends. Data are extracted from this link. In the original dataset data in correspondence of 2004-02 and 2006-03 have been removed, in order to demonstrate how to deal with missing values. The original values were 5 and 10 respectively. We exploit the pandas library to import the dataset and we transform it into a dataframe through the read_csv() function.
import pandas as pddf = pd.read_csv('cupcake.csv')df.head(5)
Missing values are values not available in the original dataset. One solution to deal with missing values could be their removal from the dataset. However, this leads to data loss. The scikit-learn library provides two mechanisms to deal with missing values:
Univariate Feature Imputation
Multivariate Feature Imputation
Nearest neighbors imputation
In the Univariate Feature Imputation involves the replacement of missing values with a constant value or some provided statistics related to a feature. The SimpleImputer class can be used to perform univariate feature imputation. We specify which is the missing value through the missing_values parameter and the replacement strategy through the strategy parameter. For example, we can replace all the NaN values (identified by the numpy.nan variable) with the average value of the column.
import numpy as npfrom sklearn.impute import SimpleImputerpreprocessor = SimpleImputer(missing_values=np.nan, strategy='mean')
Now we can fit the preprocessor with the Cupcake column of the dataframe.
X = np.array(df['Cupcake']).reshape(-1,1)preprocessor.fit(X)
We apply the transform() function to our data.
X_prep = preprocessor.transform(X)
We convert it to the original shape by applying the inverse reshape() function and we store the result into a new column of the datafram df.
df['Cupcake_univariate'] = X_prep.reshape(1,-1)[0]df.head()
In the multivariate feature imputation each feature with missing values is calculated as a function of the other features. An iterative imputation is built thus the maximum number of iteration must be specified. We can use the IterativeImputer class. We consider two features: the column Cupcake and the index of the dataframe. Since the IterativeImputer is still at the experimental stage, we must enable it explicitly.
import numpy as npfrom sklearn.experimental import enable_iterative_imputerfrom sklearn.impute import IterativeImputerpreprocessor = IterativeImputer(max_iter=10, random_state=0)
We must convert the two features into arrays and transform them in the form [[f11,f21], [f12,f22] ...]. This can be done by applying the reshape() function to each feature and then the hstack() function as follows:
X1 = np.array(df['Cupcake']).reshape(-1,1)X2 = np.array(df.index).reshape(-1,1)X = np.hstack((X1,X2))
We fit the preprocessor with the obtained features.
preprocessor.fit(X)
And we apply the preprocessor to the same features X. In order to retrieve the result of the operation, we must apply the hsplit() function, which splits the array horizontally, then we apply the inverse reshape().
X_prep = preprocessor.transform(X)df['Cupcake_multivariate'] = np.hsplit(X_prep, 2)[0].reshape(1,-1)[0]
We can check results. Missing values are located at position 26 and 1. It is interesting to note that the two types of imputation produce different values.
df.iloc[26]
which gives the following output:
Mese 2006-03Cupcake NaNCupcake_univariate 50.0792Cupcake_multivariate 28.6311Name: 26, dtype: object
and
df.iloc[1]
which gives the following output:
Mese 2004-02Cupcake NaNCupcake_univariate 50.0792Cupcake_multivariate 21.6101Name: 1, dtype: object
This category of imputation fills missing values using the k-Nearest Neighbors approach. Each missing value is calculated using values from n_neighbors nearest neighbors that have a value. We can use the KNNImputer class of the scikit-learn library. In order to work properly, we must specify at least two features. Thus we exploit the X variable, previously defined.
from sklearn.impute import KNNImputerpreprocessor = KNNImputer(n_neighbors=5, weights="distance")preprocessor.fit(X)X_prep = preprocessor.transform(X)df['Cupcake_knn'] = np.hsplit(X_prep, 2)[0].reshape(1,-1)[0]
Now we can check results:
df.iloc[26]
which gives the following output:
Mese 2006-03Cupcake NaNCupcake_univariate 50.0792Cupcake_multivariate 28.6311Cupcake_knn 10.7Name: 26, dtype: object
and:
df.iloc[1]
which gives the following output:
Mese 2004-02Cupcake NaNCupcake_univariate 50.0792Cupcake_multivariate 21.6101Cupcake_knn 4.91892Name: 1, dtype: object
Definitely, the KNNImputer produces the nearest values to those in the original dataset (10 for position 26 and 5 for position 1).
In this tutorial we have learnt how to deal with missing values using the python scikit-learn library. Three basic classes exist to fill missing values: SimpleImputer, IterativeImputer, and KNNImputer. What is the best imputer? It depends on what you have to do.
If you wanted to learn how to perform the other aspects of data preprocessing using the scikit-learn library, stay tuned...
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": 328,
"s": 172,
"text": "By popular demand from my previous article, in this tutorial I illustrate how to preprocess data using scikit-learn, a Python library for machine learning."
},
{
"code": null,
"e": 470,
"s": 328,
"text": "Data preprocessing transforms data into a format which is more suitable for estimators. Data preprocessing involves the following operations:"
},
{
"code": null,
"e": 498,
"s": 470,
"text": "dealing with missing values"
},
{
"code": null,
"e": 512,
"s": 498,
"text": "normalization"
},
{
"code": null,
"e": 528,
"s": 512,
"text": "standardization"
},
{
"code": null,
"e": 539,
"s": 528,
"text": "formatting"
},
{
"code": null,
"e": 547,
"s": 539,
"text": "binning"
},
{
"code": null,
"e": 853,
"s": 547,
"text": "In my previous articles I illustrated how to deal with missing values, normalization, standardization, formatting and binning with Python pandas. In this tutorial I show you how to deal with mising values with scikit-learn. For the other preprocessing techniques in scikit-learn, I will write other posts."
},
{
"code": null,
"e": 940,
"s": 853,
"text": "All the scikit-learn operations described in this tutorial follow the following steps:"
},
{
"code": null,
"e": 975,
"s": 940,
"text": "select a preprocessing methodology"
},
{
"code": null,
"e": 1009,
"s": 975,
"text": "fit it through the fit() function"
},
{
"code": null,
"e": 1060,
"s": 1009,
"text": "apply it to data through the transform() function."
},
{
"code": null,
"e": 1506,
"s": 1060,
"text": "The scikit-learn library works only with arrays, thus when performing every operation, a dataframe column must be converted to an array. This can be achieved through the numpy.array() function, which receives the dataframe column as input. In addition, the fit() function receives as input an array of arrays, each representing a sample of the dataset. Thus the reshape() function could be used to convert a standard array to an array of arrays."
},
{
"code": null,
"e": 1564,
"s": 1506,
"text": "You can download the full code from my Github repository."
},
{
"code": null,
"e": 2038,
"s": 1564,
"text": "In this tutorial we exploit the cupcake.csv dataset, which contains the trend search of the word cupcake on Google Trends. Data are extracted from this link. In the original dataset data in correspondence of 2004-02 and 2006-03 have been removed, in order to demonstrate how to deal with missing values. The original values were 5 and 10 respectively. We exploit the pandas library to import the dataset and we transform it into a dataframe through the read_csv() function."
},
{
"code": null,
"e": 2099,
"s": 2038,
"text": "import pandas as pddf = pd.read_csv('cupcake.csv')df.head(5)"
},
{
"code": null,
"e": 2358,
"s": 2099,
"text": "Missing values are values not available in the original dataset. One solution to deal with missing values could be their removal from the dataset. However, this leads to data loss. The scikit-learn library provides two mechanisms to deal with missing values:"
},
{
"code": null,
"e": 2388,
"s": 2358,
"text": "Univariate Feature Imputation"
},
{
"code": null,
"e": 2420,
"s": 2388,
"text": "Multivariate Feature Imputation"
},
{
"code": null,
"e": 2449,
"s": 2420,
"text": "Nearest neighbors imputation"
},
{
"code": null,
"e": 2939,
"s": 2449,
"text": "In the Univariate Feature Imputation involves the replacement of missing values with a constant value or some provided statistics related to a feature. The SimpleImputer class can be used to perform univariate feature imputation. We specify which is the missing value through the missing_values parameter and the replacement strategy through the strategy parameter. For example, we can replace all the NaN values (identified by the numpy.nan variable) with the average value of the column."
},
{
"code": null,
"e": 3066,
"s": 2939,
"text": "import numpy as npfrom sklearn.impute import SimpleImputerpreprocessor = SimpleImputer(missing_values=np.nan, strategy='mean')"
},
{
"code": null,
"e": 3140,
"s": 3066,
"text": "Now we can fit the preprocessor with the Cupcake column of the dataframe."
},
{
"code": null,
"e": 3201,
"s": 3140,
"text": "X = np.array(df['Cupcake']).reshape(-1,1)preprocessor.fit(X)"
},
{
"code": null,
"e": 3248,
"s": 3201,
"text": "We apply the transform() function to our data."
},
{
"code": null,
"e": 3283,
"s": 3248,
"text": "X_prep = preprocessor.transform(X)"
},
{
"code": null,
"e": 3424,
"s": 3283,
"text": "We convert it to the original shape by applying the inverse reshape() function and we store the result into a new column of the datafram df."
},
{
"code": null,
"e": 3484,
"s": 3424,
"text": "df['Cupcake_univariate'] = X_prep.reshape(1,-1)[0]df.head()"
},
{
"code": null,
"e": 3905,
"s": 3484,
"text": "In the multivariate feature imputation each feature with missing values is calculated as a function of the other features. An iterative imputation is built thus the maximum number of iteration must be specified. We can use the IterativeImputer class. We consider two features: the column Cupcake and the index of the dataframe. Since the IterativeImputer is still at the experimental stage, we must enable it explicitly."
},
{
"code": null,
"e": 4084,
"s": 3905,
"text": "import numpy as npfrom sklearn.experimental import enable_iterative_imputerfrom sklearn.impute import IterativeImputerpreprocessor = IterativeImputer(max_iter=10, random_state=0)"
},
{
"code": null,
"e": 4299,
"s": 4084,
"text": "We must convert the two features into arrays and transform them in the form [[f11,f21], [f12,f22] ...]. This can be done by applying the reshape() function to each feature and then the hstack() function as follows:"
},
{
"code": null,
"e": 4401,
"s": 4299,
"text": "X1 = np.array(df['Cupcake']).reshape(-1,1)X2 = np.array(df.index).reshape(-1,1)X = np.hstack((X1,X2))"
},
{
"code": null,
"e": 4453,
"s": 4401,
"text": "We fit the preprocessor with the obtained features."
},
{
"code": null,
"e": 4473,
"s": 4453,
"text": "preprocessor.fit(X)"
},
{
"code": null,
"e": 4688,
"s": 4473,
"text": "And we apply the preprocessor to the same features X. In order to retrieve the result of the operation, we must apply the hsplit() function, which splits the array horizontally, then we apply the inverse reshape()."
},
{
"code": null,
"e": 4792,
"s": 4688,
"text": "X_prep = preprocessor.transform(X)df['Cupcake_multivariate'] = np.hsplit(X_prep, 2)[0].reshape(1,-1)[0]"
},
{
"code": null,
"e": 4948,
"s": 4792,
"text": "We can check results. Missing values are located at position 26 and 1. It is interesting to note that the two types of imputation produce different values."
},
{
"code": null,
"e": 4960,
"s": 4948,
"text": "df.iloc[26]"
},
{
"code": null,
"e": 4994,
"s": 4960,
"text": "which gives the following output:"
},
{
"code": null,
"e": 5142,
"s": 4994,
"text": "Mese 2006-03Cupcake NaNCupcake_univariate 50.0792Cupcake_multivariate 28.6311Name: 26, dtype: object"
},
{
"code": null,
"e": 5146,
"s": 5142,
"text": "and"
},
{
"code": null,
"e": 5157,
"s": 5146,
"text": "df.iloc[1]"
},
{
"code": null,
"e": 5191,
"s": 5157,
"text": "which gives the following output:"
},
{
"code": null,
"e": 5338,
"s": 5191,
"text": "Mese 2004-02Cupcake NaNCupcake_univariate 50.0792Cupcake_multivariate 21.6101Name: 1, dtype: object"
},
{
"code": null,
"e": 5706,
"s": 5338,
"text": "This category of imputation fills missing values using the k-Nearest Neighbors approach. Each missing value is calculated using values from n_neighbors nearest neighbors that have a value. We can use the KNNImputer class of the scikit-learn library. In order to work properly, we must specify at least two features. Thus we exploit the X variable, previously defined."
},
{
"code": null,
"e": 5917,
"s": 5706,
"text": "from sklearn.impute import KNNImputerpreprocessor = KNNImputer(n_neighbors=5, weights=\"distance\")preprocessor.fit(X)X_prep = preprocessor.transform(X)df['Cupcake_knn'] = np.hsplit(X_prep, 2)[0].reshape(1,-1)[0]"
},
{
"code": null,
"e": 5943,
"s": 5917,
"text": "Now we can check results:"
},
{
"code": null,
"e": 5955,
"s": 5943,
"text": "df.iloc[26]"
},
{
"code": null,
"e": 5989,
"s": 5955,
"text": "which gives the following output:"
},
{
"code": null,
"e": 6168,
"s": 5989,
"text": "Mese 2006-03Cupcake NaNCupcake_univariate 50.0792Cupcake_multivariate 28.6311Cupcake_knn 10.7Name: 26, dtype: object"
},
{
"code": null,
"e": 6173,
"s": 6168,
"text": "and:"
},
{
"code": null,
"e": 6184,
"s": 6173,
"text": "df.iloc[1]"
},
{
"code": null,
"e": 6218,
"s": 6184,
"text": "which gives the following output:"
},
{
"code": null,
"e": 6396,
"s": 6218,
"text": "Mese 2004-02Cupcake NaNCupcake_univariate 50.0792Cupcake_multivariate 21.6101Cupcake_knn 4.91892Name: 1, dtype: object"
},
{
"code": null,
"e": 6527,
"s": 6396,
"text": "Definitely, the KNNImputer produces the nearest values to those in the original dataset (10 for position 26 and 5 for position 1)."
},
{
"code": null,
"e": 6790,
"s": 6527,
"text": "In this tutorial we have learnt how to deal with missing values using the python scikit-learn library. Three basic classes exist to fill missing values: SimpleImputer, IterativeImputer, and KNNImputer. What is the best imputer? It depends on what you have to do."
},
{
"code": null,
"e": 6914,
"s": 6790,
"text": "If you wanted to learn how to perform the other aspects of data preprocessing using the scikit-learn library, stay tuned..."
}
] |
Implementing an XGBoost Model in R | by Michael Grogan | Towards Data Science
|
In this example, an XGBoost model is built in R to predict incidences of customers cancelling their hotel booking. The analysis is based on data from Antonio, Almeida and Nunes (2019): Hotel booking demand datasets.
The H1 dataset is used for training and validation, while H2 is used for testing purposes.
In order to predict customers that will cancel their booking (where variable IsCanceled = 1 means a cancellation, and IsCanceled = 0 means the customer follows through with the booking), an XGBoost model is built in R with the following features:
Lead time
Country of origin
Market segment
Deposit type
Customer type
Required car parking spaces
Week of arrival
In order to make the data suitable for analysis with the XGBoost model in R — some data manipulation procedures are required.
Firstly, the xgboost and Matrix libraries are loaded:
require(xgboost)library(Matrix)
A data frame of features is formed through defining the variables as.numeric, and also defining in factor format where appropriate. The data frame is then converted into Matrix format.
leadtime<-as.numeric(H1$LeadTime)country<-as.numeric(factor(H1$Country))marketsegment<-as.numeric(factor(H1$MarketSegment))deposittype<-as.numeric(factor(H1$DepositType))customertype<-as.numeric(factor(H1$CustomerType))rcps<-as.numeric(H1$RequiredCarParkingSpaces)week<-as.numeric(H1$ArrivalDateWeekNumber)df<-data.frame(leadtime,country,marketsegment,deposittype,customertype,rcps,week)attach(df)df<-as.matrix(df)
The labels (IsCanceled) is defined as a factor.
IsCanceled<-as.numeric(factor(H1$IsCanceled))
However, R labels the 0 values as 1 with the 1 values labelled as 2.
In order for the data to work with XGBoost, 0 and 1 labels must be defined.
Therefore, the label values are replaced accordingly as follows:
IsCanceled[IsCanceled == "1"] <- "0"IsCanceled[IsCanceled == "2"] <- "1"
The training and validation sets are split, and each is defined as a dgCMatrix — which is a special type of matrix that works with the XGBoost model in R.
train <- df[1:32000,]val <- df[32001:40060,]train=as(train, "dgCMatrix")trainval=as(val, "dgCMatrix")valIsCanceled_train=IsCanceled[1:32000]IsCanceled_val=IsCanceled[32001:40060]
The boosting model is defined and predictions are generated:
bst <- xgboost(data = train, label = IsCanceled_train, max.depth = 2, eta = 1, nthread = 2, nrounds = 2, objective = "binary:logistic")pred <- predict(bst, val)
Here are the training and validation errors:
> bst <- xgboost(data = train, label = IsCanceled_train, max.depth = 2, eta = 1, nthread = 2, nrounds = 2, objective = "binary:logistic")[1] train-error:0.252000 [2] train-error:0.222188> pred <- predict(bst, val)> print(length(pred))[1] 8060> print(head(pred))[1] 0.31375486 0.31375486 0.31375486 0.31375486 0.01498148[6] 0.01498148> prediction <- as.numeric(pred > 0.5)> print(head(prediction))[1] 0 0 0 0 0 0> err <- mean(as.numeric(pred > 0.5) != IsCanceled_val)> print(paste("val-error=", err))[1] "val-error= 0.1287841191067"
From the above output, we can see that the validation error of 0.12 is significantly lower than the two reported training errors of 0.25 and 0.22.
An importance matrix is also generated to identify the most important influencing factors on hotel cancellations:
# Importance Matriximportance_matrix <- xgb.importance(model = bst)print(importance_matrix)xgb.plot.importance(importance_matrix = importance_matrix)
Here is a more detailed look at the importance matrix:
> print(importance_matrix) Feature Gain Cover Frequency1: country 0.3589183 0.2266091 0.33333332: leadtime 0.2767732 0.2807021 0.16666673: rcps 0.2198606 0.2967366 0.33333334: marketsegment 0.1444479 0.1959522 0.1666667
As elaborated in the following StackExchange post — gain, cover and frequency illustrate the following:
Gain: Illustrates the contribution of a feature for each tree in the model, with a higher value illustrating greater importance for predicting the outcome variable.
Cover: Number of relative observations related to the feature in question.
Frequency: Number of times a feature occurs across the trees in the model.
The gain is the most important feature in assessing the relative contribution of a feature to the model. With a gain of 0.35 for the country variable, this is indicated as the most important feature in the model, i.e. a customer’s country of origin will have a significant impact in determining whether or not they ultimately cancel their hotel booking.
From looking at the training and validation errors, it looks as though the model may have performed quite well in predicting cancellations for this particular validation set, but there is no guarantee that it will do so on other datasets.
For this reason, a separate test set (H2) is used to verify if the XGBoost model will still perform well in predicting cancellation incidences.
The variables across the H2 set are defined once again:
leadtime<-as.numeric(H2$LeadTime)country<-as.numeric(factor(H2$Country))marketsegment<-as.numeric(factor(H2$MarketSegment))deposittype<-as.numeric(factor(H2$DepositType))customertype<-as.numeric(factor(H2$CustomerType))rcps<-as.numeric(H2$RequiredCarParkingSpaces)week<-as.numeric(H2$ArrivalDateWeekNumber)test<-data.frame(leadtime,country,marketsegment,deposittype,customertype,rcps,week)attach(test)test<-as.matrix(test)test=as(test, "dgCMatrix")testIsCanceled_H2<-as.numeric(factor(H2$IsCanceled))IsCanceled_H2[IsCanceled_H2 == "1"] <- "0"IsCanceled_H2[IsCanceled_H2 == "2"] <- "1"IsCanceled_H2<-as.numeric(IsCanceled_H2)
The XGBoost model built using the H1 dataset is now used to incorporate the feature data across H2:
pred <- predict(bst, test)
Here is the yielded test error:
> print(length(pred))[1] 79330> print(head(pred))[1] 0.3137549 0.7707853 0.7707853 0.7707853 0.7707853 0.7707853> > prediction <- as.numeric(pred > 0.5)> print(head(prediction))[1] 0 1 1 1 1 1> > err <- mean(as.numeric(pred > 0.5) != IsCanceled_H2)> print(paste("test-error=", err))[1] "test-error= 0.274335056094794"
The test error of 0.27 is higher than the validation error of 0.12, which we would reasonably expect when predicting new data.
That said, the original training errors of 0.25 and 0.22 are just slightly lower than the test error — indicating that the model does not show evidence of overfitting. Should we encounter a situation where the training error is much lower than the test error — then this is clearly a problem as it indicates that the model performs well in predicting the data used to build the model but not new data.
In this example, you have seen how to run an XGBoost model with R.
Specifically, you have seen:
How to transform data into dgCMatrix format in order to work with R’s XGBoost model
How to visualise feature importance through an Importance Matrix
Run an XGBoost model on test data to verify model accuracy
Many thanks for reading, and any questions or feedback are greatly appreciated. You can find the relevant repository for this example with the R code and dataset, as well as other useful references below.
Antonio, Almeida and Nunes (2019): Hotel booking demand datasets
Data Science StackExchange: How to interpret the output of XGBoost importance?
GitHub: MGCodesandStats/hotel-modelling
XGBoost Documentation: XGBoost R Tutorial
|
[
{
"code": null,
"e": 387,
"s": 171,
"text": "In this example, an XGBoost model is built in R to predict incidences of customers cancelling their hotel booking. The analysis is based on data from Antonio, Almeida and Nunes (2019): Hotel booking demand datasets."
},
{
"code": null,
"e": 478,
"s": 387,
"text": "The H1 dataset is used for training and validation, while H2 is used for testing purposes."
},
{
"code": null,
"e": 725,
"s": 478,
"text": "In order to predict customers that will cancel their booking (where variable IsCanceled = 1 means a cancellation, and IsCanceled = 0 means the customer follows through with the booking), an XGBoost model is built in R with the following features:"
},
{
"code": null,
"e": 735,
"s": 725,
"text": "Lead time"
},
{
"code": null,
"e": 753,
"s": 735,
"text": "Country of origin"
},
{
"code": null,
"e": 768,
"s": 753,
"text": "Market segment"
},
{
"code": null,
"e": 781,
"s": 768,
"text": "Deposit type"
},
{
"code": null,
"e": 795,
"s": 781,
"text": "Customer type"
},
{
"code": null,
"e": 823,
"s": 795,
"text": "Required car parking spaces"
},
{
"code": null,
"e": 839,
"s": 823,
"text": "Week of arrival"
},
{
"code": null,
"e": 965,
"s": 839,
"text": "In order to make the data suitable for analysis with the XGBoost model in R — some data manipulation procedures are required."
},
{
"code": null,
"e": 1019,
"s": 965,
"text": "Firstly, the xgboost and Matrix libraries are loaded:"
},
{
"code": null,
"e": 1051,
"s": 1019,
"text": "require(xgboost)library(Matrix)"
},
{
"code": null,
"e": 1236,
"s": 1051,
"text": "A data frame of features is formed through defining the variables as.numeric, and also defining in factor format where appropriate. The data frame is then converted into Matrix format."
},
{
"code": null,
"e": 1651,
"s": 1236,
"text": "leadtime<-as.numeric(H1$LeadTime)country<-as.numeric(factor(H1$Country))marketsegment<-as.numeric(factor(H1$MarketSegment))deposittype<-as.numeric(factor(H1$DepositType))customertype<-as.numeric(factor(H1$CustomerType))rcps<-as.numeric(H1$RequiredCarParkingSpaces)week<-as.numeric(H1$ArrivalDateWeekNumber)df<-data.frame(leadtime,country,marketsegment,deposittype,customertype,rcps,week)attach(df)df<-as.matrix(df)"
},
{
"code": null,
"e": 1699,
"s": 1651,
"text": "The labels (IsCanceled) is defined as a factor."
},
{
"code": null,
"e": 1745,
"s": 1699,
"text": "IsCanceled<-as.numeric(factor(H1$IsCanceled))"
},
{
"code": null,
"e": 1814,
"s": 1745,
"text": "However, R labels the 0 values as 1 with the 1 values labelled as 2."
},
{
"code": null,
"e": 1890,
"s": 1814,
"text": "In order for the data to work with XGBoost, 0 and 1 labels must be defined."
},
{
"code": null,
"e": 1955,
"s": 1890,
"text": "Therefore, the label values are replaced accordingly as follows:"
},
{
"code": null,
"e": 2028,
"s": 1955,
"text": "IsCanceled[IsCanceled == \"1\"] <- \"0\"IsCanceled[IsCanceled == \"2\"] <- \"1\""
},
{
"code": null,
"e": 2183,
"s": 2028,
"text": "The training and validation sets are split, and each is defined as a dgCMatrix — which is a special type of matrix that works with the XGBoost model in R."
},
{
"code": null,
"e": 2362,
"s": 2183,
"text": "train <- df[1:32000,]val <- df[32001:40060,]train=as(train, \"dgCMatrix\")trainval=as(val, \"dgCMatrix\")valIsCanceled_train=IsCanceled[1:32000]IsCanceled_val=IsCanceled[32001:40060]"
},
{
"code": null,
"e": 2423,
"s": 2362,
"text": "The boosting model is defined and predictions are generated:"
},
{
"code": null,
"e": 2584,
"s": 2423,
"text": "bst <- xgboost(data = train, label = IsCanceled_train, max.depth = 2, eta = 1, nthread = 2, nrounds = 2, objective = \"binary:logistic\")pred <- predict(bst, val)"
},
{
"code": null,
"e": 2629,
"s": 2584,
"text": "Here are the training and validation errors:"
},
{
"code": null,
"e": 3161,
"s": 2629,
"text": "> bst <- xgboost(data = train, label = IsCanceled_train, max.depth = 2, eta = 1, nthread = 2, nrounds = 2, objective = \"binary:logistic\")[1] train-error:0.252000 [2] train-error:0.222188> pred <- predict(bst, val)> print(length(pred))[1] 8060> print(head(pred))[1] 0.31375486 0.31375486 0.31375486 0.31375486 0.01498148[6] 0.01498148> prediction <- as.numeric(pred > 0.5)> print(head(prediction))[1] 0 0 0 0 0 0> err <- mean(as.numeric(pred > 0.5) != IsCanceled_val)> print(paste(\"val-error=\", err))[1] \"val-error= 0.1287841191067\""
},
{
"code": null,
"e": 3308,
"s": 3161,
"text": "From the above output, we can see that the validation error of 0.12 is significantly lower than the two reported training errors of 0.25 and 0.22."
},
{
"code": null,
"e": 3422,
"s": 3308,
"text": "An importance matrix is also generated to identify the most important influencing factors on hotel cancellations:"
},
{
"code": null,
"e": 3572,
"s": 3422,
"text": "# Importance Matriximportance_matrix <- xgb.importance(model = bst)print(importance_matrix)xgb.plot.importance(importance_matrix = importance_matrix)"
},
{
"code": null,
"e": 3627,
"s": 3572,
"text": "Here is a more detailed look at the importance matrix:"
},
{
"code": null,
"e": 3884,
"s": 3627,
"text": "> print(importance_matrix) Feature Gain Cover Frequency1: country 0.3589183 0.2266091 0.33333332: leadtime 0.2767732 0.2807021 0.16666673: rcps 0.2198606 0.2967366 0.33333334: marketsegment 0.1444479 0.1959522 0.1666667"
},
{
"code": null,
"e": 3988,
"s": 3884,
"text": "As elaborated in the following StackExchange post — gain, cover and frequency illustrate the following:"
},
{
"code": null,
"e": 4153,
"s": 3988,
"text": "Gain: Illustrates the contribution of a feature for each tree in the model, with a higher value illustrating greater importance for predicting the outcome variable."
},
{
"code": null,
"e": 4228,
"s": 4153,
"text": "Cover: Number of relative observations related to the feature in question."
},
{
"code": null,
"e": 4303,
"s": 4228,
"text": "Frequency: Number of times a feature occurs across the trees in the model."
},
{
"code": null,
"e": 4657,
"s": 4303,
"text": "The gain is the most important feature in assessing the relative contribution of a feature to the model. With a gain of 0.35 for the country variable, this is indicated as the most important feature in the model, i.e. a customer’s country of origin will have a significant impact in determining whether or not they ultimately cancel their hotel booking."
},
{
"code": null,
"e": 4896,
"s": 4657,
"text": "From looking at the training and validation errors, it looks as though the model may have performed quite well in predicting cancellations for this particular validation set, but there is no guarantee that it will do so on other datasets."
},
{
"code": null,
"e": 5040,
"s": 4896,
"text": "For this reason, a separate test set (H2) is used to verify if the XGBoost model will still perform well in predicting cancellation incidences."
},
{
"code": null,
"e": 5096,
"s": 5040,
"text": "The variables across the H2 set are defined once again:"
},
{
"code": null,
"e": 5721,
"s": 5096,
"text": "leadtime<-as.numeric(H2$LeadTime)country<-as.numeric(factor(H2$Country))marketsegment<-as.numeric(factor(H2$MarketSegment))deposittype<-as.numeric(factor(H2$DepositType))customertype<-as.numeric(factor(H2$CustomerType))rcps<-as.numeric(H2$RequiredCarParkingSpaces)week<-as.numeric(H2$ArrivalDateWeekNumber)test<-data.frame(leadtime,country,marketsegment,deposittype,customertype,rcps,week)attach(test)test<-as.matrix(test)test=as(test, \"dgCMatrix\")testIsCanceled_H2<-as.numeric(factor(H2$IsCanceled))IsCanceled_H2[IsCanceled_H2 == \"1\"] <- \"0\"IsCanceled_H2[IsCanceled_H2 == \"2\"] <- \"1\"IsCanceled_H2<-as.numeric(IsCanceled_H2)"
},
{
"code": null,
"e": 5821,
"s": 5721,
"text": "The XGBoost model built using the H1 dataset is now used to incorporate the feature data across H2:"
},
{
"code": null,
"e": 5848,
"s": 5821,
"text": "pred <- predict(bst, test)"
},
{
"code": null,
"e": 5880,
"s": 5848,
"text": "Here is the yielded test error:"
},
{
"code": null,
"e": 6198,
"s": 5880,
"text": "> print(length(pred))[1] 79330> print(head(pred))[1] 0.3137549 0.7707853 0.7707853 0.7707853 0.7707853 0.7707853> > prediction <- as.numeric(pred > 0.5)> print(head(prediction))[1] 0 1 1 1 1 1> > err <- mean(as.numeric(pred > 0.5) != IsCanceled_H2)> print(paste(\"test-error=\", err))[1] \"test-error= 0.274335056094794\""
},
{
"code": null,
"e": 6325,
"s": 6198,
"text": "The test error of 0.27 is higher than the validation error of 0.12, which we would reasonably expect when predicting new data."
},
{
"code": null,
"e": 6727,
"s": 6325,
"text": "That said, the original training errors of 0.25 and 0.22 are just slightly lower than the test error — indicating that the model does not show evidence of overfitting. Should we encounter a situation where the training error is much lower than the test error — then this is clearly a problem as it indicates that the model performs well in predicting the data used to build the model but not new data."
},
{
"code": null,
"e": 6794,
"s": 6727,
"text": "In this example, you have seen how to run an XGBoost model with R."
},
{
"code": null,
"e": 6823,
"s": 6794,
"text": "Specifically, you have seen:"
},
{
"code": null,
"e": 6907,
"s": 6823,
"text": "How to transform data into dgCMatrix format in order to work with R’s XGBoost model"
},
{
"code": null,
"e": 6972,
"s": 6907,
"text": "How to visualise feature importance through an Importance Matrix"
},
{
"code": null,
"e": 7031,
"s": 6972,
"text": "Run an XGBoost model on test data to verify model accuracy"
},
{
"code": null,
"e": 7236,
"s": 7031,
"text": "Many thanks for reading, and any questions or feedback are greatly appreciated. You can find the relevant repository for this example with the R code and dataset, as well as other useful references below."
},
{
"code": null,
"e": 7301,
"s": 7236,
"text": "Antonio, Almeida and Nunes (2019): Hotel booking demand datasets"
},
{
"code": null,
"e": 7380,
"s": 7301,
"text": "Data Science StackExchange: How to interpret the output of XGBoost importance?"
},
{
"code": null,
"e": 7420,
"s": 7380,
"text": "GitHub: MGCodesandStats/hotel-modelling"
}
] |
Text Classifier with Multiple Outputs and Multiple Losses in Keras | by Daniel Da Costa | Towards Data Science
|
In this post, we'll go through the definition of a multi-label classifier, multiple losses, text preprocessing and a step-by-step explanation on how to build a multi-output RNN-LSTM in Keras.
The dataset that we'll be working on consists of natural disaster messages that are classified into 36 different classes. The dataset was provided by Figure Eight. Example of input messages:
['Weather update - a cold front from Cuba that could pass over Haiti', 'Is the Hurricane over or is it not over', 'Looking for someone but no name', 'UN reports Leogane 80-90 destroyed. Only Hospital St. Croix functioning. Needs supplies desperately.', 'says: west side of Haiti, rest of the country today and tonight']
Before explaining what it is, let's first go through the definition of a more common classification type: Multiclass. In a multiclass, the classes are mutually exclusive, i.e, you can only classify one class at a time. For example, if you have the classes: {Car, Person, Motorcycle}, your model will have to output: Car OR Person OR Motorcycle. For this kind of problem, a Softmax function is used for classification:
For the multi-label classification, a data sample can belong to multiple classes. From the example above, your model can classify, for the same sample, the classes: Car AND Person (imagining that each sample is an image that may contain these 3 classes).
In the studied dataset, there are 36 different classes where 35 of them have a binary output: 0 or 1; and 1 of them has 3 possible classes (a multiclass case): 0, 1 or 2.
Using multiple loss functions in the same model means that you are doing different tasks and sharing part of your model between these tasks. Sometimes, you may think that maybe it's better to build different models for each different type of output, but in some situations sharing some layers of your Neural Network helps the models generalize better.
How does Keras handle multiple losses?
From the Keras documentation, "...the loss value that will be minimized by the model will then be the weighted sum of all individual losses, weighted by the loss_weightscoefficients.". Therefore, the final loss is a weighted sum of each loss, passed to the loss parameter.
In the studied case, two different losses will be used:
For the binary classes, the metric used will be the binary_accuracy with the corresponding binary_crossentropyloss. Since there are only two possible classes for each output (0 or 1), the sigmoid function will be used as the activation function.
For the multiclass output, the metric used will be the sparse_categorical_accuracy with the corresponding sparse_categorical_crossentropy loss. For this output, there are 3 possible classes: 0, 1 and 2, this way the softmax activation function will be used. Differently than the classical categorical_crossentropy loss, the first doesn't require the output Y to be one-hot encoded. Hence, instead of transforming the output into: [1, 0, 0], [0, 1, 0] and [0, 0, 1], we can leave it as integers: [0], [1] and [2]. It's important to highlight that both losses share the same equation:
Just like any other NLP problem, before applying the text input data into the model, we have to preprocess it. In this dataset, punctuations, url links and '@' mentions were removed. Even though '@' mentions adds some information to the message, it doesn't add value to the classification model. Hashtags ('#') may contain useful information since they are usually related to events. Therefore, they were kept, removing only the '#' character.
Stop words (most common words in a language) removal and lemmatization were also applied to the dataset.
The text samples are formatted into tensors that can be fed into a neural network using Keras utilities:
The above procedure includes mainly 3 steps :
First, a Tokenizer instance is fitted (fit_on_texts) to the corpus creating a vocabulary index based on word frequency. Every word is mapped to an index, so every word gets a unique integer value, lower integer means more frequent words. The size of words to keep is defined by the num_words parameter, i.e, vocabulary size. Only the most common words will be kept. In our dataset, the words were mapped as follows:
print(tokenizer.word_index){'water': 1, 'people': 2, 'food': 3, 'need': 4, 'help': 5, 'please': 6, 'earthquake': 7, 'would': 8, 'area': 9, 'like': 10, 'said': 11, 'country': 12,...}
The sentences from the input are then mapped to integers using the tokenizer.texts_to_sequences method. From our example:
'weather update cold front cuba could pa haiti'
is mapped to:
[138, 1480, 335, 863, 2709, 80, 411, 18]
Lastly, in order to create embeddings, all of our sentences need to be of same length. Hence, we use the pad_sequencesto pad each sentence with zero.
For building this model we'll be using Keras functional API and not the Sequential API since the first allows us to build more complex models, such as multiple outputs and inputs problems.
In order to summarize what we have until now:
each Input sample is a vector of integers of size MAXLEN (50)
each sample will be classified into 36 different classes where 35 of them have a binary output: 0 or 1; and 1 of them has 3 possible classes (a multiclass case): 0, 1 or 2.
In this section, we’ll be training our own embeddings using Keras Embedding Layer.
The Embedding layer takes as input:
input_dim: the vocabulary size that we chose
output_dim: the size of the embedding. In our case, it was set to 50d.
input_length: Length of input sequences. In our case: MAXLEN
A Convolutional layer was added before the LSTM in order to speed-up the training time. CNN are more likely to extract local and deep features from sentences. You can read more about the CNN and RNN combination in this article.
The majority of the output classes are binary, but one of them is a multiclass output. As explained in the Multiple Losses section, the losses used are: binary_crossentropy and sparse_categorical_crossentropy .
Since the dataset is highly imbalanced, the class_weight parameter was added in order to reduce the imbalanced distributions. A Dense layer will be created for each output. The outputs will be stored into an array, while the metrics and losses, for each output, will be stored into corresponding dictionaries.
The above code iterates through each of the output binary columns and creates a dense layer, saving the corresponding metric and loss into a dictionary.
The code below applies the same process to the single multiclass output column.
For each output we then define the weight for each class in a dictionary format:
We then can instantiate a Model class and train our model:
The model follows the format:
Apparently, Keras has an open issue with class_weights and binary_crossentropy for multi label outputs. The solution proposed above, adding one dense layer per output, is a valid solution.
In this post, we’ve built a RNN text classifier using Keras functional API with multiple outputs and losses. We walked through an explanation about multiple losses and also the difference between a multi-label and multiclass classification problem.
You can check the full code, with extra analysis, in Here! In this post, we trained our own embeddings, in the GitHub Repo you can check the same model retrained using Pre-trained GloVe vectors.
|
[
{
"code": null,
"e": 363,
"s": 171,
"text": "In this post, we'll go through the definition of a multi-label classifier, multiple losses, text preprocessing and a step-by-step explanation on how to build a multi-output RNN-LSTM in Keras."
},
{
"code": null,
"e": 554,
"s": 363,
"text": "The dataset that we'll be working on consists of natural disaster messages that are classified into 36 different classes. The dataset was provided by Figure Eight. Example of input messages:"
},
{
"code": null,
"e": 874,
"s": 554,
"text": "['Weather update - a cold front from Cuba that could pass over Haiti', 'Is the Hurricane over or is it not over', 'Looking for someone but no name', 'UN reports Leogane 80-90 destroyed. Only Hospital St. Croix functioning. Needs supplies desperately.', 'says: west side of Haiti, rest of the country today and tonight']"
},
{
"code": null,
"e": 1292,
"s": 874,
"text": "Before explaining what it is, let's first go through the definition of a more common classification type: Multiclass. In a multiclass, the classes are mutually exclusive, i.e, you can only classify one class at a time. For example, if you have the classes: {Car, Person, Motorcycle}, your model will have to output: Car OR Person OR Motorcycle. For this kind of problem, a Softmax function is used for classification:"
},
{
"code": null,
"e": 1547,
"s": 1292,
"text": "For the multi-label classification, a data sample can belong to multiple classes. From the example above, your model can classify, for the same sample, the classes: Car AND Person (imagining that each sample is an image that may contain these 3 classes)."
},
{
"code": null,
"e": 1718,
"s": 1547,
"text": "In the studied dataset, there are 36 different classes where 35 of them have a binary output: 0 or 1; and 1 of them has 3 possible classes (a multiclass case): 0, 1 or 2."
},
{
"code": null,
"e": 2070,
"s": 1718,
"text": "Using multiple loss functions in the same model means that you are doing different tasks and sharing part of your model between these tasks. Sometimes, you may think that maybe it's better to build different models for each different type of output, but in some situations sharing some layers of your Neural Network helps the models generalize better."
},
{
"code": null,
"e": 2109,
"s": 2070,
"text": "How does Keras handle multiple losses?"
},
{
"code": null,
"e": 2382,
"s": 2109,
"text": "From the Keras documentation, \"...the loss value that will be minimized by the model will then be the weighted sum of all individual losses, weighted by the loss_weightscoefficients.\". Therefore, the final loss is a weighted sum of each loss, passed to the loss parameter."
},
{
"code": null,
"e": 2438,
"s": 2382,
"text": "In the studied case, two different losses will be used:"
},
{
"code": null,
"e": 2684,
"s": 2438,
"text": "For the binary classes, the metric used will be the binary_accuracy with the corresponding binary_crossentropyloss. Since there are only two possible classes for each output (0 or 1), the sigmoid function will be used as the activation function."
},
{
"code": null,
"e": 3267,
"s": 2684,
"text": "For the multiclass output, the metric used will be the sparse_categorical_accuracy with the corresponding sparse_categorical_crossentropy loss. For this output, there are 3 possible classes: 0, 1 and 2, this way the softmax activation function will be used. Differently than the classical categorical_crossentropy loss, the first doesn't require the output Y to be one-hot encoded. Hence, instead of transforming the output into: [1, 0, 0], [0, 1, 0] and [0, 0, 1], we can leave it as integers: [0], [1] and [2]. It's important to highlight that both losses share the same equation:"
},
{
"code": null,
"e": 3711,
"s": 3267,
"text": "Just like any other NLP problem, before applying the text input data into the model, we have to preprocess it. In this dataset, punctuations, url links and '@' mentions were removed. Even though '@' mentions adds some information to the message, it doesn't add value to the classification model. Hashtags ('#') may contain useful information since they are usually related to events. Therefore, they were kept, removing only the '#' character."
},
{
"code": null,
"e": 3816,
"s": 3711,
"text": "Stop words (most common words in a language) removal and lemmatization were also applied to the dataset."
},
{
"code": null,
"e": 3921,
"s": 3816,
"text": "The text samples are formatted into tensors that can be fed into a neural network using Keras utilities:"
},
{
"code": null,
"e": 3967,
"s": 3921,
"text": "The above procedure includes mainly 3 steps :"
},
{
"code": null,
"e": 4383,
"s": 3967,
"text": "First, a Tokenizer instance is fitted (fit_on_texts) to the corpus creating a vocabulary index based on word frequency. Every word is mapped to an index, so every word gets a unique integer value, lower integer means more frequent words. The size of words to keep is defined by the num_words parameter, i.e, vocabulary size. Only the most common words will be kept. In our dataset, the words were mapped as follows:"
},
{
"code": null,
"e": 4565,
"s": 4383,
"text": "print(tokenizer.word_index){'water': 1, 'people': 2, 'food': 3, 'need': 4, 'help': 5, 'please': 6, 'earthquake': 7, 'would': 8, 'area': 9, 'like': 10, 'said': 11, 'country': 12,...}"
},
{
"code": null,
"e": 4687,
"s": 4565,
"text": "The sentences from the input are then mapped to integers using the tokenizer.texts_to_sequences method. From our example:"
},
{
"code": null,
"e": 4735,
"s": 4687,
"text": "'weather update cold front cuba could pa haiti'"
},
{
"code": null,
"e": 4749,
"s": 4735,
"text": "is mapped to:"
},
{
"code": null,
"e": 4790,
"s": 4749,
"text": "[138, 1480, 335, 863, 2709, 80, 411, 18]"
},
{
"code": null,
"e": 4940,
"s": 4790,
"text": "Lastly, in order to create embeddings, all of our sentences need to be of same length. Hence, we use the pad_sequencesto pad each sentence with zero."
},
{
"code": null,
"e": 5129,
"s": 4940,
"text": "For building this model we'll be using Keras functional API and not the Sequential API since the first allows us to build more complex models, such as multiple outputs and inputs problems."
},
{
"code": null,
"e": 5175,
"s": 5129,
"text": "In order to summarize what we have until now:"
},
{
"code": null,
"e": 5237,
"s": 5175,
"text": "each Input sample is a vector of integers of size MAXLEN (50)"
},
{
"code": null,
"e": 5410,
"s": 5237,
"text": "each sample will be classified into 36 different classes where 35 of them have a binary output: 0 or 1; and 1 of them has 3 possible classes (a multiclass case): 0, 1 or 2."
},
{
"code": null,
"e": 5493,
"s": 5410,
"text": "In this section, we’ll be training our own embeddings using Keras Embedding Layer."
},
{
"code": null,
"e": 5529,
"s": 5493,
"text": "The Embedding layer takes as input:"
},
{
"code": null,
"e": 5574,
"s": 5529,
"text": "input_dim: the vocabulary size that we chose"
},
{
"code": null,
"e": 5645,
"s": 5574,
"text": "output_dim: the size of the embedding. In our case, it was set to 50d."
},
{
"code": null,
"e": 5706,
"s": 5645,
"text": "input_length: Length of input sequences. In our case: MAXLEN"
},
{
"code": null,
"e": 5934,
"s": 5706,
"text": "A Convolutional layer was added before the LSTM in order to speed-up the training time. CNN are more likely to extract local and deep features from sentences. You can read more about the CNN and RNN combination in this article."
},
{
"code": null,
"e": 6145,
"s": 5934,
"text": "The majority of the output classes are binary, but one of them is a multiclass output. As explained in the Multiple Losses section, the losses used are: binary_crossentropy and sparse_categorical_crossentropy ."
},
{
"code": null,
"e": 6455,
"s": 6145,
"text": "Since the dataset is highly imbalanced, the class_weight parameter was added in order to reduce the imbalanced distributions. A Dense layer will be created for each output. The outputs will be stored into an array, while the metrics and losses, for each output, will be stored into corresponding dictionaries."
},
{
"code": null,
"e": 6608,
"s": 6455,
"text": "The above code iterates through each of the output binary columns and creates a dense layer, saving the corresponding metric and loss into a dictionary."
},
{
"code": null,
"e": 6688,
"s": 6608,
"text": "The code below applies the same process to the single multiclass output column."
},
{
"code": null,
"e": 6769,
"s": 6688,
"text": "For each output we then define the weight for each class in a dictionary format:"
},
{
"code": null,
"e": 6828,
"s": 6769,
"text": "We then can instantiate a Model class and train our model:"
},
{
"code": null,
"e": 6858,
"s": 6828,
"text": "The model follows the format:"
},
{
"code": null,
"e": 7047,
"s": 6858,
"text": "Apparently, Keras has an open issue with class_weights and binary_crossentropy for multi label outputs. The solution proposed above, adding one dense layer per output, is a valid solution."
},
{
"code": null,
"e": 7296,
"s": 7047,
"text": "In this post, we’ve built a RNN text classifier using Keras functional API with multiple outputs and losses. We walked through an explanation about multiple losses and also the difference between a multi-label and multiclass classification problem."
}
] |
Finding the longest string in an array in JavaScript
|
We are required to write a JavaScript function that takes in an array of strings. Our function should iterate through the array and find and return the longest string from the array.
Our function should do this without changing the content of the input array.
The code for this will be −
const arr = ["aaaa", "aa", "aa", "aaaaa", "acc", "aaaaaaaa"];
const findLargest = (arr = []) => {
if(!arr?.length){
return '';
};
let res = '';
res = arr.reduce((acc, val) => {
return acc.length >= val.length ? acc : val;
});
return res;
};
console.log(findLargest(arr));
And the output in the console will be −
aaaaaaaa
|
[
{
"code": null,
"e": 1245,
"s": 1062,
"text": "We are required to write a JavaScript function that takes in an array of strings. Our function should iterate through the array and find and return the longest string from the array."
},
{
"code": null,
"e": 1322,
"s": 1245,
"text": "Our function should do this without changing the content of the input array."
},
{
"code": null,
"e": 1350,
"s": 1322,
"text": "The code for this will be −"
},
{
"code": null,
"e": 1652,
"s": 1350,
"text": "const arr = [\"aaaa\", \"aa\", \"aa\", \"aaaaa\", \"acc\", \"aaaaaaaa\"];\nconst findLargest = (arr = []) => {\n if(!arr?.length){\n return '';\n };\n let res = '';\n res = arr.reduce((acc, val) => {\n return acc.length >= val.length ? acc : val;\n });\n return res;\n};\nconsole.log(findLargest(arr));"
},
{
"code": null,
"e": 1692,
"s": 1652,
"text": "And the output in the console will be −"
},
{
"code": null,
"e": 1701,
"s": 1692,
"text": "aaaaaaaa"
}
] |
How to create an ordinal variable in R?
|
An ordinal variable is a type of categorical variable which has natural ordering. For example, an ordinal variable could be level of salary something defined with Low, Medium, and High categories here we have three categories but there exists a natural order in these categories as low salary is always less than the medium, medium is always less than high. To create an ordinal variable in R, we can use the order argument along with factor function while creating the variable. Follow the below steps to create an ordinal variable in R −
Create a categorical column with factor function where order argument is set to TRUE
Look at the structure of the data frame
Let's create a data frame as shown below −
Live Demo
x<-
factor(sample(c("Low","Medium","High"),20,replace=TRUE),order=TRUE,levels=c("Lo
w","Medium","High"))
df<-data.frame(x)
df
On executing, the above script generates the below output(this output will vary on your system due to randomization) −
x
1 Medium
2 Medium
3 Low
4 Medium
5 Low
6 Medium
7 High
8 Low
9 Medium
10 High
11 Medium
12 High
13 Medium
14 Medium
15 Low
16 Low
17 Low
18 Medium
19 Low
20 Medium
Use str function to check the structure of data frame df −
Live Demo
x<-
factor(sample(c("Low","Medium","High"),20,replace=TRUE),order=TRUE,levels=c("Lo
w","Medium","High"))
df<-data.frame(x)
str(df)
'data.frame': 20 obs. of 1 variable:
$ x: Ord.factor w/ 3 levels "Low"<"Medium"<..: 2 2 1 2 1 2 3 1 2 3 ...
Here we can see that x is an ordered factor which means it is an ordinal variable.
|
[
{
"code": null,
"e": 1727,
"s": 1187,
"text": "An ordinal variable is a type of categorical variable which has natural ordering. For example, an ordinal variable could be level of salary something defined with Low, Medium, and High categories here we have three categories but there exists a natural order in these categories as low salary is always less than the medium, medium is always less than high. To create an ordinal variable in R, we can use the order argument along with factor function while creating the variable. Follow the below steps to create an ordinal variable in R −"
},
{
"code": null,
"e": 1812,
"s": 1727,
"text": "Create a categorical column with factor function where order argument is set to TRUE"
},
{
"code": null,
"e": 1852,
"s": 1812,
"text": "Look at the structure of the data frame"
},
{
"code": null,
"e": 1895,
"s": 1852,
"text": "Let's create a data frame as shown below −"
},
{
"code": null,
"e": 1906,
"s": 1895,
"text": " Live Demo"
},
{
"code": null,
"e": 2032,
"s": 1906,
"text": "x<-\nfactor(sample(c(\"Low\",\"Medium\",\"High\"),20,replace=TRUE),order=TRUE,levels=c(\"Lo\nw\",\"Medium\",\"High\"))\ndf<-data.frame(x)\ndf"
},
{
"code": null,
"e": 2151,
"s": 2032,
"text": "On executing, the above script generates the below output(this output will vary on your system due to randomization) −"
},
{
"code": null,
"e": 2321,
"s": 2151,
"text": " x\n1 Medium\n2 Medium\n3 Low\n4 Medium\n5 Low\n6 Medium\n7 High\n8 Low\n9 Medium\n10 High\n11 Medium\n12 High\n13 Medium\n14 Medium\n15 Low\n16 Low\n17 Low\n18 Medium\n19 Low\n20 Medium"
},
{
"code": null,
"e": 2380,
"s": 2321,
"text": "Use str function to check the structure of data frame df −"
},
{
"code": null,
"e": 2391,
"s": 2380,
"text": " Live Demo"
},
{
"code": null,
"e": 2522,
"s": 2391,
"text": "x<-\nfactor(sample(c(\"Low\",\"Medium\",\"High\"),20,replace=TRUE),order=TRUE,levels=c(\"Lo\nw\",\"Medium\",\"High\"))\ndf<-data.frame(x)\nstr(df)"
},
{
"code": null,
"e": 2630,
"s": 2522,
"text": "'data.frame': 20 obs. of 1 variable:\n$ x: Ord.factor w/ 3 levels \"Low\"<\"Medium\"<..: 2 2 1 2 1 2 3 1 2 3 ..."
},
{
"code": null,
"e": 2713,
"s": 2630,
"text": "Here we can see that x is an ordered factor which means it is an ordinal variable."
}
] |
How to send an Email from your Android App?
|
17 Jan, 2020
In this article, you will make a basic android application which can be used to send email through your android application.
You can do so with the help of Intent with action as ACTION_SEND with extra fields:
email id to which you want to send mail,
subject of email and
body of the email.
Basically Intent is a simple message object that is used to communicate between android components such as activities, content providers, broadcast receivers and services, here use to send the email.
This application basically contains one activity with EditText to take input of email address, subject and body of the email from user and button to send that email.
Step 1. activity_main.xmlactivity_main.xml contains a Relative Layout which contains three Edit texts for receiver mail id, other for the subject of the mail and last one for the body of the email and three TextViews for the label and a button for starting intent or sending mail:activity_main.xmlactivity_main.xml<?xml version="1.0" encoding="utf-8"?> <!--Relative Layout--><RelativeLayout xmlns:androclass="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <!--Edit text for email id--> <EditText android:id="@+id/editText1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentRight="true" android:layout_alignParentTop="true" android:layout_marginRight="22dp" android:layout_marginTop="18dp" /> <!--Edit text for email subject--> <EditText android:id="@+id/editText2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@+id/editText1" android:layout_alignLeft="@+id/editText1" android:layout_marginTop="20dp" /> <!--Edit text for email body--> <EditText android:id="@+id/editText3" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="30dp" android:layout_below="@+id/editText2" android:layout_alignLeft="@+id/editText2" /> <!--text Views for label--> <TextView android:id="@+id/textView1" android:textColor="#0F9D58" android:text="Send To:" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignBaseline="@+id/editText1" android:layout_alignBottom="@+id/editText1" android:layout_alignParentLeft="true" /> <TextView android:id="@+id/textView2" android:textColor="#0F9D58" android:text="Email Subject:" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignBaseline="@+id/editText2" android:layout_alignBottom="@+id/editText2" android:layout_alignParentLeft="true" /> <TextView android:id="@+id/textView3" android:textColor="#0F9D58" android:text="Email Body:" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignBaseline="@+id/editText3" android:layout_alignBottom="@+id/editText3" /> <!--Button to send email--> <Button android:id="@+id/button" android:text="Send email!!" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignLeft="@+id/editText3" android:layout_below="@+id/editText3" android:layout_marginLeft="76dp" android:layout_marginTop="20dp" /> </RelativeLayout>
activity_main.xml
<?xml version="1.0" encoding="utf-8"?> <!--Relative Layout--><RelativeLayout xmlns:androclass="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <!--Edit text for email id--> <EditText android:id="@+id/editText1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentRight="true" android:layout_alignParentTop="true" android:layout_marginRight="22dp" android:layout_marginTop="18dp" /> <!--Edit text for email subject--> <EditText android:id="@+id/editText2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@+id/editText1" android:layout_alignLeft="@+id/editText1" android:layout_marginTop="20dp" /> <!--Edit text for email body--> <EditText android:id="@+id/editText3" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="30dp" android:layout_below="@+id/editText2" android:layout_alignLeft="@+id/editText2" /> <!--text Views for label--> <TextView android:id="@+id/textView1" android:textColor="#0F9D58" android:text="Send To:" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignBaseline="@+id/editText1" android:layout_alignBottom="@+id/editText1" android:layout_alignParentLeft="true" /> <TextView android:id="@+id/textView2" android:textColor="#0F9D58" android:text="Email Subject:" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignBaseline="@+id/editText2" android:layout_alignBottom="@+id/editText2" android:layout_alignParentLeft="true" /> <TextView android:id="@+id/textView3" android:textColor="#0F9D58" android:text="Email Body:" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignBaseline="@+id/editText3" android:layout_alignBottom="@+id/editText3" /> <!--Button to send email--> <Button android:id="@+id/button" android:text="Send email!!" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignLeft="@+id/editText3" android:layout_below="@+id/editText3" android:layout_marginLeft="76dp" android:layout_marginTop="20dp" /> </RelativeLayout>
Step 2. MainActivity.javaIn Main activity Intent object is created and its action is defined to ACTION_SEND to send email, with Intent three extra fields are also added using putExtra function.These fields are:Email of receiverSubject of emailBody of emailsetOnClickListener is attached to button with intent object in it to make intent with action as ACTION_SEND to send email and intent type as shown in code.Here is complete java code to send email through intent from android application:MainActivity.javaMainActivity.javapackage com.geeksforgeeks.phonecall; import android.os.Bundle;import android.support.v7.app.AppCompatActivity;import android.content.Intent;import android.widget.EditText;import android.view.View;import android.view.View.OnClickListener;import android.net.Uri;import android.widget.Button; public class MainActivity extends AppCompatActivity { // define objects for edit text and button Button button; EditText sendto, subject, body; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // Getting instance of edittext and button sendto = findViewById(R.id.editText1); subject = findViewById(R.id.editText2); body = findViewById(R.id.editText3); button = findViewById(R.id.button); // attach setOnClickListener to button // with Intent object define in it button.setOnClickListener(new OnClickListener() { @Override public void onClick(View view) { String emailsend = sendto.getText().toString(); String emailsubject = subject.getText().toString(); String emailbody = body.getText().toString(); // define Intent object // with action attribute as ACTION_SEND Intent intent = new Intent(Intent.ACTION_SEND); // add three fiels to intent using putExtra function intent.putExtra(Intent.EXTRA_EMAIL, new String[] { emailsend }); intent.putExtra(Intent.EXTRA_SUBJECT, emailsubject); intent.putExtra(Intent.EXTRA_TEXT, emailbody); // set type of intent intent.setType("message/rfc822"); // startActivity with intent with chooser // as Email client using createChooser function startActivity( Intent .createChooser(intent, "Choose an Email client :")); } }); }}
Email of receiver
Subject of email
Body of email
setOnClickListener is attached to button with intent object in it to make intent with action as ACTION_SEND to send email and intent type as shown in code.
Here is complete java code to send email through intent from android application:
MainActivity.java
package com.geeksforgeeks.phonecall; import android.os.Bundle;import android.support.v7.app.AppCompatActivity;import android.content.Intent;import android.widget.EditText;import android.view.View;import android.view.View.OnClickListener;import android.net.Uri;import android.widget.Button; public class MainActivity extends AppCompatActivity { // define objects for edit text and button Button button; EditText sendto, subject, body; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // Getting instance of edittext and button sendto = findViewById(R.id.editText1); subject = findViewById(R.id.editText2); body = findViewById(R.id.editText3); button = findViewById(R.id.button); // attach setOnClickListener to button // with Intent object define in it button.setOnClickListener(new OnClickListener() { @Override public void onClick(View view) { String emailsend = sendto.getText().toString(); String emailsubject = subject.getText().toString(); String emailbody = body.getText().toString(); // define Intent object // with action attribute as ACTION_SEND Intent intent = new Intent(Intent.ACTION_SEND); // add three fiels to intent using putExtra function intent.putExtra(Intent.EXTRA_EMAIL, new String[] { emailsend }); intent.putExtra(Intent.EXTRA_SUBJECT, emailsubject); intent.putExtra(Intent.EXTRA_TEXT, emailbody); // set type of intent intent.setType("message/rfc822"); // startActivity with intent with chooser // as Email client using createChooser function startActivity( Intent .createChooser(intent, "Choose an Email client :")); } }); }}
Output:
android
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Introduction to Java
Constructors in Java
Exceptions in Java
Generics in Java
Functional Interfaces in Java
Java Programming Examples
Strings in Java
Differences between JDK, JRE and JVM
Abstraction in Java
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n17 Jan, 2020"
},
{
"code": null,
"e": 179,
"s": 54,
"text": "In this article, you will make a basic android application which can be used to send email through your android application."
},
{
"code": null,
"e": 263,
"s": 179,
"text": "You can do so with the help of Intent with action as ACTION_SEND with extra fields:"
},
{
"code": null,
"e": 304,
"s": 263,
"text": "email id to which you want to send mail,"
},
{
"code": null,
"e": 325,
"s": 304,
"text": "subject of email and"
},
{
"code": null,
"e": 344,
"s": 325,
"text": "body of the email."
},
{
"code": null,
"e": 544,
"s": 344,
"text": "Basically Intent is a simple message object that is used to communicate between android components such as activities, content providers, broadcast receivers and services, here use to send the email."
},
{
"code": null,
"e": 710,
"s": 544,
"text": "This application basically contains one activity with EditText to take input of email address, subject and body of the email from user and button to send that email."
},
{
"code": null,
"e": 3917,
"s": 710,
"text": "Step 1. activity_main.xmlactivity_main.xml contains a Relative Layout which contains three Edit texts for receiver mail id, other for the subject of the mail and last one for the body of the email and three TextViews for the label and a button for starting intent or sending mail:activity_main.xmlactivity_main.xml<?xml version=\"1.0\" encoding=\"utf-8\"?> <!--Relative Layout--><RelativeLayout xmlns:androclass=\"http://schemas.android.com/apk/res/android\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" tools:context=\".MainActivity\"> <!--Edit text for email id--> <EditText android:id=\"@+id/editText1\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_alignParentRight=\"true\" android:layout_alignParentTop=\"true\" android:layout_marginRight=\"22dp\" android:layout_marginTop=\"18dp\" /> <!--Edit text for email subject--> <EditText android:id=\"@+id/editText2\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_below=\"@+id/editText1\" android:layout_alignLeft=\"@+id/editText1\" android:layout_marginTop=\"20dp\" /> <!--Edit text for email body--> <EditText android:id=\"@+id/editText3\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_marginTop=\"30dp\" android:layout_below=\"@+id/editText2\" android:layout_alignLeft=\"@+id/editText2\" /> <!--text Views for label--> <TextView android:id=\"@+id/textView1\" android:textColor=\"#0F9D58\" android:text=\"Send To:\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_alignBaseline=\"@+id/editText1\" android:layout_alignBottom=\"@+id/editText1\" android:layout_alignParentLeft=\"true\" /> <TextView android:id=\"@+id/textView2\" android:textColor=\"#0F9D58\" android:text=\"Email Subject:\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_alignBaseline=\"@+id/editText2\" android:layout_alignBottom=\"@+id/editText2\" android:layout_alignParentLeft=\"true\" /> <TextView android:id=\"@+id/textView3\" android:textColor=\"#0F9D58\" android:text=\"Email Body:\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_alignBaseline=\"@+id/editText3\" android:layout_alignBottom=\"@+id/editText3\" /> <!--Button to send email--> <Button android:id=\"@+id/button\" android:text=\"Send email!!\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_alignLeft=\"@+id/editText3\" android:layout_below=\"@+id/editText3\" android:layout_marginLeft=\"76dp\" android:layout_marginTop=\"20dp\" /> </RelativeLayout>"
},
{
"code": null,
"e": 3935,
"s": 3917,
"text": "activity_main.xml"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?> <!--Relative Layout--><RelativeLayout xmlns:androclass=\"http://schemas.android.com/apk/res/android\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" tools:context=\".MainActivity\"> <!--Edit text for email id--> <EditText android:id=\"@+id/editText1\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_alignParentRight=\"true\" android:layout_alignParentTop=\"true\" android:layout_marginRight=\"22dp\" android:layout_marginTop=\"18dp\" /> <!--Edit text for email subject--> <EditText android:id=\"@+id/editText2\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_below=\"@+id/editText1\" android:layout_alignLeft=\"@+id/editText1\" android:layout_marginTop=\"20dp\" /> <!--Edit text for email body--> <EditText android:id=\"@+id/editText3\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_marginTop=\"30dp\" android:layout_below=\"@+id/editText2\" android:layout_alignLeft=\"@+id/editText2\" /> <!--text Views for label--> <TextView android:id=\"@+id/textView1\" android:textColor=\"#0F9D58\" android:text=\"Send To:\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_alignBaseline=\"@+id/editText1\" android:layout_alignBottom=\"@+id/editText1\" android:layout_alignParentLeft=\"true\" /> <TextView android:id=\"@+id/textView2\" android:textColor=\"#0F9D58\" android:text=\"Email Subject:\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_alignBaseline=\"@+id/editText2\" android:layout_alignBottom=\"@+id/editText2\" android:layout_alignParentLeft=\"true\" /> <TextView android:id=\"@+id/textView3\" android:textColor=\"#0F9D58\" android:text=\"Email Body:\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_alignBaseline=\"@+id/editText3\" android:layout_alignBottom=\"@+id/editText3\" /> <!--Button to send email--> <Button android:id=\"@+id/button\" android:text=\"Send email!!\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_alignLeft=\"@+id/editText3\" android:layout_below=\"@+id/editText3\" android:layout_marginLeft=\"76dp\" android:layout_marginTop=\"20dp\" /> </RelativeLayout>",
"e": 6828,
"s": 3935,
"text": null
},
{
"code": null,
"e": 9493,
"s": 6828,
"text": "Step 2. MainActivity.javaIn Main activity Intent object is created and its action is defined to ACTION_SEND to send email, with Intent three extra fields are also added using putExtra function.These fields are:Email of receiverSubject of emailBody of emailsetOnClickListener is attached to button with intent object in it to make intent with action as ACTION_SEND to send email and intent type as shown in code.Here is complete java code to send email through intent from android application:MainActivity.javaMainActivity.javapackage com.geeksforgeeks.phonecall; import android.os.Bundle;import android.support.v7.app.AppCompatActivity;import android.content.Intent;import android.widget.EditText;import android.view.View;import android.view.View.OnClickListener;import android.net.Uri;import android.widget.Button; public class MainActivity extends AppCompatActivity { // define objects for edit text and button Button button; EditText sendto, subject, body; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // Getting instance of edittext and button sendto = findViewById(R.id.editText1); subject = findViewById(R.id.editText2); body = findViewById(R.id.editText3); button = findViewById(R.id.button); // attach setOnClickListener to button // with Intent object define in it button.setOnClickListener(new OnClickListener() { @Override public void onClick(View view) { String emailsend = sendto.getText().toString(); String emailsubject = subject.getText().toString(); String emailbody = body.getText().toString(); // define Intent object // with action attribute as ACTION_SEND Intent intent = new Intent(Intent.ACTION_SEND); // add three fiels to intent using putExtra function intent.putExtra(Intent.EXTRA_EMAIL, new String[] { emailsend }); intent.putExtra(Intent.EXTRA_SUBJECT, emailsubject); intent.putExtra(Intent.EXTRA_TEXT, emailbody); // set type of intent intent.setType(\"message/rfc822\"); // startActivity with intent with chooser // as Email client using createChooser function startActivity( Intent .createChooser(intent, \"Choose an Email client :\")); } }); }}"
},
{
"code": null,
"e": 9511,
"s": 9493,
"text": "Email of receiver"
},
{
"code": null,
"e": 9528,
"s": 9511,
"text": "Subject of email"
},
{
"code": null,
"e": 9542,
"s": 9528,
"text": "Body of email"
},
{
"code": null,
"e": 9698,
"s": 9542,
"text": "setOnClickListener is attached to button with intent object in it to make intent with action as ACTION_SEND to send email and intent type as shown in code."
},
{
"code": null,
"e": 9780,
"s": 9698,
"text": "Here is complete java code to send email through intent from android application:"
},
{
"code": null,
"e": 9798,
"s": 9780,
"text": "MainActivity.java"
},
{
"code": "package com.geeksforgeeks.phonecall; import android.os.Bundle;import android.support.v7.app.AppCompatActivity;import android.content.Intent;import android.widget.EditText;import android.view.View;import android.view.View.OnClickListener;import android.net.Uri;import android.widget.Button; public class MainActivity extends AppCompatActivity { // define objects for edit text and button Button button; EditText sendto, subject, body; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // Getting instance of edittext and button sendto = findViewById(R.id.editText1); subject = findViewById(R.id.editText2); body = findViewById(R.id.editText3); button = findViewById(R.id.button); // attach setOnClickListener to button // with Intent object define in it button.setOnClickListener(new OnClickListener() { @Override public void onClick(View view) { String emailsend = sendto.getText().toString(); String emailsubject = subject.getText().toString(); String emailbody = body.getText().toString(); // define Intent object // with action attribute as ACTION_SEND Intent intent = new Intent(Intent.ACTION_SEND); // add three fiels to intent using putExtra function intent.putExtra(Intent.EXTRA_EMAIL, new String[] { emailsend }); intent.putExtra(Intent.EXTRA_SUBJECT, emailsubject); intent.putExtra(Intent.EXTRA_TEXT, emailbody); // set type of intent intent.setType(\"message/rfc822\"); // startActivity with intent with chooser // as Email client using createChooser function startActivity( Intent .createChooser(intent, \"Choose an Email client :\")); } }); }}",
"e": 11937,
"s": 9798,
"text": null
},
{
"code": null,
"e": 11945,
"s": 11937,
"text": "Output:"
},
{
"code": null,
"e": 11953,
"s": 11945,
"text": "android"
},
{
"code": null,
"e": 11958,
"s": 11953,
"text": "Java"
},
{
"code": null,
"e": 11963,
"s": 11958,
"text": "Java"
},
{
"code": null,
"e": 12061,
"s": 11963,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 12076,
"s": 12061,
"text": "Stream In Java"
},
{
"code": null,
"e": 12097,
"s": 12076,
"text": "Introduction to Java"
},
{
"code": null,
"e": 12118,
"s": 12097,
"text": "Constructors in Java"
},
{
"code": null,
"e": 12137,
"s": 12118,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 12154,
"s": 12137,
"text": "Generics in Java"
},
{
"code": null,
"e": 12184,
"s": 12154,
"text": "Functional Interfaces in Java"
},
{
"code": null,
"e": 12210,
"s": 12184,
"text": "Java Programming Examples"
},
{
"code": null,
"e": 12226,
"s": 12210,
"text": "Strings in Java"
},
{
"code": null,
"e": 12263,
"s": 12226,
"text": "Differences between JDK, JRE and JVM"
}
] |
Lodash | _.clone() Method
|
02 Feb, 2022
The _.clone() method is used to create a shallow copy of the value. This method supports cloning arrays, array buffers, booleans, date objects, maps, numbers, Object objects, regexes, sets, strings, symbols, and typed arrays. It is loosely based on the structured clone algorithm.
Syntax:
_.clone( value )
Parameters: This method accepts single parameter as mentioned above and described below:
value: This parameter holds the value that need to be clone.
Return Value: This method returns the shallow copy of value.
Example 1: Cloning Simple Object
javascript
const _ = require('lodash'); var obj = { x: 23}; // Shallow copyvar shallowCopy = _.clone(obj); console.log('Comparing original with' + ' shallow ', obj === shallowCopy); obj.x = 10; // Changing original value console.log('After changing original value'); console.log("Original value ", obj); console.log("Shallow Copy value ", shallowCopy);
Here, const _ = require('lodash') is used to import the lodash library into the file.
Output:
Comparing original with shallow false
After changing original value
Original value { x: 10 }
Shallow Copy value { x: 23 }
Example 2: Cloning complex object
javascript
const _ = require('lodash'); var obj = [{ x: 1 }, {y: 2}]; // Shallow copyvar shallowCopy = _.clone(obj); console.log('Comparing original with shallow ', obj[0] === shallowCopy[0]); // Changing original valueobj[0].x = 10; // Values after changing original valueconsole.log("After changing original value"); console.log("Original value ", obj); console.log("Shallow Copy value ", shallowCopy);
Output:
Comparing original with shallow true
After changing original value
Original value [ { x: 10 }, { y: 2 } ]
Shallow Copy value [ { x: 10 }, { y: 2 } ]
So, here we have seen that after changing original value the shallow copy value also changed because _.clone() doesn’t copy deeply it just passed the reference.
Note: This will not work in normal JavaScript because it requires the library lodash to be installed.
Reference: https://lodash.com/docs/4.17.15#clone
sagar0719kumar
JavaScript-Lodash
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
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": "\n02 Feb, 2022"
},
{
"code": null,
"e": 309,
"s": 28,
"text": "The _.clone() method is used to create a shallow copy of the value. This method supports cloning arrays, array buffers, booleans, date objects, maps, numbers, Object objects, regexes, sets, strings, symbols, and typed arrays. It is loosely based on the structured clone algorithm."
},
{
"code": null,
"e": 317,
"s": 309,
"text": "Syntax:"
},
{
"code": null,
"e": 334,
"s": 317,
"text": "_.clone( value )"
},
{
"code": null,
"e": 423,
"s": 334,
"text": "Parameters: This method accepts single parameter as mentioned above and described below:"
},
{
"code": null,
"e": 484,
"s": 423,
"text": "value: This parameter holds the value that need to be clone."
},
{
"code": null,
"e": 545,
"s": 484,
"text": "Return Value: This method returns the shallow copy of value."
},
{
"code": null,
"e": 578,
"s": 545,
"text": "Example 1: Cloning Simple Object"
},
{
"code": null,
"e": 589,
"s": 578,
"text": "javascript"
},
{
"code": "const _ = require('lodash'); var obj = { x: 23}; // Shallow copyvar shallowCopy = _.clone(obj); console.log('Comparing original with' + ' shallow ', obj === shallowCopy); obj.x = 10; // Changing original value console.log('After changing original value'); console.log(\"Original value \", obj); console.log(\"Shallow Copy value \", shallowCopy);",
"e": 944,
"s": 589,
"text": null
},
{
"code": null,
"e": 1030,
"s": 944,
"text": "Here, const _ = require('lodash') is used to import the lodash library into the file."
},
{
"code": null,
"e": 1038,
"s": 1030,
"text": "Output:"
},
{
"code": null,
"e": 1163,
"s": 1038,
"text": "Comparing original with shallow false\nAfter changing original value\nOriginal value { x: 10 }\nShallow Copy value { x: 23 }"
},
{
"code": null,
"e": 1197,
"s": 1163,
"text": "Example 2: Cloning complex object"
},
{
"code": null,
"e": 1208,
"s": 1197,
"text": "javascript"
},
{
"code": "const _ = require('lodash'); var obj = [{ x: 1 }, {y: 2}]; // Shallow copyvar shallowCopy = _.clone(obj); console.log('Comparing original with shallow ', obj[0] === shallowCopy[0]); // Changing original valueobj[0].x = 10; // Values after changing original valueconsole.log(\"After changing original value\"); console.log(\"Original value \", obj); console.log(\"Shallow Copy value \", shallowCopy);",
"e": 1627,
"s": 1208,
"text": null
},
{
"code": null,
"e": 1635,
"s": 1627,
"text": "Output:"
},
{
"code": null,
"e": 1787,
"s": 1635,
"text": "Comparing original with shallow true\nAfter changing original value\nOriginal value [ { x: 10 }, { y: 2 } ]\nShallow Copy value [ { x: 10 }, { y: 2 } ]"
},
{
"code": null,
"e": 1948,
"s": 1787,
"text": "So, here we have seen that after changing original value the shallow copy value also changed because _.clone() doesn’t copy deeply it just passed the reference."
},
{
"code": null,
"e": 2050,
"s": 1948,
"text": "Note: This will not work in normal JavaScript because it requires the library lodash to be installed."
},
{
"code": null,
"e": 2099,
"s": 2050,
"text": "Reference: https://lodash.com/docs/4.17.15#clone"
},
{
"code": null,
"e": 2114,
"s": 2099,
"text": "sagar0719kumar"
},
{
"code": null,
"e": 2132,
"s": 2114,
"text": "JavaScript-Lodash"
},
{
"code": null,
"e": 2143,
"s": 2132,
"text": "JavaScript"
},
{
"code": null,
"e": 2160,
"s": 2143,
"text": "Web Technologies"
},
{
"code": null,
"e": 2258,
"s": 2160,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2319,
"s": 2258,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 2391,
"s": 2319,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 2431,
"s": 2391,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 2484,
"s": 2431,
"text": "Hide or show elements in HTML using display property"
},
{
"code": null,
"e": 2525,
"s": 2484,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 2558,
"s": 2525,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 2620,
"s": 2558,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 2681,
"s": 2620,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 2731,
"s": 2681,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
What is DNS TXT Record?
|
19 Oct, 2021
Domain Name System (DNS) plays an essential role in maintaining the whole Internet infrastructure, so its failure makes the system unreachable for the user. DNS connects data with various domain names for each participating entity. This application or model was developed using Microsoft visual basic 6.0 and the access databases. DNS maintains a directory of domain names (just like our phonebook) and translates them to IPs (Internet Protocol) addresses. This makes the domain names easy for people to remember so that they can easily access websites (GOOGLE, YOUTUBE, GMAIL) on computers or machines rather than accessing the websites by searching the IP addresses.
TXT Records :A TXT record is used to provide the capacity of the domain administrator to connect the text with a zone. The text can be either human or machine-readable. One can add these records to their respective domain setting. This record permits area heads to insert any text content into DNS records. These records are utilized for different purposes.
One model is ownership validation: To demonstrate you own the area, a supplier might expect you to add a TXT record with a specific worth to your space and email security. One domain can have many TXT records. TXT records contain a large amount of text up to 255 characters per string with special characters and spaces.
Format of DNS TXT Record :
Record: geeksforgeeks.com / type: TXT / value: "attribute=value" / TTL(Time to Live)
To prove that you are the actual owner of that particular domain name. Numerous suppliers, for example, Google, Office 365, and so forth, regularly require an uncommon verification code through TXT record to be included in DNS (Domain Name System) zone.
TXT records can be checked using $ dig txt your-domain.com or $ nslookup -type=txt your-domain.com
Common uses of DNS TXT Records :
Site Verification Records –This record demonstrates responsibility for domain and can be utilized to relate administrations, for example, Microsoft 365 and G-Suite to a particular area.
DKIM records –This record stores significant data utilized in the approval of email on the way. Kindly note that business email doesn’t uphold giving a private key expected to DKIM records.
SPF record –This record is utilized to demonstrate to mail trades which hosts are approved to send letters for a domain. This diminishes spam by letting getting mail servers check a message’s sending address against the area’s SPF record.
DMARC records –Domain-based Message Authentication Reporting and Conformance records improve phishing and spoofing email attacks.
Picked
TrueGeek-2021
Computer Networks
TrueGeek
Computer Networks
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Design Issues of Distributed System
What is P2P(Peer-to-peer process) ?
Secure Socket Layer (SSL)
IP security (IPSec)
IPSec Architecture
How to Convert Char to String in Java?
Types of Network Firewall
How to redirect to another page in ReactJS ?
Basics of API Testing Using Postman
Monotonic Reasoning vs Non-Monotonic Reasoning
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n19 Oct, 2021"
},
{
"code": null,
"e": 697,
"s": 28,
"text": "Domain Name System (DNS) plays an essential role in maintaining the whole Internet infrastructure, so its failure makes the system unreachable for the user. DNS connects data with various domain names for each participating entity. This application or model was developed using Microsoft visual basic 6.0 and the access databases. DNS maintains a directory of domain names (just like our phonebook) and translates them to IPs (Internet Protocol) addresses. This makes the domain names easy for people to remember so that they can easily access websites (GOOGLE, YOUTUBE, GMAIL) on computers or machines rather than accessing the websites by searching the IP addresses."
},
{
"code": null,
"e": 1056,
"s": 697,
"text": "TXT Records :A TXT record is used to provide the capacity of the domain administrator to connect the text with a zone. The text can be either human or machine-readable. One can add these records to their respective domain setting. This record permits area heads to insert any text content into DNS records. These records are utilized for different purposes. "
},
{
"code": null,
"e": 1377,
"s": 1056,
"text": "One model is ownership validation: To demonstrate you own the area, a supplier might expect you to add a TXT record with a specific worth to your space and email security. One domain can have many TXT records. TXT records contain a large amount of text up to 255 characters per string with special characters and spaces."
},
{
"code": null,
"e": 1404,
"s": 1377,
"text": "Format of DNS TXT Record :"
},
{
"code": null,
"e": 1494,
"s": 1404,
"text": " Record: geeksforgeeks.com / type: TXT / value: \"attribute=value\" / TTL(Time to Live)"
},
{
"code": null,
"e": 1748,
"s": 1494,
"text": "To prove that you are the actual owner of that particular domain name. Numerous suppliers, for example, Google, Office 365, and so forth, regularly require an uncommon verification code through TXT record to be included in DNS (Domain Name System) zone."
},
{
"code": null,
"e": 1847,
"s": 1748,
"text": "TXT records can be checked using $ dig txt your-domain.com or $ nslookup -type=txt your-domain.com"
},
{
"code": null,
"e": 1880,
"s": 1847,
"text": "Common uses of DNS TXT Records :"
},
{
"code": null,
"e": 2066,
"s": 1880,
"text": "Site Verification Records –This record demonstrates responsibility for domain and can be utilized to relate administrations, for example, Microsoft 365 and G-Suite to a particular area."
},
{
"code": null,
"e": 2256,
"s": 2066,
"text": "DKIM records –This record stores significant data utilized in the approval of email on the way. Kindly note that business email doesn’t uphold giving a private key expected to DKIM records."
},
{
"code": null,
"e": 2495,
"s": 2256,
"text": "SPF record –This record is utilized to demonstrate to mail trades which hosts are approved to send letters for a domain. This diminishes spam by letting getting mail servers check a message’s sending address against the area’s SPF record."
},
{
"code": null,
"e": 2625,
"s": 2495,
"text": "DMARC records –Domain-based Message Authentication Reporting and Conformance records improve phishing and spoofing email attacks."
},
{
"code": null,
"e": 2632,
"s": 2625,
"text": "Picked"
},
{
"code": null,
"e": 2646,
"s": 2632,
"text": "TrueGeek-2021"
},
{
"code": null,
"e": 2664,
"s": 2646,
"text": "Computer Networks"
},
{
"code": null,
"e": 2673,
"s": 2664,
"text": "TrueGeek"
},
{
"code": null,
"e": 2691,
"s": 2673,
"text": "Computer Networks"
},
{
"code": null,
"e": 2789,
"s": 2691,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2825,
"s": 2789,
"text": "Design Issues of Distributed System"
},
{
"code": null,
"e": 2861,
"s": 2825,
"text": "What is P2P(Peer-to-peer process) ?"
},
{
"code": null,
"e": 2887,
"s": 2861,
"text": "Secure Socket Layer (SSL)"
},
{
"code": null,
"e": 2907,
"s": 2887,
"text": "IP security (IPSec)"
},
{
"code": null,
"e": 2926,
"s": 2907,
"text": "IPSec Architecture"
},
{
"code": null,
"e": 2965,
"s": 2926,
"text": "How to Convert Char to String in Java?"
},
{
"code": null,
"e": 2991,
"s": 2965,
"text": "Types of Network Firewall"
},
{
"code": null,
"e": 3036,
"s": 2991,
"text": "How to redirect to another page in ReactJS ?"
},
{
"code": null,
"e": 3072,
"s": 3036,
"text": "Basics of API Testing Using Postman"
}
] |
new vs malloc() and free() vs delete in C++
|
21 Apr, 2021
We use new and delete operators in C++ to dynamically allocate memory whereas malloc() and free() functions are also used for the same purpose in C and C++. The functionality of the new or malloc() and delete or free() seems to be the same but they differ in various ways.The behavior with respect to constructors and destructors calls differ in the following ways:malloc() vs new():
malloc(): It is a C library function that can also be used in C++, while the “new” operator is specific for C++ only.
Both malloc() and new are used to allocate the memory dynamically in heap. But “new” does call the constructor of a class whereas “malloc()” does not.
Below is the program to illustrate the functionality of new and malloc():
CPP
// C++ program to illustrate malloc()// and new operator in C++#include "bits/stdc++.h"using namespace std; // Class Aclass A { int a; public: int* ptr; // Constructor of class A A() { cout << "Constructor was Called!" << endl; }}; // Driver Codeint main(){ // Create an object of class A // using new operator A* a = new A; cout << "Object of class A was " << "created using new operator!" << endl; // Create an object of class A // using malloc operator A* b = (A*)malloc(sizeof(A)); cout << "Object of class A was " << "created using malloc()!" << endl; return 0;}
Constructor was Called!
Object of class A was created using new operator!
Object of class A was created using malloc()!
In the above program we can clearly see that while creating object using new operator Default Constructor was called and using malloc function Default Constructor was not called.free() vs delete:
free() is a C library function that can also be used in C++, while “delete” is a C++ keyword.
free() frees memory but doesn’t call Destructor of a class whereas “delete” frees the memory and also calls the Destructor of the class.
Below is the program to illustrate the functionality of new and malloc():
CPP
// C++ program to illustrate free()// and delete keyword in C++#include "bits/stdc++.h"using namespace std; // Class Aclass A { int a; public: int* ptr; // Constructor of class A A() { cout << "Constructor was Called!" << endl; } // Destructor of class A ~A() { cout << "Destructor was Called!" << endl; }}; // Driver Codeint main(){ // Create an object of class A // using new operator A* a = new A; cout << "Object of class A was " << "created using new operator!" << endl; delete (a); cout << "Object of class A was " << "deleted using delete keyword!" << endl; cout << endl; A* b = (A*)malloc(sizeof(A)); cout << "Object of class A was " << "created using malloc()!" << endl; free(b); cout << "Object of class A was " << "deleted using free()!" << endl; return 0;}
Constructor was Called!
Object of class A was created using new operator!
Destructor was Called!
Object of class A was deleted using delete keyword!
Object of class A was created using malloc()!
Object of class A was deleted using free()!
Below are the programs for more illustrations:Program 1:
CPP
// C++ program to illustrate new, delete// malloc() and free()#include "bits/stdc++.h"using namespace std; // Class Aclass A { int a; public: int* ptr; // Constructor of class A A() { cout << "Constructor was Called!" << endl; } // Destructor of class A ~A() { cout << "Destructor was Called!" << endl; }}; // Driver Codeint main(){ // Object Created of class A A a; return 0;}
Constructor was Called!
Destructor was Called!
In the above program, the destructor is still called even though the delete operator is not used. The reason for the destructor call is the statement “return 0”. This statement when executed within the main function calls the destructor of each class for which object was created.To avoid the Destructor calling we can replace the statement “return 0” with “exit(0)”. Below is the code for the same:Program 2:
CPP
// C++ program to illustrate new, delete// malloc() and free()#include "bits/stdc++.h"using namespace std; // Class Aclass A { int a; public: int* ptr; // Constructor of class A A() { cout << "Constructor was Called!" << endl; } // Destructor of class A ~A() { cout << "Destructor was Called!" << endl; }}; // Driver Codeint main(){ // Object Created of class A A a; exit(0);}
Constructor was Called!
Program 3:
CPP
// C++ program to illustrate new, delete// malloc() and free()#include "bits/stdc++.h"using namespace std; // Class Aclass A { int a; public: int* ptr; // Constructor of class A A() { cout << "Constructor was Called!" << endl; } // Destructor of class A ~A() { cout << "Destructor was Called!" << endl; }}; // Driver Codeint main(){ // Object Created of class A A *a = new A; return 0;}
Constructor was Called!
There is no Destructor call even after using the statement “return 0”. The reason lies in the difference of allocating an object of a class. When we create an object with class_name object_name within a block is created, the object has an automatic storage duration, i.e., it will automatically be destroyed on going out of scope. But when we use new class_name the object has a dynamic storage duration, which means one has to delete it explicitly using delete keyword.
shivamtripathi91
jicao
arorakashish0911
C++-new and delete
Constructors
Dynamic Memory Allocation
Articles
C++
Difference Between
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n21 Apr, 2021"
},
{
"code": null,
"e": 437,
"s": 52,
"text": "We use new and delete operators in C++ to dynamically allocate memory whereas malloc() and free() functions are also used for the same purpose in C and C++. The functionality of the new or malloc() and delete or free() seems to be the same but they differ in various ways.The behavior with respect to constructors and destructors calls differ in the following ways:malloc() vs new(): "
},
{
"code": null,
"e": 557,
"s": 437,
"text": "malloc(): It is a C library function that can also be used in C++, while the “new” operator is specific for C++ only. "
},
{
"code": null,
"e": 708,
"s": 557,
"text": "Both malloc() and new are used to allocate the memory dynamically in heap. But “new” does call the constructor of a class whereas “malloc()” does not."
},
{
"code": null,
"e": 783,
"s": 708,
"text": "Below is the program to illustrate the functionality of new and malloc(): "
},
{
"code": null,
"e": 787,
"s": 783,
"text": "CPP"
},
{
"code": "// C++ program to illustrate malloc()// and new operator in C++#include \"bits/stdc++.h\"using namespace std; // Class Aclass A { int a; public: int* ptr; // Constructor of class A A() { cout << \"Constructor was Called!\" << endl; }}; // Driver Codeint main(){ // Create an object of class A // using new operator A* a = new A; cout << \"Object of class A was \" << \"created using new operator!\" << endl; // Create an object of class A // using malloc operator A* b = (A*)malloc(sizeof(A)); cout << \"Object of class A was \" << \"created using malloc()!\" << endl; return 0;}",
"e": 1455,
"s": 787,
"text": null
},
{
"code": null,
"e": 1575,
"s": 1455,
"text": "Constructor was Called!\nObject of class A was created using new operator!\nObject of class A was created using malloc()!"
},
{
"code": null,
"e": 1774,
"s": 1577,
"text": "In the above program we can clearly see that while creating object using new operator Default Constructor was called and using malloc function Default Constructor was not called.free() vs delete: "
},
{
"code": null,
"e": 1868,
"s": 1774,
"text": "free() is a C library function that can also be used in C++, while “delete” is a C++ keyword."
},
{
"code": null,
"e": 2005,
"s": 1868,
"text": "free() frees memory but doesn’t call Destructor of a class whereas “delete” frees the memory and also calls the Destructor of the class."
},
{
"code": null,
"e": 2079,
"s": 2005,
"text": "Below is the program to illustrate the functionality of new and malloc():"
},
{
"code": null,
"e": 2083,
"s": 2079,
"text": "CPP"
},
{
"code": "// C++ program to illustrate free()// and delete keyword in C++#include \"bits/stdc++.h\"using namespace std; // Class Aclass A { int a; public: int* ptr; // Constructor of class A A() { cout << \"Constructor was Called!\" << endl; } // Destructor of class A ~A() { cout << \"Destructor was Called!\" << endl; }}; // Driver Codeint main(){ // Create an object of class A // using new operator A* a = new A; cout << \"Object of class A was \" << \"created using new operator!\" << endl; delete (a); cout << \"Object of class A was \" << \"deleted using delete keyword!\" << endl; cout << endl; A* b = (A*)malloc(sizeof(A)); cout << \"Object of class A was \" << \"created using malloc()!\" << endl; free(b); cout << \"Object of class A was \" << \"deleted using free()!\" << endl; return 0;}",
"e": 3028,
"s": 2083,
"text": null
},
{
"code": null,
"e": 3268,
"s": 3028,
"text": "Constructor was Called!\nObject of class A was created using new operator!\nDestructor was Called!\nObject of class A was deleted using delete keyword!\n\nObject of class A was created using malloc()!\nObject of class A was deleted using free()!"
},
{
"code": null,
"e": 3328,
"s": 3270,
"text": "Below are the programs for more illustrations:Program 1: "
},
{
"code": null,
"e": 3332,
"s": 3328,
"text": "CPP"
},
{
"code": "// C++ program to illustrate new, delete// malloc() and free()#include \"bits/stdc++.h\"using namespace std; // Class Aclass A { int a; public: int* ptr; // Constructor of class A A() { cout << \"Constructor was Called!\" << endl; } // Destructor of class A ~A() { cout << \"Destructor was Called!\" << endl; }}; // Driver Codeint main(){ // Object Created of class A A a; return 0;}",
"e": 3790,
"s": 3332,
"text": null
},
{
"code": null,
"e": 3837,
"s": 3790,
"text": "Constructor was Called!\nDestructor was Called!"
},
{
"code": null,
"e": 4250,
"s": 3839,
"text": "In the above program, the destructor is still called even though the delete operator is not used. The reason for the destructor call is the statement “return 0”. This statement when executed within the main function calls the destructor of each class for which object was created.To avoid the Destructor calling we can replace the statement “return 0” with “exit(0)”. Below is the code for the same:Program 2: "
},
{
"code": null,
"e": 4254,
"s": 4250,
"text": "CPP"
},
{
"code": "// C++ program to illustrate new, delete// malloc() and free()#include \"bits/stdc++.h\"using namespace std; // Class Aclass A { int a; public: int* ptr; // Constructor of class A A() { cout << \"Constructor was Called!\" << endl; } // Destructor of class A ~A() { cout << \"Destructor was Called!\" << endl; }}; // Driver Codeint main(){ // Object Created of class A A a; exit(0);}",
"e": 4711,
"s": 4254,
"text": null
},
{
"code": null,
"e": 4735,
"s": 4711,
"text": "Constructor was Called!"
},
{
"code": null,
"e": 4749,
"s": 4737,
"text": "Program 3: "
},
{
"code": null,
"e": 4753,
"s": 4749,
"text": "CPP"
},
{
"code": "// C++ program to illustrate new, delete// malloc() and free()#include \"bits/stdc++.h\"using namespace std; // Class Aclass A { int a; public: int* ptr; // Constructor of class A A() { cout << \"Constructor was Called!\" << endl; } // Destructor of class A ~A() { cout << \"Destructor was Called!\" << endl; }}; // Driver Codeint main(){ // Object Created of class A A *a = new A; return 0;}",
"e": 5220,
"s": 4753,
"text": null
},
{
"code": null,
"e": 5244,
"s": 5220,
"text": "Constructor was Called!"
},
{
"code": null,
"e": 5717,
"s": 5246,
"text": "There is no Destructor call even after using the statement “return 0”. The reason lies in the difference of allocating an object of a class. When we create an object with class_name object_name within a block is created, the object has an automatic storage duration, i.e., it will automatically be destroyed on going out of scope. But when we use new class_name the object has a dynamic storage duration, which means one has to delete it explicitly using delete keyword."
},
{
"code": null,
"e": 5734,
"s": 5717,
"text": "shivamtripathi91"
},
{
"code": null,
"e": 5740,
"s": 5734,
"text": "jicao"
},
{
"code": null,
"e": 5757,
"s": 5740,
"text": "arorakashish0911"
},
{
"code": null,
"e": 5776,
"s": 5757,
"text": "C++-new and delete"
},
{
"code": null,
"e": 5789,
"s": 5776,
"text": "Constructors"
},
{
"code": null,
"e": 5815,
"s": 5789,
"text": "Dynamic Memory Allocation"
},
{
"code": null,
"e": 5824,
"s": 5815,
"text": "Articles"
},
{
"code": null,
"e": 5828,
"s": 5824,
"text": "C++"
},
{
"code": null,
"e": 5847,
"s": 5828,
"text": "Difference Between"
},
{
"code": null,
"e": 5851,
"s": 5847,
"text": "CPP"
}
] |
Python Tweepy – Getting the location of a user
|
06 Dec, 2021
In this article we will see how we can get the location of a user. The location of the user account need not be the exact physical location of the user. As the user is free to change their location, the location of the account can even by a hypothetical place. The location attribute is optional and is Nullable.
Identifying the location in the GUI :
In the above mentioned profile, India is the location of the profile.
In order to get the location we have to do the following :
Identify the user ID or the screen name of the profile.Get the User object of the profile using the get_user() method with the user ID or the screen name.From this object, fetch the location attribute present in it.
Identify the user ID or the screen name of the profile.
Get the User object of the profile using the get_user() method with the user ID or the screen name.
From this object, fetch the location attribute present in it.
Example 1: Consider the following profile :We will use the user ID to fetch the user. The user ID of the above mentioned profile is 57741058.
Python3
# import the moduleimport tweepy # assign the values accordinglyconsumer_key = ""consumer_secret = ""access_token = ""access_token_secret = "" # authorization of consumer key and consumer secretauth = tweepy.OAuthHandler(consumer_key, consumer_secret) # set access to user's access key and access secret auth.set_access_token(access_token, access_token_secret) # calling the api api = tweepy.API(auth) # the ID of the userid = 57741058 # fetching the useruser = api.get_user(id) # fetching the locationlocation = user.location print("The location of the user is : " + location)
Output :
The location of the user is : India
Example 2: Consider the following profile :We will use the screen name to fetch the user. The screen name of the above mentioned profile is PracticeGfG. Here the location is not mentioned.
Python3
# the screen name of the userscreen_name = "PracticeGfG" # fetching the useruser = api.get_user(screen_name) # fetching the namename = user.name if location == "": print("The user has not mentioned their location.")else: print("The location of the user is : " + location)
Output :
The user has not mentioned their location.
kashishsoda
Python-Tweepy
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": "\n06 Dec, 2021"
},
{
"code": null,
"e": 341,
"s": 28,
"text": "In this article we will see how we can get the location of a user. The location of the user account need not be the exact physical location of the user. As the user is free to change their location, the location of the account can even by a hypothetical place. The location attribute is optional and is Nullable."
},
{
"code": null,
"e": 379,
"s": 341,
"text": "Identifying the location in the GUI :"
},
{
"code": null,
"e": 449,
"s": 379,
"text": "In the above mentioned profile, India is the location of the profile."
},
{
"code": null,
"e": 508,
"s": 449,
"text": "In order to get the location we have to do the following :"
},
{
"code": null,
"e": 724,
"s": 508,
"text": "Identify the user ID or the screen name of the profile.Get the User object of the profile using the get_user() method with the user ID or the screen name.From this object, fetch the location attribute present in it."
},
{
"code": null,
"e": 780,
"s": 724,
"text": "Identify the user ID or the screen name of the profile."
},
{
"code": null,
"e": 880,
"s": 780,
"text": "Get the User object of the profile using the get_user() method with the user ID or the screen name."
},
{
"code": null,
"e": 942,
"s": 880,
"text": "From this object, fetch the location attribute present in it."
},
{
"code": null,
"e": 1084,
"s": 942,
"text": "Example 1: Consider the following profile :We will use the user ID to fetch the user. The user ID of the above mentioned profile is 57741058."
},
{
"code": null,
"e": 1092,
"s": 1084,
"text": "Python3"
},
{
"code": "# import the moduleimport tweepy # assign the values accordinglyconsumer_key = \"\"consumer_secret = \"\"access_token = \"\"access_token_secret = \"\" # authorization of consumer key and consumer secretauth = tweepy.OAuthHandler(consumer_key, consumer_secret) # set access to user's access key and access secret auth.set_access_token(access_token, access_token_secret) # calling the api api = tweepy.API(auth) # the ID of the userid = 57741058 # fetching the useruser = api.get_user(id) # fetching the locationlocation = user.location print(\"The location of the user is : \" + location)",
"e": 1678,
"s": 1092,
"text": null
},
{
"code": null,
"e": 1687,
"s": 1678,
"text": "Output :"
},
{
"code": null,
"e": 1724,
"s": 1687,
"text": "The location of the user is : India\n"
},
{
"code": null,
"e": 1913,
"s": 1724,
"text": "Example 2: Consider the following profile :We will use the screen name to fetch the user. The screen name of the above mentioned profile is PracticeGfG. Here the location is not mentioned."
},
{
"code": null,
"e": 1921,
"s": 1913,
"text": "Python3"
},
{
"code": "# the screen name of the userscreen_name = \"PracticeGfG\" # fetching the useruser = api.get_user(screen_name) # fetching the namename = user.name if location == \"\": print(\"The user has not mentioned their location.\")else: print(\"The location of the user is : \" + location)",
"e": 2202,
"s": 1921,
"text": null
},
{
"code": null,
"e": 2211,
"s": 2202,
"text": "Output :"
},
{
"code": null,
"e": 2255,
"s": 2211,
"text": "The user has not mentioned their location.\n"
},
{
"code": null,
"e": 2267,
"s": 2255,
"text": "kashishsoda"
},
{
"code": null,
"e": 2281,
"s": 2267,
"text": "Python-Tweepy"
},
{
"code": null,
"e": 2288,
"s": 2281,
"text": "Python"
},
{
"code": null,
"e": 2386,
"s": 2288,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2418,
"s": 2386,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 2445,
"s": 2418,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 2466,
"s": 2445,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 2489,
"s": 2466,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 2545,
"s": 2489,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 2576,
"s": 2545,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 2618,
"s": 2576,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 2660,
"s": 2618,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 2699,
"s": 2660,
"text": "Python | datetime.timedelta() function"
}
] |
C Program for ID3 Tagging
|
01 Jul, 2020
Introduction:
Digital audio files can contain, in addition to the audio track, related text and/or graphical information. The information you’re probably familiar with takes the form of Song title, Artist name, Album name, Year, and Genre. This is the information displayed when you playback a digital audio file on your computer or portable device.
The process of including information other than sound into these digital audio files is commonly referred to as “tagging” in which you “tag” the audio file with additional information that describes the audio file. The original standard for tagging digital files was developed in 1996 by Eric Kemp and he coined the term ID3. At that time ID3 simply meant “IDentify an MP3”.
Versions of ID3:
There are majorly 2 versions of ID3, ID3v1, and ID3v2 as described below:
1. ID3v1: The MP3 standard did not include a method for storing file metadata. In 1996 Eric Kemp had the idea to add a small chunk of data to the audio file, thus solving the problem. The method, now known as ID3v1, quickly became the standard for storing metadata in MP3s.
The ID3v1 tag occupies 128 bytes, beginning with the string TAG 128 bytes from the end of the file. The tag was placed at the end of the file to maintain compatibility with older media players. Some players would play a small burst of static when they read the tag, but most ignored it, and almost all modern players will correctly skip it. This tag allows 30 bytes each for the title, artist, album, and a “comment”, four bytes for the year, and a byte to identify the genre of the song from a predefined list of 80 values (Winamp later extended this list to 148 values).
One improvement to ID3v1 was made by Michael Mutschler in 1997. Since the comment field was too small to write anything useful, he decided to trim it by two bytes and use those two bytes to store the track number. Such tags are referred to as ID3v1.1
2. ID3v2: In 1998, a new specification called ID3v2 was created by multiple contributors.[13] Although it bears the name ID3, its structure is very different from ID3v1.
ID3v2 tags are of variable size and usually occur at the start of the file, which aids streaming media as the metadata is essentially available as soon as the file starts streaming instead of requiring the entire file to be read first as is the case with ID3v1. ID3v2 tags consist of a number of frames, each of which contains a piece of metadata. For example, the TIT2 frame contains the title, and the WOAR frame contains the URL of the artist’s website. Frames can be up to 16MB in length, while the total tag size is limited to 256MB. The internationalization problem was solved by allowing the encoding of strings not only in ISO-8859-1, but also in Unicode. ID3v2 has further sub-classifications to 3 versions as ID3v2.2, ID3v2.3, and ID3v2.4 with minor changes in frames amongst them.
ID3 Taggers:
ID3 tags may be edited in a variety of ways. On some platforms, the file’s properties may be edited by viewing extended information in the file manager. Additionally, most audio players allow editing single or groups of files. Editing groups of files are often referred to as “batch tagging”. There are also specialized applications, called taggers, which concentrate specifically on editing the tags and related tasks. Some, such as puddletag offer advanced features such as advanced batch tagging or editing based on regular expressions.
Below is the code for implementing your own tagger.
Examples:
Input: Input MP3 file name which needs to tagged like input.mp3 and output MP3
file name which would be created as a tagged MP3 file like output.mp3.
Output: MP3 file with tagging information as entered by the user.
Below is the C code for implementing your own tagger:
// C program for ID3 tagging of music files#include <stdio.h>#include <stdlib.h>#include <string.h> struct tags // Structure to store tagging information.{ char title[100], artist[100], album[100], track_num[100], year[100], genre[100];}; void merge_file(char* file1, char* file2, char* file3){ FILE *f1, *f2, *f3; int ch; f1 = fopen(file1, "rb"); // Opening in write mode. f2 = fopen(file2, "rb"); f3 = fopen(file3, "wb"); if (f1 == NULL || f2 == NULL) { exit(EXIT_FAILURE); } while ((ch = fgetc(f1)) != EOF) // Appending tagging info. fputc(ch, f3); while ((ch = fgetc(f2)) != EOF) // Appending media file info. fputc(ch, f3); // Closing the files. fclose(f1); fclose(f2); fclose(f3);} void tagging(char* file1, char* file2, char* file3){ int size = 0; char clean[100]; struct tags t; unsigned char pad1[7] = { 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x76 }; unsigned char pad2[3] = { 0x00, 0x00, 0x00 }; FILE* f1; f1 = fopen(file1, "wb"); fprintf(f1, "ID3"); fwrite(pad1, sizeof(pad1), 1, f1); /*Essential tag to identify as an ID3 tagged media file.*/ gets(clean); // Clearing the input stream. // Taking input from user. printf("\nEnter the title of the mp3:"); scanf("%[^\n]%*c", t.title); printf("\nEnter the artist of the mp3:"); scanf("%[^\n]%*c", t.artist); printf("\nEnter the album of the mp3.\n"); scanf("%[^\n]%*c", t.album); printf("\nEnter the year of the mp3.\n"); scanf("%[^\n]%*c", t.year); printf("\nEnter the track number of the mp3.\n"); scanf("%[^\n]%*c", t.track_num); // Track Number // Tag to identify track number. fprintf(f1, "TRCK"); // Essential 3 NULL bits required for separation. fwrite(pad2, sizeof(pad2), 1, f1); size = strlen(t.track_num); size++; // Calculating size. // Appending the size of the track number to tag. fprintf(f1, "%c", size); // Essential 3 NULL bits required for separation. fwrite(pad2, sizeof(pad2), 1, f1); // Adding tag number entered by the user. fprintf(f1, "%s", t.track_num); // Print Year fprintf(f1, "TYER"); fwrite(pad2, sizeof(pad2), 1, f1); size = strlen(t.year); size++; // Calculating size. fprintf(f1, "%c", size); fwrite(pad2, sizeof(pad2), 1, f1); fprintf(f1, "%s", t.year); // Print Title fprintf(f1, "TIT2"); fwrite(pad2, sizeof(pad2), 1, f1); size = strlen(t.title); size++; // Calculating size. fprintf(f1, "%c", size); fwrite(pad2, sizeof(pad2), 1, f1); fprintf(f1, "%s", t.title); // Print Artist fprintf(f1, "TPE1"); fwrite(pad2, sizeof(pad2), 1, f1); size = strlen(t.artist); size++; // Calculating size. fprintf(f1, "%c", size); fwrite(pad2, sizeof(pad2), 1, f1); fprintf(f1, "%s", t.artist); // Print Album fprintf(f1, "TALB"); fwrite(pad2, sizeof(pad2), 1, f1); size = strlen(t.album); size++; // Calculating size. fprintf(f1, "%c", size); fwrite(pad2, sizeof(pad2), 1, f1); fprintf(f1, "%s", t.album); // Print Genre fprintf(f1, "TCON"); // Tag to identify genre. fwrite(pad2, sizeof(pad2), 1, f1); size = strlen(t.genre); size++; // Calculating size. fprintf(f1, "%c", size); fwrite(pad2, sizeof(pad2), 1, f1); fprintf(f1, "%s", t.genre); fclose(f1); // Closing the file.} int main(){ char file1[100] = "media_info.txt", file2[100], file3[100]; printf("\nEnter the input mp3 file name\n"); scanf("%s", file2); printf("\nEnter the output mp3 file name\n"); scanf("%s", file3); // Function to append media info to input file. tagging(file1, file2, file3); // Function to merge media info and media // input file. merge_file(file1, file2, file3); return 0;}
Note: The folder in which you are running the code should contain your input.mp3 file.
References:http://id3.org/id3v2.3.0https://en.wikipedia.org/wiki/ID3#ID3v2
nidhi_biet
C Programs
C++ Programs
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
C Program to read contents of Whole File
Producer Consumer Problem in C
Difference between break and continue statement in C
Exit codes in C/C++ with Examples
C Hello World Program
Sorting a Map by value in C++ STL
Shallow Copy and Deep Copy in C++
C++ program for hashing with chaining
C++ Program to check if a given String is Palindrome or not
delete keyword in C++
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n01 Jul, 2020"
},
{
"code": null,
"e": 42,
"s": 28,
"text": "Introduction:"
},
{
"code": null,
"e": 378,
"s": 42,
"text": "Digital audio files can contain, in addition to the audio track, related text and/or graphical information. The information you’re probably familiar with takes the form of Song title, Artist name, Album name, Year, and Genre. This is the information displayed when you playback a digital audio file on your computer or portable device."
},
{
"code": null,
"e": 753,
"s": 378,
"text": "The process of including information other than sound into these digital audio files is commonly referred to as “tagging” in which you “tag” the audio file with additional information that describes the audio file. The original standard for tagging digital files was developed in 1996 by Eric Kemp and he coined the term ID3. At that time ID3 simply meant “IDentify an MP3”."
},
{
"code": null,
"e": 770,
"s": 753,
"text": "Versions of ID3:"
},
{
"code": null,
"e": 844,
"s": 770,
"text": "There are majorly 2 versions of ID3, ID3v1, and ID3v2 as described below:"
},
{
"code": null,
"e": 1118,
"s": 844,
"text": "1. ID3v1: The MP3 standard did not include a method for storing file metadata. In 1996 Eric Kemp had the idea to add a small chunk of data to the audio file, thus solving the problem. The method, now known as ID3v1, quickly became the standard for storing metadata in MP3s."
},
{
"code": null,
"e": 1691,
"s": 1118,
"text": "The ID3v1 tag occupies 128 bytes, beginning with the string TAG 128 bytes from the end of the file. The tag was placed at the end of the file to maintain compatibility with older media players. Some players would play a small burst of static when they read the tag, but most ignored it, and almost all modern players will correctly skip it. This tag allows 30 bytes each for the title, artist, album, and a “comment”, four bytes for the year, and a byte to identify the genre of the song from a predefined list of 80 values (Winamp later extended this list to 148 values)."
},
{
"code": null,
"e": 1942,
"s": 1691,
"text": "One improvement to ID3v1 was made by Michael Mutschler in 1997. Since the comment field was too small to write anything useful, he decided to trim it by two bytes and use those two bytes to store the track number. Such tags are referred to as ID3v1.1"
},
{
"code": null,
"e": 2112,
"s": 1942,
"text": "2. ID3v2: In 1998, a new specification called ID3v2 was created by multiple contributors.[13] Although it bears the name ID3, its structure is very different from ID3v1."
},
{
"code": null,
"e": 2904,
"s": 2112,
"text": "ID3v2 tags are of variable size and usually occur at the start of the file, which aids streaming media as the metadata is essentially available as soon as the file starts streaming instead of requiring the entire file to be read first as is the case with ID3v1. ID3v2 tags consist of a number of frames, each of which contains a piece of metadata. For example, the TIT2 frame contains the title, and the WOAR frame contains the URL of the artist’s website. Frames can be up to 16MB in length, while the total tag size is limited to 256MB. The internationalization problem was solved by allowing the encoding of strings not only in ISO-8859-1, but also in Unicode. ID3v2 has further sub-classifications to 3 versions as ID3v2.2, ID3v2.3, and ID3v2.4 with minor changes in frames amongst them."
},
{
"code": null,
"e": 2917,
"s": 2904,
"text": "ID3 Taggers:"
},
{
"code": null,
"e": 3457,
"s": 2917,
"text": "ID3 tags may be edited in a variety of ways. On some platforms, the file’s properties may be edited by viewing extended information in the file manager. Additionally, most audio players allow editing single or groups of files. Editing groups of files are often referred to as “batch tagging”. There are also specialized applications, called taggers, which concentrate specifically on editing the tags and related tasks. Some, such as puddletag offer advanced features such as advanced batch tagging or editing based on regular expressions."
},
{
"code": null,
"e": 3509,
"s": 3457,
"text": "Below is the code for implementing your own tagger."
},
{
"code": null,
"e": 3519,
"s": 3509,
"text": "Examples:"
},
{
"code": null,
"e": 3738,
"s": 3519,
"text": "Input: Input MP3 file name which needs to tagged like input.mp3 and output MP3 \nfile name which would be created as a tagged MP3 file like output.mp3.\n\nOutput: MP3 file with tagging information as entered by the user.\n"
},
{
"code": null,
"e": 3792,
"s": 3738,
"text": "Below is the C code for implementing your own tagger:"
},
{
"code": "// C program for ID3 tagging of music files#include <stdio.h>#include <stdlib.h>#include <string.h> struct tags // Structure to store tagging information.{ char title[100], artist[100], album[100], track_num[100], year[100], genre[100];}; void merge_file(char* file1, char* file2, char* file3){ FILE *f1, *f2, *f3; int ch; f1 = fopen(file1, \"rb\"); // Opening in write mode. f2 = fopen(file2, \"rb\"); f3 = fopen(file3, \"wb\"); if (f1 == NULL || f2 == NULL) { exit(EXIT_FAILURE); } while ((ch = fgetc(f1)) != EOF) // Appending tagging info. fputc(ch, f3); while ((ch = fgetc(f2)) != EOF) // Appending media file info. fputc(ch, f3); // Closing the files. fclose(f1); fclose(f2); fclose(f3);} void tagging(char* file1, char* file2, char* file3){ int size = 0; char clean[100]; struct tags t; unsigned char pad1[7] = { 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x76 }; unsigned char pad2[3] = { 0x00, 0x00, 0x00 }; FILE* f1; f1 = fopen(file1, \"wb\"); fprintf(f1, \"ID3\"); fwrite(pad1, sizeof(pad1), 1, f1); /*Essential tag to identify as an ID3 tagged media file.*/ gets(clean); // Clearing the input stream. // Taking input from user. printf(\"\\nEnter the title of the mp3:\"); scanf(\"%[^\\n]%*c\", t.title); printf(\"\\nEnter the artist of the mp3:\"); scanf(\"%[^\\n]%*c\", t.artist); printf(\"\\nEnter the album of the mp3.\\n\"); scanf(\"%[^\\n]%*c\", t.album); printf(\"\\nEnter the year of the mp3.\\n\"); scanf(\"%[^\\n]%*c\", t.year); printf(\"\\nEnter the track number of the mp3.\\n\"); scanf(\"%[^\\n]%*c\", t.track_num); // Track Number // Tag to identify track number. fprintf(f1, \"TRCK\"); // Essential 3 NULL bits required for separation. fwrite(pad2, sizeof(pad2), 1, f1); size = strlen(t.track_num); size++; // Calculating size. // Appending the size of the track number to tag. fprintf(f1, \"%c\", size); // Essential 3 NULL bits required for separation. fwrite(pad2, sizeof(pad2), 1, f1); // Adding tag number entered by the user. fprintf(f1, \"%s\", t.track_num); // Print Year fprintf(f1, \"TYER\"); fwrite(pad2, sizeof(pad2), 1, f1); size = strlen(t.year); size++; // Calculating size. fprintf(f1, \"%c\", size); fwrite(pad2, sizeof(pad2), 1, f1); fprintf(f1, \"%s\", t.year); // Print Title fprintf(f1, \"TIT2\"); fwrite(pad2, sizeof(pad2), 1, f1); size = strlen(t.title); size++; // Calculating size. fprintf(f1, \"%c\", size); fwrite(pad2, sizeof(pad2), 1, f1); fprintf(f1, \"%s\", t.title); // Print Artist fprintf(f1, \"TPE1\"); fwrite(pad2, sizeof(pad2), 1, f1); size = strlen(t.artist); size++; // Calculating size. fprintf(f1, \"%c\", size); fwrite(pad2, sizeof(pad2), 1, f1); fprintf(f1, \"%s\", t.artist); // Print Album fprintf(f1, \"TALB\"); fwrite(pad2, sizeof(pad2), 1, f1); size = strlen(t.album); size++; // Calculating size. fprintf(f1, \"%c\", size); fwrite(pad2, sizeof(pad2), 1, f1); fprintf(f1, \"%s\", t.album); // Print Genre fprintf(f1, \"TCON\"); // Tag to identify genre. fwrite(pad2, sizeof(pad2), 1, f1); size = strlen(t.genre); size++; // Calculating size. fprintf(f1, \"%c\", size); fwrite(pad2, sizeof(pad2), 1, f1); fprintf(f1, \"%s\", t.genre); fclose(f1); // Closing the file.} int main(){ char file1[100] = \"media_info.txt\", file2[100], file3[100]; printf(\"\\nEnter the input mp3 file name\\n\"); scanf(\"%s\", file2); printf(\"\\nEnter the output mp3 file name\\n\"); scanf(\"%s\", file3); // Function to append media info to input file. tagging(file1, file2, file3); // Function to merge media info and media // input file. merge_file(file1, file2, file3); return 0;}",
"e": 7681,
"s": 3792,
"text": null
},
{
"code": null,
"e": 7768,
"s": 7681,
"text": "Note: The folder in which you are running the code should contain your input.mp3 file."
},
{
"code": null,
"e": 7843,
"s": 7768,
"text": "References:http://id3.org/id3v2.3.0https://en.wikipedia.org/wiki/ID3#ID3v2"
},
{
"code": null,
"e": 7854,
"s": 7843,
"text": "nidhi_biet"
},
{
"code": null,
"e": 7865,
"s": 7854,
"text": "C Programs"
},
{
"code": null,
"e": 7878,
"s": 7865,
"text": "C++ Programs"
},
{
"code": null,
"e": 7897,
"s": 7878,
"text": "Technical Scripter"
},
{
"code": null,
"e": 7995,
"s": 7897,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 8036,
"s": 7995,
"text": "C Program to read contents of Whole File"
},
{
"code": null,
"e": 8067,
"s": 8036,
"text": "Producer Consumer Problem in C"
},
{
"code": null,
"e": 8120,
"s": 8067,
"text": "Difference between break and continue statement in C"
},
{
"code": null,
"e": 8154,
"s": 8120,
"text": "Exit codes in C/C++ with Examples"
},
{
"code": null,
"e": 8176,
"s": 8154,
"text": "C Hello World Program"
},
{
"code": null,
"e": 8210,
"s": 8176,
"text": "Sorting a Map by value in C++ STL"
},
{
"code": null,
"e": 8244,
"s": 8210,
"text": "Shallow Copy and Deep Copy in C++"
},
{
"code": null,
"e": 8282,
"s": 8244,
"text": "C++ program for hashing with chaining"
},
{
"code": null,
"e": 8342,
"s": 8282,
"text": "C++ Program to check if a given String is Palindrome or not"
}
] |
HTML Canvas Basics
|
10 Dec, 2021
In this article, we will know HTML Canvas Basics, their implementation through the examples.
The HTML “canvas” element is used to draw graphics via JavaScript. The “canvas” element is only a container for graphics. One must use JavaScript to actually draw the graphics. Canvas has several methods for drawing paths, boxes, circles, text, and adding images. The canvas would be a rectangular area on an HTML page. By default, a canvas has no border and no content.
Syntax:
<canvas>
Content...
</canvas>
It is recommended to have an id attribute (to be referred to in a script), and a width and height attribute to define the size of the canvas. To add a border, use the style attribute.
Supported Properties: The properties like Colors, Styles, Shadows, Line Styles, Rectangles, Paths, Transformations, Text, Pixel Manipulation, Compositing & Image Drawing, are the global attributes that are supported by all the canvas tags. Please refer to the HTML Canvas Complete Reference article for the details.
Example 1: This example illustrates the use of canvas with a linear gradient & stroke style text in HTML.
HTML
<html> <body> <canvas id="gfg" width="300px" height="100px" style="border:1px solid #d3d3d3;"> </canvas> <script> var g = document.getElementById("gfg"); var geeks = g.getContext("2d"); var gradient = geeks.createLinearGradient(1, 4, g.width, 2); gradient.addColorStop("0", "green"); gradient.addColorStop("0.4", "yellow"); gradient.addColorStop("1.0", "aqua"); geeks.font = "40px sans-serif"; geeks.fillStyle = "red"; geeks.strokeStyle = gradient; geeks.strokeText("GeeksforGeeks", 10, 60); </script></body> </html>
Output:
HTML canvas with a linear gradient
Example 2: The following code demonstrates the empty canvas.
HTML
<!DOCTYPE html><html> <body> <canvas id="myCanvas" width="400" height="200" style="border:2px solid #000000;"> </canvas></body> </html>
Output:
HTML empty canvas
There are various shapes that can be possible to draw using Canvas, which are discussed below.
Example 1: This example shows the HTML Canvas to draw a circle.
HTML
<!DOCTYPE html><html> <body> <canvas id="GFG" width="400" height="200" style="border:2px solid #d3d3d3;"> </canvas> <script> var g = document.getElementById("GFG "); var geeks = g.getContext("2d "); geeks.beginPath(); geeks.arc(200, 100, 50, 0, 2 * Math.PI); geeks.stroke(); </script></body> </html>
Output:
Drawing Circle with HTML Canvas
Example 2: In this example, we will write a text using HTML Canvas.
HTML
<!DOCTYPE html><html> <body> <canvas id="GFG" width="600" height="200" style="border:1px solid #d3d3d3;"> </canvas> <script> var g = document.getElementById("GFG"); var geeks = g.getContext("2d"); geeks.font = "30px Arial"; geeks.fillText("GeeksForGeeks", 170, 50); </script></body> </html>
Output:
Writing text with HTML Canvas
Example 3: This example illustrates the use of linear-gradient property in HTML Canvas.
HTML
<!DOCTYPE html><html> <body> <canvas id="GFG" width="400" height="200" style="border:2px solid #d3d3d3;"> </canvas> <script> var G = document.getElementById("GFG"); var geeks = G.getContext("2d"); var grd = geeks.createLinearGradient(0, 0, 200, 0); grd.addColorStop(0, "yellow"); grd.addColorStop(1, "grey"); geeks.fillStyle = grd; geeks.fillRect(50, 50, 300, 80); </script></body> </html>
Output:
HTML Canvas with linear-gradient
Example 4: In this example, we will draw the image by using the <canvas> tag.
HTML
<!DOCTYPE html><html> <body> <p>Image to use:</p> <img id="image" src="https://media.geeksforgeeks.org/wp-content/uploads/20210916184234/gfg3-300x300.png" alt="GeeksforGeeks logo" width="250" height="200"> <p>Canvas to fill:</p> <canvas id="gfg" width="300" height="300" style="border:1px solid #d3d3d3; "> </canvas> <p> <button onclick="gfg()">Click to Try</button> </p> <script> function gfg() { var g = document.getElementById("gfg"); var geeks = g.getContext("2d"); var img = document.getElementById("image"); geeks.drawImage(img, 0, 0); } </script></body> </html>
Output:
Drawing image with <canvas> tag
Example 5: This example demonstrates the use of the Shadow blur property in HTML Canvas.
HTML
<!DOCTYPE html><html><body> <canvas id="GFG" width="500" height="250" ;> </canvas> <script> var g = document.getElementById("GFG"); var geeks = g.getContext("2d"); geeks.shadowBlur = 20; geeks.shadowColor = "yellow"; geeks.fillStyle = "red"; geeks.fillRect(30, 20, 100, 80); </script></body></html>
Output:
HTML Canvas with Shadow blur property
Example 6: In this example, we will use rotate() method in the HTML Canvas.
HTML
<!DOCTYPE html><html><body> <canvas id="GFG" width="300" height="150;"> </canvas> <script> var g = document.getElementById("GFG"); var geeks = g.getContext("2d"); geeks.rotate(20 * Math.PI / 180); geeks.fillRect(100, 20, 100, 50); </script></body></html>
Output:
HTML Canvas with rotate() method
Example 7: In this example, we have used the translate() method to remaps the (0,0) position on the canvas.
HTML
<!DOCTYPE html><html><body> <canvas id="GFG" width="300" height="150;"> </canvas> <script> var g = document.getElementById("GFG"); var geeks = g.getContext("2d"); geeks.fillRect(10, 10, 100, 50); geeks.translate(80, 90); geeks.fillRect(10, 10, 100, 50); </script></body></html>
Output:
HTML Canvas with translate() method
Example 8: This example illustrates the use of the transform() method in HTML Canvas.
HTML
<!DOCTYPE html><html><body> <canvas id="GFG" width="300" height="150;"> </canvas> <script> var g = document.getElementById("GFG"); var geeks = g.getContext("2d"); geeks.fillStyle = "yellow"; geeks.fillRect(0, 0, 250, 100) geeks.transform(1, 0.5, -0.5, 1, 30, 10); geeks.fillStyle = "grey"; geeks.fillRect(0, 0, 250, 100); geeks.transform(1, 0.5, -0.5, 1, 30, 10); geeks.fillStyle = "black"; geeks.fillRect(0, 0, 250, 100); </script></body></html>
Output:
HTML Canvas with transform() method
Creating Animation in HTML Canvas: JavaScript helps to simulate good animation over an HTML5 canvas. Two important JavaScript methods which can be used to animate an image on a canvas:
setInterval(callback, time): This method repeatedly executes the supplied code after a given time.setTimeout(callback, time): This method executes the supplied code only once after a given time.
setInterval(callback, time): This method repeatedly executes the supplied code after a given time.
setTimeout(callback, time): This method executes the supplied code only once after a given time.
Supported Browser:
Google Chrome 93.0
Microsoft Edge 93.0
IE 11.0
Firefox 92.0
Opera 78.0
Safari 14.1
ysachin2314
bhaskargeeksforgeeks
HTML and XML
HTML-Basics
Web technologies-HTML and XML
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n10 Dec, 2021"
},
{
"code": null,
"e": 146,
"s": 52,
"text": "In this article, we will know HTML Canvas Basics, their implementation through the examples. "
},
{
"code": null,
"e": 517,
"s": 146,
"text": "The HTML “canvas” element is used to draw graphics via JavaScript. The “canvas” element is only a container for graphics. One must use JavaScript to actually draw the graphics. Canvas has several methods for drawing paths, boxes, circles, text, and adding images. The canvas would be a rectangular area on an HTML page. By default, a canvas has no border and no content."
},
{
"code": null,
"e": 525,
"s": 517,
"text": "Syntax:"
},
{
"code": null,
"e": 559,
"s": 525,
"text": "<canvas>\n Content...\n</canvas>"
},
{
"code": null,
"e": 743,
"s": 559,
"text": "It is recommended to have an id attribute (to be referred to in a script), and a width and height attribute to define the size of the canvas. To add a border, use the style attribute."
},
{
"code": null,
"e": 1059,
"s": 743,
"text": "Supported Properties: The properties like Colors, Styles, Shadows, Line Styles, Rectangles, Paths, Transformations, Text, Pixel Manipulation, Compositing & Image Drawing, are the global attributes that are supported by all the canvas tags. Please refer to the HTML Canvas Complete Reference article for the details."
},
{
"code": null,
"e": 1165,
"s": 1059,
"text": "Example 1: This example illustrates the use of canvas with a linear gradient & stroke style text in HTML."
},
{
"code": null,
"e": 1170,
"s": 1165,
"text": "HTML"
},
{
"code": "<html> <body> <canvas id=\"gfg\" width=\"300px\" height=\"100px\" style=\"border:1px solid #d3d3d3;\"> </canvas> <script> var g = document.getElementById(\"gfg\"); var geeks = g.getContext(\"2d\"); var gradient = geeks.createLinearGradient(1, 4, g.width, 2); gradient.addColorStop(\"0\", \"green\"); gradient.addColorStop(\"0.4\", \"yellow\"); gradient.addColorStop(\"1.0\", \"aqua\"); geeks.font = \"40px sans-serif\"; geeks.fillStyle = \"red\"; geeks.strokeStyle = gradient; geeks.strokeText(\"GeeksforGeeks\", 10, 60); </script></body> </html>",
"e": 1802,
"s": 1170,
"text": null
},
{
"code": null,
"e": 1810,
"s": 1802,
"text": "Output:"
},
{
"code": null,
"e": 1845,
"s": 1810,
"text": "HTML canvas with a linear gradient"
},
{
"code": null,
"e": 1906,
"s": 1845,
"text": "Example 2: The following code demonstrates the empty canvas."
},
{
"code": null,
"e": 1911,
"s": 1906,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <body> <canvas id=\"myCanvas\" width=\"400\" height=\"200\" style=\"border:2px solid #000000;\"> </canvas></body> </html>",
"e": 2086,
"s": 1911,
"text": null
},
{
"code": null,
"e": 2094,
"s": 2086,
"text": "Output:"
},
{
"code": null,
"e": 2112,
"s": 2094,
"text": "HTML empty canvas"
},
{
"code": null,
"e": 2207,
"s": 2112,
"text": "There are various shapes that can be possible to draw using Canvas, which are discussed below."
},
{
"code": null,
"e": 2271,
"s": 2207,
"text": "Example 1: This example shows the HTML Canvas to draw a circle."
},
{
"code": null,
"e": 2276,
"s": 2271,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <body> <canvas id=\"GFG\" width=\"400\" height=\"200\" style=\"border:2px solid #d3d3d3;\"> </canvas> <script> var g = document.getElementById(\"GFG \"); var geeks = g.getContext(\"2d \"); geeks.beginPath(); geeks.arc(200, 100, 50, 0, 2 * Math.PI); geeks.stroke(); </script></body> </html>",
"e": 2656,
"s": 2276,
"text": null
},
{
"code": null,
"e": 2664,
"s": 2656,
"text": "Output:"
},
{
"code": null,
"e": 2696,
"s": 2664,
"text": "Drawing Circle with HTML Canvas"
},
{
"code": null,
"e": 2764,
"s": 2696,
"text": "Example 2: In this example, we will write a text using HTML Canvas."
},
{
"code": null,
"e": 2769,
"s": 2764,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <body> <canvas id=\"GFG\" width=\"600\" height=\"200\" style=\"border:1px solid #d3d3d3;\"> </canvas> <script> var g = document.getElementById(\"GFG\"); var geeks = g.getContext(\"2d\"); geeks.font = \"30px Arial\"; geeks.fillText(\"GeeksForGeeks\", 170, 50); </script></body> </html>",
"e": 3133,
"s": 2769,
"text": null
},
{
"code": null,
"e": 3141,
"s": 3133,
"text": "Output:"
},
{
"code": null,
"e": 3171,
"s": 3141,
"text": "Writing text with HTML Canvas"
},
{
"code": null,
"e": 3259,
"s": 3171,
"text": "Example 3: This example illustrates the use of linear-gradient property in HTML Canvas."
},
{
"code": null,
"e": 3264,
"s": 3259,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <body> <canvas id=\"GFG\" width=\"400\" height=\"200\" style=\"border:2px solid #d3d3d3;\"> </canvas> <script> var G = document.getElementById(\"GFG\"); var geeks = G.getContext(\"2d\"); var grd = geeks.createLinearGradient(0, 0, 200, 0); grd.addColorStop(0, \"yellow\"); grd.addColorStop(1, \"grey\"); geeks.fillStyle = grd; geeks.fillRect(50, 50, 300, 80); </script></body> </html>",
"e": 3748,
"s": 3264,
"text": null
},
{
"code": null,
"e": 3756,
"s": 3748,
"text": "Output:"
},
{
"code": null,
"e": 3789,
"s": 3756,
"text": "HTML Canvas with linear-gradient"
},
{
"code": null,
"e": 3867,
"s": 3789,
"text": "Example 4: In this example, we will draw the image by using the <canvas> tag."
},
{
"code": null,
"e": 3872,
"s": 3867,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <body> <p>Image to use:</p> <img id=\"image\" src=\"https://media.geeksforgeeks.org/wp-content/uploads/20210916184234/gfg3-300x300.png\" alt=\"GeeksforGeeks logo\" width=\"250\" height=\"200\"> <p>Canvas to fill:</p> <canvas id=\"gfg\" width=\"300\" height=\"300\" style=\"border:1px solid #d3d3d3; \"> </canvas> <p> <button onclick=\"gfg()\">Click to Try</button> </p> <script> function gfg() { var g = document.getElementById(\"gfg\"); var geeks = g.getContext(\"2d\"); var img = document.getElementById(\"image\"); geeks.drawImage(img, 0, 0); } </script></body> </html>",
"e": 4584,
"s": 3872,
"text": null
},
{
"code": null,
"e": 4592,
"s": 4584,
"text": "Output:"
},
{
"code": null,
"e": 4624,
"s": 4592,
"text": "Drawing image with <canvas> tag"
},
{
"code": null,
"e": 4713,
"s": 4624,
"text": "Example 5: This example demonstrates the use of the Shadow blur property in HTML Canvas."
},
{
"code": null,
"e": 4718,
"s": 4713,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html><body> <canvas id=\"GFG\" width=\"500\" height=\"250\" ;> </canvas> <script> var g = document.getElementById(\"GFG\"); var geeks = g.getContext(\"2d\"); geeks.shadowBlur = 20; geeks.shadowColor = \"yellow\"; geeks.fillStyle = \"red\"; geeks.fillRect(30, 20, 100, 80); </script></body></html>",
"e": 5095,
"s": 4718,
"text": null
},
{
"code": null,
"e": 5103,
"s": 5095,
"text": "Output:"
},
{
"code": null,
"e": 5141,
"s": 5103,
"text": "HTML Canvas with Shadow blur property"
},
{
"code": null,
"e": 5217,
"s": 5141,
"text": "Example 6: In this example, we will use rotate() method in the HTML Canvas."
},
{
"code": null,
"e": 5222,
"s": 5217,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html><body> <canvas id=\"GFG\" width=\"300\" height=\"150;\"> </canvas> <script> var g = document.getElementById(\"GFG\"); var geeks = g.getContext(\"2d\"); geeks.rotate(20 * Math.PI / 180); geeks.fillRect(100, 20, 100, 50); </script></body></html>",
"e": 5539,
"s": 5222,
"text": null
},
{
"code": null,
"e": 5547,
"s": 5539,
"text": "Output:"
},
{
"code": null,
"e": 5580,
"s": 5547,
"text": "HTML Canvas with rotate() method"
},
{
"code": null,
"e": 5688,
"s": 5580,
"text": "Example 7: In this example, we have used the translate() method to remaps the (0,0) position on the canvas."
},
{
"code": null,
"e": 5693,
"s": 5688,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html><body> <canvas id=\"GFG\" width=\"300\" height=\"150;\"> </canvas> <script> var g = document.getElementById(\"GFG\"); var geeks = g.getContext(\"2d\"); geeks.fillRect(10, 10, 100, 50); geeks.translate(80, 90); geeks.fillRect(10, 10, 100, 50); </script></body></html>",
"e": 6042,
"s": 5693,
"text": null
},
{
"code": null,
"e": 6050,
"s": 6042,
"text": "Output:"
},
{
"code": null,
"e": 6086,
"s": 6050,
"text": "HTML Canvas with translate() method"
},
{
"code": null,
"e": 6172,
"s": 6086,
"text": "Example 8: This example illustrates the use of the transform() method in HTML Canvas."
},
{
"code": null,
"e": 6177,
"s": 6172,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html><body> <canvas id=\"GFG\" width=\"300\" height=\"150;\"> </canvas> <script> var g = document.getElementById(\"GFG\"); var geeks = g.getContext(\"2d\"); geeks.fillStyle = \"yellow\"; geeks.fillRect(0, 0, 250, 100) geeks.transform(1, 0.5, -0.5, 1, 30, 10); geeks.fillStyle = \"grey\"; geeks.fillRect(0, 0, 250, 100); geeks.transform(1, 0.5, -0.5, 1, 30, 10); geeks.fillStyle = \"black\"; geeks.fillRect(0, 0, 250, 100); </script></body></html>",
"e": 6728,
"s": 6177,
"text": null
},
{
"code": null,
"e": 6736,
"s": 6728,
"text": "Output:"
},
{
"code": null,
"e": 6772,
"s": 6736,
"text": "HTML Canvas with transform() method"
},
{
"code": null,
"e": 6957,
"s": 6772,
"text": "Creating Animation in HTML Canvas: JavaScript helps to simulate good animation over an HTML5 canvas. Two important JavaScript methods which can be used to animate an image on a canvas:"
},
{
"code": null,
"e": 7152,
"s": 6957,
"text": "setInterval(callback, time): This method repeatedly executes the supplied code after a given time.setTimeout(callback, time): This method executes the supplied code only once after a given time."
},
{
"code": null,
"e": 7251,
"s": 7152,
"text": "setInterval(callback, time): This method repeatedly executes the supplied code after a given time."
},
{
"code": null,
"e": 7348,
"s": 7251,
"text": "setTimeout(callback, time): This method executes the supplied code only once after a given time."
},
{
"code": null,
"e": 7367,
"s": 7348,
"text": "Supported Browser:"
},
{
"code": null,
"e": 7386,
"s": 7367,
"text": "Google Chrome 93.0"
},
{
"code": null,
"e": 7406,
"s": 7386,
"text": "Microsoft Edge 93.0"
},
{
"code": null,
"e": 7414,
"s": 7406,
"text": "IE 11.0"
},
{
"code": null,
"e": 7427,
"s": 7414,
"text": "Firefox 92.0"
},
{
"code": null,
"e": 7438,
"s": 7427,
"text": "Opera 78.0"
},
{
"code": null,
"e": 7450,
"s": 7438,
"text": "Safari 14.1"
},
{
"code": null,
"e": 7462,
"s": 7450,
"text": "ysachin2314"
},
{
"code": null,
"e": 7483,
"s": 7462,
"text": "bhaskargeeksforgeeks"
},
{
"code": null,
"e": 7496,
"s": 7483,
"text": "HTML and XML"
},
{
"code": null,
"e": 7508,
"s": 7496,
"text": "HTML-Basics"
},
{
"code": null,
"e": 7538,
"s": 7508,
"text": "Web technologies-HTML and XML"
},
{
"code": null,
"e": 7543,
"s": 7538,
"text": "HTML"
},
{
"code": null,
"e": 7560,
"s": 7543,
"text": "Web Technologies"
},
{
"code": null,
"e": 7565,
"s": 7560,
"text": "HTML"
}
] |
Python | Sympy Line.intersection() method
|
10 Feb, 2020
Syntax: Line.intersection(o)
Parameters:
o: Point or LinearEntity
Returns:
intersection: list of geometrical entities
Example #1:
# import sympy and Point, Linefrom sympy import Point, Line p1, p2, p3 = Point(0, 0), Point(1, 1), Point(7, 7)l1 = Line(p1, p2) # using intersection() methodshowIntersection = l1.intersection(p3) print(showIntersection)
Output:
[Point2D(7, 7)]
Example #2:
# import sympy and Point, Line, Segmentfrom sympy import Point, Line, Segment p1, p2, p3, p4 = Point(0, 0), Point(1, 1), Point(0, 5), Point(2, 6)l1 = Line(p1, p2)s1 = Segment(p3, p4) # using intersection() methodshowIntersection = l1.intersection(s1) print(showIntersection)
Output:
[]
Python SymPy-Geometry
SymPy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
Python | os.path.join() method
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python | Get unique values from a list
Python | datetime.timedelta() function
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n10 Feb, 2020"
},
{
"code": null,
"e": 151,
"s": 28,
"text": "Syntax: Line.intersection(o)\n\nParameters:\n o: Point or LinearEntity\n\nReturns:\n intersection: list of geometrical entities\n"
},
{
"code": null,
"e": 163,
"s": 151,
"text": "Example #1:"
},
{
"code": "# import sympy and Point, Linefrom sympy import Point, Line p1, p2, p3 = Point(0, 0), Point(1, 1), Point(7, 7)l1 = Line(p1, p2) # using intersection() methodshowIntersection = l1.intersection(p3) print(showIntersection)",
"e": 386,
"s": 163,
"text": null
},
{
"code": null,
"e": 394,
"s": 386,
"text": "Output:"
},
{
"code": null,
"e": 410,
"s": 394,
"text": "[Point2D(7, 7)]"
},
{
"code": null,
"e": 422,
"s": 410,
"text": "Example #2:"
},
{
"code": "# import sympy and Point, Line, Segmentfrom sympy import Point, Line, Segment p1, p2, p3, p4 = Point(0, 0), Point(1, 1), Point(0, 5), Point(2, 6)l1 = Line(p1, p2)s1 = Segment(p3, p4) # using intersection() methodshowIntersection = l1.intersection(s1) print(showIntersection)",
"e": 702,
"s": 422,
"text": null
},
{
"code": null,
"e": 710,
"s": 702,
"text": "Output:"
},
{
"code": null,
"e": 713,
"s": 710,
"text": "[]"
},
{
"code": null,
"e": 735,
"s": 713,
"text": "Python SymPy-Geometry"
},
{
"code": null,
"e": 741,
"s": 735,
"text": "SymPy"
},
{
"code": null,
"e": 748,
"s": 741,
"text": "Python"
},
{
"code": null,
"e": 846,
"s": 748,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 878,
"s": 846,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 905,
"s": 878,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 926,
"s": 905,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 949,
"s": 926,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 1005,
"s": 949,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 1036,
"s": 1005,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 1078,
"s": 1036,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 1120,
"s": 1078,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 1159,
"s": 1120,
"text": "Python | Get unique values from a list"
}
] |
How to divide the row values by row sum in R matrix?
|
To divide matrix row values by row sum in R, we can follow the below steps −
First of all, create a matrix.
Then, use apply function to divide the matrix row values by row sum.
Let’s create a matrix as shown below −
Live Demo
M<-matrix(sample(1:100,75),ncol=3)
M
On executing, the above script generates the below output(this output will vary on your system due to randomization) −
[,1] [,2] [,3]
[1,] 29 69 82
[2,] 60 22 87
[3,] 86 49 16
[4,] 66 14 96
[5,] 19 92 13
[6,] 90 80 35
[7,] 32 3 30
[8,] 44 2 59
[9,] 24 54 97
[10,] 75 37 70
[11,] 31 58 38
[12,] 76 72 55
[13,] 94 81 95
[14,] 18 28 1
[15,] 78 33 61
[16,] 63 25 93
[17,] 4 47 46
[18,] 21 42 68
[19,] 71 57 62
[20,] 43 12 64
[21,] 40 73 99
[22,] 84 5 15
[23,] 39 56 27
[24,] 45 100 98
[25,] 88 11 7
Using apply function to divide the row values of M by row sum −
Live Demo
M<-matrix(sample(1:100,75),ncol=3)
M_new<-t(apply(M,1, function(x) x/sum(x)))
M_new
[,1] [,2] [,3]
[1,] 0.16111111 0.38333333 0.45555556
[2,] 0.35502959 0.13017751 0.51479290
[3,] 0.56953642 0.32450331 0.10596026
[4,] 0.37500000 0.07954545 0.54545455
[5,] 0.15322581 0.74193548 0.10483871
[6,] 0.43902439 0.39024390 0.17073171
[7,] 0.49230769 0.04615385 0.46153846
[8,] 0.41904762 0.01904762 0.56190476
[9,] 0.13714286 0.30857143 0.55428571
[10,] 0.41208791 0.20329670 0.38461538
[11,] 0.24409449 0.45669291 0.29921260
[12,] 0.37438424 0.35467980 0.27093596
[13,] 0.34814815 0.30000000 0.35185185
[14,] 0.38297872 0.59574468 0.02127660
[15,] 0.45348837 0.19186047 0.35465116
[16,] 0.34806630 0.13812155 0.51381215
[17,] 0.04123711 0.48453608 0.47422680
[18,] 0.16030534 0.32061069 0.51908397
[19,] 0.37368421 0.30000000 0.32631579
[20,] 0.36134454 0.10084034 0.53781513
[21,] 0.18867925 0.34433962 0.46698113
[22,] 0.80769231 0.04807692 0.14423077
[23,] 0.31967213 0.45901639 0.22131148
[24,] 0.18518519 0.41152263 0.40329218
[25,] 0.83018868 0.10377358 0.06603774
|
[
{
"code": null,
"e": 1139,
"s": 1062,
"text": "To divide matrix row values by row sum in R, we can follow the below steps −"
},
{
"code": null,
"e": 1170,
"s": 1139,
"text": "First of all, create a matrix."
},
{
"code": null,
"e": 1239,
"s": 1170,
"text": "Then, use apply function to divide the matrix row values by row sum."
},
{
"code": null,
"e": 1278,
"s": 1239,
"text": "Let’s create a matrix as shown below −"
},
{
"code": null,
"e": 1289,
"s": 1278,
"text": " Live Demo"
},
{
"code": null,
"e": 1326,
"s": 1289,
"text": "M<-matrix(sample(1:100,75),ncol=3)\nM"
},
{
"code": null,
"e": 1445,
"s": 1326,
"text": "On executing, the above script generates the below output(this output will vary on your system due to randomization) −"
},
{
"code": null,
"e": 1821,
"s": 1445,
"text": "[,1] [,2] [,3]\n[1,] 29 69 82\n[2,] 60 22 87\n[3,] 86 49 16\n[4,] 66 14 96\n[5,] 19 92 13\n[6,] 90 80 35\n[7,] 32 3 30\n[8,] 44 2 59\n[9,] 24 54 97\n[10,] 75 37 70\n[11,] 31 58 38\n[12,] 76 72 55\n[13,] 94 81 95\n[14,] 18 28 1\n[15,] 78 33 61\n[16,] 63 25 93\n[17,] 4 47 46\n[18,] 21 42 68\n[19,] 71 57 62\n[20,] 43 12 64\n[21,] 40 73 99\n[22,] 84 5 15\n[23,] 39 56 27\n[24,] 45 100 98\n[25,] 88 11 7"
},
{
"code": null,
"e": 1885,
"s": 1821,
"text": "Using apply function to divide the row values of M by row sum −"
},
{
"code": null,
"e": 1896,
"s": 1885,
"text": " Live Demo"
},
{
"code": null,
"e": 1980,
"s": 1896,
"text": "M<-matrix(sample(1:100,75),ncol=3)\nM_new<-t(apply(M,1, function(x) x/sum(x)))\nM_new"
},
{
"code": null,
"e": 2961,
"s": 1980,
"text": "[,1] [,2] [,3]\n[1,] 0.16111111 0.38333333 0.45555556\n[2,] 0.35502959 0.13017751 0.51479290\n[3,] 0.56953642 0.32450331 0.10596026\n[4,] 0.37500000 0.07954545 0.54545455\n[5,] 0.15322581 0.74193548 0.10483871\n[6,] 0.43902439 0.39024390 0.17073171\n[7,] 0.49230769 0.04615385 0.46153846\n[8,] 0.41904762 0.01904762 0.56190476\n[9,] 0.13714286 0.30857143 0.55428571\n[10,] 0.41208791 0.20329670 0.38461538\n[11,] 0.24409449 0.45669291 0.29921260\n[12,] 0.37438424 0.35467980 0.27093596\n[13,] 0.34814815 0.30000000 0.35185185\n[14,] 0.38297872 0.59574468 0.02127660\n[15,] 0.45348837 0.19186047 0.35465116\n[16,] 0.34806630 0.13812155 0.51381215\n[17,] 0.04123711 0.48453608 0.47422680\n[18,] 0.16030534 0.32061069 0.51908397\n[19,] 0.37368421 0.30000000 0.32631579\n[20,] 0.36134454 0.10084034 0.53781513\n[21,] 0.18867925 0.34433962 0.46698113\n[22,] 0.80769231 0.04807692 0.14423077\n[23,] 0.31967213 0.45901639 0.22131148\n[24,] 0.18518519 0.41152263 0.40329218\n[25,] 0.83018868 0.10377358 0.06603774"
}
] |
CSS ::placeholder Selector - GeeksforGeeks
|
21 Oct, 2021
The placeholder selector in the CSS pseudo-element is used to design the placeholder text by changing the text color and it allows to modify the style of the text.
The ::first-line pseudo-element is the only subset of CSS properties that is applicable & can be applied in a rule using ::placeholder in its selector. By default, the placeholder text appearance is a translucent or light gray color for most of the browsers.
Syntax:
::placeholder {
// CSS property
}
We will understand the concept of ::placeholder selector & its implementation through the examples.
Example 1: This example illustrates the ::placeholder selector for changing the text color along with the background color for the placeholder text.
HTML
<!DOCTYPE html><html><head> <title>::placeholder selector</title> <style> input::placeholder { background-color: #fff; margin: 10px; padding: 5px; color: Green; } h1 { color: green; } body { text-align: center; } </style></head> <body> <h1>Geeksforgeeks</h1> <h2>::placeholder selector</h2> <p>Name: <input placeholder="GeeksforGeeks"> </p> </body></html>
Output:
Example 2: This example illustrates the ::placeholder selector for setting up the placeholder text with its attribute that identifies the hint which describes the expected value of an input field.
HTML
<!DOCTYPE html><html><head> <title>::placeholder selector</title> <style> h1 { color: green; } body { text-align: center } input::placeholder { background-color: white; color: green; text-align: center; } </style></head> <body> <h1>GeeksForGeeks</h1> <h2>::placeholder Selector </h2> <input type="text" placeholder="Geeks"> <input type="text" placeholder="Computer Science"> </body></html>
Output:
Supported Browser: The browser supported by ::placeholder selector are listed below:
Google Chrome 57.0, 4.0 -webkit-
Microsoft Edge 12.0 -webkit-, 10.0 -ms-
Firefox 51.0, 4.0 -moz-
Safari 10.1, 5.0 -webkit-
Opera 44.0, 15.0 -webkit-
bhaskargeeksforgeeks
CSS-Selectors
Picked
Technical Scripter 2018
CSS
Technical Scripter
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
How to create footer to stay at the bottom of a Web page?
How to update Node.js and NPM to next version ?
CSS to put icon inside an input element in a form
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": 23644,
"s": 23616,
"text": "\n21 Oct, 2021"
},
{
"code": null,
"e": 23808,
"s": 23644,
"text": "The placeholder selector in the CSS pseudo-element is used to design the placeholder text by changing the text color and it allows to modify the style of the text."
},
{
"code": null,
"e": 24067,
"s": 23808,
"text": "The ::first-line pseudo-element is the only subset of CSS properties that is applicable & can be applied in a rule using ::placeholder in its selector. By default, the placeholder text appearance is a translucent or light gray color for most of the browsers."
},
{
"code": null,
"e": 24075,
"s": 24067,
"text": "Syntax:"
},
{
"code": null,
"e": 24113,
"s": 24075,
"text": "::placeholder {\n // CSS property\n}"
},
{
"code": null,
"e": 24213,
"s": 24113,
"text": "We will understand the concept of ::placeholder selector & its implementation through the examples."
},
{
"code": null,
"e": 24362,
"s": 24213,
"text": "Example 1: This example illustrates the ::placeholder selector for changing the text color along with the background color for the placeholder text."
},
{
"code": null,
"e": 24367,
"s": 24362,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html><head> <title>::placeholder selector</title> <style> input::placeholder { background-color: #fff; margin: 10px; padding: 5px; color: Green; } h1 { color: green; } body { text-align: center; } </style></head> <body> <h1>Geeksforgeeks</h1> <h2>::placeholder selector</h2> <p>Name: <input placeholder=\"GeeksforGeeks\"> </p> </body></html>",
"e": 24825,
"s": 24367,
"text": null
},
{
"code": null,
"e": 24833,
"s": 24825,
"text": "Output:"
},
{
"code": null,
"e": 25031,
"s": 24833,
"text": "Example 2: This example illustrates the ::placeholder selector for setting up the placeholder text with its attribute that identifies the hint which describes the expected value of an input field."
},
{
"code": null,
"e": 25036,
"s": 25031,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html><head> <title>::placeholder selector</title> <style> h1 { color: green; } body { text-align: center } input::placeholder { background-color: white; color: green; text-align: center; } </style></head> <body> <h1>GeeksForGeeks</h1> <h2>::placeholder Selector </h2> <input type=\"text\" placeholder=\"Geeks\"> <input type=\"text\" placeholder=\"Computer Science\"> </body></html>",
"e": 25535,
"s": 25036,
"text": null
},
{
"code": null,
"e": 25543,
"s": 25535,
"text": "Output:"
},
{
"code": null,
"e": 25628,
"s": 25543,
"text": "Supported Browser: The browser supported by ::placeholder selector are listed below:"
},
{
"code": null,
"e": 25661,
"s": 25628,
"text": "Google Chrome 57.0, 4.0 -webkit-"
},
{
"code": null,
"e": 25701,
"s": 25661,
"text": "Microsoft Edge 12.0 -webkit-, 10.0 -ms-"
},
{
"code": null,
"e": 25725,
"s": 25701,
"text": "Firefox 51.0, 4.0 -moz-"
},
{
"code": null,
"e": 25751,
"s": 25725,
"text": "Safari 10.1, 5.0 -webkit-"
},
{
"code": null,
"e": 25777,
"s": 25751,
"text": "Opera 44.0, 15.0 -webkit-"
},
{
"code": null,
"e": 25798,
"s": 25777,
"text": "bhaskargeeksforgeeks"
},
{
"code": null,
"e": 25812,
"s": 25798,
"text": "CSS-Selectors"
},
{
"code": null,
"e": 25819,
"s": 25812,
"text": "Picked"
},
{
"code": null,
"e": 25843,
"s": 25819,
"text": "Technical Scripter 2018"
},
{
"code": null,
"e": 25847,
"s": 25843,
"text": "CSS"
},
{
"code": null,
"e": 25866,
"s": 25847,
"text": "Technical Scripter"
},
{
"code": null,
"e": 25883,
"s": 25866,
"text": "Web Technologies"
},
{
"code": null,
"e": 25981,
"s": 25883,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26043,
"s": 25981,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 26093,
"s": 26043,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
},
{
"code": null,
"e": 26151,
"s": 26093,
"text": "How to create footer to stay at the bottom of a Web page?"
},
{
"code": null,
"e": 26199,
"s": 26151,
"text": "How to update Node.js and NPM to next version ?"
},
{
"code": null,
"e": 26249,
"s": 26199,
"text": "CSS to put icon inside an input element in a form"
},
{
"code": null,
"e": 26291,
"s": 26249,
"text": "Roadmap to Become a Web Developer in 2022"
},
{
"code": null,
"e": 26324,
"s": 26291,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 26367,
"s": 26324,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 26429,
"s": 26367,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
}
] |
GATE | GATE-CS-2017 (Set 2) | Question 55 - GeeksforGeeks
|
28 Jun, 2021
Consider a binary code that consists only four valid codewords as given below.00000, 01011, 10101, 11110
Let minimum Hamming distance of code be p and maximum number of erroneous bits that can be corrected by the code be q. The value of p and q are:
(A) p = 3 and q = 1(B) p = 3 and q = 2(C) p = 4 and q = 1(D) p = 4 and q = 2Answer: (A)Explanation: We need to find minimum hamming distance(difference in their corresponding bit position)
00000, 01011, 10101, 11110
For two binary strings, hamming distance is number
of ones in XOR of the two strings.
Hamming distance of first and second is 3, so is
for first and third. Hamming distance of first and
fourth is 4.
Hamming distance of second and third is 4, and
second and fourth is 3.
Hamming distance of third and fourth is 3.
Thus a code with minimum Hamming distance d
between its codewords can detect at most d-1
errors and can correct ⌊(d-1)/2⌋ errors.
Here d = 3. So number of errors that can be
corrected is 1.
Quiz of this Question
GATE-CS-2017 (Set 2)
GATE-GATE-CS-2017 (Set 2)
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GATE | GATE-IT-2004 | Question 66
GATE | GATE-CS-2016 (Set 2) | Question 48
GATE | GATE-IT-2004 | Question 71
GATE | GATE-CS-2014-(Set-3) | Question 65
GATE | GATE CS 2011 | Question 7
GATE | GATE CS 2010 | Question 24
GATE | GATE-CS-2016 (Set 2) | Question 61
GATE | GATE-CS-2015 (Set 3) | Question 65
GATE | GATE-CS-2016 (Set 1) | Question 65
GATE | GATE-CS-2014-(Set-3) | Question 38
|
[
{
"code": null,
"e": 24070,
"s": 24042,
"text": "\n28 Jun, 2021"
},
{
"code": null,
"e": 24175,
"s": 24070,
"text": "Consider a binary code that consists only four valid codewords as given below.00000, 01011, 10101, 11110"
},
{
"code": null,
"e": 24320,
"s": 24175,
"text": "Let minimum Hamming distance of code be p and maximum number of erroneous bits that can be corrected by the code be q. The value of p and q are:"
},
{
"code": null,
"e": 24509,
"s": 24320,
"text": "(A) p = 3 and q = 1(B) p = 3 and q = 2(C) p = 4 and q = 1(D) p = 4 and q = 2Answer: (A)Explanation: We need to find minimum hamming distance(difference in their corresponding bit position)"
},
{
"code": null,
"e": 25048,
"s": 24509,
"text": "00000, 01011, 10101, 11110\n\nFor two binary strings, hamming distance is number\nof ones in XOR of the two strings.\n\nHamming distance of first and second is 3, so is \nfor first and third. Hamming distance of first and\nfourth is 4.\n\nHamming distance of second and third is 4, and \nsecond and fourth is 3.\n\nHamming distance of third and fourth is 3.\n\nThus a code with minimum Hamming distance d \nbetween its codewords can detect at most d-1\nerrors and can correct ⌊(d-1)/2⌋ errors.\n\nHere d = 3. So number of errors that can be\ncorrected is 1."
},
{
"code": null,
"e": 25070,
"s": 25048,
"text": "Quiz of this Question"
},
{
"code": null,
"e": 25091,
"s": 25070,
"text": "GATE-CS-2017 (Set 2)"
},
{
"code": null,
"e": 25117,
"s": 25091,
"text": "GATE-GATE-CS-2017 (Set 2)"
},
{
"code": null,
"e": 25122,
"s": 25117,
"text": "GATE"
},
{
"code": null,
"e": 25220,
"s": 25122,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25254,
"s": 25220,
"text": "GATE | GATE-IT-2004 | Question 66"
},
{
"code": null,
"e": 25296,
"s": 25254,
"text": "GATE | GATE-CS-2016 (Set 2) | Question 48"
},
{
"code": null,
"e": 25330,
"s": 25296,
"text": "GATE | GATE-IT-2004 | Question 71"
},
{
"code": null,
"e": 25372,
"s": 25330,
"text": "GATE | GATE-CS-2014-(Set-3) | Question 65"
},
{
"code": null,
"e": 25405,
"s": 25372,
"text": "GATE | GATE CS 2011 | Question 7"
},
{
"code": null,
"e": 25439,
"s": 25405,
"text": "GATE | GATE CS 2010 | Question 24"
},
{
"code": null,
"e": 25481,
"s": 25439,
"text": "GATE | GATE-CS-2016 (Set 2) | Question 61"
},
{
"code": null,
"e": 25523,
"s": 25481,
"text": "GATE | GATE-CS-2015 (Set 3) | Question 65"
},
{
"code": null,
"e": 25565,
"s": 25523,
"text": "GATE | GATE-CS-2016 (Set 1) | Question 65"
}
] |
Why cannot we specify access modifiers inside an interface in C#?
|
Interface methods are contract with the outside world which specifies that class implementing this interface does a certain set of things.
Interface members are always public because the purpose of an interface is to enable other types to access a class or struct.
Interfaces can have access specifiers like protected or internal etc. Thus limiting 'the outside world' to a subset of 'the whole outside world'.
interface IInterface{
void Save();
}
class Program{
static void Main(){
Console.ReadLine();
}
}
The above example will compile properly without any errors
Prior to C# 8, interface members were public by default. In fact, if you put an access modifier on an interface member (including public), it would generate a compiler error.
interface IInterface{
Public void Save();
}
class Program{
static void Main(){
Console.ReadLine();
}
}
The above code throws compile time error in c# 7.0,but in c# 8.0 it compiles without any error
|
[
{
"code": null,
"e": 1201,
"s": 1062,
"text": "Interface methods are contract with the outside world which specifies that class implementing this interface does a certain set of things."
},
{
"code": null,
"e": 1327,
"s": 1201,
"text": "Interface members are always public because the purpose of an interface is to enable other types to access a class or struct."
},
{
"code": null,
"e": 1473,
"s": 1327,
"text": "Interfaces can have access specifiers like protected or internal etc. Thus limiting 'the outside world' to a subset of 'the whole outside world'."
},
{
"code": null,
"e": 1584,
"s": 1473,
"text": "interface IInterface{\n void Save();\n}\nclass Program{\n static void Main(){\n Console.ReadLine();\n }\n}"
},
{
"code": null,
"e": 1643,
"s": 1584,
"text": "The above example will compile properly without any errors"
},
{
"code": null,
"e": 1818,
"s": 1643,
"text": "Prior to C# 8, interface members were public by default. In fact, if you put an access modifier on an interface member (including public), it would generate a compiler error."
},
{
"code": null,
"e": 1936,
"s": 1818,
"text": "interface IInterface{\n Public void Save();\n}\nclass Program{\n static void Main(){\n Console.ReadLine();\n }\n}"
},
{
"code": null,
"e": 2031,
"s": 1936,
"text": "The above code throws compile time error in c# 7.0,but in c# 8.0 it compiles without any error"
}
] |
SQL Aliases
|
SQL aliases are used to give a table, or a column in a table, a temporary name.
Aliases are often used to make column names more readable.
An alias only exists for the duration of that query.
An alias is created with the AS keyword.
In this tutorial we will use the well-known Northwind sample database.
Below is a selection from the "Customers" table:
And a selection from the "Orders" table:
The following SQL statement creates two aliases, one for the CustomerID
column and one for the CustomerName column:
The following SQL statement creates two aliases, one for the CustomerName
column and one for the ContactName column. Note: It requires
double quotation marks or square brackets if the alias name contains spaces:
The following SQL statement creates an alias named "Address" that combine four columns (Address, PostalCode,
City and Country):
Note: To get the SQL statement above to work in MySQL use the following:
Note: To get the SQL statement above to work in Oracle use the following:
The following SQL statement selects all the orders from the customer with
CustomerID=4 (Around the Horn). We use the "Customers" and "Orders" tables, and
give them the table aliases of "c" and "o" respectively (Here we use
aliases to make the SQL shorter):
The following SQL statement is the same as above, but without aliases:
Aliases can be useful when:
There are more than one table involved in a query
Functions are used in the query
Column names are big or not very readable
Two or more columns are combined together
When displaying the Customers table,
make an ALIAS of the PostalCode column,
the column should be called Pno instead.
SELECT CustomerName,
Address,
PostalCode
FROM Customers;
Start the Exercise
We just launchedW3Schools videos
Get certifiedby completinga course today!
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
help@w3schools.com
Your message has been sent to W3Schools.
|
[
{
"code": null,
"e": 80,
"s": 0,
"text": "SQL aliases are used to give a table, or a column in a table, a temporary name."
},
{
"code": null,
"e": 139,
"s": 80,
"text": "Aliases are often used to make column names more readable."
},
{
"code": null,
"e": 192,
"s": 139,
"text": "An alias only exists for the duration of that query."
},
{
"code": null,
"e": 233,
"s": 192,
"text": "An alias is created with the AS keyword."
},
{
"code": null,
"e": 304,
"s": 233,
"text": "In this tutorial we will use the well-known Northwind sample database."
},
{
"code": null,
"e": 353,
"s": 304,
"text": "Below is a selection from the \"Customers\" table:"
},
{
"code": null,
"e": 394,
"s": 353,
"text": "And a selection from the \"Orders\" table:"
},
{
"code": null,
"e": 511,
"s": 394,
"text": "The following SQL statement creates two aliases, one for the CustomerID \ncolumn and one for the CustomerName column:"
},
{
"code": null,
"e": 725,
"s": 511,
"text": "The following SQL statement creates two aliases, one for the CustomerName \ncolumn and one for the ContactName column. Note: It requires \ndouble quotation marks or square brackets if the alias name contains spaces:"
},
{
"code": null,
"e": 854,
"s": 725,
"text": "The following SQL statement creates an alias named \"Address\" that combine four columns (Address, PostalCode, \nCity and Country):"
},
{
"code": null,
"e": 927,
"s": 854,
"text": "Note: To get the SQL statement above to work in MySQL use the following:"
},
{
"code": null,
"e": 1001,
"s": 927,
"text": "Note: To get the SQL statement above to work in Oracle use the following:"
},
{
"code": null,
"e": 1261,
"s": 1001,
"text": "The following SQL statement selects all the orders from the customer with \nCustomerID=4 (Around the Horn). We use the \"Customers\" and \"Orders\" tables, and \ngive them the table aliases of \"c\" and \"o\" respectively (Here we use \naliases to make the SQL shorter):"
},
{
"code": null,
"e": 1332,
"s": 1261,
"text": "The following SQL statement is the same as above, but without aliases:"
},
{
"code": null,
"e": 1360,
"s": 1332,
"text": "Aliases can be useful when:"
},
{
"code": null,
"e": 1410,
"s": 1360,
"text": "There are more than one table involved in a query"
},
{
"code": null,
"e": 1442,
"s": 1410,
"text": "Functions are used in the query"
},
{
"code": null,
"e": 1484,
"s": 1442,
"text": "Column names are big or not very readable"
},
{
"code": null,
"e": 1526,
"s": 1484,
"text": "Two or more columns are combined together"
},
{
"code": null,
"e": 1644,
"s": 1526,
"text": "When displaying the Customers table,\nmake an ALIAS of the PostalCode column,\nthe column should be called Pno instead."
},
{
"code": null,
"e": 1703,
"s": 1644,
"text": "SELECT CustomerName,\nAddress,\nPostalCode \nFROM Customers;\n"
},
{
"code": null,
"e": 1722,
"s": 1703,
"text": "Start the Exercise"
},
{
"code": null,
"e": 1755,
"s": 1722,
"text": "We just launchedW3Schools videos"
},
{
"code": null,
"e": 1797,
"s": 1755,
"text": "Get certifiedby completinga course today!"
},
{
"code": null,
"e": 1904,
"s": 1797,
"text": "If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:"
},
{
"code": null,
"e": 1923,
"s": 1904,
"text": "help@w3schools.com"
}
] |
Difference between highest and least frequencies in an array - GeeksforGeeks
|
01 Jul, 2021
Given an array, find the difference between highest occurrence and least occurrence of any number in an arrayExamples:
Input : arr[] = [7, 8, 4, 5, 4, 1, 1, 7, 7, 2, 5]
Output : 2
Lowest occurring element (5) occurs once.
Highest occurring element (1 or 7) occurs 3 times
Input : arr[] = [1, 1, 1, 3, 3, 3]
Output : 0
A simple solution is to use two loops to count frequency of every element and keep track of maximum and minimum frequencies.A better solution is to sort the array in O(n log n) and check consecutive element’s occurrence and compare their count respectively.
C++
Java
Python3
C#
PHP
Javascript
// CPP code to find the difference between highest// and least frequencies#include <bits/stdc++.h>using namespace std; int findDiff(int arr[], int n){ // sort the array sort(arr, arr + n); int count = 0, max_count = 0, min_count = n; for (int i = 0; i < (n - 1); i++) { // checking consecutive elements if (arr[i] == arr[i + 1]) { count += 1; continue; } else { max_count = max(max_count, count); min_count = min(min_count, count); count = 0; } } return (max_count - min_count);} // Driver codeint main(){ int arr[] = { 7, 8, 4, 5, 4, 1, 1, 7, 7, 2, 5 }; int n = sizeof(arr) / sizeof(arr[0]); cout << findDiff(arr, n) << "\n"; return 0;}
// JAVA Code for Difference between// highest and least frequencies// in an arrayimport java.util.*; class GFG { static int findDiff(int arr[], int n) { // sort the array Arrays.sort(arr); int count = 0, max_count = 0, min_count = n; for (int i = 0; i < (n - 1); i++) { // checking consecutive elements if (arr[i] == arr[i + 1]) { count += 1; continue; } else { max_count = Math.max(max_count, count); min_count = Math.min(min_count, count); count = 0; } } return (max_count - min_count); } // Driver program to test above function public static void main(String[] args) { int arr[] = { 7, 8, 4, 5, 4, 1, 1, 7, 7, 2, 5 }; int n = arr.length; System.out.println(findDiff(arr, n)); }} // This code is contributed by Arnav Kr. Mandal.
# Python3 code to find the difference# between highest nd least frequencies def findDiff(arr, n): # sort the array arr.sort() count = 0; max_count = 0; min_count = n for i in range(0, (n-1)): # checking consecutive elements if arr[i] == arr[i + 1]: count += 1 continue else: max_count = max(max_count, count) min_count = min(min_count, count) count = 0 return max_count - min_count # Driver Codearr = [ 7, 8, 4, 5, 4, 1, 1, 7, 7, 2, 5 ]n = len(arr)print (findDiff(arr, n)) # This code is contributed by Shreyanshi Arun.
// C# Code for Difference between// highest and least frequencies// in an arrayusing System; class GFG { static int findDiff(int[] arr, int n) { // sort the array Array.Sort(arr); int count = 0, max_count = 0, min_count = n; for (int i = 0; i < (n - 1); i++) { // checking consecutive elements if (arr[i] == arr[i + 1]) { count += 1; continue; } else { max_count = Math.Max(max_count, count); min_count = Math.Min(min_count, count); count = 0; } } return (max_count - min_count); } // Driver program to test above function public static void Main() { int[] arr = { 7, 8, 4, 5, 4, 1, 1, 7, 7, 2, 5 }; int n = arr.Length; Console.WriteLine(findDiff(arr, n)); }} // This code is contributed by vt_m.
<?php// PHP code to find the// difference between highest// and least frequencies // function that// returns differencefunction findDiff($arr, $n){ // sort the array sort($arr); $count = 0; $max_count = 0; $min_count = $n; for ($i = 0; $i < ($n - 1); $i++) { // checking consecutive elements if ($arr[$i] == $arr[$i + 1]) { $count += 1; continue; } else { $max_count = max($max_count, $count); $min_count = min($min_count, $count); $count = 0; } } return ($max_count - $min_count);} // Driver Code$arr = array(7, 8, 4, 5, 4, 1, 1, 7, 7, 2, 5);$n = sizeof($arr); echo(findDiff($arr, $n) . "\n"); // This code is contributed by Ajit.?>
<script> // Javascript Code for Difference between // highest and least frequencies // in an array function findDiff(arr, n) { // sort the array arr.sort(function(a, b){return a - b}); let count = 0, max_count = 0, min_count = n; for (let i = 0; i < (n - 1); i++) { // checking consecutive elements if (arr[i] == arr[i + 1]) { count += 1; continue; } else { max_count = Math.max(max_count, count); min_count = Math.min(min_count, count); count = 0; } } return (max_count - min_count); } let arr = [ 7, 8, 4, 5, 4, 1, 1, 7, 7, 2, 5 ]; let n = arr.length; document.write(findDiff(arr, n)); </script>
Output:
2
An efficient solution is to use hashing. We count frequencies of all elements and finally traverse the hash table to find maximum and minimum.Below is the implementation.
C++
Java
Python3
C#
Javascript
// CPP code to find the difference between highest// and least frequencies#include <bits/stdc++.h>using namespace std; int findDiff(int arr[], int n){ // Put all elements in a hash map unordered_map<int, int> hm; for (int i = 0; i < n; i++) hm[arr[i]]++; // Find counts of maximum and minimum // frequent elements int max_count = 0, min_count = n; for (auto x : hm) { max_count = max(max_count, x.second); min_count = min(min_count, x.second); } return (max_count - min_count);} // Driverint main(){ int arr[] = { 7, 8, 4, 5, 4, 1, 1, 7, 7, 2, 5 }; int n = sizeof(arr) / sizeof(arr[0]); cout << findDiff(arr, n) << "\n"; return 0;}
// Java code to find the difference between highest// and least frequenciesimport java.util.*; class GFG{ static int findDiff(int arr[], int n){ // Put all elements in a hash map Map<Integer,Integer> mp = new HashMap<>(); for (int i = 0 ; i < n; i++) { if(mp.containsKey(arr[i])) { mp.put(arr[i], mp.get(arr[i])+1); } else { mp.put(arr[i], 1); } } // Find counts of maximum and minimum // frequent elements int max_count = 0, min_count = n; for (Map.Entry<Integer,Integer> x : mp.entrySet()) { max_count = Math.max(max_count, x.getValue()); min_count = Math.min(min_count, x.getValue()); } return (max_count - min_count);} // Driver codepublic static void main(String[] args){ int arr[] = { 7, 8, 4, 5, 4, 1, 1, 7, 7, 2, 5 }; int n = arr.length; System.out.println(findDiff(arr, n));}} /* This code is contributed by PrinciRaj1992 */
# Python code to find the difference between highest# and least frequencies from collections import defaultdictdef findDiff(arr,n): # Put all elements in a hash map mp = defaultdict(lambda:0) for i in range(n): mp[arr[i]]+=1 # Find counts of maximum and minimum # frequent elements max_count=0;min_count=n for key,values in mp.items(): max_count= max(max_count,values) min_count = min(min_count,values) return max_count-min_count # Driver codearr = [ 7, 8, 4, 5, 4, 1, 1, 7, 7, 2, 5]n = len(arr)print(findDiff(arr,n)) # This code is contributed by Shrikant13
// C# code to find the difference between highest// and least frequenciesusing System;using System.Collections.Generic; class GFG{ static int findDiff(int []arr, int n){ // Put all elements in a hash map Dictionary<int,int> mp = new Dictionary<int,int>(); for (int i = 0 ; i < n; i++) { if(mp.ContainsKey(arr[i])) { var val = mp[arr[i]]; mp.Remove(arr[i]); mp.Add(arr[i], val + 1); } else { mp.Add(arr[i], 1); } } // Find counts of maximum and minimum // frequent elements int max_count = 0, min_count = n; foreach(KeyValuePair<int, int> entry in mp) { max_count = Math.Max(max_count, entry.Value); min_count = Math.Min(min_count, entry.Value); } return (max_count - min_count);} // Driver codepublic static void Main(String[] args){ int []arr = { 7, 8, 4, 5, 4, 1, 1, 7, 7, 2, 5 }; int n = arr.Length; Console.WriteLine(findDiff(arr, n));}} // This code is contributed by Princi Singh
<script> // JavaScript code to find the difference between highest // and least frequencies function findDiff(arr, n) { // Put all elements in a hash map var mp = {}; for (var i = 0; i < n; i++) { if (mp.hasOwnProperty(arr[i])) { var val = mp[arr[i]]; delete mp[arr[i]]; mp[arr[i]] = val + 1; } else { mp[arr[i]] = 1; } } // Find counts of maximum and minimum // frequent elements var max_count = 0, min_count = n; for (const [key, value] of Object.entries(mp)) { max_count = Math.max(max_count, value); min_count = Math.min(min_count, value); } return max_count - min_count; } // Driver code var arr = [7, 8, 4, 5, 4, 1, 1, 7, 7, 2, 5]; var n = arr.length; document.write(findDiff(arr, n)); // This code is contributed by rdtank. </script>
Output:
2
Time Complexity : O(n)This article is contributed by Himanshu Ranjan. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
vt_m
jit_t
shrikanth13
princiraj1992
princi singh
divyesh072019
rdtank
Arrays
Difference Between
Hash
Sorting
Arrays
Hash
Sorting
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Multidimensional Arrays in Java
Introduction to Arrays
Maximum and minimum of an array using minimum number of comparisons
Python | Using 2D arrays/lists the right way
Linked List vs Array
Difference between BFS and DFS
Class method vs Static method in Python
Differences between TCP and UDP
Difference between Process and Thread
Difference between var, let and const keywords in JavaScript
|
[
{
"code": null,
"e": 25566,
"s": 25538,
"text": "\n01 Jul, 2021"
},
{
"code": null,
"e": 25687,
"s": 25566,
"text": "Given an array, find the difference between highest occurrence and least occurrence of any number in an arrayExamples: "
},
{
"code": null,
"e": 25889,
"s": 25687,
"text": "Input : arr[] = [7, 8, 4, 5, 4, 1, 1, 7, 7, 2, 5]\nOutput : 2\nLowest occurring element (5) occurs once.\nHighest occurring element (1 or 7) occurs 3 times\n\nInput : arr[] = [1, 1, 1, 3, 3, 3]\nOutput : 0"
},
{
"code": null,
"e": 26151,
"s": 25891,
"text": "A simple solution is to use two loops to count frequency of every element and keep track of maximum and minimum frequencies.A better solution is to sort the array in O(n log n) and check consecutive element’s occurrence and compare their count respectively. "
},
{
"code": null,
"e": 26155,
"s": 26151,
"text": "C++"
},
{
"code": null,
"e": 26160,
"s": 26155,
"text": "Java"
},
{
"code": null,
"e": 26168,
"s": 26160,
"text": "Python3"
},
{
"code": null,
"e": 26171,
"s": 26168,
"text": "C#"
},
{
"code": null,
"e": 26175,
"s": 26171,
"text": "PHP"
},
{
"code": null,
"e": 26186,
"s": 26175,
"text": "Javascript"
},
{
"code": "// CPP code to find the difference between highest// and least frequencies#include <bits/stdc++.h>using namespace std; int findDiff(int arr[], int n){ // sort the array sort(arr, arr + n); int count = 0, max_count = 0, min_count = n; for (int i = 0; i < (n - 1); i++) { // checking consecutive elements if (arr[i] == arr[i + 1]) { count += 1; continue; } else { max_count = max(max_count, count); min_count = min(min_count, count); count = 0; } } return (max_count - min_count);} // Driver codeint main(){ int arr[] = { 7, 8, 4, 5, 4, 1, 1, 7, 7, 2, 5 }; int n = sizeof(arr) / sizeof(arr[0]); cout << findDiff(arr, n) << \"\\n\"; return 0;}",
"e": 26948,
"s": 26186,
"text": null
},
{
"code": "// JAVA Code for Difference between// highest and least frequencies// in an arrayimport java.util.*; class GFG { static int findDiff(int arr[], int n) { // sort the array Arrays.sort(arr); int count = 0, max_count = 0, min_count = n; for (int i = 0; i < (n - 1); i++) { // checking consecutive elements if (arr[i] == arr[i + 1]) { count += 1; continue; } else { max_count = Math.max(max_count, count); min_count = Math.min(min_count, count); count = 0; } } return (max_count - min_count); } // Driver program to test above function public static void main(String[] args) { int arr[] = { 7, 8, 4, 5, 4, 1, 1, 7, 7, 2, 5 }; int n = arr.length; System.out.println(findDiff(arr, n)); }} // This code is contributed by Arnav Kr. Mandal.",
"e": 28007,
"s": 26948,
"text": null
},
{
"code": "# Python3 code to find the difference# between highest nd least frequencies def findDiff(arr, n): # sort the array arr.sort() count = 0; max_count = 0; min_count = n for i in range(0, (n-1)): # checking consecutive elements if arr[i] == arr[i + 1]: count += 1 continue else: max_count = max(max_count, count) min_count = min(min_count, count) count = 0 return max_count - min_count # Driver Codearr = [ 7, 8, 4, 5, 4, 1, 1, 7, 7, 2, 5 ]n = len(arr)print (findDiff(arr, n)) # This code is contributed by Shreyanshi Arun.",
"e": 28629,
"s": 28007,
"text": null
},
{
"code": "// C# Code for Difference between// highest and least frequencies// in an arrayusing System; class GFG { static int findDiff(int[] arr, int n) { // sort the array Array.Sort(arr); int count = 0, max_count = 0, min_count = n; for (int i = 0; i < (n - 1); i++) { // checking consecutive elements if (arr[i] == arr[i + 1]) { count += 1; continue; } else { max_count = Math.Max(max_count, count); min_count = Math.Min(min_count, count); count = 0; } } return (max_count - min_count); } // Driver program to test above function public static void Main() { int[] arr = { 7, 8, 4, 5, 4, 1, 1, 7, 7, 2, 5 }; int n = arr.Length; Console.WriteLine(findDiff(arr, n)); }} // This code is contributed by vt_m.",
"e": 29661,
"s": 28629,
"text": null
},
{
"code": "<?php// PHP code to find the// difference between highest// and least frequencies // function that// returns differencefunction findDiff($arr, $n){ // sort the array sort($arr); $count = 0; $max_count = 0; $min_count = $n; for ($i = 0; $i < ($n - 1); $i++) { // checking consecutive elements if ($arr[$i] == $arr[$i + 1]) { $count += 1; continue; } else { $max_count = max($max_count, $count); $min_count = min($min_count, $count); $count = 0; } } return ($max_count - $min_count);} // Driver Code$arr = array(7, 8, 4, 5, 4, 1, 1, 7, 7, 2, 5);$n = sizeof($arr); echo(findDiff($arr, $n) . \"\\n\"); // This code is contributed by Ajit.?>",
"e": 30443,
"s": 29661,
"text": null
},
{
"code": "<script> // Javascript Code for Difference between // highest and least frequencies // in an array function findDiff(arr, n) { // sort the array arr.sort(function(a, b){return a - b}); let count = 0, max_count = 0, min_count = n; for (let i = 0; i < (n - 1); i++) { // checking consecutive elements if (arr[i] == arr[i + 1]) { count += 1; continue; } else { max_count = Math.max(max_count, count); min_count = Math.min(min_count, count); count = 0; } } return (max_count - min_count); } let arr = [ 7, 8, 4, 5, 4, 1, 1, 7, 7, 2, 5 ]; let n = arr.length; document.write(findDiff(arr, n)); </script>",
"e": 31285,
"s": 30443,
"text": null
},
{
"code": null,
"e": 31295,
"s": 31285,
"text": "Output: "
},
{
"code": null,
"e": 31298,
"s": 31295,
"text": " 2"
},
{
"code": null,
"e": 31470,
"s": 31298,
"text": "An efficient solution is to use hashing. We count frequencies of all elements and finally traverse the hash table to find maximum and minimum.Below is the implementation. "
},
{
"code": null,
"e": 31474,
"s": 31470,
"text": "C++"
},
{
"code": null,
"e": 31479,
"s": 31474,
"text": "Java"
},
{
"code": null,
"e": 31487,
"s": 31479,
"text": "Python3"
},
{
"code": null,
"e": 31490,
"s": 31487,
"text": "C#"
},
{
"code": null,
"e": 31501,
"s": 31490,
"text": "Javascript"
},
{
"code": "// CPP code to find the difference between highest// and least frequencies#include <bits/stdc++.h>using namespace std; int findDiff(int arr[], int n){ // Put all elements in a hash map unordered_map<int, int> hm; for (int i = 0; i < n; i++) hm[arr[i]]++; // Find counts of maximum and minimum // frequent elements int max_count = 0, min_count = n; for (auto x : hm) { max_count = max(max_count, x.second); min_count = min(min_count, x.second); } return (max_count - min_count);} // Driverint main(){ int arr[] = { 7, 8, 4, 5, 4, 1, 1, 7, 7, 2, 5 }; int n = sizeof(arr) / sizeof(arr[0]); cout << findDiff(arr, n) << \"\\n\"; return 0;}",
"e": 32196,
"s": 31501,
"text": null
},
{
"code": "// Java code to find the difference between highest// and least frequenciesimport java.util.*; class GFG{ static int findDiff(int arr[], int n){ // Put all elements in a hash map Map<Integer,Integer> mp = new HashMap<>(); for (int i = 0 ; i < n; i++) { if(mp.containsKey(arr[i])) { mp.put(arr[i], mp.get(arr[i])+1); } else { mp.put(arr[i], 1); } } // Find counts of maximum and minimum // frequent elements int max_count = 0, min_count = n; for (Map.Entry<Integer,Integer> x : mp.entrySet()) { max_count = Math.max(max_count, x.getValue()); min_count = Math.min(min_count, x.getValue()); } return (max_count - min_count);} // Driver codepublic static void main(String[] args){ int arr[] = { 7, 8, 4, 5, 4, 1, 1, 7, 7, 2, 5 }; int n = arr.length; System.out.println(findDiff(arr, n));}} /* This code is contributed by PrinciRaj1992 */",
"e": 33155,
"s": 32196,
"text": null
},
{
"code": "# Python code to find the difference between highest# and least frequencies from collections import defaultdictdef findDiff(arr,n): # Put all elements in a hash map mp = defaultdict(lambda:0) for i in range(n): mp[arr[i]]+=1 # Find counts of maximum and minimum # frequent elements max_count=0;min_count=n for key,values in mp.items(): max_count= max(max_count,values) min_count = min(min_count,values) return max_count-min_count # Driver codearr = [ 7, 8, 4, 5, 4, 1, 1, 7, 7, 2, 5]n = len(arr)print(findDiff(arr,n)) # This code is contributed by Shrikant13",
"e": 33763,
"s": 33155,
"text": null
},
{
"code": "// C# code to find the difference between highest// and least frequenciesusing System;using System.Collections.Generic; class GFG{ static int findDiff(int []arr, int n){ // Put all elements in a hash map Dictionary<int,int> mp = new Dictionary<int,int>(); for (int i = 0 ; i < n; i++) { if(mp.ContainsKey(arr[i])) { var val = mp[arr[i]]; mp.Remove(arr[i]); mp.Add(arr[i], val + 1); } else { mp.Add(arr[i], 1); } } // Find counts of maximum and minimum // frequent elements int max_count = 0, min_count = n; foreach(KeyValuePair<int, int> entry in mp) { max_count = Math.Max(max_count, entry.Value); min_count = Math.Min(min_count, entry.Value); } return (max_count - min_count);} // Driver codepublic static void Main(String[] args){ int []arr = { 7, 8, 4, 5, 4, 1, 1, 7, 7, 2, 5 }; int n = arr.Length; Console.WriteLine(findDiff(arr, n));}} // This code is contributed by Princi Singh",
"e": 34796,
"s": 33763,
"text": null
},
{
"code": "<script> // JavaScript code to find the difference between highest // and least frequencies function findDiff(arr, n) { // Put all elements in a hash map var mp = {}; for (var i = 0; i < n; i++) { if (mp.hasOwnProperty(arr[i])) { var val = mp[arr[i]]; delete mp[arr[i]]; mp[arr[i]] = val + 1; } else { mp[arr[i]] = 1; } } // Find counts of maximum and minimum // frequent elements var max_count = 0, min_count = n; for (const [key, value] of Object.entries(mp)) { max_count = Math.max(max_count, value); min_count = Math.min(min_count, value); } return max_count - min_count; } // Driver code var arr = [7, 8, 4, 5, 4, 1, 1, 7, 7, 2, 5]; var n = arr.length; document.write(findDiff(arr, n)); // This code is contributed by rdtank. </script>",
"e": 35775,
"s": 34796,
"text": null
},
{
"code": null,
"e": 35785,
"s": 35775,
"text": "Output: "
},
{
"code": null,
"e": 35788,
"s": 35785,
"text": " 2"
},
{
"code": null,
"e": 36234,
"s": 35788,
"text": "Time Complexity : O(n)This article is contributed by Himanshu Ranjan. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. 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": 36239,
"s": 36234,
"text": "vt_m"
},
{
"code": null,
"e": 36245,
"s": 36239,
"text": "jit_t"
},
{
"code": null,
"e": 36257,
"s": 36245,
"text": "shrikanth13"
},
{
"code": null,
"e": 36271,
"s": 36257,
"text": "princiraj1992"
},
{
"code": null,
"e": 36284,
"s": 36271,
"text": "princi singh"
},
{
"code": null,
"e": 36298,
"s": 36284,
"text": "divyesh072019"
},
{
"code": null,
"e": 36305,
"s": 36298,
"text": "rdtank"
},
{
"code": null,
"e": 36312,
"s": 36305,
"text": "Arrays"
},
{
"code": null,
"e": 36331,
"s": 36312,
"text": "Difference Between"
},
{
"code": null,
"e": 36336,
"s": 36331,
"text": "Hash"
},
{
"code": null,
"e": 36344,
"s": 36336,
"text": "Sorting"
},
{
"code": null,
"e": 36351,
"s": 36344,
"text": "Arrays"
},
{
"code": null,
"e": 36356,
"s": 36351,
"text": "Hash"
},
{
"code": null,
"e": 36364,
"s": 36356,
"text": "Sorting"
},
{
"code": null,
"e": 36462,
"s": 36364,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 36494,
"s": 36462,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 36517,
"s": 36494,
"text": "Introduction to Arrays"
},
{
"code": null,
"e": 36585,
"s": 36517,
"text": "Maximum and minimum of an array using minimum number of comparisons"
},
{
"code": null,
"e": 36630,
"s": 36585,
"text": "Python | Using 2D arrays/lists the right way"
},
{
"code": null,
"e": 36651,
"s": 36630,
"text": "Linked List vs Array"
},
{
"code": null,
"e": 36682,
"s": 36651,
"text": "Difference between BFS and DFS"
},
{
"code": null,
"e": 36722,
"s": 36682,
"text": "Class method vs Static method in Python"
},
{
"code": null,
"e": 36754,
"s": 36722,
"text": "Differences between TCP and UDP"
},
{
"code": null,
"e": 36792,
"s": 36754,
"text": "Difference between Process and Thread"
}
] |
Java Program to sort an array in case-insensitive order
|
An array can be sorted in case-insensitive order using the java.util.Arrays.sort() method. Also the java.text.Collator class is required as Collator.getInstance() is used to obtain the Collator object for the required locale.
A program that demonstrates this is given as follows −
Live Demo
import java.text.Collator;
import java.util.Arrays;
public class Demo {
public static void main(String args[]) {
String[] arr = new String[] { "apple", "mango", "Banana", "Melon", "orange" };
System.out.print("The unsorted array is: ");
System.out.println(Arrays.toString(arr));
Arrays.sort(arr, Collator.getInstance());
System.out.print("The sorted array in case-insensitive order is: ");
System.out.println(Arrays.toString(arr));
}
}
The unsorted array is: [apple, mango, Banana, Melon, orange]
The sorted array in case-insensitive order is: [apple, Banana, mango, Melon, orange]
Now let us understand the above program.
First the array arr[] is defined. Then the unsorted array is printed. A code snippet which demonstrates this is as follows −
String[] arr = new String[] { "apple", "mango", "Banana", "Melon", "orange" };
System.out.print("The unsorted array is: ");
System.out.println(Arrays.toString(arr));
The Arrays.sort(arr, Collator.getInstance()) method is used to sort the array in a case-insensitive order. Then the sorted array is displayed. A code snippet which demonstrates this is as follows −
Arrays.sort(arr, Collator.getInstance())
System.out.print("The sorted array in case-insensitive order is: ");
System.out.println(Arrays.toString(arr));
|
[
{
"code": null,
"e": 1288,
"s": 1062,
"text": "An array can be sorted in case-insensitive order using the java.util.Arrays.sort() method. Also the java.text.Collator class is required as Collator.getInstance() is used to obtain the Collator object for the required locale."
},
{
"code": null,
"e": 1343,
"s": 1288,
"text": "A program that demonstrates this is given as follows −"
},
{
"code": null,
"e": 1354,
"s": 1343,
"text": " Live Demo"
},
{
"code": null,
"e": 1832,
"s": 1354,
"text": "import java.text.Collator;\nimport java.util.Arrays;\npublic class Demo {\n public static void main(String args[]) {\n String[] arr = new String[] { \"apple\", \"mango\", \"Banana\", \"Melon\", \"orange\" };\n System.out.print(\"The unsorted array is: \");\n System.out.println(Arrays.toString(arr));\n Arrays.sort(arr, Collator.getInstance());\n System.out.print(\"The sorted array in case-insensitive order is: \");\n System.out.println(Arrays.toString(arr));\n }\n}"
},
{
"code": null,
"e": 1978,
"s": 1832,
"text": "The unsorted array is: [apple, mango, Banana, Melon, orange]\nThe sorted array in case-insensitive order is: [apple, Banana, mango, Melon, orange]"
},
{
"code": null,
"e": 2019,
"s": 1978,
"text": "Now let us understand the above program."
},
{
"code": null,
"e": 2144,
"s": 2019,
"text": "First the array arr[] is defined. Then the unsorted array is printed. A code snippet which demonstrates this is as follows −"
},
{
"code": null,
"e": 2310,
"s": 2144,
"text": "String[] arr = new String[] { \"apple\", \"mango\", \"Banana\", \"Melon\", \"orange\" };\nSystem.out.print(\"The unsorted array is: \");\nSystem.out.println(Arrays.toString(arr));"
},
{
"code": null,
"e": 2508,
"s": 2310,
"text": "The Arrays.sort(arr, Collator.getInstance()) method is used to sort the array in a case-insensitive order. Then the sorted array is displayed. A code snippet which demonstrates this is as follows −"
},
{
"code": null,
"e": 2660,
"s": 2508,
"text": "Arrays.sort(arr, Collator.getInstance())\nSystem.out.print(\"The sorted array in case-insensitive order is: \");\nSystem.out.println(Arrays.toString(arr));"
}
] |
htmlspecialchars() function in PHP
|
The htmlspecialchars() function is used to convert special characters to HTML entities.
The predefined characters are −
& (ampersand) becomes & amp;
" (double quote) becomes & quot;
' (single quote) becomes & #039;
< (less than) becomes & lt;
> (greater than) becomes & gt;
htmlspecialchars(str,flags,character-set,double_encode)
str − The string to convert.
str − The string to convert.
flags −How to handle quotes, invalid encoding and the used document type.
flags −How to handle quotes, invalid encoding and the used document type.
The following are the available quote styles −ENT_COMPAT − Default. Encodes only double quotesENT_QUOTES − Encodes double and single quotesENT_NOQUOTES − Does not encode any quotes
The following are the available quote styles −
ENT_COMPAT − Default. Encodes only double quotes
ENT_COMPAT − Default. Encodes only double quotes
ENT_QUOTES − Encodes double and single quotes
ENT_QUOTES − Encodes double and single quotes
ENT_NOQUOTES − Does not encode any quotes
ENT_NOQUOTES − Does not encode any quotes
Invalid encoding −ENT_IGNORE − Ignores invalid encoding instead of having the function return an empty string. Should be avoided, as it may have security implications.ENT_SUBSTITUTE − Replaces invalid encoding for a specified character set with a Unicode Replacement Character U+FFFD (UTF-8) or &#FFFD; instead of returning an empty string.ENT_DISALLOWED − Replaces code points that are invalid in the specified doctype with a Unicode Replacement Character U+FFFD (UTF-8) or &#FFFD;
Invalid encoding −
ENT_IGNORE − Ignores invalid encoding instead of having the function return an empty string. Should be avoided, as it may have security implications.
ENT_IGNORE − Ignores invalid encoding instead of having the function return an empty string. Should be avoided, as it may have security implications.
ENT_SUBSTITUTE − Replaces invalid encoding for a specified character set with a Unicode Replacement Character U+FFFD (UTF-8) or &#FFFD; instead of returning an empty string.
ENT_SUBSTITUTE − Replaces invalid encoding for a specified character set with a Unicode Replacement Character U+FFFD (UTF-8) or &#FFFD; instead of returning an empty string.
ENT_DISALLOWED − Replaces code points that are invalid in the specified doctype with a Unicode Replacement Character U+FFFD (UTF-8) or &#FFFD;
ENT_DISALLOWED − Replaces code points that are invalid in the specified doctype with a Unicode Replacement Character U+FFFD (UTF-8) or &#FFFD;
The following are the additional flags for specifying the used doctype −ENT_HTML401 − Default. Handle code as HTML 4.01ENT_HTML5 − Handle code as HTML 5ENT_XML1 − Handle code as XML 1ENT_XHTML − Handle code as XHTML
The following are the additional flags for specifying the used doctype −
ENT_HTML401 − Default. Handle code as HTML 4.01
ENT_HTML401 − Default. Handle code as HTML 4.01
ENT_HTML5 − Handle code as HTML 5
ENT_HTML5 − Handle code as HTML 5
ENT_XML1 − Handle code as XML 1
ENT_XML1 − Handle code as XML 1
ENT_XHTML − Handle code as XHTML
ENT_XHTML − Handle code as XHTML
character-set − The character-set to use
character-set − The character-set to use
The following are the allowed values are −UTF-8 − Default. ASCII compatible multi-byte 8-bit UnicodeISO-8859-1 − Western EuropeanISO-8859-15 − Western European (adds the Euro sign + French and Finnish letters missing in ISO-8859-1)cp866 − DOS-specific Cyrillic charsetcp1251 − Windows-specific Cyrillic charsetcp1252 − Windows specific charset for Western EuropeanKOI8-R − RussianBIG5 − Traditional Chinese, mainly used in TaiwanGB2312 − Simplified Chinese, national standard character setBIG5-HKSCS − Big5 with Hong Kong extensionsShift_JIS − JapaneseEUC-JP − JapaneseMacRoman − Character-set that was used by Mac OS
The following are the allowed values are −
UTF-8 − Default. ASCII compatible multi-byte 8-bit Unicode
UTF-8 − Default. ASCII compatible multi-byte 8-bit Unicode
ISO-8859-1 − Western European
ISO-8859-1 − Western European
ISO-8859-15 − Western European (adds the Euro sign + French and Finnish letters missing in ISO-8859-1)
ISO-8859-15 − Western European (adds the Euro sign + French and Finnish letters missing in ISO-8859-1)
cp866 − DOS-specific Cyrillic charset
cp866 − DOS-specific Cyrillic charset
cp1251 − Windows-specific Cyrillic charset
cp1251 − Windows-specific Cyrillic charset
cp1252 − Windows specific charset for Western European
cp1252 − Windows specific charset for Western European
KOI8-R − Russian
KOI8-R − Russian
BIG5 − Traditional Chinese, mainly used in Taiwan
BIG5 − Traditional Chinese, mainly used in Taiwan
GB2312 − Simplified Chinese, national standard character set
GB2312 − Simplified Chinese, national standard character set
BIG5-HKSCS − Big5 with Hong Kong extensions
BIG5-HKSCS − Big5 with Hong Kong extensions
Shift_JIS − Japanese
Shift_JIS − Japanese
EUC-JP − Japanese
EUC-JP − Japanese
MacRoman − Character-set that was used by Mac OS
MacRoman − Character-set that was used by Mac OS
double_encode − A boolean value that specifies whether to encode existing html entities or not.TRUE − Default. Will convert everythingFALSE − Will not encode existing html entities
double_encode − A boolean value that specifies whether to encode existing html entities or not.
TRUE − Default. Will convert everything
TRUE − Default. Will convert everything
FALSE − Will not encode existing html entities
FALSE − Will not encode existing html entities
The htmlspecialchars() function returns the converted string.
The following is an example −
Live Demo
<?php
$res = htmlspecialchars("<a href='mylink' rel=”nofollow”><strong>Demo</strong></a>", ENT_QUOTES);
echo $res //
?>
& lt;a href=& #039;mylink& #039; rel=”nofollow”& gt;& lt;strong& gt;Demo& lt;/strong& gt;& lt;/a >
|
[
{
"code": null,
"e": 1150,
"s": 1062,
"text": "The htmlspecialchars() function is used to convert special characters to HTML entities."
},
{
"code": null,
"e": 1182,
"s": 1150,
"text": "The predefined characters are −"
},
{
"code": null,
"e": 1211,
"s": 1182,
"text": "& (ampersand) becomes & amp;"
},
{
"code": null,
"e": 1244,
"s": 1211,
"text": "\" (double quote) becomes & quot;"
},
{
"code": null,
"e": 1277,
"s": 1244,
"text": "' (single quote) becomes & #039;"
},
{
"code": null,
"e": 1305,
"s": 1277,
"text": "< (less than) becomes & lt;"
},
{
"code": null,
"e": 1336,
"s": 1305,
"text": "> (greater than) becomes & gt;"
},
{
"code": null,
"e": 1392,
"s": 1336,
"text": "htmlspecialchars(str,flags,character-set,double_encode)"
},
{
"code": null,
"e": 1422,
"s": 1392,
"text": "str − The string to convert."
},
{
"code": null,
"e": 1452,
"s": 1422,
"text": "str − The string to convert."
},
{
"code": null,
"e": 1527,
"s": 1452,
"text": "flags −How to handle quotes, invalid encoding and the used document type."
},
{
"code": null,
"e": 1602,
"s": 1527,
"text": "flags −How to handle quotes, invalid encoding and the used document type."
},
{
"code": null,
"e": 1786,
"s": 1602,
"text": "The following are the available quote styles −ENT_COMPAT − Default. Encodes only double quotesENT_QUOTES − Encodes double and single quotesENT_NOQUOTES − Does not encode any quotes"
},
{
"code": null,
"e": 1833,
"s": 1786,
"text": "The following are the available quote styles −"
},
{
"code": null,
"e": 1883,
"s": 1833,
"text": "ENT_COMPAT − Default. Encodes only double quotes"
},
{
"code": null,
"e": 1933,
"s": 1883,
"text": "ENT_COMPAT − Default. Encodes only double quotes"
},
{
"code": null,
"e": 1980,
"s": 1933,
"text": "ENT_QUOTES − Encodes double and single quotes"
},
{
"code": null,
"e": 2027,
"s": 1980,
"text": "ENT_QUOTES − Encodes double and single quotes"
},
{
"code": null,
"e": 2070,
"s": 2027,
"text": "ENT_NOQUOTES − Does not encode any quotes"
},
{
"code": null,
"e": 2113,
"s": 2070,
"text": "ENT_NOQUOTES − Does not encode any quotes"
},
{
"code": null,
"e": 2599,
"s": 2113,
"text": "Invalid encoding −ENT_IGNORE − Ignores invalid encoding instead of having the function return an empty string. Should be avoided, as it may have security implications.ENT_SUBSTITUTE − Replaces invalid encoding for a specified character set with a Unicode Replacement Character U+FFFD (UTF-8) or &#FFFD; instead of returning an empty string.ENT_DISALLOWED − Replaces code points that are invalid in the specified doctype with a Unicode Replacement Character U+FFFD (UTF-8) or &#FFFD;"
},
{
"code": null,
"e": 2618,
"s": 2599,
"text": "Invalid encoding −"
},
{
"code": null,
"e": 2769,
"s": 2618,
"text": "ENT_IGNORE − Ignores invalid encoding instead of having the function return an empty string. Should be avoided, as it may have security implications."
},
{
"code": null,
"e": 2920,
"s": 2769,
"text": "ENT_IGNORE − Ignores invalid encoding instead of having the function return an empty string. Should be avoided, as it may have security implications."
},
{
"code": null,
"e": 3095,
"s": 2920,
"text": "ENT_SUBSTITUTE − Replaces invalid encoding for a specified character set with a Unicode Replacement Character U+FFFD (UTF-8) or &#FFFD; instead of returning an empty string."
},
{
"code": null,
"e": 3270,
"s": 3095,
"text": "ENT_SUBSTITUTE − Replaces invalid encoding for a specified character set with a Unicode Replacement Character U+FFFD (UTF-8) or &#FFFD; instead of returning an empty string."
},
{
"code": null,
"e": 3414,
"s": 3270,
"text": "ENT_DISALLOWED − Replaces code points that are invalid in the specified doctype with a Unicode Replacement Character U+FFFD (UTF-8) or &#FFFD;"
},
{
"code": null,
"e": 3558,
"s": 3414,
"text": "ENT_DISALLOWED − Replaces code points that are invalid in the specified doctype with a Unicode Replacement Character U+FFFD (UTF-8) or &#FFFD;"
},
{
"code": null,
"e": 3778,
"s": 3558,
"text": "The following are the additional flags for specifying the used doctype −ENT_HTML401 − Default. Handle code as HTML 4.01ENT_HTML5 − Handle code as HTML 5ENT_XML1 − Handle code as XML 1ENT_XHTML − Handle code as XHTML"
},
{
"code": null,
"e": 3851,
"s": 3778,
"text": "The following are the additional flags for specifying the used doctype −"
},
{
"code": null,
"e": 3900,
"s": 3851,
"text": "ENT_HTML401 − Default. Handle code as HTML 4.01"
},
{
"code": null,
"e": 3949,
"s": 3900,
"text": "ENT_HTML401 − Default. Handle code as HTML 4.01"
},
{
"code": null,
"e": 3984,
"s": 3949,
"text": "ENT_HTML5 − Handle code as HTML 5"
},
{
"code": null,
"e": 4019,
"s": 3984,
"text": "ENT_HTML5 − Handle code as HTML 5"
},
{
"code": null,
"e": 4052,
"s": 4019,
"text": "ENT_XML1 − Handle code as XML 1"
},
{
"code": null,
"e": 4085,
"s": 4052,
"text": "ENT_XML1 − Handle code as XML 1"
},
{
"code": null,
"e": 4119,
"s": 4085,
"text": "ENT_XHTML − Handle code as XHTML"
},
{
"code": null,
"e": 4153,
"s": 4119,
"text": "ENT_XHTML − Handle code as XHTML"
},
{
"code": null,
"e": 4194,
"s": 4153,
"text": "character-set − The character-set to use"
},
{
"code": null,
"e": 4235,
"s": 4194,
"text": "character-set − The character-set to use"
},
{
"code": null,
"e": 4866,
"s": 4235,
"text": "The following are the allowed values are −UTF-8 − Default. ASCII compatible multi-byte 8-bit UnicodeISO-8859-1 − Western EuropeanISO-8859-15 − Western European (adds the Euro sign + French and Finnish letters missing in ISO-8859-1)cp866 − DOS-specific Cyrillic charsetcp1251 − Windows-specific Cyrillic charsetcp1252 − Windows specific charset for Western EuropeanKOI8-R − RussianBIG5 − Traditional Chinese, mainly used in TaiwanGB2312 − Simplified Chinese, national standard character setBIG5-HKSCS − Big5 with Hong Kong extensionsShift_JIS − JapaneseEUC-JP − JapaneseMacRoman − Character-set that was used by Mac OS"
},
{
"code": null,
"e": 4909,
"s": 4866,
"text": "The following are the allowed values are −"
},
{
"code": null,
"e": 4969,
"s": 4909,
"text": "UTF-8 − Default. ASCII compatible multi-byte 8-bit Unicode"
},
{
"code": null,
"e": 5029,
"s": 4969,
"text": "UTF-8 − Default. ASCII compatible multi-byte 8-bit Unicode"
},
{
"code": null,
"e": 5060,
"s": 5029,
"text": "ISO-8859-1 − Western European"
},
{
"code": null,
"e": 5091,
"s": 5060,
"text": "ISO-8859-1 − Western European"
},
{
"code": null,
"e": 5195,
"s": 5091,
"text": "ISO-8859-15 − Western European (adds the Euro sign + French and Finnish letters missing in ISO-8859-1)"
},
{
"code": null,
"e": 5299,
"s": 5195,
"text": "ISO-8859-15 − Western European (adds the Euro sign + French and Finnish letters missing in ISO-8859-1)"
},
{
"code": null,
"e": 5338,
"s": 5299,
"text": "cp866 − DOS-specific Cyrillic charset"
},
{
"code": null,
"e": 5377,
"s": 5338,
"text": "cp866 − DOS-specific Cyrillic charset"
},
{
"code": null,
"e": 5421,
"s": 5377,
"text": "cp1251 − Windows-specific Cyrillic charset"
},
{
"code": null,
"e": 5465,
"s": 5421,
"text": "cp1251 − Windows-specific Cyrillic charset"
},
{
"code": null,
"e": 5521,
"s": 5465,
"text": "cp1252 − Windows specific charset for Western European"
},
{
"code": null,
"e": 5577,
"s": 5521,
"text": "cp1252 − Windows specific charset for Western European"
},
{
"code": null,
"e": 5595,
"s": 5577,
"text": "KOI8-R − Russian"
},
{
"code": null,
"e": 5613,
"s": 5595,
"text": "KOI8-R − Russian"
},
{
"code": null,
"e": 5664,
"s": 5613,
"text": "BIG5 − Traditional Chinese, mainly used in Taiwan"
},
{
"code": null,
"e": 5715,
"s": 5664,
"text": "BIG5 − Traditional Chinese, mainly used in Taiwan"
},
{
"code": null,
"e": 5777,
"s": 5715,
"text": "GB2312 − Simplified Chinese, national standard character set"
},
{
"code": null,
"e": 5839,
"s": 5777,
"text": "GB2312 − Simplified Chinese, national standard character set"
},
{
"code": null,
"e": 5884,
"s": 5839,
"text": "BIG5-HKSCS − Big5 with Hong Kong extensions"
},
{
"code": null,
"e": 5929,
"s": 5884,
"text": "BIG5-HKSCS − Big5 with Hong Kong extensions"
},
{
"code": null,
"e": 5951,
"s": 5929,
"text": "Shift_JIS − Japanese"
},
{
"code": null,
"e": 5973,
"s": 5951,
"text": "Shift_JIS − Japanese"
},
{
"code": null,
"e": 5992,
"s": 5973,
"text": "EUC-JP − Japanese"
},
{
"code": null,
"e": 6011,
"s": 5992,
"text": "EUC-JP − Japanese"
},
{
"code": null,
"e": 6061,
"s": 6011,
"text": "MacRoman − Character-set that was used by Mac OS"
},
{
"code": null,
"e": 6111,
"s": 6061,
"text": "MacRoman − Character-set that was used by Mac OS"
},
{
"code": null,
"e": 6294,
"s": 6111,
"text": "double_encode − A boolean value that specifies whether to encode existing html entities or not.TRUE − Default. Will convert everythingFALSE − Will not encode existing html entities"
},
{
"code": null,
"e": 6390,
"s": 6294,
"text": "double_encode − A boolean value that specifies whether to encode existing html entities or not."
},
{
"code": null,
"e": 6431,
"s": 6390,
"text": "TRUE − Default. Will convert everything"
},
{
"code": null,
"e": 6472,
"s": 6431,
"text": "TRUE − Default. Will convert everything"
},
{
"code": null,
"e": 6520,
"s": 6472,
"text": "FALSE − Will not encode existing html entities"
},
{
"code": null,
"e": 6568,
"s": 6520,
"text": "FALSE − Will not encode existing html entities"
},
{
"code": null,
"e": 6630,
"s": 6568,
"text": "The htmlspecialchars() function returns the converted string."
},
{
"code": null,
"e": 6660,
"s": 6630,
"text": "The following is an example −"
},
{
"code": null,
"e": 6671,
"s": 6660,
"text": " Live Demo"
},
{
"code": null,
"e": 6791,
"s": 6671,
"text": "<?php\n$res = htmlspecialchars(\"<a href='mylink' rel=”nofollow”><strong>Demo</strong></a>\", ENT_QUOTES);\necho $res //\n?>"
},
{
"code": null,
"e": 6891,
"s": 6791,
"text": "& lt;a href=& #039;mylink& #039; rel=”nofollow”& gt;& lt;strong& gt;Demo& lt;/strong& gt;& lt;/a >\n"
}
] |
Creating a Priority Queue using Javascript
|
Our class will have the following functions −
enqueue(element): Function to add an element in the queue.
dequeue(): Function that removes an element from the queue.
peek(): Returns the element from the front of the queue.
isFull(): Checks if we reached the element limit on the queue.
isEmpty(): checks if the queue is empty.
clear(): Remove all elements.
display(): display all contents of the array
Let's start by defining a simple class with a constructor that takes the max size of the queue and a helper function that'll help us when we implement the other functions for this class. We'll also have to define another structure as part of the PriorityQueue class prototype that'll have the priority and data about each node. As we implemented stacks, we'll implement Priority Queue using Arrays as well.
class PriorityQueue {
constructor(maxSize) {
// Set default max size if not provided
if (isNaN(maxSize)) {
maxSize = 10;
}
this.maxSize = maxSize;
// Init an array that'll contain the queue values.
this.container = [];
}
// Helper function to display all values while developing
display() {
console.log(this.container);
}
// Checks if queue is empty
isEmpty() {
return this.container.length === 0;
}
// checks if queue is full
isFull() {
return this.container.length >= this.maxSize;
}
}
// Create an inner class that we'll use to create new nodes in the queue
// Each element has some data and a priority
PriorityQueue.prototype.Element = class {
constructor (data, priority) {
this.data = data; this.priority = priority;
}
}
We have also defined 2 more functions, isFull and isEmpty to check if the stack is full or empty.
The isFull function just checks if the length of the container is equal to or more than maxSize and returns accordingly.
The isEmpty function checks if the size of the container is 0.
These will be helpful when we define other operations. The functions we define from this point onwards will all go into the PriorityQueue class.
|
[
{
"code": null,
"e": 1108,
"s": 1062,
"text": "Our class will have the following functions −"
},
{
"code": null,
"e": 1167,
"s": 1108,
"text": "enqueue(element): Function to add an element in the queue."
},
{
"code": null,
"e": 1227,
"s": 1167,
"text": "dequeue(): Function that removes an element from the queue."
},
{
"code": null,
"e": 1284,
"s": 1227,
"text": "peek(): Returns the element from the front of the queue."
},
{
"code": null,
"e": 1347,
"s": 1284,
"text": "isFull(): Checks if we reached the element limit on the queue."
},
{
"code": null,
"e": 1388,
"s": 1347,
"text": "isEmpty(): checks if the queue is empty."
},
{
"code": null,
"e": 1418,
"s": 1388,
"text": "clear(): Remove all elements."
},
{
"code": null,
"e": 1463,
"s": 1418,
"text": "display(): display all contents of the array"
},
{
"code": null,
"e": 1871,
"s": 1463,
"text": "Let's start by defining a simple class with a constructor that takes the max size of the queue and a helper function that'll help us when we implement the other functions for this class. We'll also have to define another structure as part of the PriorityQueue class prototype that'll have the priority and data about each node. As we implemented stacks, we'll implement Priority Queue using Arrays as well. "
},
{
"code": null,
"e": 2706,
"s": 1871,
"text": "class PriorityQueue {\n constructor(maxSize) {\n // Set default max size if not provided\n if (isNaN(maxSize)) {\n maxSize = 10;\n }\n this.maxSize = maxSize;\n // Init an array that'll contain the queue values.\n this.container = [];\n }\n // Helper function to display all values while developing\n display() {\n console.log(this.container);\n }\n // Checks if queue is empty\n isEmpty() {\n return this.container.length === 0;\n }\n // checks if queue is full\n isFull() {\n return this.container.length >= this.maxSize;\n }\n}\n// Create an inner class that we'll use to create new nodes in the queue\n// Each element has some data and a priority\nPriorityQueue.prototype.Element = class {\n constructor (data, priority) {\n this.data = data; this.priority = priority;\n }\n}"
},
{
"code": null,
"e": 2804,
"s": 2706,
"text": "We have also defined 2 more functions, isFull and isEmpty to check if the stack is full or empty."
},
{
"code": null,
"e": 2925,
"s": 2804,
"text": "The isFull function just checks if the length of the container is equal to or more than maxSize and returns accordingly."
},
{
"code": null,
"e": 2988,
"s": 2925,
"text": "The isEmpty function checks if the size of the container is 0."
},
{
"code": null,
"e": 3133,
"s": 2988,
"text": "These will be helpful when we define other operations. The functions we define from this point onwards will all go into the PriorityQueue class."
}
] |
How to find the index of an item in a C# list in a single step?
|
To get the index of an item in a single line, use the FindIndex() and Contains() method.
int index = myList.FindIndex(a => a.Contains("Tennis"));
Above, we got the index of an element using the FindIndex(), which is assisted by Contains method for that specific element.
Here is the complete code −
Live Demo
using System;
using System.Collections.Generic;
public class Program {
public static void Main() {
List < string > myList = new List < string > () {
"Football",
"Soccer",
"Tennis",
};
// finding index
int index = myList.FindIndex(a => a.Contains("Tennis"));
// displaying index
Console.WriteLine("List Item Tennis Found at index: " + index);
}
}
List Item Tennis Found at index: 2
|
[
{
"code": null,
"e": 1151,
"s": 1062,
"text": "To get the index of an item in a single line, use the FindIndex() and Contains() method."
},
{
"code": null,
"e": 1208,
"s": 1151,
"text": "int index = myList.FindIndex(a => a.Contains(\"Tennis\"));"
},
{
"code": null,
"e": 1333,
"s": 1208,
"text": "Above, we got the index of an element using the FindIndex(), which is assisted by Contains method for that specific element."
},
{
"code": null,
"e": 1361,
"s": 1333,
"text": "Here is the complete code −"
},
{
"code": null,
"e": 1372,
"s": 1361,
"text": " Live Demo"
},
{
"code": null,
"e": 1789,
"s": 1372,
"text": "using System;\nusing System.Collections.Generic;\npublic class Program {\n public static void Main() {\n List < string > myList = new List < string > () {\n \"Football\",\n \"Soccer\",\n \"Tennis\",\n };\n\n // finding index\n int index = myList.FindIndex(a => a.Contains(\"Tennis\"));\n\n // displaying index\n Console.WriteLine(\"List Item Tennis Found at index: \" + index);\n }\n}"
},
{
"code": null,
"e": 1824,
"s": 1789,
"text": "List Item Tennis Found at index: 2"
}
] |
Check for Valid hex code - JavaScript
|
A string can be considered as a valid hex code if it contains no characters other than the 0-9 and a-f alphabets
For example −
'3423ad' is a valid hex code
'4234es' is an invalid hex code
We are required to write a JavaScript function that takes in a string and checks whether its a valid hex code or not.
Following is the code −
const str1 = '4234es';
const str2 = '3423ad';
const isHexValid = str => {
const legend = '0123456789abcdef';
for(let i = 0; i < str.length; i++){
if(legend.includes(str[i])){
continue;
};
return false;
};
return true;
};
console.log(isHexValid(str1));
console.log(isHexValid(str2));
Following is the output in the console −
false
true
|
[
{
"code": null,
"e": 1175,
"s": 1062,
"text": "A string can be considered as a valid hex code if it contains no characters other than the 0-9 and a-f alphabets"
},
{
"code": null,
"e": 1189,
"s": 1175,
"text": "For example −"
},
{
"code": null,
"e": 1250,
"s": 1189,
"text": "'3423ad' is a valid hex code\n'4234es' is an invalid hex code"
},
{
"code": null,
"e": 1368,
"s": 1250,
"text": "We are required to write a JavaScript function that takes in a string and checks whether its a valid hex code or not."
},
{
"code": null,
"e": 1392,
"s": 1368,
"text": "Following is the code −"
},
{
"code": null,
"e": 1714,
"s": 1392,
"text": "const str1 = '4234es';\nconst str2 = '3423ad';\nconst isHexValid = str => {\n const legend = '0123456789abcdef';\n for(let i = 0; i < str.length; i++){\n if(legend.includes(str[i])){\n continue;\n };\n return false;\n };\n return true;\n};\nconsole.log(isHexValid(str1));\nconsole.log(isHexValid(str2));"
},
{
"code": null,
"e": 1755,
"s": 1714,
"text": "Following is the output in the console −"
},
{
"code": null,
"e": 1766,
"s": 1755,
"text": "false\ntrue"
}
] |
Class Binding in Angular 8
|
23 Sep, 2020
Class binding in Angular makes it very easy to set the class property of a view element. We can set or remove the CSS class names from an element’s class attribute with the help of class binding.
We bind a class of a DOM element to a field that is a defined property in our Typescript Code. Its syntax is like that of property binding.
Syntax:
<element [class] = "typescript_property">
Approach:
Define a property element in the app.component.ts file.
In the app.component.html file, set the class of the HTML element by assigning the property value to the app.component.ts file’s element.
Example 1: Setting the class element using class binding.
app.component.html
HTML
<h1 [class] = "geeky"> GeeksforGeeks</h1>Upper Heading's class is : "{{ g[0].className }}"
app.component.ts
Javascript
import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html'})export class AppComponent { geeky = "GeekClass"; g = document.getElementsByClassName(this.geeky);}
Output:
Example 2: setting the class element using a function.
app.component.html
HTML
<h1 [class] = "setClass()"> GeeksforGeeks</h1>Upper Heading's class is : "{{ g[0].className }}"
app.component.ts
Javascript
import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html'})export class AppComponent { setClass() { return "GeeksforGeeks"; } g = document.getElementsByClassName(this.setClass());}
Output:
AngularJS-Misc
Picked
AngularJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to bundle an Angular app for production?
How to create button dynamically with click event in Angular ?
Difference between One-way Binding and Two-way Binding
How to detect click event outside Angular component ?
Define ng-if, ng-show and ng-hide
How to insert spaces/tabs in text using HTML/CSS?
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Node.js fs.readFileSync() Method
How to set the default value for an HTML <select> element ?
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n23 Sep, 2020"
},
{
"code": null,
"e": 224,
"s": 28,
"text": "Class binding in Angular makes it very easy to set the class property of a view element. We can set or remove the CSS class names from an element’s class attribute with the help of class binding."
},
{
"code": null,
"e": 364,
"s": 224,
"text": "We bind a class of a DOM element to a field that is a defined property in our Typescript Code. Its syntax is like that of property binding."
},
{
"code": null,
"e": 372,
"s": 364,
"text": "Syntax:"
},
{
"code": null,
"e": 415,
"s": 372,
"text": "<element [class] = \"typescript_property\">\n"
},
{
"code": null,
"e": 425,
"s": 415,
"text": "Approach:"
},
{
"code": null,
"e": 481,
"s": 425,
"text": "Define a property element in the app.component.ts file."
},
{
"code": null,
"e": 619,
"s": 481,
"text": "In the app.component.html file, set the class of the HTML element by assigning the property value to the app.component.ts file’s element."
},
{
"code": null,
"e": 677,
"s": 619,
"text": "Example 1: Setting the class element using class binding."
},
{
"code": null,
"e": 696,
"s": 677,
"text": "app.component.html"
},
{
"code": null,
"e": 701,
"s": 696,
"text": "HTML"
},
{
"code": "<h1 [class] = \"geeky\"> GeeksforGeeks</h1>Upper Heading's class is : \"{{ g[0].className }}\"",
"e": 793,
"s": 701,
"text": null
},
{
"code": null,
"e": 810,
"s": 793,
"text": "app.component.ts"
},
{
"code": null,
"e": 821,
"s": 810,
"text": "Javascript"
},
{
"code": "import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html'})export class AppComponent { geeky = \"GeekClass\"; g = document.getElementsByClassName(this.geeky);}",
"e": 1056,
"s": 821,
"text": null
},
{
"code": null,
"e": 1064,
"s": 1056,
"text": "Output:"
},
{
"code": null,
"e": 1119,
"s": 1064,
"text": "Example 2: setting the class element using a function."
},
{
"code": null,
"e": 1138,
"s": 1119,
"text": "app.component.html"
},
{
"code": null,
"e": 1143,
"s": 1138,
"text": "HTML"
},
{
"code": "<h1 [class] = \"setClass()\"> GeeksforGeeks</h1>Upper Heading's class is : \"{{ g[0].className }}\"",
"e": 1240,
"s": 1143,
"text": null
},
{
"code": null,
"e": 1257,
"s": 1240,
"text": "app.component.ts"
},
{
"code": null,
"e": 1268,
"s": 1257,
"text": "Javascript"
},
{
"code": "import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html'})export class AppComponent { setClass() { return \"GeeksforGeeks\"; } g = document.getElementsByClassName(this.setClass());}",
"e": 1536,
"s": 1268,
"text": null
},
{
"code": null,
"e": 1544,
"s": 1536,
"text": "Output:"
},
{
"code": null,
"e": 1559,
"s": 1544,
"text": "AngularJS-Misc"
},
{
"code": null,
"e": 1566,
"s": 1559,
"text": "Picked"
},
{
"code": null,
"e": 1576,
"s": 1566,
"text": "AngularJS"
},
{
"code": null,
"e": 1593,
"s": 1576,
"text": "Web Technologies"
},
{
"code": null,
"e": 1691,
"s": 1593,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1736,
"s": 1691,
"text": "How to bundle an Angular app for production?"
},
{
"code": null,
"e": 1799,
"s": 1736,
"text": "How to create button dynamically with click event in Angular ?"
},
{
"code": null,
"e": 1854,
"s": 1799,
"text": "Difference between One-way Binding and Two-way Binding"
},
{
"code": null,
"e": 1908,
"s": 1854,
"text": "How to detect click event outside Angular component ?"
},
{
"code": null,
"e": 1942,
"s": 1908,
"text": "Define ng-if, ng-show and ng-hide"
},
{
"code": null,
"e": 1992,
"s": 1942,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
},
{
"code": null,
"e": 2025,
"s": 1992,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 2087,
"s": 2025,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 2120,
"s": 2087,
"text": "Node.js fs.readFileSync() Method"
}
] |
Sparta Tool in Kali Linux
|
06 Jan, 2021
Information Gathering is a very important step before starting penetration testing. Mostly, Pen Testers begin their work by collecting information and this requires a lot of patience and effort. The information Gathering category has many tools that work differently, but the sole purpose is to gather information. The major tools are MSFConsole, dnsenum, dnmap, dnsmap, DNSRecon, dnswalk, dnstracer, Miranda, Fierce, Firewalk, SPARTA, hping3, iSMTP, Maltego Teeth, masscan, Faraday, DMitry, nbtstat nbtscan, Nikto, Nmap, Ghost Phisher, theHarvester, and many more. In this article, we will only study the tool Sparta.
Vulnerability Analysis: You can perform vulnerability analysis with lots of tools available in Kali Linux. This category has a few subcategories such as Cisco tools, stress testing, fuzzing tools, and others. The major tools are Sparta, BED, BBQSQL, cisco-global- exploiter, cisco-auditing-tool, cisco-ocs, cisco-torch, copy-router-config, DBPwAudit, jSQL Injection, Nmap, Oscanner, openvas, Powerfuzzer, sfuzz, SidGuesser, SIPArmyKnife, sqlmap, Sqlninja, sqlsus, THC-IPV6, Yersini, and many more.
Sparta: Sparta is a python GUI application that automates scanning, vulnerability assessment, and information gathering. It allows the tester to save a lot of time by having quick and direct access to their toolkit, and it can display the output of various tools in a very easy way.
Installing Sparta: You don’t have to install Sparta in Kali Linux as Sparta is pre-installed in most versions of Kali Linux. If you are using the Light version of Kali then install Sparta by following the below command.
apt-get update && apt-get install sparta python-requests
After the complete execution of the above command, you can start the Sparta tool from any terminal with the “Sparta” command. If you are using Kali Linux 2020.1 or up. Then instead of Sparta, Kali Linux comes with the Legion, fork version of Sparta with improved features. We will learn about Legion in another article.
sparta
Scan Networks and Web Apps with Sparta: Sparta can be used to scan a range of IP addresses on a network and website domain names. Once you know the range of IP addresses on the network or about the web app you want to check, click on the “Click here to add a host(s) to scope” option available under the “Scan” tab. If you want to scan a web app instead, enter its URL or IP address. Hit the “Add to Scope” option when ready to scan.
Analyze the Results: Once the scanning of a web app is done, you can see various services reported within seconds of the scan. The thing to notice in this web app is that SSH service is on port 22222. There is very little chance that the administrator changed the default SSH port from 22. This attempt of hiding the SSH service is called “security through obscurity” and is considered a bad security practice. The administrator believes that changing the port number to something non-standard will make it harder for the hackers or attackers to find the service. As we can now understand that this is not true — Sparta still detected the SSH service in its scanning.
If you want to perform more actions, simply right-click on the service. You’ll have a list of options in front of you to perform.
Portscan
Send to Brute
Grab banner
Mark as checked
Open with telnet
Run nikto
Open with netcat
Launch dirbuster
Open in browser
Take screenshot
Run whatweb
Run nmap (scripts) on port
Launch webslayer
Open with ssh client (as root)
Saving Your Sparta Progress: In Sparta, click “File” in the menu bar, then “Save As.” Select a save location, name it, and click “Save”. The saved results can be re-opened in Sparta whenever you want to.
Kali-Linux
Technical Scripter 2020
Linux-Unix
Technical Scripter
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
Introduction to Linux Operating System
Array Basics in Shell Scripting | Set 1
nohup Command in Linux with Examples
chmod command in Linux with examples
mv command in Linux with examples
Basic Operators in Shell Scripting
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n06 Jan, 2021"
},
{
"code": null,
"e": 647,
"s": 28,
"text": "Information Gathering is a very important step before starting penetration testing. Mostly, Pen Testers begin their work by collecting information and this requires a lot of patience and effort. The information Gathering category has many tools that work differently, but the sole purpose is to gather information. The major tools are MSFConsole, dnsenum, dnmap, dnsmap, DNSRecon, dnswalk, dnstracer, Miranda, Fierce, Firewalk, SPARTA, hping3, iSMTP, Maltego Teeth, masscan, Faraday, DMitry, nbtstat nbtscan, Nikto, Nmap, Ghost Phisher, theHarvester, and many more. In this article, we will only study the tool Sparta."
},
{
"code": null,
"e": 1145,
"s": 647,
"text": "Vulnerability Analysis: You can perform vulnerability analysis with lots of tools available in Kali Linux. This category has a few subcategories such as Cisco tools, stress testing, fuzzing tools, and others. The major tools are Sparta, BED, BBQSQL, cisco-global- exploiter, cisco-auditing-tool, cisco-ocs, cisco-torch, copy-router-config, DBPwAudit, jSQL Injection, Nmap, Oscanner, openvas, Powerfuzzer, sfuzz, SidGuesser, SIPArmyKnife, sqlmap, Sqlninja, sqlsus, THC-IPV6, Yersini, and many more."
},
{
"code": null,
"e": 1429,
"s": 1145,
"text": "Sparta: Sparta is a python GUI application that automates scanning, vulnerability assessment, and information gathering. It allows the tester to save a lot of time by having quick and direct access to their toolkit, and it can display the output of various tools in a very easy way. "
},
{
"code": null,
"e": 1649,
"s": 1429,
"text": "Installing Sparta: You don’t have to install Sparta in Kali Linux as Sparta is pre-installed in most versions of Kali Linux. If you are using the Light version of Kali then install Sparta by following the below command."
},
{
"code": null,
"e": 1706,
"s": 1649,
"text": "apt-get update && apt-get install sparta python-requests"
},
{
"code": null,
"e": 2027,
"s": 1706,
"text": "After the complete execution of the above command, you can start the Sparta tool from any terminal with the “Sparta” command. If you are using Kali Linux 2020.1 or up. Then instead of Sparta, Kali Linux comes with the Legion, fork version of Sparta with improved features. We will learn about Legion in another article. "
},
{
"code": null,
"e": 2034,
"s": 2027,
"text": "sparta"
},
{
"code": null,
"e": 2468,
"s": 2034,
"text": "Scan Networks and Web Apps with Sparta: Sparta can be used to scan a range of IP addresses on a network and website domain names. Once you know the range of IP addresses on the network or about the web app you want to check, click on the “Click here to add a host(s) to scope” option available under the “Scan” tab. If you want to scan a web app instead, enter its URL or IP address. Hit the “Add to Scope” option when ready to scan."
},
{
"code": null,
"e": 3136,
"s": 2468,
"text": "Analyze the Results: Once the scanning of a web app is done, you can see various services reported within seconds of the scan. The thing to notice in this web app is that SSH service is on port 22222. There is very little chance that the administrator changed the default SSH port from 22. This attempt of hiding the SSH service is called “security through obscurity” and is considered a bad security practice. The administrator believes that changing the port number to something non-standard will make it harder for the hackers or attackers to find the service. As we can now understand that this is not true — Sparta still detected the SSH service in its scanning."
},
{
"code": null,
"e": 3267,
"s": 3136,
"text": " If you want to perform more actions, simply right-click on the service. You’ll have a list of options in front of you to perform."
},
{
"code": null,
"e": 3276,
"s": 3267,
"text": "Portscan"
},
{
"code": null,
"e": 3290,
"s": 3276,
"text": "Send to Brute"
},
{
"code": null,
"e": 3302,
"s": 3290,
"text": "Grab banner"
},
{
"code": null,
"e": 3318,
"s": 3302,
"text": "Mark as checked"
},
{
"code": null,
"e": 3335,
"s": 3318,
"text": "Open with telnet"
},
{
"code": null,
"e": 3345,
"s": 3335,
"text": "Run nikto"
},
{
"code": null,
"e": 3362,
"s": 3345,
"text": "Open with netcat"
},
{
"code": null,
"e": 3379,
"s": 3362,
"text": "Launch dirbuster"
},
{
"code": null,
"e": 3395,
"s": 3379,
"text": "Open in browser"
},
{
"code": null,
"e": 3411,
"s": 3395,
"text": "Take screenshot"
},
{
"code": null,
"e": 3423,
"s": 3411,
"text": "Run whatweb"
},
{
"code": null,
"e": 3450,
"s": 3423,
"text": "Run nmap (scripts) on port"
},
{
"code": null,
"e": 3467,
"s": 3450,
"text": "Launch webslayer"
},
{
"code": null,
"e": 3498,
"s": 3467,
"text": "Open with ssh client (as root)"
},
{
"code": null,
"e": 3702,
"s": 3498,
"text": "Saving Your Sparta Progress: In Sparta, click “File” in the menu bar, then “Save As.” Select a save location, name it, and click “Save”. The saved results can be re-opened in Sparta whenever you want to."
},
{
"code": null,
"e": 3713,
"s": 3702,
"text": "Kali-Linux"
},
{
"code": null,
"e": 3737,
"s": 3713,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 3748,
"s": 3737,
"text": "Linux-Unix"
},
{
"code": null,
"e": 3767,
"s": 3748,
"text": "Technical Scripter"
},
{
"code": null,
"e": 3865,
"s": 3767,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3891,
"s": 3865,
"text": "Docker - COPY Instruction"
},
{
"code": null,
"e": 3926,
"s": 3891,
"text": "scp command in Linux with Examples"
},
{
"code": null,
"e": 3963,
"s": 3926,
"text": "chown command in Linux with Examples"
},
{
"code": null,
"e": 3992,
"s": 3963,
"text": "SED command in Linux | Set 2"
},
{
"code": null,
"e": 4031,
"s": 3992,
"text": "Introduction to Linux Operating System"
},
{
"code": null,
"e": 4071,
"s": 4031,
"text": "Array Basics in Shell Scripting | Set 1"
},
{
"code": null,
"e": 4108,
"s": 4071,
"text": "nohup Command in Linux with Examples"
},
{
"code": null,
"e": 4145,
"s": 4108,
"text": "chmod command in Linux with examples"
},
{
"code": null,
"e": 4179,
"s": 4145,
"text": "mv command in Linux with examples"
}
] |
Python program to check if a word is a noun
|
11 Dec, 2020
Given a word, the task is to write a Python program to find if the word is a noun or not using Python.
Examples:
Input: India
Output: India is noun.
Input: Writing
Output: Writing is not a noun.
There are various libraries that can be used to solve this problem.
Approach 1: PoS tagging using NLTK
Python3
# import required modulesimport nltknltk.download('averaged_perceptron_tagger') # taking input text as Indiatext = "India"ans = nltk.pos_tag() # ans returns a list of tupleval = ans[0][1] # checking if it is a noun or notif(val == 'NN' or val == 'NNS' or val == 'NNPS' or val == 'NNP'): print(text, " is a noun.")else: print(text, " is not a noun.")
Output:
India is a noun.
Approach 2: PoS tagging using Spacy
Python3
# import required modulesimport spacynlp = spacy.load("en_core_web_sm") # taking inputtext = "Writing" # returns a document of objectdoc = nlp(text) # checking if it is a noun or notif(doc[0].tag_ == 'NNP'): print(text, " is a noun.")else: print(text, " is not a noun.")
Output:
Writing is not a noun.
Python string-programs
Technical Scripter 2020
Python
Python Programs
Technical Scripter
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
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python | Convert string dictionary to dictionary
Python Program for Fibonacci numbers
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n11 Dec, 2020"
},
{
"code": null,
"e": 131,
"s": 28,
"text": "Given a word, the task is to write a Python program to find if the word is a noun or not using Python."
},
{
"code": null,
"e": 141,
"s": 131,
"text": "Examples:"
},
{
"code": null,
"e": 224,
"s": 141,
"text": "Input: India\nOutput: India is noun.\n\nInput: Writing\nOutput: Writing is not a noun."
},
{
"code": null,
"e": 292,
"s": 224,
"text": "There are various libraries that can be used to solve this problem."
},
{
"code": null,
"e": 327,
"s": 292,
"text": "Approach 1: PoS tagging using NLTK"
},
{
"code": null,
"e": 335,
"s": 327,
"text": "Python3"
},
{
"code": "# import required modulesimport nltknltk.download('averaged_perceptron_tagger') # taking input text as Indiatext = \"India\"ans = nltk.pos_tag() # ans returns a list of tupleval = ans[0][1] # checking if it is a noun or notif(val == 'NN' or val == 'NNS' or val == 'NNPS' or val == 'NNP'): print(text, \" is a noun.\")else: print(text, \" is not a noun.\")",
"e": 694,
"s": 335,
"text": null
},
{
"code": null,
"e": 703,
"s": 694,
"text": "Output: "
},
{
"code": null,
"e": 720,
"s": 703,
"text": "India is a noun."
},
{
"code": null,
"e": 756,
"s": 720,
"text": "Approach 2: PoS tagging using Spacy"
},
{
"code": null,
"e": 764,
"s": 756,
"text": "Python3"
},
{
"code": "# import required modulesimport spacynlp = spacy.load(\"en_core_web_sm\") # taking inputtext = \"Writing\" # returns a document of objectdoc = nlp(text) # checking if it is a noun or notif(doc[0].tag_ == 'NNP'): print(text, \" is a noun.\")else: print(text, \" is not a noun.\")",
"e": 1044,
"s": 764,
"text": null
},
{
"code": null,
"e": 1053,
"s": 1044,
"text": "Output: "
},
{
"code": null,
"e": 1076,
"s": 1053,
"text": "Writing is not a noun."
},
{
"code": null,
"e": 1099,
"s": 1076,
"text": "Python string-programs"
},
{
"code": null,
"e": 1123,
"s": 1099,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 1130,
"s": 1123,
"text": "Python"
},
{
"code": null,
"e": 1146,
"s": 1130,
"text": "Python Programs"
},
{
"code": null,
"e": 1165,
"s": 1146,
"text": "Technical Scripter"
},
{
"code": null,
"e": 1263,
"s": 1165,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1295,
"s": 1263,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 1322,
"s": 1295,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 1343,
"s": 1322,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 1366,
"s": 1343,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 1422,
"s": 1366,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 1444,
"s": 1422,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 1483,
"s": 1444,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 1521,
"s": 1483,
"text": "Python | Convert a list to dictionary"
},
{
"code": null,
"e": 1570,
"s": 1521,
"text": "Python | Convert string dictionary to dictionary"
}
] |
How to write Comments in Python3?
|
13 Jun, 2022
Comments are text notes added to the program to provide explanatory information about the source code. They are used in a programming language to document the program and remind programmers of what tricky things they just did with the code and also help the later generation for understanding and maintenance of code. The compiler considers these as non-executable statements. Since comments do not execute, when you run a program you will not see any indication of the comment in the output.
Syntax: The hash(#) symbol denotes the starting of a comment in Python.
# This is a comment in Python
Example:
python3
# This is the syntax of a comment in Pythonprint("GFG") # Comments dont have any effect on the interpreter / output
Output :
GFG
Comments should be made at the same indent as the code it is commenting on.
python3
def GFG(): # Since, this comment is inside a function # It would have indent same as the function body print("GeeksforGeeks") for i in range(1, 2): # Be careful of indentation # This comment is inside the body of for loop print("Welcome to Comments in Python") # This comment is again outside the body# of function so it wont have any indent. print("Hello !!")GFG()
Hello!!
GeeksforGeeks
Welcome to Comments in Python
1. Single-Line Comments: Comments starting with a ‘#’ and whitespace are called single-line comments in Python. These comments can only stretch to a single line and are the only way for comments in Python. e.g.
# This a single line comment.
2. Multi-line (Block) comments: Unlike other programming languages Python doesn’t support multi-line comment blocks out of the box. However we can use consecutive # single-line comments to comment out multiple lines of code. Some examples of block comments-
# This type of comments can serve
# both as a single-line as well
# as multi-line (block) in Python.
3. Inline Style comments: Inline comments occur on the same line of a statement, following the code itself. Generally, inline comments look like this:
x = 3 # This is called an inline comment
a = b + c # Adding value of 'b' and 'c' to 'a'
4. Docstring comments: Python documentation strings (or docstrings) provide a convenient way of associating documentation with Python modules, functions, classes, and methods. It’s specified in source code that is used, like a comment, to document a specific segment of code. Unlike conventional source code comments, the docstring should describe what the function does, not how.
Example:
python3
def my_function(): """Demonstrates docstrings and does nothing really.""" return None print("Using __doc__:")print(my_function.__doc__) print("Using help:")help(my_function)
Output:
Using __doc__:
Demonstrates docstrings and does nothing really.
Using help:
Help on function my_function in module __main__:
my_function()
Demonstrates docstrings and does nothing really.
Planning and reviewing: In the comments, we can write the pseudocode which we planned before writing the source code. Pseudocode is a mixture of natural language and high-level programming language. This helps in reviewing the source code more easily because pseudocode is more understandable than the program.
Example:
python3
# This function is adding two given numbersdef addition(a, b): # storing the sum of given numbers in 'c'. c = a + b # returning the sum here return c # passing the value of a and b to addition()a = 10b = 3sum = addition(a, b) # printing the sum calculated by above functionprint(sum)
Output :
13
Debugging: The brute force method is a common method of debugging. In this approach, print statements are inserted throughout the program to print the intermediate values with the hope that some of the printed values will help to identify the errors. After doing debugging we comment on those print statements. Hence comment is also used for debugging.
python3
a = 12 if(a == 12): print("True") # elif(a == 0): # print("False") else: print("Debugging")
Output :
True
akshaysingh98088
sumitgumber28
jayanth_mkv
python-basics
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 53,
"s": 25,
"text": "\n13 Jun, 2022"
},
{
"code": null,
"e": 546,
"s": 53,
"text": "Comments are text notes added to the program to provide explanatory information about the source code. They are used in a programming language to document the program and remind programmers of what tricky things they just did with the code and also help the later generation for understanding and maintenance of code. The compiler considers these as non-executable statements. Since comments do not execute, when you run a program you will not see any indication of the comment in the output."
},
{
"code": null,
"e": 620,
"s": 546,
"text": "Syntax: The hash(#) symbol denotes the starting of a comment in Python. "
},
{
"code": null,
"e": 650,
"s": 620,
"text": "# This is a comment in Python"
},
{
"code": null,
"e": 659,
"s": 650,
"text": "Example:"
},
{
"code": null,
"e": 667,
"s": 659,
"text": "python3"
},
{
"code": "# This is the syntax of a comment in Pythonprint(\"GFG\") # Comments dont have any effect on the interpreter / output",
"e": 783,
"s": 667,
"text": null
},
{
"code": null,
"e": 794,
"s": 783,
"text": "Output : "
},
{
"code": null,
"e": 798,
"s": 794,
"text": "GFG"
},
{
"code": null,
"e": 874,
"s": 798,
"text": "Comments should be made at the same indent as the code it is commenting on."
},
{
"code": null,
"e": 882,
"s": 874,
"text": "python3"
},
{
"code": "def GFG(): # Since, this comment is inside a function # It would have indent same as the function body print(\"GeeksforGeeks\") for i in range(1, 2): # Be careful of indentation # This comment is inside the body of for loop print(\"Welcome to Comments in Python\") # This comment is again outside the body# of function so it wont have any indent. print(\"Hello !!\")GFG()",
"e": 1270,
"s": 882,
"text": null
},
{
"code": null,
"e": 1322,
"s": 1270,
"text": "Hello!!\nGeeksforGeeks\nWelcome to Comments in Python"
},
{
"code": null,
"e": 1533,
"s": 1322,
"text": "1. Single-Line Comments: Comments starting with a ‘#’ and whitespace are called single-line comments in Python. These comments can only stretch to a single line and are the only way for comments in Python. e.g."
},
{
"code": null,
"e": 1563,
"s": 1533,
"text": "# This a single line comment."
},
{
"code": null,
"e": 1821,
"s": 1563,
"text": "2. Multi-line (Block) comments: Unlike other programming languages Python doesn’t support multi-line comment blocks out of the box. However we can use consecutive # single-line comments to comment out multiple lines of code. Some examples of block comments-"
},
{
"code": null,
"e": 1922,
"s": 1821,
"text": "# This type of comments can serve\n# both as a single-line as well\n# as multi-line (block) in Python."
},
{
"code": null,
"e": 2073,
"s": 1922,
"text": "3. Inline Style comments: Inline comments occur on the same line of a statement, following the code itself. Generally, inline comments look like this:"
},
{
"code": null,
"e": 2172,
"s": 2073,
"text": "x = 3 # This is called an inline comment\n\na = b + c # Adding value of 'b' and 'c' to 'a'"
},
{
"code": null,
"e": 2553,
"s": 2172,
"text": "4. Docstring comments: Python documentation strings (or docstrings) provide a convenient way of associating documentation with Python modules, functions, classes, and methods. It’s specified in source code that is used, like a comment, to document a specific segment of code. Unlike conventional source code comments, the docstring should describe what the function does, not how."
},
{
"code": null,
"e": 2563,
"s": 2553,
"text": "Example: "
},
{
"code": null,
"e": 2571,
"s": 2563,
"text": "python3"
},
{
"code": "def my_function(): \"\"\"Demonstrates docstrings and does nothing really.\"\"\" return None print(\"Using __doc__:\")print(my_function.__doc__) print(\"Using help:\")help(my_function)",
"e": 2753,
"s": 2571,
"text": null
},
{
"code": null,
"e": 2762,
"s": 2753,
"text": "Output: "
},
{
"code": null,
"e": 2955,
"s": 2762,
"text": "Using __doc__:\nDemonstrates docstrings and does nothing really.\nUsing help:\nHelp on function my_function in module __main__:\n\nmy_function()\n Demonstrates docstrings and does nothing really."
},
{
"code": null,
"e": 3267,
"s": 2955,
"text": "Planning and reviewing: In the comments, we can write the pseudocode which we planned before writing the source code. Pseudocode is a mixture of natural language and high-level programming language. This helps in reviewing the source code more easily because pseudocode is more understandable than the program. "
},
{
"code": null,
"e": 3276,
"s": 3267,
"text": "Example:"
},
{
"code": null,
"e": 3284,
"s": 3276,
"text": "python3"
},
{
"code": "# This function is adding two given numbersdef addition(a, b): # storing the sum of given numbers in 'c'. c = a + b # returning the sum here return c # passing the value of a and b to addition()a = 10b = 3sum = addition(a, b) # printing the sum calculated by above functionprint(sum)",
"e": 3578,
"s": 3284,
"text": null
},
{
"code": null,
"e": 3587,
"s": 3578,
"text": "Output :"
},
{
"code": null,
"e": 3590,
"s": 3587,
"text": "13"
},
{
"code": null,
"e": 3943,
"s": 3590,
"text": "Debugging: The brute force method is a common method of debugging. In this approach, print statements are inserted throughout the program to print the intermediate values with the hope that some of the printed values will help to identify the errors. After doing debugging we comment on those print statements. Hence comment is also used for debugging."
},
{
"code": null,
"e": 3951,
"s": 3943,
"text": "python3"
},
{
"code": "a = 12 if(a == 12): print(\"True\") # elif(a == 0): # print(\"False\") else: print(\"Debugging\")",
"e": 4050,
"s": 3951,
"text": null
},
{
"code": null,
"e": 4060,
"s": 4050,
"text": " Output :"
},
{
"code": null,
"e": 4065,
"s": 4060,
"text": "True"
},
{
"code": null,
"e": 4082,
"s": 4065,
"text": "akshaysingh98088"
},
{
"code": null,
"e": 4096,
"s": 4082,
"text": "sumitgumber28"
},
{
"code": null,
"e": 4108,
"s": 4096,
"text": "jayanth_mkv"
},
{
"code": null,
"e": 4122,
"s": 4108,
"text": "python-basics"
},
{
"code": null,
"e": 4129,
"s": 4122,
"text": "Python"
}
] |
Remove All Spaces From a String in SQL Server
|
26 Sep, 2021
There are scenarios of the occurrence of spaces before and after a string and we may need to remove/trim the spaces for our use. Let us see how it is getting handled in SQL Server. Till SQL Server 2016, we have the functions called SQL LTRIM and SQL RTRIM functions. The name itself implies that LTRIM is helpful to remove the leftmost spaces and RTRIM is helpful to remove the rightmost spaces.
From SQL Server 2017 onwards, we have TRIM() function also which trim both leading and trailing characters together with a single function. In this article, let us cover them in detail.
It removes the spaces from the beginning of the string. We may be having spaces before and after the string. By using LTRIM() function, we can remove leftmost spaces. Let us use DATALENGTH() function to calculate data length in bytes before and after using SQL LTRIM function. Combining all these, let us see with the below example
Query:
DECLARE @gfgString VARCHAR(26)=
' GeeksForGeeks ';
SELECT @gfgString as OriginalString,
LTRIM(@gfgString) AS StringAfterLTRIM,
DATALENGTH(@gfgString) AS 'DataLength String (Bytes)',
DATALENGTH(LTRIM(@gfgString)) AS
'DataLength String (Bytes) After LTRIM';
Output:
It removes the spaces from the end(starting from the right side) of the string. We may be having spaces before and after the string. By using RTRIM() function, we can remove the rightmost spaces. Let us use DATALENGTH() function to calculate data length in bytes before and after using SQL RTRIM function. Combining all these, let us see with the below example
Query:
DECLARE @gfgString VARCHAR(26)=
' GeeksForGeeks ';
SELECT @gfgString as OriginalString,
RTRIM(@gfgString) AS StringAfterRTRIM,
DATALENGTH(@gfgString) AS 'DataLength String (Bytes)',
DATALENGTH(RTRIM(@gfgString))
AS 'DataLength String (Bytes) After RTRIM';
Output:
From SQL Server 2017 onwards, we have TRIM() functionality also. It removes the beginning spaces as well as end spaces of the string.
Query:
DECLARE @gfgString VARCHAR(26)=
' GeeksForGeeks ';
SELECT @gfgString as OriginalString,
TRIM(@gfgString) AS StringAfterTRIM,
DATALENGTH(@gfgString) AS 'DataLength String (Bytes)',
DATALENGTH(TRIM(@gfgString))
AS 'DataLength String (Bytes) After TRIM';
Output:
We can use the above 3 functionalities to remove the spaces according to the requirement. Generally, to remove all the spaces means, we need to go for TRIM(). We can use the same to trim the column values also.
Query:
use GEEKSFORGEEKS
SELECT AuthorName, LTRIM(AuthorName) as 'String after LTRIM', RTRIM(AuthorName) as 'String after RTRIM',
TRIM(AuthorName) as 'String after TRIM' FROM Authors;
Output:
SQL Server provides many string manipulation functions and here we have seen LTRIM(), RTRIM(), and TRIM() functions to remove the spaces.
Picked
SQL-Server
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Update Multiple Columns in Single Update Statement in SQL?
Window functions in SQL
SQL | Sub queries in From Clause
What is Temporary Table in SQL?
SQL using Python
SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter
SQL Query to Convert VARCHAR to INT
RANK() Function in SQL Server
SQL Query to Compare Two Dates
How to Write a SQL Query For a Specific Date Range and Date Time?
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n26 Sep, 2021"
},
{
"code": null,
"e": 424,
"s": 28,
"text": "There are scenarios of the occurrence of spaces before and after a string and we may need to remove/trim the spaces for our use. Let us see how it is getting handled in SQL Server. Till SQL Server 2016, we have the functions called SQL LTRIM and SQL RTRIM functions. The name itself implies that LTRIM is helpful to remove the leftmost spaces and RTRIM is helpful to remove the rightmost spaces."
},
{
"code": null,
"e": 610,
"s": 424,
"text": "From SQL Server 2017 onwards, we have TRIM() function also which trim both leading and trailing characters together with a single function. In this article, let us cover them in detail."
},
{
"code": null,
"e": 942,
"s": 610,
"text": "It removes the spaces from the beginning of the string. We may be having spaces before and after the string. By using LTRIM() function, we can remove leftmost spaces. Let us use DATALENGTH() function to calculate data length in bytes before and after using SQL LTRIM function. Combining all these, let us see with the below example"
},
{
"code": null,
"e": 949,
"s": 942,
"text": "Query:"
},
{
"code": null,
"e": 1256,
"s": 949,
"text": "DECLARE @gfgString VARCHAR(26)= \n ' GeeksForGeeks ';\n\nSELECT @gfgString as OriginalString, \n LTRIM(@gfgString) AS StringAfterLTRIM, \n DATALENGTH(@gfgString) AS 'DataLength String (Bytes)', \n DATALENGTH(LTRIM(@gfgString)) AS\n 'DataLength String (Bytes) After LTRIM';"
},
{
"code": null,
"e": 1265,
"s": 1256,
"text": " Output:"
},
{
"code": null,
"e": 1626,
"s": 1265,
"text": "It removes the spaces from the end(starting from the right side) of the string. We may be having spaces before and after the string. By using RTRIM() function, we can remove the rightmost spaces. Let us use DATALENGTH() function to calculate data length in bytes before and after using SQL RTRIM function. Combining all these, let us see with the below example"
},
{
"code": null,
"e": 1633,
"s": 1626,
"text": "Query:"
},
{
"code": null,
"e": 1939,
"s": 1633,
"text": "DECLARE @gfgString VARCHAR(26)=\n ' GeeksForGeeks ';\n\nSELECT @gfgString as OriginalString, \n RTRIM(@gfgString) AS StringAfterRTRIM, \n DATALENGTH(@gfgString) AS 'DataLength String (Bytes)', \n DATALENGTH(RTRIM(@gfgString))\n AS 'DataLength String (Bytes) After RTRIM';"
},
{
"code": null,
"e": 1947,
"s": 1939,
"text": "Output:"
},
{
"code": null,
"e": 2081,
"s": 1947,
"text": "From SQL Server 2017 onwards, we have TRIM() functionality also. It removes the beginning spaces as well as end spaces of the string."
},
{
"code": null,
"e": 2088,
"s": 2081,
"text": "Query:"
},
{
"code": null,
"e": 2390,
"s": 2088,
"text": "DECLARE @gfgString VARCHAR(26)= \n ' GeeksForGeeks ';\nSELECT @gfgString as OriginalString, \n TRIM(@gfgString) AS StringAfterTRIM, \n DATALENGTH(@gfgString) AS 'DataLength String (Bytes)', \n DATALENGTH(TRIM(@gfgString))\n AS 'DataLength String (Bytes) After TRIM';"
},
{
"code": null,
"e": 2398,
"s": 2390,
"text": "Output:"
},
{
"code": null,
"e": 2609,
"s": 2398,
"text": "We can use the above 3 functionalities to remove the spaces according to the requirement. Generally, to remove all the spaces means, we need to go for TRIM(). We can use the same to trim the column values also."
},
{
"code": null,
"e": 2616,
"s": 2609,
"text": "Query:"
},
{
"code": null,
"e": 2794,
"s": 2616,
"text": "use GEEKSFORGEEKS\nSELECT AuthorName, LTRIM(AuthorName) as 'String after LTRIM', RTRIM(AuthorName) as 'String after RTRIM', \nTRIM(AuthorName) as 'String after TRIM' FROM Authors;"
},
{
"code": null,
"e": 2802,
"s": 2794,
"text": "Output:"
},
{
"code": null,
"e": 2940,
"s": 2802,
"text": "SQL Server provides many string manipulation functions and here we have seen LTRIM(), RTRIM(), and TRIM() functions to remove the spaces."
},
{
"code": null,
"e": 2947,
"s": 2940,
"text": "Picked"
},
{
"code": null,
"e": 2958,
"s": 2947,
"text": "SQL-Server"
},
{
"code": null,
"e": 2962,
"s": 2958,
"text": "SQL"
},
{
"code": null,
"e": 2966,
"s": 2962,
"text": "SQL"
},
{
"code": null,
"e": 3064,
"s": 2966,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3130,
"s": 3064,
"text": "How to Update Multiple Columns in Single Update Statement in SQL?"
},
{
"code": null,
"e": 3154,
"s": 3130,
"text": "Window functions in SQL"
},
{
"code": null,
"e": 3187,
"s": 3154,
"text": "SQL | Sub queries in From Clause"
},
{
"code": null,
"e": 3219,
"s": 3187,
"text": "What is Temporary Table in SQL?"
},
{
"code": null,
"e": 3236,
"s": 3219,
"text": "SQL using Python"
},
{
"code": null,
"e": 3314,
"s": 3236,
"text": "SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter"
},
{
"code": null,
"e": 3350,
"s": 3314,
"text": "SQL Query to Convert VARCHAR to INT"
},
{
"code": null,
"e": 3380,
"s": 3350,
"text": "RANK() Function in SQL Server"
},
{
"code": null,
"e": 3411,
"s": 3380,
"text": "SQL Query to Compare Two Dates"
}
] |
How To Reorder Boxplots in R with ggplot2?
|
17 Oct, 2021
In this article, we will discuss how to reorder the boxplot with ggplot2 in R Programming Language.
To reorder the boxplot we will use reorder() function of ggplot2.
Syntax: ggplot(sample_data, aes(x=reorder(name,value),y=value))
By default, ggplot2 orders the groups in alphabetical order. But for better visualization of data sometimes we need to reorder them in increasing and decreasing order. This is where the reorder() function comes into play. We use reorder() function, when we specify x-axis variable inside the aesthetics function aes(). Reorder() function sorts the carriers by mean values of x-axis variable by default.
In this example, the boxplot has been reordered using reorder() function. All the points of boxplots are arranged in increasing order of mean of their x-axis value.
R
# load library tidyverselibrary(tidyverse) # Diamonds dataset is provided by R natively# we will use that same dataset for our plot# basic boxplot# reorder plot using reorder() function# reorder function reorders plot according to # mean of variableggplot(diamonds, aes(x=reorder(cut,price), y=price)) + # geom_boxplot is used to plot the boxplot geom_boxplot()
Output:
Here, in this boxplot, all the boxes are arranged in increasing order of mean of value price due to the use of the reorder() function.
To reorder the data in descending order, we pass the -ve value as an argument to reorder() function. This reorders the plot according to decreasing order of the mean value of data passed as a parameter.
R
# load library tidyverselibrary(tidyverse) # Diamonds dataset is provided by R natively# we will use that same dataset for our plot# basic boxplot# reorder plot using reorder() function# reorder function reorders plot according to mean of variable# Add -ve sign in price to get result in descending orderggplot(diamonds, aes(x=reorder(cut, -price), y=price)) + # geom_boxplot is used to plot the boxplot geom_boxplot()
Output:
Here, in this boxplot, all the boxes are arranged in decreasing order of mean of value price due to the use of the reorder() function.
Picked
R-ggplot
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n17 Oct, 2021"
},
{
"code": null,
"e": 128,
"s": 28,
"text": "In this article, we will discuss how to reorder the boxplot with ggplot2 in R Programming Language."
},
{
"code": null,
"e": 194,
"s": 128,
"text": "To reorder the boxplot we will use reorder() function of ggplot2."
},
{
"code": null,
"e": 258,
"s": 194,
"text": "Syntax: ggplot(sample_data, aes(x=reorder(name,value),y=value))"
},
{
"code": null,
"e": 661,
"s": 258,
"text": "By default, ggplot2 orders the groups in alphabetical order. But for better visualization of data sometimes we need to reorder them in increasing and decreasing order. This is where the reorder() function comes into play. We use reorder() function, when we specify x-axis variable inside the aesthetics function aes(). Reorder() function sorts the carriers by mean values of x-axis variable by default."
},
{
"code": null,
"e": 827,
"s": 661,
"text": "In this example, the boxplot has been reordered using reorder() function. All the points of boxplots are arranged in increasing order of mean of their x-axis value. "
},
{
"code": null,
"e": 829,
"s": 827,
"text": "R"
},
{
"code": "# load library tidyverselibrary(tidyverse) # Diamonds dataset is provided by R natively# we will use that same dataset for our plot# basic boxplot# reorder plot using reorder() function# reorder function reorders plot according to # mean of variableggplot(diamonds, aes(x=reorder(cut,price), y=price)) + # geom_boxplot is used to plot the boxplot geom_boxplot()",
"e": 1196,
"s": 829,
"text": null
},
{
"code": null,
"e": 1204,
"s": 1196,
"text": "Output:"
},
{
"code": null,
"e": 1339,
"s": 1204,
"text": "Here, in this boxplot, all the boxes are arranged in increasing order of mean of value price due to the use of the reorder() function."
},
{
"code": null,
"e": 1542,
"s": 1339,
"text": "To reorder the data in descending order, we pass the -ve value as an argument to reorder() function. This reorders the plot according to decreasing order of the mean value of data passed as a parameter."
},
{
"code": null,
"e": 1544,
"s": 1542,
"text": "R"
},
{
"code": "# load library tidyverselibrary(tidyverse) # Diamonds dataset is provided by R natively# we will use that same dataset for our plot# basic boxplot# reorder plot using reorder() function# reorder function reorders plot according to mean of variable# Add -ve sign in price to get result in descending orderggplot(diamonds, aes(x=reorder(cut, -price), y=price)) + # geom_boxplot is used to plot the boxplot geom_boxplot() ",
"e": 1969,
"s": 1544,
"text": null
},
{
"code": null,
"e": 1977,
"s": 1969,
"text": "Output:"
},
{
"code": null,
"e": 2112,
"s": 1977,
"text": "Here, in this boxplot, all the boxes are arranged in decreasing order of mean of value price due to the use of the reorder() function."
},
{
"code": null,
"e": 2119,
"s": 2112,
"text": "Picked"
},
{
"code": null,
"e": 2128,
"s": 2119,
"text": "R-ggplot"
},
{
"code": null,
"e": 2139,
"s": 2128,
"text": "R Language"
}
] |
Python Arithmetic Operators
|
29 Aug, 2020
Arithmetic operators are used to perform mathematical operations like addition, subtraction, multiplication and division.
There are 7 arithmetic operators in Python :
AdditionSubtractionMultiplicationDivisionModulusExponentiationFloor division
Addition
Subtraction
Multiplication
Division
Modulus
Exponentiation
Floor division
1. Addition Operator : In Python, + is the addition operator. It is used to add 2 values.Example :
val1 = 2val2 = 3 # using the addition operatorres = val1 + val2print(res)
Output :
5
2. Subtraction Operator : In Python, – is the subtraction operator. It is used to subtract the second value from the first value.Example :
val1 = 2val2 = 3 # using the subtraction operatorres = val1 - val2print(res)
Output :
-1
3. Multiplication Operator : In Python, * is the multiplication operator. It is used to find the product of 2 values.Example :
val1 = 2val2 = 3 # using the multiplication operatorres = val1 * val2print(res)
Output :
6
4. Division Operator : In Python, / is the division operator. It is used to find the quotient when first operand is divided by the second.Example :
val1 = 3val2 = 2 # using the division operatorres = val1 / val2print(res)
Output :
1.5
5. Modulus Operator : In Python, % is the modulus operator. It is used to find the remainder when first operand is divided by the second.Example :
val1 = 3val2 = 2 # using the modulus operatorres = val1 % val2print(res)
Output :
1
6. Exponentiation Operator : In Python, ** is the exponentiation operator. It is used to raise the first operand to power of second.Example :
val1 = 2val2 = 3 # using the exponentiation operatorres = val1 ** val2print(res)
Output :
8
7. Floor division : In Python, // is used to conduct the floor division. It is used to find the floorof the quotient when first operand is divided by the second.Example :
val1 = 3val2 = 2 # using the floor divisionres = val1 // val2print(res)
Output :
1
Below is the summary of all the 7 operators :
python-basics
Python-Operators
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Iterate over a list in Python
Convert integer to string in Python
Python OOPs Concepts
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n29 Aug, 2020"
},
{
"code": null,
"e": 176,
"s": 54,
"text": "Arithmetic operators are used to perform mathematical operations like addition, subtraction, multiplication and division."
},
{
"code": null,
"e": 221,
"s": 176,
"text": "There are 7 arithmetic operators in Python :"
},
{
"code": null,
"e": 298,
"s": 221,
"text": "AdditionSubtractionMultiplicationDivisionModulusExponentiationFloor division"
},
{
"code": null,
"e": 307,
"s": 298,
"text": "Addition"
},
{
"code": null,
"e": 319,
"s": 307,
"text": "Subtraction"
},
{
"code": null,
"e": 334,
"s": 319,
"text": "Multiplication"
},
{
"code": null,
"e": 343,
"s": 334,
"text": "Division"
},
{
"code": null,
"e": 351,
"s": 343,
"text": "Modulus"
},
{
"code": null,
"e": 366,
"s": 351,
"text": "Exponentiation"
},
{
"code": null,
"e": 381,
"s": 366,
"text": "Floor division"
},
{
"code": null,
"e": 480,
"s": 381,
"text": "1. Addition Operator : In Python, + is the addition operator. It is used to add 2 values.Example :"
},
{
"code": "val1 = 2val2 = 3 # using the addition operatorres = val1 + val2print(res)",
"e": 555,
"s": 480,
"text": null
},
{
"code": null,
"e": 564,
"s": 555,
"text": "Output :"
},
{
"code": null,
"e": 566,
"s": 564,
"text": "5"
},
{
"code": null,
"e": 705,
"s": 566,
"text": "2. Subtraction Operator : In Python, – is the subtraction operator. It is used to subtract the second value from the first value.Example :"
},
{
"code": "val1 = 2val2 = 3 # using the subtraction operatorres = val1 - val2print(res)",
"e": 783,
"s": 705,
"text": null
},
{
"code": null,
"e": 792,
"s": 783,
"text": "Output :"
},
{
"code": null,
"e": 795,
"s": 792,
"text": "-1"
},
{
"code": null,
"e": 922,
"s": 795,
"text": "3. Multiplication Operator : In Python, * is the multiplication operator. It is used to find the product of 2 values.Example :"
},
{
"code": "val1 = 2val2 = 3 # using the multiplication operatorres = val1 * val2print(res)",
"e": 1003,
"s": 922,
"text": null
},
{
"code": null,
"e": 1012,
"s": 1003,
"text": "Output :"
},
{
"code": null,
"e": 1014,
"s": 1012,
"text": "6"
},
{
"code": null,
"e": 1162,
"s": 1014,
"text": "4. Division Operator : In Python, / is the division operator. It is used to find the quotient when first operand is divided by the second.Example :"
},
{
"code": "val1 = 3val2 = 2 # using the division operatorres = val1 / val2print(res)",
"e": 1237,
"s": 1162,
"text": null
},
{
"code": null,
"e": 1246,
"s": 1237,
"text": "Output :"
},
{
"code": null,
"e": 1250,
"s": 1246,
"text": "1.5"
},
{
"code": null,
"e": 1397,
"s": 1250,
"text": "5. Modulus Operator : In Python, % is the modulus operator. It is used to find the remainder when first operand is divided by the second.Example :"
},
{
"code": "val1 = 3val2 = 2 # using the modulus operatorres = val1 % val2print(res)",
"e": 1471,
"s": 1397,
"text": null
},
{
"code": null,
"e": 1480,
"s": 1471,
"text": "Output :"
},
{
"code": null,
"e": 1482,
"s": 1480,
"text": "1"
},
{
"code": null,
"e": 1624,
"s": 1482,
"text": "6. Exponentiation Operator : In Python, ** is the exponentiation operator. It is used to raise the first operand to power of second.Example :"
},
{
"code": "val1 = 2val2 = 3 # using the exponentiation operatorres = val1 ** val2print(res)",
"e": 1706,
"s": 1624,
"text": null
},
{
"code": null,
"e": 1715,
"s": 1706,
"text": "Output :"
},
{
"code": null,
"e": 1717,
"s": 1715,
"text": "8"
},
{
"code": null,
"e": 1888,
"s": 1717,
"text": "7. Floor division : In Python, // is used to conduct the floor division. It is used to find the floorof the quotient when first operand is divided by the second.Example :"
},
{
"code": "val1 = 3val2 = 2 # using the floor divisionres = val1 // val2print(res)",
"e": 1961,
"s": 1888,
"text": null
},
{
"code": null,
"e": 1970,
"s": 1961,
"text": "Output :"
},
{
"code": null,
"e": 1972,
"s": 1970,
"text": "1"
},
{
"code": null,
"e": 2018,
"s": 1972,
"text": "Below is the summary of all the 7 operators :"
},
{
"code": null,
"e": 2032,
"s": 2018,
"text": "python-basics"
},
{
"code": null,
"e": 2049,
"s": 2032,
"text": "Python-Operators"
},
{
"code": null,
"e": 2056,
"s": 2049,
"text": "Python"
},
{
"code": null,
"e": 2154,
"s": 2056,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2196,
"s": 2154,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 2218,
"s": 2196,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 2253,
"s": 2218,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 2279,
"s": 2253,
"text": "Python String | replace()"
},
{
"code": null,
"e": 2311,
"s": 2279,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 2340,
"s": 2311,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 2367,
"s": 2340,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 2397,
"s": 2367,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 2433,
"s": 2397,
"text": "Convert integer to string in Python"
}
] |
How to Use Google Play Install Referrer API in Android?
|
10 Mar, 2021
Google Play Install Referrer is the API that is used in most of the applications but it is not been seen in the app. This functionality works under the hood and is used to check the sources from where the app is getting most of the downloads. Google Play Install Referrer API tells us that from where the app has to go installs and the sources. This will helps us to improve the presence of our apps on different platforms.
Google Play Referrer API provides us information from where our app has been installed whether it may be play store or any other platform. With the help of this API, we can track the actions which are taken by the user to download our App. Below are some of the important data which we can gather using this API.
With the help of this API, we can track from where the user has installed our application. We can get the URL from which our app has been downloaded.
We can get the timestamp when the user clicks on the referrer URL.
We can get the timestamp of the user when the user downloads our app from a specific URL.
We can get the app version when our app was first installed.
We can track whether the user has used the app’s instant experience with the previous 7 days.
We will be building a simple application in which we will be adding our Google Play Referrer API and we will be displaying the data which is tracked by this API in a simple text view. Note that as we have not published our App to Google Play. So we will only get the source from which our app installed as organic. Below is the screenshot in which we will get to see what we are going to build in this article. Note that we are going to implement this project using the Java language.
Step 1: Create a New Project
To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language.
Step 2: Add the dependency for Google Play Referrer API in the build.gradle file
Navigate to Gradle scripts and then to build.gradle(Module) level. Add below line in build.gradle file in the dependencies section.
// below is the dependency for referer
implementation “com.android.installreferrer:installreferrer:2.2”
Step 3: Working with the activity_main.xml file
Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file.
XML
<?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context=".MainActivity"> <!--text view for displaying referer details--> <TextView android:id="@+id/idTVRefrer" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_centerInParent="true" android:layout_margin="3dp" android:gravity="center_horizontal" android:padding="4dp" android:text="Refrer" android:textAlignment="center" android:textColor="@color/purple_200" android:textSize="18sp" /> </RelativeLayout>
Step 4: Working with the MainActivity.java file
Go to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail.
Java
import android.os.Bundle;import android.os.RemoteException;import android.widget.TextView;import android.widget.Toast; import androidx.appcompat.app.AppCompatActivity; import com.android.installreferrer.api.InstallReferrerClient;import com.android.installreferrer.api.InstallReferrerStateListener;import com.android.installreferrer.api.ReferrerDetails; public class MainActivity extends AppCompatActivity { // creating variables for text view. private TextView refrerTV; // variable for install referer client. InstallReferrerClient referrerClient; // creating an empty string for our referer. String refrer = ""; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // initializing all our variables. refrerTV = findViewById(R.id.idTVRefrer); // on below line we are building our install referrer client and building it. referrerClient = InstallReferrerClient.newBuilder(this).build(); // on below line we are starting its connection. referrerClient.startConnection(new InstallReferrerStateListener() { @Override public void onInstallReferrerSetupFinished(int responseCode) { // this method is called when install referer setup is finished. switch (responseCode) { // we are using switch case to check the response. case InstallReferrerClient.InstallReferrerResponse.OK: // this case is called when the status is OK and ReferrerDetails response = null; try { // on below line we are getting referrer details // by calling get install referrer. response = referrerClient.getInstallReferrer(); // on below line we are getting referrer url. String referrerUrl = response.getInstallReferrer(); // on below line we are getting referrer click time. long referrerClickTime = response.getReferrerClickTimestampSeconds(); // on below line we are getting app install time long appInstallTime = response.getInstallBeginTimestampSeconds(); // on below line we are getting our time when // user has used our apps instant experience. boolean instantExperienceLaunched = response.getGooglePlayInstantParam(); // on below line we are getting our // apps install referrer. refrer = response.getInstallReferrer(); // on below line we are setting all detail to our text view. refrerTV.setText("Referrer is : \n" + referrerUrl + "\n" + "Referrer Click Time is : " + referrerClickTime + "\nApp Install Time : " + appInstallTime); } catch (RemoteException e) { // handling error case. e.printStackTrace(); } break; case InstallReferrerClient.InstallReferrerResponse.FEATURE_NOT_SUPPORTED: // API not available on the current Play Store app. Toast.makeText(MainActivity.this, "Feature not supported..", Toast.LENGTH_SHORT).show(); break; case InstallReferrerClient.InstallReferrerResponse.SERVICE_UNAVAILABLE: // Connection couldn't be established. Toast.makeText(MainActivity.this, "Fail to establish connection", Toast.LENGTH_SHORT).show(); break; } } @Override public void onInstallReferrerServiceDisconnected() { // Try to restart the connection on the next request to // Google Play by calling the startConnection() method. Toast.makeText(MainActivity.this, "Service disconnected..", Toast.LENGTH_SHORT).show(); } }); }}
Now run your app and see the output of the app.
Note: As our app is not published on Google Play so we will only get the referrer details as organic and other details will get as zero.
Output:
Android
Java
Java
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Add Views Dynamically and Store Data in Arraylist in Android?
Android SDK and it's Components
Flutter - Custom Bottom Navigation Bar
How to Communicate Between Fragments in Android?
Retrofit with Kotlin Coroutine in Android
Arrays in Java
Arrays.sort() in Java with examples
Split() String method in Java with examples
Reverse a string in Java
Object Oriented Programming (OOPs) Concept in Java
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n10 Mar, 2021"
},
{
"code": null,
"e": 453,
"s": 28,
"text": "Google Play Install Referrer is the API that is used in most of the applications but it is not been seen in the app. This functionality works under the hood and is used to check the sources from where the app is getting most of the downloads. Google Play Install Referrer API tells us that from where the app has to go installs and the sources. This will helps us to improve the presence of our apps on different platforms. "
},
{
"code": null,
"e": 767,
"s": 453,
"text": "Google Play Referrer API provides us information from where our app has been installed whether it may be play store or any other platform. With the help of this API, we can track the actions which are taken by the user to download our App. Below are some of the important data which we can gather using this API. "
},
{
"code": null,
"e": 917,
"s": 767,
"text": "With the help of this API, we can track from where the user has installed our application. We can get the URL from which our app has been downloaded."
},
{
"code": null,
"e": 984,
"s": 917,
"text": "We can get the timestamp when the user clicks on the referrer URL."
},
{
"code": null,
"e": 1074,
"s": 984,
"text": "We can get the timestamp of the user when the user downloads our app from a specific URL."
},
{
"code": null,
"e": 1135,
"s": 1074,
"text": "We can get the app version when our app was first installed."
},
{
"code": null,
"e": 1229,
"s": 1135,
"text": "We can track whether the user has used the app’s instant experience with the previous 7 days."
},
{
"code": null,
"e": 1715,
"s": 1229,
"text": "We will be building a simple application in which we will be adding our Google Play Referrer API and we will be displaying the data which is tracked by this API in a simple text view. Note that as we have not published our App to Google Play. So we will only get the source from which our app installed as organic. Below is the screenshot in which we will get to see what we are going to build in this article. Note that we are going to implement this project using the Java language. "
},
{
"code": null,
"e": 1744,
"s": 1715,
"text": "Step 1: Create a New Project"
},
{
"code": null,
"e": 1906,
"s": 1744,
"text": "To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language."
},
{
"code": null,
"e": 1987,
"s": 1906,
"text": "Step 2: Add the dependency for Google Play Referrer API in the build.gradle file"
},
{
"code": null,
"e": 2119,
"s": 1987,
"text": "Navigate to Gradle scripts and then to build.gradle(Module) level. Add below line in build.gradle file in the dependencies section."
},
{
"code": null,
"e": 2158,
"s": 2119,
"text": "// below is the dependency for referer"
},
{
"code": null,
"e": 2223,
"s": 2158,
"text": "implementation “com.android.installreferrer:installreferrer:2.2”"
},
{
"code": null,
"e": 2271,
"s": 2223,
"text": "Step 3: Working with the activity_main.xml file"
},
{
"code": null,
"e": 2414,
"s": 2271,
"text": "Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file. "
},
{
"code": null,
"e": 2418,
"s": 2414,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:orientation=\"vertical\" tools:context=\".MainActivity\"> <!--text view for displaying referer details--> <TextView android:id=\"@+id/idTVRefrer\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_centerInParent=\"true\" android:layout_margin=\"3dp\" android:gravity=\"center_horizontal\" android:padding=\"4dp\" android:text=\"Refrer\" android:textAlignment=\"center\" android:textColor=\"@color/purple_200\" android:textSize=\"18sp\" /> </RelativeLayout>",
"e": 3236,
"s": 2418,
"text": null
},
{
"code": null,
"e": 3284,
"s": 3236,
"text": "Step 4: Working with the MainActivity.java file"
},
{
"code": null,
"e": 3474,
"s": 3284,
"text": "Go to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail."
},
{
"code": null,
"e": 3479,
"s": 3474,
"text": "Java"
},
{
"code": "import android.os.Bundle;import android.os.RemoteException;import android.widget.TextView;import android.widget.Toast; import androidx.appcompat.app.AppCompatActivity; import com.android.installreferrer.api.InstallReferrerClient;import com.android.installreferrer.api.InstallReferrerStateListener;import com.android.installreferrer.api.ReferrerDetails; public class MainActivity extends AppCompatActivity { // creating variables for text view. private TextView refrerTV; // variable for install referer client. InstallReferrerClient referrerClient; // creating an empty string for our referer. String refrer = \"\"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // initializing all our variables. refrerTV = findViewById(R.id.idTVRefrer); // on below line we are building our install referrer client and building it. referrerClient = InstallReferrerClient.newBuilder(this).build(); // on below line we are starting its connection. referrerClient.startConnection(new InstallReferrerStateListener() { @Override public void onInstallReferrerSetupFinished(int responseCode) { // this method is called when install referer setup is finished. switch (responseCode) { // we are using switch case to check the response. case InstallReferrerClient.InstallReferrerResponse.OK: // this case is called when the status is OK and ReferrerDetails response = null; try { // on below line we are getting referrer details // by calling get install referrer. response = referrerClient.getInstallReferrer(); // on below line we are getting referrer url. String referrerUrl = response.getInstallReferrer(); // on below line we are getting referrer click time. long referrerClickTime = response.getReferrerClickTimestampSeconds(); // on below line we are getting app install time long appInstallTime = response.getInstallBeginTimestampSeconds(); // on below line we are getting our time when // user has used our apps instant experience. boolean instantExperienceLaunched = response.getGooglePlayInstantParam(); // on below line we are getting our // apps install referrer. refrer = response.getInstallReferrer(); // on below line we are setting all detail to our text view. refrerTV.setText(\"Referrer is : \\n\" + referrerUrl + \"\\n\" + \"Referrer Click Time is : \" + referrerClickTime + \"\\nApp Install Time : \" + appInstallTime); } catch (RemoteException e) { // handling error case. e.printStackTrace(); } break; case InstallReferrerClient.InstallReferrerResponse.FEATURE_NOT_SUPPORTED: // API not available on the current Play Store app. Toast.makeText(MainActivity.this, \"Feature not supported..\", Toast.LENGTH_SHORT).show(); break; case InstallReferrerClient.InstallReferrerResponse.SERVICE_UNAVAILABLE: // Connection couldn't be established. Toast.makeText(MainActivity.this, \"Fail to establish connection\", Toast.LENGTH_SHORT).show(); break; } } @Override public void onInstallReferrerServiceDisconnected() { // Try to restart the connection on the next request to // Google Play by calling the startConnection() method. Toast.makeText(MainActivity.this, \"Service disconnected..\", Toast.LENGTH_SHORT).show(); } }); }}",
"e": 8016,
"s": 3479,
"text": null
},
{
"code": null,
"e": 8064,
"s": 8016,
"text": "Now run your app and see the output of the app."
},
{
"code": null,
"e": 8202,
"s": 8064,
"text": "Note: As our app is not published on Google Play so we will only get the referrer details as organic and other details will get as zero. "
},
{
"code": null,
"e": 8210,
"s": 8202,
"text": "Output:"
},
{
"code": null,
"e": 8218,
"s": 8210,
"text": "Android"
},
{
"code": null,
"e": 8223,
"s": 8218,
"text": "Java"
},
{
"code": null,
"e": 8228,
"s": 8223,
"text": "Java"
},
{
"code": null,
"e": 8236,
"s": 8228,
"text": "Android"
},
{
"code": null,
"e": 8334,
"s": 8236,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 8403,
"s": 8334,
"text": "How to Add Views Dynamically and Store Data in Arraylist in Android?"
},
{
"code": null,
"e": 8435,
"s": 8403,
"text": "Android SDK and it's Components"
},
{
"code": null,
"e": 8474,
"s": 8435,
"text": "Flutter - Custom Bottom Navigation Bar"
},
{
"code": null,
"e": 8523,
"s": 8474,
"text": "How to Communicate Between Fragments in Android?"
},
{
"code": null,
"e": 8565,
"s": 8523,
"text": "Retrofit with Kotlin Coroutine in Android"
},
{
"code": null,
"e": 8580,
"s": 8565,
"text": "Arrays in Java"
},
{
"code": null,
"e": 8616,
"s": 8580,
"text": "Arrays.sort() in Java with examples"
},
{
"code": null,
"e": 8660,
"s": 8616,
"text": "Split() String method in Java with examples"
},
{
"code": null,
"e": 8685,
"s": 8660,
"text": "Reverse a string in Java"
}
] |
Create a stopwatch using python
|
12 Jul, 2021
This article focus on creating a stopwatch using Tkinter in python Tkinter : Tkinter is the standard GUI library for Python. Python when combined with Tkinter provides a fast and easy way to create GUI applications. Tkinter provides a powerful object-oriented interface to the Tk GUI toolkit. It’s very easy to get started with Tkinter, here are some sample codes to get your hands on Tkinter in python.
Python3
# Python program to create a# a new window using Tkinter# importing the required librariesimport tkinter # creating a object 'top' as instance of class Tktop = tkinter.Tk() # This will start the blank windowtop.mainloop()
Output:
Creating a Stopwatch Using Python | GeeksforGeeks - YouTubeGeeksforGeeks529K subscribersCreating a Stopwatch Using Python | 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 / 47:27•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=On8dNuKo4Dw" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
Creating Stopwatch using Tkinter
Now lets try to create a program using Tkinter module to create a stopwatch. A stopwatch is a handheld timepiece designed to measure the amount of time elapsed from a particular time when it is activated to the time when the piece is deactivated. A large digital version of a stopwatch designed for viewing at a distance, as in a sports stadium, is called a stop clock. In manual timing, the clock is started and stopped by a person pressing a button. In fully automatic time, both starting and stopping are triggered automatically, by sensors. Required Modules: We are only going to use Tkinter for creating GUI and no other libraries will be used in this program.Source Code:
Python3
# Python program to illustrate a stop watch# using Tkinter#importing the required librariesimport tkinter as Tkinterfrom datetime import datetimecounter = 66600running = Falsedef counter_label(label): def count(): if running: global counter # To manage the initial delay. if counter==66600: display="Starting..." else: tt = datetime.fromtimestamp(counter) string = tt.strftime("%H:%M:%S") display=string label['text']=display # Or label.config(text=display) # label.after(arg1, arg2) delays by # first argument given in milliseconds # and then calls the function given as second argument. # Generally like here we need to call the # function in which it is present repeatedly. # Delays by 1000ms=1 seconds and call count again. label.after(1000, count) counter += 1 # Triggering the start of the counter. count() # start function of the stopwatchdef Start(label): global running running=True counter_label(label) start['state']='disabled' stop['state']='normal' reset['state']='normal' # Stop function of the stopwatchdef Stop(): global running start['state']='normal' stop['state']='disabled' reset['state']='normal' running = False # Reset function of the stopwatchdef Reset(label): global counter counter=66600 # If rest is pressed after pressing stop. if running==False: reset['state']='disabled' label['text']='Welcome!' # If reset is pressed while the stopwatch is running. else: label['text']='Starting...' root = Tkinter.Tk()root.title("Stopwatch") # Fixing the window size.root.minsize(width=250, height=70)label = Tkinter.Label(root, text="Welcome!", fg="black", font="Verdana 30 bold")label.pack()f = Tkinter.Frame(root)start = Tkinter.Button(f, text='Start', width=6, command=lambda:Start(label))stop = Tkinter.Button(f, text='Stop',width=6,state='disabled', command=Stop)reset = Tkinter.Button(f, text='Reset',width=6, state='disabled', command=lambda:Reset(label))f.pack(anchor = 'center',pady=5)start.pack(side="left")stop.pack(side ="left")reset.pack(side="left")root.mainloop()
Output:
This article is contributed by Subhajit Saha. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. 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.
kiran_online
sweetyty
sooda367
python-utility
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": 52,
"s": 24,
"text": "\n12 Jul, 2021"
},
{
"code": null,
"e": 458,
"s": 52,
"text": "This article focus on creating a stopwatch using Tkinter in python Tkinter : Tkinter is the standard GUI library for Python. Python when combined with Tkinter provides a fast and easy way to create GUI applications. Tkinter provides a powerful object-oriented interface to the Tk GUI toolkit. It’s very easy to get started with Tkinter, here are some sample codes to get your hands on Tkinter in python. "
},
{
"code": null,
"e": 466,
"s": 458,
"text": "Python3"
},
{
"code": "# Python program to create a# a new window using Tkinter# importing the required librariesimport tkinter # creating a object 'top' as instance of class Tktop = tkinter.Tk() # This will start the blank windowtop.mainloop()",
"e": 688,
"s": 466,
"text": null
},
{
"code": null,
"e": 698,
"s": 688,
"text": "Output: "
},
{
"code": null,
"e": 1585,
"s": 700,
"text": "Creating a Stopwatch Using Python | GeeksforGeeks - YouTubeGeeksforGeeks529K subscribersCreating a Stopwatch Using Python | 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 / 47:27•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=On8dNuKo4Dw\" 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": 1618,
"s": 1585,
"text": "Creating Stopwatch using Tkinter"
},
{
"code": null,
"e": 2298,
"s": 1618,
"text": "Now lets try to create a program using Tkinter module to create a stopwatch. A stopwatch is a handheld timepiece designed to measure the amount of time elapsed from a particular time when it is activated to the time when the piece is deactivated. A large digital version of a stopwatch designed for viewing at a distance, as in a sports stadium, is called a stop clock. In manual timing, the clock is started and stopped by a person pressing a button. In fully automatic time, both starting and stopping are triggered automatically, by sensors. Required Modules: We are only going to use Tkinter for creating GUI and no other libraries will be used in this program.Source Code: "
},
{
"code": null,
"e": 2306,
"s": 2298,
"text": "Python3"
},
{
"code": "# Python program to illustrate a stop watch# using Tkinter#importing the required librariesimport tkinter as Tkinterfrom datetime import datetimecounter = 66600running = Falsedef counter_label(label): def count(): if running: global counter # To manage the initial delay. if counter==66600: display=\"Starting...\" else: tt = datetime.fromtimestamp(counter) string = tt.strftime(\"%H:%M:%S\") display=string label['text']=display # Or label.config(text=display) # label.after(arg1, arg2) delays by # first argument given in milliseconds # and then calls the function given as second argument. # Generally like here we need to call the # function in which it is present repeatedly. # Delays by 1000ms=1 seconds and call count again. label.after(1000, count) counter += 1 # Triggering the start of the counter. count() # start function of the stopwatchdef Start(label): global running running=True counter_label(label) start['state']='disabled' stop['state']='normal' reset['state']='normal' # Stop function of the stopwatchdef Stop(): global running start['state']='normal' stop['state']='disabled' reset['state']='normal' running = False # Reset function of the stopwatchdef Reset(label): global counter counter=66600 # If rest is pressed after pressing stop. if running==False: reset['state']='disabled' label['text']='Welcome!' # If reset is pressed while the stopwatch is running. else: label['text']='Starting...' root = Tkinter.Tk()root.title(\"Stopwatch\") # Fixing the window size.root.minsize(width=250, height=70)label = Tkinter.Label(root, text=\"Welcome!\", fg=\"black\", font=\"Verdana 30 bold\")label.pack()f = Tkinter.Frame(root)start = Tkinter.Button(f, text='Start', width=6, command=lambda:Start(label))stop = Tkinter.Button(f, text='Stop',width=6,state='disabled', command=Stop)reset = Tkinter.Button(f, text='Reset',width=6, state='disabled', command=lambda:Reset(label))f.pack(anchor = 'center',pady=5)start.pack(side=\"left\")stop.pack(side =\"left\")reset.pack(side=\"left\")root.mainloop()",
"e": 4663,
"s": 2306,
"text": null
},
{
"code": null,
"e": 4673,
"s": 4663,
"text": "Output: "
},
{
"code": null,
"e": 5099,
"s": 4677,
"text": "This article is contributed by Subhajit Saha. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. 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": 5112,
"s": 5099,
"text": "kiran_online"
},
{
"code": null,
"e": 5121,
"s": 5112,
"text": "sweetyty"
},
{
"code": null,
"e": 5130,
"s": 5121,
"text": "sooda367"
},
{
"code": null,
"e": 5145,
"s": 5130,
"text": "python-utility"
},
{
"code": null,
"e": 5152,
"s": 5145,
"text": "Python"
},
{
"code": null,
"e": 5250,
"s": 5152,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 5268,
"s": 5250,
"text": "Python Dictionary"
},
{
"code": null,
"e": 5310,
"s": 5268,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 5332,
"s": 5310,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 5367,
"s": 5332,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 5393,
"s": 5367,
"text": "Python String | replace()"
},
{
"code": null,
"e": 5425,
"s": 5393,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 5454,
"s": 5425,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 5481,
"s": 5454,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 5511,
"s": 5481,
"text": "Iterate over a list in Python"
}
] |
Dynamic RadioButton in Kotlin
|
19 Feb, 2021
Android Radio Button is bi-state button which can either be checked or unchecked. Also, it’s working is same as Checkbox except that radio button can not allow to be unchecked once it was selected.
Generally, we use RadioButton controls to allow users to select one option from multiple options.
By default, the RadioButton in OFF(Unchecked) state but we can change the default state of RadioButton by using android:checked attribute.
In order to create a radio button, first we need to create a project. We are naming it a DynamicRadioButton
Click on File, then New => New Project
Then, check Include Kotlin Support and click next button.
Select minimum SDK, whatever you need.
Select Empty activity and then click finish.
First of all define the RadioGroup in the Linearlayout and access into the Kotlin file.
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/container" xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity" android:orientation="vertical"> <RadioGroup android:id="@+id/radioGroup" android:layout_width="match_parent" android:layout_height="wrap_content" android:paddingStart="25dp"> </RadioGroup></LinearLayout>
The above code will still produce some errors, to resolve these add the following code snippet to app/res/values/strings.xml
<resources> <string name="app_name">DynamicRadioButton</string> <string name="black">Black</string> <string name="white">White</string> <string name="blue">Blue</string> <string name="you_selected">You selected:</string> </resources>
Here, we define three radio buttons for the color and set their attributes.
val radioButton1 = RadioButton(this)
then, use them into RadioGroup using code:
radioGroup.addView(radioButton1)
radioGroup.addView(radioButton2)
radioGroup.addView(radioButton3)
package com.geeksforgeeks.myfirstkotlinappimport android.annotation.SuppressLintimport androidx.appcompat.app.AppCompatActivityimport android.os.Bundleimport android.view.ViewGroupimport android.widget.LinearLayoutimport android.widget.RadioButtonimport android.widget.RadioGroupimport android.widget.Toast class MainActivity : AppCompatActivity() { @SuppressLint("ResourceType") override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) val linearLayout = findViewById<LinearLayout>(R.id.container) // Create RadioButton programmatically val radioButton1 = RadioButton(this) radioButton1.layoutParams= LinearLayout.LayoutParams( ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT) radioButton1.setText("Black") radioButton1.id = 1 val radioButton2 = RadioButton(this) radioButton2.layoutParams = LinearLayout.LayoutParams( ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT) radioButton2.setText("White") radioButton2.id = 2 val radioButton3 = RadioButton(this) radioButton3.layoutParams = LinearLayout.LayoutParams( ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT) radioButton3.setText("Blue") radioButton3.id = 3 val radioGroup = findViewById<RadioGroup>(R.id.radioGroup) if (radioGroup != null) { radioGroup.addView(radioButton1) radioGroup.addView(radioButton2) radioGroup.addView(radioButton3) radioGroup.setOnCheckedChangeListener { group, checkedId -> var string = getString(R.string.you_selected) string += " " + getString( if (checkedId == 1) R.string.black else if(checkedId == 2 ) R.string.white else R.string.blue ) Toast.makeText(applicationContext, string, Toast.LENGTH_SHORT).show() } } }}
<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android"package="com.geeksforgeeks.myfirstkotlinapp"> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity></application> </manifest>
Android-Button
Kotlin Android
Picked
Android
Kotlin
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Add Views Dynamically and Store Data in Arraylist in Android?
Android SDK and it's Components
How to Communicate Between Fragments in Android?
Flutter - Custom Bottom Navigation Bar
Retrofit with Kotlin Coroutine in Android
How to Add Views Dynamically and Store Data in Arraylist in Android?
Android UI Layouts
How to Communicate Between Fragments in Android?
Kotlin Array
Retrofit with Kotlin Coroutine in Android
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n19 Feb, 2021"
},
{
"code": null,
"e": 226,
"s": 28,
"text": "Android Radio Button is bi-state button which can either be checked or unchecked. Also, it’s working is same as Checkbox except that radio button can not allow to be unchecked once it was selected."
},
{
"code": null,
"e": 324,
"s": 226,
"text": "Generally, we use RadioButton controls to allow users to select one option from multiple options."
},
{
"code": null,
"e": 463,
"s": 324,
"text": "By default, the RadioButton in OFF(Unchecked) state but we can change the default state of RadioButton by using android:checked attribute."
},
{
"code": null,
"e": 571,
"s": 463,
"text": "In order to create a radio button, first we need to create a project. We are naming it a DynamicRadioButton"
},
{
"code": null,
"e": 610,
"s": 571,
"text": "Click on File, then New => New Project"
},
{
"code": null,
"e": 668,
"s": 610,
"text": "Then, check Include Kotlin Support and click next button."
},
{
"code": null,
"e": 707,
"s": 668,
"text": "Select minimum SDK, whatever you need."
},
{
"code": null,
"e": 752,
"s": 707,
"text": "Select Empty activity and then click finish."
},
{
"code": null,
"e": 840,
"s": 752,
"text": "First of all define the RadioGroup in the Linearlayout and access into the Kotlin file."
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:tools=\"http://schemas.android.com/tools\" android:id=\"@+id/container\" xmlns:app=\"http://schemas.android.com/apk/res-auto\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" tools:context=\".MainActivity\" android:orientation=\"vertical\"> <RadioGroup android:id=\"@+id/radioGroup\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:paddingStart=\"25dp\"> </RadioGroup></LinearLayout>",
"e": 1445,
"s": 840,
"text": null
},
{
"code": null,
"e": 1570,
"s": 1445,
"text": "The above code will still produce some errors, to resolve these add the following code snippet to app/res/values/strings.xml"
},
{
"code": "<resources> <string name=\"app_name\">DynamicRadioButton</string> <string name=\"black\">Black</string> <string name=\"white\">White</string> <string name=\"blue\">Blue</string> <string name=\"you_selected\">You selected:</string> </resources>",
"e": 1820,
"s": 1570,
"text": null
},
{
"code": null,
"e": 1896,
"s": 1820,
"text": "Here, we define three radio buttons for the color and set their attributes."
},
{
"code": null,
"e": 1934,
"s": 1896,
"text": " val radioButton1 = RadioButton(this)"
},
{
"code": null,
"e": 1977,
"s": 1934,
"text": "then, use them into RadioGroup using code:"
},
{
"code": null,
"e": 2077,
"s": 1977,
"text": "radioGroup.addView(radioButton1)\nradioGroup.addView(radioButton2)\nradioGroup.addView(radioButton3)\n"
},
{
"code": "package com.geeksforgeeks.myfirstkotlinappimport android.annotation.SuppressLintimport androidx.appcompat.app.AppCompatActivityimport android.os.Bundleimport android.view.ViewGroupimport android.widget.LinearLayoutimport android.widget.RadioButtonimport android.widget.RadioGroupimport android.widget.Toast class MainActivity : AppCompatActivity() { @SuppressLint(\"ResourceType\") override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) val linearLayout = findViewById<LinearLayout>(R.id.container) // Create RadioButton programmatically val radioButton1 = RadioButton(this) radioButton1.layoutParams= LinearLayout.LayoutParams( ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT) radioButton1.setText(\"Black\") radioButton1.id = 1 val radioButton2 = RadioButton(this) radioButton2.layoutParams = LinearLayout.LayoutParams( ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT) radioButton2.setText(\"White\") radioButton2.id = 2 val radioButton3 = RadioButton(this) radioButton3.layoutParams = LinearLayout.LayoutParams( ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT) radioButton3.setText(\"Blue\") radioButton3.id = 3 val radioGroup = findViewById<RadioGroup>(R.id.radioGroup) if (radioGroup != null) { radioGroup.addView(radioButton1) radioGroup.addView(radioButton2) radioGroup.addView(radioButton3) radioGroup.setOnCheckedChangeListener { group, checkedId -> var string = getString(R.string.you_selected) string += \" \" + getString( if (checkedId == 1) R.string.black else if(checkedId == 2 ) R.string.white else R.string.blue ) Toast.makeText(applicationContext, string, Toast.LENGTH_SHORT).show() } } }}",
"e": 4206,
"s": 2077,
"text": null
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><manifest xmlns:android=\"http://schemas.android.com/apk/res/android\"package=\"com.geeksforgeeks.myfirstkotlinapp\"> <application android:allowBackup=\"true\" android:icon=\"@mipmap/ic_launcher\" android:label=\"@string/app_name\" android:roundIcon=\"@mipmap/ic_launcher_round\" android:supportsRtl=\"true\" android:theme=\"@style/AppTheme\"> <activity android:name=\".MainActivity\"> <intent-filter> <action android:name=\"android.intent.action.MAIN\" /> <category android:name=\"android.intent.category.LAUNCHER\" /> </intent-filter> </activity></application> </manifest>",
"e": 4861,
"s": 4206,
"text": null
},
{
"code": null,
"e": 4878,
"s": 4863,
"text": "Android-Button"
},
{
"code": null,
"e": 4893,
"s": 4878,
"text": "Kotlin Android"
},
{
"code": null,
"e": 4900,
"s": 4893,
"text": "Picked"
},
{
"code": null,
"e": 4908,
"s": 4900,
"text": "Android"
},
{
"code": null,
"e": 4915,
"s": 4908,
"text": "Kotlin"
},
{
"code": null,
"e": 4923,
"s": 4915,
"text": "Android"
},
{
"code": null,
"e": 5021,
"s": 4923,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 5090,
"s": 5021,
"text": "How to Add Views Dynamically and Store Data in Arraylist in Android?"
},
{
"code": null,
"e": 5122,
"s": 5090,
"text": "Android SDK and it's Components"
},
{
"code": null,
"e": 5171,
"s": 5122,
"text": "How to Communicate Between Fragments in Android?"
},
{
"code": null,
"e": 5210,
"s": 5171,
"text": "Flutter - Custom Bottom Navigation Bar"
},
{
"code": null,
"e": 5252,
"s": 5210,
"text": "Retrofit with Kotlin Coroutine in Android"
},
{
"code": null,
"e": 5321,
"s": 5252,
"text": "How to Add Views Dynamically and Store Data in Arraylist in Android?"
},
{
"code": null,
"e": 5340,
"s": 5321,
"text": "Android UI Layouts"
},
{
"code": null,
"e": 5389,
"s": 5340,
"text": "How to Communicate Between Fragments in Android?"
},
{
"code": null,
"e": 5402,
"s": 5389,
"text": "Kotlin Array"
}
] |
Partition a set into two subsets such that the difference of subset sums is minimum
|
27 May, 2022
Given a set of integers, the task is to divide it into two sets S1 and S2 such that the absolute difference between their sums is minimum. If there is a set S with n elements, then if we assume Subset1 has m elements, Subset2 must have n-m elements and the value of abs(sum(Subset1) – sum(Subset2)) should be minimum.
Example:
Input: arr[] = {1, 6, 11, 5}
Output: 1
Explanation:
Subset1 = {1, 5, 6}, sum of Subset1 = 12
Subset2 = {11}, sum of Subset2 = 11
This problem is mainly an extension to the Dynamic Programming| Set 18 (Partition Problem). Recursive Solution The recursive approach is to generate all possible sums from all the values of the array and to check which solution is the most optimal one. To generate sums we either include the i’th item in set 1 or don’t include, i.e., include in set 2.
C++
Java
Python3
C#
Javascript
// A Recursive C++ program to solve minimum sum partition// problem.#include <bits/stdc++.h>using namespace std; // Function to find the minimum sumint findMinRec(int arr[], int i, int sumCalculated, int sumTotal){ // If we have reached last element. Sum of one // subset is sumCalculated, sum of other subset is // sumTotal-sumCalculated. Return absolute difference // of two sums. if (i == 0) return abs((sumTotal - sumCalculated) - sumCalculated); // For every item arr[i], we have two choices // (1) We do not include it first set // (2) We include it in first set // We return minimum of two choices return min( findMinRec(arr, i - 1, sumCalculated + arr[i - 1], sumTotal), findMinRec(arr, i - 1, sumCalculated, sumTotal));} // Returns minimum possible difference between sums// of two subsetsint findMin(int arr[], int n){ // Compute total sum of elements int sumTotal = 0; for (int i = 0; i < n; i++) sumTotal += arr[i]; // Compute result using recursive function return findMinRec(arr, n, 0, sumTotal);} // Driver program to test above functionint main(){ int arr[] = { 3, 1, 4, 2, 2, 1 }; int n = sizeof(arr) / sizeof(arr[0]); cout << "The minimum difference between two sets is " << findMin(arr, n); return 0;}
// JAVA code to partition a set into two subsets// such that the difference of subset sums// is minimumimport java.util.*; class GFG { // Function to find the minimum sum public static int findMinRec(int arr[], int i, int sumCalculated, int sumTotal) { // If we have reached last element. // Sum of one subset is sumCalculated, // sum of other subset is sumTotal- // sumCalculated. Return absolute // difference of two sums. if (i == 0) return Math.abs((sumTotal - sumCalculated) - sumCalculated); // For every item arr[i], we have two choices // (1) We do not include it first set // (2) We include it in first set // We return minimum of two choices return Math.min( findMinRec(arr, i - 1, sumCalculated + arr[i - 1], sumTotal), findMinRec(arr, i - 1, sumCalculated, sumTotal)); } // Returns minimum possible difference between // sums of two subsets public static int findMin(int arr[], int n) { // Compute total sum of elements int sumTotal = 0; for (int i = 0; i < n; i++) sumTotal += arr[i]; // Compute result using recursive function return findMinRec(arr, n, 0, sumTotal); } /* Driver program to test above function */ public static void main(String[] args) { int arr[] = { 3, 1, 4, 2, 2, 1 }; int n = arr.length; System.out.print("The minimum difference" + " between two sets is " + findMin(arr, n)); }} // This code is contributed by Arnav Kr. Mandal.
# Python3 program for the# above approach# A Recursive C program to# solve minimum sum partition# problem. # Function to find the minimum sum def findMinRec(arr, i, sumCalculated, sumTotal): # If we have reached last element. # Sum of one subset is sumCalculated, # sum of other subset is sumTotal- # sumCalculated. Return absolute # difference of two sums. if (i == 0): return abs((sumTotal - sumCalculated) - sumCalculated) # For every item arr[i], we have two choices # (1) We do not include it first set # (2) We include it in first set # We return minimum of two choices return min(findMinRec(arr, i - 1, sumCalculated+arr[i - 1], sumTotal), findMinRec(arr, i - 1, sumCalculated, sumTotal)) # Returns minimum possible# difference between sums# of two subsets def findMin(arr, n): # Compute total sum # of elements sumTotal = 0 for i in range(n): sumTotal += arr[i] # Compute result using # recursive function return findMinRec(arr, n, 0, sumTotal) # Driver codeif __name__ == "__main__": arr = [3, 1, 4, 2, 2, 1] n = len(arr) print("The minimum difference " + "between two sets is ", findMin(arr, n)) # This code is contributed by Chitranayal
// C# code to partition a set into two subsets// such that the difference of subset sums// is minimumusing System; class GFG { // Function to find the minimum sum public static int findMinRec(int[] arr, int i, int sumCalculated, int sumTotal) { // If we have reached last element. // Sum of one subset is sumCalculated, // sum of other subset is sumTotal- // sumCalculated. Return absolute // difference of two sums. if (i == 0) return Math.Abs((sumTotal - sumCalculated) - sumCalculated); // For every item arr[i], we have two choices // (1) We do not include it first set // (2) We include it in first set // We return minimum of two choices return Math.Min( findMinRec(arr, i - 1, sumCalculated + arr[i - 1], sumTotal), findMinRec(arr, i - 1, sumCalculated, sumTotal)); } // Returns minimum possible difference between // sums of two subsets public static int findMin(int[] arr, int n) { // Compute total sum of elements int sumTotal = 0; for (int i = 0; i < n; i++) sumTotal += arr[i]; // Compute result using recursive function return findMinRec(arr, n, 0, sumTotal); } /* Driver program to test above function */ public static void Main() { int[] arr = { 3, 1, 4, 2, 2, 1 }; int n = arr.Length; Console.Write("The minimum difference" + " between two sets is " + findMin(arr, n)); }} // This code is contributed by nitin mittal.
<script> // JAVAscript code to partition a set into two subsets// such that the difference of subset sums// is minimum // Function to find the minimum sum function findMinRec(arr, i, sumCalculated, sumTotal) { // If we have reached last element. // Sum of one subset is sumCalculated, // sum of other subset is sumTotal- // sumCalculated. Return absolute // difference of two sums. if (i == 0) return Math.abs((sumTotal-sumCalculated) - sumCalculated); // For every item arr[i], we have two choices // (1) We do not include it first set // (2) We include it in first set // We return minimum of two choices return Math.min(findMinRec(arr, i - 1, sumCalculated + arr[i-1], sumTotal), findMinRec(arr, i-1, sumCalculated, sumTotal)); } // Returns minimum possible difference between // sums of two subsets function findMin(arr, n) { // Compute total sum of elements let sumTotal = 0; for (let i = 0; i < n; i++) sumTotal += arr[i]; // Compute result using recursive function return findMinRec(arr, n, 0, sumTotal); } /* Driver program to test above function */ let arr=[3, 1, 4, 2, 2, 1]; let n = arr.length; document.write("The minimum difference"+ " between two sets is " + findMin(arr, n)); // This code is contributed by rag2127</script>
Output:
The minimum difference between two sets is 1
Time Complexity:
All the sums can be generated by either
(1) including that element in set 1.
(2) without including that element in set 1.
So possible combinations are :-
arr[0] (1 or 2) -> 2 values
arr[1] (1 or 2) -> 2 values
.
.
.
arr[n] (2 or 2) -> 2 values
So time complexity will be 2*2*..... *2 (For n times),
that is O(2^n).
Dynamic Programming The problem can be solved using dynamic programming when the sum of the elements is not too big. We can create a 2D array dp[n+1][sum+1] where n is the number of elements in a given set and sum is the sum of all elements. We can construct the solution in a bottom-up manner.
The task is to divide the set into two parts.
We will consider the following factors for dividing it.
Let
dp[n+1][sum+1] = {1 if some subset from 1st to i'th has a sum
equal to j
0 otherwise}
i ranges from {1..n}
j ranges from {0..(sum of all elements)}
So
dp[n+1][sum+1] will be 1 if
1) The sum j is achieved including i'th item
2) The sum j is achieved excluding i'th item.
Let sum of all the elements be S.
To find Minimum sum difference, w have to find j such
that Min{sum - j*2 : dp[n][j] == 1 }
where j varies from 0 to sum/2
The idea is, sum of S1 is j and it should be closest
to sum/2, i.e., 2*j should be closest to sum.
Below is the implementation of the above code.
C++
Java
Python3
C#
Javascript
// A Recursive C++ program to solve minimum sum partition// problem.#include <bits/stdc++.h>using namespace std; // Returns the minimum value of the difference of the two// sets.int findMin(int arr[], int n){ // Calculate sum of all elements int sum = 0; for (int i = 0; i < n; i++) sum += arr[i]; // Create an array to store results of subproblems bool dp[n + 1][sum + 1]; // Initialize first column as true. 0 sum is possible // with all elements. for (int i = 0; i <= n; i++) dp[i][0] = true; // Initialize top row, except dp[0][0], as false. With // 0 elements, no other sum except 0 is possible for (int i = 1; i <= sum; i++) dp[0][i] = false; // Fill the partition table in bottom up manner for (int i = 1; i <= n; i++) { for (int j = 1; j <= sum; j++) { // If i'th element is excluded dp[i][j] = dp[i - 1][j]; // If i'th element is included if (arr[i - 1] <= j) dp[i][j] |= dp[i - 1][j - arr[i - 1]]; } } // Initialize difference of two sums. int diff = INT_MAX; // Find the largest j such that dp[n][j] // is true where j loops from sum/2 t0 0 for (int j = sum / 2; j >= 0; j--) { // Find the if (dp[n][j] == true) { diff = sum - 2 * j; break; } } return diff;} // Driver program to test above functionint main(){ int arr[] = { 3, 1, 4, 2, 2, 1 }; int n = sizeof(arr) / sizeof(arr[0]); cout << "The minimum difference between 2 sets is " << findMin(arr, n); return 0;}
// A Recursive java program to solve// minimum sum partition problem.import java.io.*; class GFG { // Returns the minimum value of // the difference of the two sets. static int findMin(int arr[], int n) { // Calculate sum of all elements int sum = 0; for (int i = 0; i < n; i++) sum += arr[i]; // Create an array to store // results of subproblems boolean dp[][] = new boolean[n + 1][sum + 1]; // Initialize first column as true. // 0 sum is possible with all elements. for (int i = 0; i <= n; i++) dp[i][0] = true; // Initialize top row, except dp[0][0], // as false. With 0 elements, no other // sum except 0 is possible for (int i = 1; i <= sum; i++) dp[0][i] = false; // Fill the partition table // in bottom up manner for (int i = 1; i <= n; i++) { for (int j = 1; j <= sum; j++) { // If i'th element is excluded dp[i][j] = dp[i - 1][j]; // If i'th element is included if (arr[i - 1] <= j) dp[i][j] |= dp[i - 1][j - arr[i - 1]]; } } // Initialize difference of two sums. int diff = Integer.MAX_VALUE; // Find the largest j such that dp[n][j] // is true where j loops from sum/2 t0 0 for (int j = sum / 2; j >= 0; j--) { // Find the if (dp[n][j] == true) { diff = sum - 2 * j; break; } } return diff; } // Driver program public static void main(String[] args) { int arr[] = { 3, 1, 4, 2, 2, 1 }; int n = arr.length; System.out.println( "The minimum difference between 2 sets is " + findMin(arr, n)); }}// This code is contributed by vt_m
# A Recursive Python3 program to solve# minimum sum partition problem.import sys # Returns the minimum value of the# difference of the two sets. def findMin(a, n): su = 0 # Calculate sum of all elements su = sum(a) # Create an 2d list to store # results of subproblems dp = [[0 for i in range(su + 1)] for j in range(n + 1)] # Initialize first column as true. # 0 sum is possible # with all elements. for i in range(n + 1): dp[i][0] = True # Initialize top row, except dp[0][0], # as false. With 0 elements, no other # sum except 0 is possible for j in range(1, su + 1): dp[0][j] = False # Fill the partition table in # bottom up manner for i in range(1, n + 1): for j in range(1, su + 1): # If i'th element is excluded dp[i][j] = dp[i - 1][j] # If i'th element is included if a[i - 1] <= j: dp[i][j] |= dp[i - 1][j - a[i - 1]] # Initialize difference # of two sums. diff = sys.maxsize # Find the largest j such that dp[n][j] # is true where j loops from sum/2 t0 0 for j in range(su // 2, -1, -1): if dp[n][j] == True: diff = su - (2 * j) break return diff # Driver codea = [3, 1, 4, 2, 2, 1]n = len(a) print("The minimum difference between " "2 sets is ", findMin(a, n)) # This code is contributed by Tokir Manva
// A Recursive C# program to solve// minimum sum partition problem.using System; class GFG { // Returns the minimum value of // the difference of the two sets. static int findMin(int[] arr, int n) { // Calculate sum of all elements int sum = 0; for (int i = 0; i < n; i++) sum += arr[i]; // Create an array to store // results of subproblems bool[, ] dp = new bool[n + 1, sum + 1]; // Initialize first column as true. // 0 sum is possible with all elements. for (int i = 0; i <= n; i++) dp[i, 0] = true; // Initialize top row, except dp[0,0], // as false. With 0 elements, no other // sum except 0 is possible for (int i = 1; i <= sum; i++) dp[0, i] = false; // Fill the partition table // in bottom up manner for (int i = 1; i <= n; i++) { for (int j = 1; j <= sum; j++) { // If i'th element is excluded dp[i, j] = dp[i - 1, j]; // If i'th element is included if (arr[i - 1] <= j) dp[i, j] |= dp[i - 1, j - arr[i - 1]]; } } // Initialize difference of two sums. int diff = int.MaxValue; // Find the largest j such that dp[n,j] // is true where j loops from sum/2 t0 0 for (int j = sum / 2; j >= 0; j--) { // Find the if (dp[n, j] == true) { diff = sum - 2 * j; break; } } return diff; } // Driver code public static void Main(String[] args) { int[] arr = { 3, 1, 4, 2, 2, 1 }; int n = arr.Length; Console.WriteLine("The minimum difference " + "between 2 sets is " + findMin(arr, n)); }} // This code is contributed by Rajput-Ji
<script> // A Recursive JavaScript program to solve minimum sum partition// problem. // Returns the minimum value of the difference of the two sets.function findMin(arr, n){ // Calculate sum of all elements let sum = 0; for (let i = 0; i < n; i++) sum += arr[i]; // Create an array to store results of subproblems let dp = new Array(n + 1); // Initialize first column as true. 0 sum is possible // with all elements. for (let i = 0; i <= n; i++) { dp[i] = new Array(sum + 1); for(let j = 0; j <= sum; j++) { if(j == 0) dp[i][j] = true; } } // Initialize top row, except dp[0][0], as false. With // 0 elements, no other sum except 0 is possible for (let i = 1; i <= sum; i++) dp[0][i] = false; // Fill the partition table in bottom up manner for (let i=1; i<=n; i++) { for (let j=1; j<=sum; j++) { // If i'th element is excluded dp[i][j] = dp[i-1][j]; // If i'th element is included if (arr[i-1] <= j) dp[i][j] |= dp[i-1][j-arr[i-1]]; } } // Initialize difference of two sums. let diff = Number.MAX_VALUE; // Find the largest j such that dp[n][j] // is true where j loops from sum/2 t0 0 for (let j=Math.floor(sum/2); j>=0; j--) { // Find the if (dp[n][j] == true) { diff = sum-2*j; break; } } return diff;} // Driver program to test above function let arr = [ 3, 1, 4, 2, 2, 1 ]; let n = arr.length; document.write( "The minimum difference between 2 sets is " + findMin(arr, n)); // This code is contributed by Dharanendra L V. </script>
Output:
The minimum difference between 2 sets is 1
Time Complexity = O(n*sum) where n is the number of elements and sum is the sum of all elements.
Dynamic Programming with less Space Complexity:
Instead of using 2D array we can solve this problem using 1D array dp[sum/2+1] .
lets say sum of elements of set 1 is x than sum of elements of set 2 will be sm-x (sm is sum of all elements of arr).
So we have to minimize abs(sm-2*x).
So for minimizing difference between two sets, we need to know a number that is just less than sum/2 (sum is sum of all elements in array) and can be generated by addition of elements from array.
C++
Java
Python3
C#
Javascript
#include <iostream>using namespace std; int minDifference(int arr[], int n){ int sum = 0; for (int i = 0; i < n; i++) sum += arr[i]; int y = sum / 2 + 1; // dp[i] gives whether is it possible to get i as sum of // elements dd is helper variable // we use dd to ignoring duplicates bool dp[y], dd[y]; // Initialising dp and dd for (int i = 0; i < y; i++) { dp[i] = dd[i] = false; } // sum = 0 is possible dd[0] = true; for (int i = 0; i < n; i++) { // updating dd[k] as true if k can be formed using // elements from 1 to i+1 for (int j = 0; j + arr[i] < y; j++) { if (dp[j]) dd[j + arr[i]] = true; } // updating dd for (int j = 0; j < y; j++) { if (dd[j]) dp[j] = true; dd[j] = false; // reset dd } } // checking the number from sum/2 to 1 which is possible // to get as sum for (int i = y - 1; i >= 0; i--) { if (dp[i]) return (sum - 2 * i); // since i is possible to form then another number // is sum-i // so mindifference is sum-i-i }}int main(){ int arr[] = { 1, 6, 11, 5 }; int n = sizeof(arr) / sizeof(arr[0]); cout << "The Minimum difference of 2 sets is " << minDifference(arr, n) << '\n'; return 0;}
import java.util.*; class GFG { static int minDifference(int arr[], int n) { int sum = 0; for (int i = 0; i < n; i++) sum += arr[i]; int y = sum / 2 + 1; // dp[i] gives whether is it possible to get i as // sum of elements dd is helper variable we use dd // to ignoring duplicates boolean dp[] = new boolean[y], dd[] = new boolean[y]; // Initialising dp and dd for (int i = 0; i < y; i++) { dp[i] = dd[i] = false; } // sum = 0 is possible dd[0] = true; for (int i = 0; i < n; i++) { // updating dd[k] as true if k can be formed // using elements from 1 to i+1 for (int j = 0; j + arr[i] < y; j++) { if (dp[j]) dd[j + arr[i]] = true; } // updating dd for (int j = 0; j < y; j++) { if (dd[j]) dp[j] = true; dd[j] = false; // reset dd } } // checking the number from sum/2 to 1 which is // possible to get as sum for (int i = y - 1; i >= 0; i--) { if (dp[i]) return (sum - 2 * i); // since i is possible to form then another // number is sum-i so mindifference is sum-i-i } return 0; } public static void main(String[] args) { int arr[] = { 1, 6, 11, 5 }; int n = arr.length; System.out.print( "The Minimum difference of 2 sets is " + minDifference(arr, n) + '\n'); }} // This code is contributed by umadevi9616
def minDifference(arr, n): sum = 0; for i in range(n): sum += arr[i]; y = sum // 2 + 1; # dp[i] gives whether is it possible to get i as # sum of elements dd is helper variable we use dd # to ignoring duplicates dp = [False for i in range(y)] dd = [False for i in range(y)] # Initialising dp and dd # sum = 0 is possible dd[0] = True; for i in range(n): # updating dd[k] as True if k can be formed # using elements from 1 to i+1 for j in range(y): if (j + arr[i] < y and dp[j]): dd[j + arr[i]] = True; # updating dd for j in range(y): if (dd[j]): dp[j] = True; dd[j] = False; # reset dd # checking the number from sum/2 to 1 which is # possible to get as sum for i in range(y-1, 0, -1): if (dp[i]): return (sum - 2 * i); # since i is possible to form then another # number is sum-i so mindifference is sum-i-i return 0; if __name__ == '__main__': arr = [ 1, 6, 11, 5 ]; n = len(arr); print("The Minimum difference of 2 sets is ", minDifference(arr, n)); # This code is contributed by umadevi9616
using System; public class GFG { static int minDifference(int []arr, int n) { int sum = 0; for (int i = 0; i < n; i++) sum += arr[i]; int y = sum / 2 + 1; // dp[i] gives whether is it possible to get i as // sum of elements dd is helper variable we use dd // to ignoring duplicates bool []dp = new bool[y];bool []dd = new bool[y]; // Initialising dp and dd for (int i = 0; i < y; i++) { dp[i] = dd[i] = false; } // sum = 0 is possible dd[0] = true; for (int i = 0; i < n; i++) { // updating dd[k] as true if k can be formed // using elements from 1 to i+1 for (int j = 0; j + arr[i] < y; j++) { if (dp[j]) dd[j + arr[i]] = true; } // updating dd for (int j = 0; j < y; j++) { if (dd[j]) dp[j] = true; dd[j] = false; // reset dd } } // checking the number from sum/2 to 1 which is // possible to get as sum for (int i = y - 1; i >= 0; i--) { if (dp[i]) return (sum - 2 * i); // since i is possible to form then another // number is sum-i so mindifference is sum-i-i } return 0; } public static void Main(String[] args) { int []arr = { 1, 6, 11, 5 }; int n = arr.Length; Console.Write( "The Minimum difference of 2 sets is " + minDifference(arr, n) + '\n'); }} // This code contributed by gauravrajput1
<script> function minDifference(arr , n) { var sum = 0; for (var i = 0; i < n; i++) sum += arr[i]; var y = parseInt(sum / 2) + 1; // dp[i] gives whether is it possible to get i as // sum of elements dd is helper variable we use dd // to ignoring duplicates var dp = Array(y).fill(false), dd = Array(y).fill(false); // Initialising dp and dd for (var i = 0; i < y; i++) { dp[i] = dd[i] = false; } // sum = 0 is possible dd[0] = true; for ( var i = 0; i < n; i++) { // updating dd[k] as true if k can be formed // using elements from 1 to i+1 for (var j = 0; j + arr[i] < y; j++) { if (dp[j]) dd[j + arr[i]] = true; } // updating dd for (var j = 0; j < y; j++) { if (dd[j]) dp[j] = true; dd[j] = false; // reset dd } } // checking the number from sum/2 to 1 which is // possible to get as sum for (var i = y - 1; i >= 0; i--) { if (dp[i]) return (sum - 2 * i); // since i is possible to form then another // number is sum-i so mindifference is sum-i-i } return 0; } var arr = [ 1, 6, 11, 5 ]; var n = arr.length; document.write("The Minimum difference of 2 sets is " + minDifference(arr, n) + '\n'); // This code is contributed by gauravrajput1</script>
The Minimum difference of 2 sets is 1
Time Complexity: O(n*sum)Auxiliary Space: O(sum)
Note that the above solution is in Pseudo Polynomial Time (time complexity is dependent on the numeric value of input).This article is contributed by Abhiraj Smit. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
nitin mittal
draculemihawk
Rajput-Ji
ukasp
rag2127
dharanendralv23
mehtabalam
dinijain99
umadevi9616
GauravRajput1
rkbhola5
sanskar84
Amazon
Samsung
Dynamic Programming
Amazon
Samsung
Dynamic Programming
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n27 May, 2022"
},
{
"code": null,
"e": 370,
"s": 52,
"text": "Given a set of integers, the task is to divide it into two sets S1 and S2 such that the absolute difference between their sums is minimum. If there is a set S with n elements, then if we assume Subset1 has m elements, Subset2 must have n-m elements and the value of abs(sum(Subset1) – sum(Subset2)) should be minimum."
},
{
"code": null,
"e": 380,
"s": 370,
"text": "Example: "
},
{
"code": null,
"e": 520,
"s": 380,
"text": "Input: arr[] = {1, 6, 11, 5} \nOutput: 1\nExplanation:\nSubset1 = {1, 5, 6}, sum of Subset1 = 12 \nSubset2 = {11}, sum of Subset2 = 11 "
},
{
"code": null,
"e": 875,
"s": 520,
"text": "This problem is mainly an extension to the Dynamic Programming| Set 18 (Partition Problem). Recursive Solution The recursive approach is to generate all possible sums from all the values of the array and to check which solution is the most optimal one. To generate sums we either include the i’th item in set 1 or don’t include, i.e., include in set 2. "
},
{
"code": null,
"e": 879,
"s": 875,
"text": "C++"
},
{
"code": null,
"e": 884,
"s": 879,
"text": "Java"
},
{
"code": null,
"e": 892,
"s": 884,
"text": "Python3"
},
{
"code": null,
"e": 895,
"s": 892,
"text": "C#"
},
{
"code": null,
"e": 906,
"s": 895,
"text": "Javascript"
},
{
"code": "// A Recursive C++ program to solve minimum sum partition// problem.#include <bits/stdc++.h>using namespace std; // Function to find the minimum sumint findMinRec(int arr[], int i, int sumCalculated, int sumTotal){ // If we have reached last element. Sum of one // subset is sumCalculated, sum of other subset is // sumTotal-sumCalculated. Return absolute difference // of two sums. if (i == 0) return abs((sumTotal - sumCalculated) - sumCalculated); // For every item arr[i], we have two choices // (1) We do not include it first set // (2) We include it in first set // We return minimum of two choices return min( findMinRec(arr, i - 1, sumCalculated + arr[i - 1], sumTotal), findMinRec(arr, i - 1, sumCalculated, sumTotal));} // Returns minimum possible difference between sums// of two subsetsint findMin(int arr[], int n){ // Compute total sum of elements int sumTotal = 0; for (int i = 0; i < n; i++) sumTotal += arr[i]; // Compute result using recursive function return findMinRec(arr, n, 0, sumTotal);} // Driver program to test above functionint main(){ int arr[] = { 3, 1, 4, 2, 2, 1 }; int n = sizeof(arr) / sizeof(arr[0]); cout << \"The minimum difference between two sets is \" << findMin(arr, n); return 0;}",
"e": 2274,
"s": 906,
"text": null
},
{
"code": "// JAVA code to partition a set into two subsets// such that the difference of subset sums// is minimumimport java.util.*; class GFG { // Function to find the minimum sum public static int findMinRec(int arr[], int i, int sumCalculated, int sumTotal) { // If we have reached last element. // Sum of one subset is sumCalculated, // sum of other subset is sumTotal- // sumCalculated. Return absolute // difference of two sums. if (i == 0) return Math.abs((sumTotal - sumCalculated) - sumCalculated); // For every item arr[i], we have two choices // (1) We do not include it first set // (2) We include it in first set // We return minimum of two choices return Math.min( findMinRec(arr, i - 1, sumCalculated + arr[i - 1], sumTotal), findMinRec(arr, i - 1, sumCalculated, sumTotal)); } // Returns minimum possible difference between // sums of two subsets public static int findMin(int arr[], int n) { // Compute total sum of elements int sumTotal = 0; for (int i = 0; i < n; i++) sumTotal += arr[i]; // Compute result using recursive function return findMinRec(arr, n, 0, sumTotal); } /* Driver program to test above function */ public static void main(String[] args) { int arr[] = { 3, 1, 4, 2, 2, 1 }; int n = arr.length; System.out.print(\"The minimum difference\" + \" between two sets is \" + findMin(arr, n)); }} // This code is contributed by Arnav Kr. Mandal.",
"e": 4063,
"s": 2274,
"text": null
},
{
"code": "# Python3 program for the# above approach# A Recursive C program to# solve minimum sum partition# problem. # Function to find the minimum sum def findMinRec(arr, i, sumCalculated, sumTotal): # If we have reached last element. # Sum of one subset is sumCalculated, # sum of other subset is sumTotal- # sumCalculated. Return absolute # difference of two sums. if (i == 0): return abs((sumTotal - sumCalculated) - sumCalculated) # For every item arr[i], we have two choices # (1) We do not include it first set # (2) We include it in first set # We return minimum of two choices return min(findMinRec(arr, i - 1, sumCalculated+arr[i - 1], sumTotal), findMinRec(arr, i - 1, sumCalculated, sumTotal)) # Returns minimum possible# difference between sums# of two subsets def findMin(arr, n): # Compute total sum # of elements sumTotal = 0 for i in range(n): sumTotal += arr[i] # Compute result using # recursive function return findMinRec(arr, n, 0, sumTotal) # Driver codeif __name__ == \"__main__\": arr = [3, 1, 4, 2, 2, 1] n = len(arr) print(\"The minimum difference \" + \"between two sets is \", findMin(arr, n)) # This code is contributed by Chitranayal",
"e": 5458,
"s": 4063,
"text": null
},
{
"code": "// C# code to partition a set into two subsets// such that the difference of subset sums// is minimumusing System; class GFG { // Function to find the minimum sum public static int findMinRec(int[] arr, int i, int sumCalculated, int sumTotal) { // If we have reached last element. // Sum of one subset is sumCalculated, // sum of other subset is sumTotal- // sumCalculated. Return absolute // difference of two sums. if (i == 0) return Math.Abs((sumTotal - sumCalculated) - sumCalculated); // For every item arr[i], we have two choices // (1) We do not include it first set // (2) We include it in first set // We return minimum of two choices return Math.Min( findMinRec(arr, i - 1, sumCalculated + arr[i - 1], sumTotal), findMinRec(arr, i - 1, sumCalculated, sumTotal)); } // Returns minimum possible difference between // sums of two subsets public static int findMin(int[] arr, int n) { // Compute total sum of elements int sumTotal = 0; for (int i = 0; i < n; i++) sumTotal += arr[i]; // Compute result using recursive function return findMinRec(arr, n, 0, sumTotal); } /* Driver program to test above function */ public static void Main() { int[] arr = { 3, 1, 4, 2, 2, 1 }; int n = arr.Length; Console.Write(\"The minimum difference\" + \" between two sets is \" + findMin(arr, n)); }} // This code is contributed by nitin mittal.",
"e": 7213,
"s": 5458,
"text": null
},
{
"code": "<script> // JAVAscript code to partition a set into two subsets// such that the difference of subset sums// is minimum // Function to find the minimum sum function findMinRec(arr, i, sumCalculated, sumTotal) { // If we have reached last element. // Sum of one subset is sumCalculated, // sum of other subset is sumTotal- // sumCalculated. Return absolute // difference of two sums. if (i == 0) return Math.abs((sumTotal-sumCalculated) - sumCalculated); // For every item arr[i], we have two choices // (1) We do not include it first set // (2) We include it in first set // We return minimum of two choices return Math.min(findMinRec(arr, i - 1, sumCalculated + arr[i-1], sumTotal), findMinRec(arr, i-1, sumCalculated, sumTotal)); } // Returns minimum possible difference between // sums of two subsets function findMin(arr, n) { // Compute total sum of elements let sumTotal = 0; for (let i = 0; i < n; i++) sumTotal += arr[i]; // Compute result using recursive function return findMinRec(arr, n, 0, sumTotal); } /* Driver program to test above function */ let arr=[3, 1, 4, 2, 2, 1]; let n = arr.length; document.write(\"The minimum difference\"+ \" between two sets is \" + findMin(arr, n)); // This code is contributed by rag2127</script>",
"e": 8859,
"s": 7213,
"text": null
},
{
"code": null,
"e": 8868,
"s": 8859,
"text": "Output: "
},
{
"code": null,
"e": 8913,
"s": 8868,
"text": "The minimum difference between two sets is 1"
},
{
"code": null,
"e": 8931,
"s": 8913,
"text": "Time Complexity: "
},
{
"code": null,
"e": 9264,
"s": 8931,
"text": "All the sums can be generated by either \n(1) including that element in set 1.\n(2) without including that element in set 1.\nSo possible combinations are :- \narr[0] (1 or 2) -> 2 values\narr[1] (1 or 2) -> 2 values\n.\n.\n.\narr[n] (2 or 2) -> 2 values\nSo time complexity will be 2*2*..... *2 (For n times),\nthat is O(2^n)."
},
{
"code": null,
"e": 9561,
"s": 9266,
"text": "Dynamic Programming The problem can be solved using dynamic programming when the sum of the elements is not too big. We can create a 2D array dp[n+1][sum+1] where n is the number of elements in a given set and sum is the sum of all elements. We can construct the solution in a bottom-up manner."
},
{
"code": null,
"e": 10288,
"s": 9561,
"text": "The task is to divide the set into two parts. \nWe will consider the following factors for dividing it. \nLet \n dp[n+1][sum+1] = {1 if some subset from 1st to i'th has a sum \n equal to j\n 0 otherwise}\n \n i ranges from {1..n}\n j ranges from {0..(sum of all elements)} \n\nSo \n dp[n+1][sum+1] will be 1 if \n 1) The sum j is achieved including i'th item\n 2) The sum j is achieved excluding i'th item.\n\nLet sum of all the elements be S. \n\nTo find Minimum sum difference, w have to find j such \nthat Min{sum - j*2 : dp[n][j] == 1 } \n where j varies from 0 to sum/2\n\nThe idea is, sum of S1 is j and it should be closest\nto sum/2, i.e., 2*j should be closest to sum."
},
{
"code": null,
"e": 10336,
"s": 10288,
"text": "Below is the implementation of the above code. "
},
{
"code": null,
"e": 10340,
"s": 10336,
"text": "C++"
},
{
"code": null,
"e": 10345,
"s": 10340,
"text": "Java"
},
{
"code": null,
"e": 10353,
"s": 10345,
"text": "Python3"
},
{
"code": null,
"e": 10356,
"s": 10353,
"text": "C#"
},
{
"code": null,
"e": 10367,
"s": 10356,
"text": "Javascript"
},
{
"code": "// A Recursive C++ program to solve minimum sum partition// problem.#include <bits/stdc++.h>using namespace std; // Returns the minimum value of the difference of the two// sets.int findMin(int arr[], int n){ // Calculate sum of all elements int sum = 0; for (int i = 0; i < n; i++) sum += arr[i]; // Create an array to store results of subproblems bool dp[n + 1][sum + 1]; // Initialize first column as true. 0 sum is possible // with all elements. for (int i = 0; i <= n; i++) dp[i][0] = true; // Initialize top row, except dp[0][0], as false. With // 0 elements, no other sum except 0 is possible for (int i = 1; i <= sum; i++) dp[0][i] = false; // Fill the partition table in bottom up manner for (int i = 1; i <= n; i++) { for (int j = 1; j <= sum; j++) { // If i'th element is excluded dp[i][j] = dp[i - 1][j]; // If i'th element is included if (arr[i - 1] <= j) dp[i][j] |= dp[i - 1][j - arr[i - 1]]; } } // Initialize difference of two sums. int diff = INT_MAX; // Find the largest j such that dp[n][j] // is true where j loops from sum/2 t0 0 for (int j = sum / 2; j >= 0; j--) { // Find the if (dp[n][j] == true) { diff = sum - 2 * j; break; } } return diff;} // Driver program to test above functionint main(){ int arr[] = { 3, 1, 4, 2, 2, 1 }; int n = sizeof(arr) / sizeof(arr[0]); cout << \"The minimum difference between 2 sets is \" << findMin(arr, n); return 0;}",
"e": 11971,
"s": 10367,
"text": null
},
{
"code": "// A Recursive java program to solve// minimum sum partition problem.import java.io.*; class GFG { // Returns the minimum value of // the difference of the two sets. static int findMin(int arr[], int n) { // Calculate sum of all elements int sum = 0; for (int i = 0; i < n; i++) sum += arr[i]; // Create an array to store // results of subproblems boolean dp[][] = new boolean[n + 1][sum + 1]; // Initialize first column as true. // 0 sum is possible with all elements. for (int i = 0; i <= n; i++) dp[i][0] = true; // Initialize top row, except dp[0][0], // as false. With 0 elements, no other // sum except 0 is possible for (int i = 1; i <= sum; i++) dp[0][i] = false; // Fill the partition table // in bottom up manner for (int i = 1; i <= n; i++) { for (int j = 1; j <= sum; j++) { // If i'th element is excluded dp[i][j] = dp[i - 1][j]; // If i'th element is included if (arr[i - 1] <= j) dp[i][j] |= dp[i - 1][j - arr[i - 1]]; } } // Initialize difference of two sums. int diff = Integer.MAX_VALUE; // Find the largest j such that dp[n][j] // is true where j loops from sum/2 t0 0 for (int j = sum / 2; j >= 0; j--) { // Find the if (dp[n][j] == true) { diff = sum - 2 * j; break; } } return diff; } // Driver program public static void main(String[] args) { int arr[] = { 3, 1, 4, 2, 2, 1 }; int n = arr.length; System.out.println( \"The minimum difference between 2 sets is \" + findMin(arr, n)); }}// This code is contributed by vt_m",
"e": 13857,
"s": 11971,
"text": null
},
{
"code": "# A Recursive Python3 program to solve# minimum sum partition problem.import sys # Returns the minimum value of the# difference of the two sets. def findMin(a, n): su = 0 # Calculate sum of all elements su = sum(a) # Create an 2d list to store # results of subproblems dp = [[0 for i in range(su + 1)] for j in range(n + 1)] # Initialize first column as true. # 0 sum is possible # with all elements. for i in range(n + 1): dp[i][0] = True # Initialize top row, except dp[0][0], # as false. With 0 elements, no other # sum except 0 is possible for j in range(1, su + 1): dp[0][j] = False # Fill the partition table in # bottom up manner for i in range(1, n + 1): for j in range(1, su + 1): # If i'th element is excluded dp[i][j] = dp[i - 1][j] # If i'th element is included if a[i - 1] <= j: dp[i][j] |= dp[i - 1][j - a[i - 1]] # Initialize difference # of two sums. diff = sys.maxsize # Find the largest j such that dp[n][j] # is true where j loops from sum/2 t0 0 for j in range(su // 2, -1, -1): if dp[n][j] == True: diff = su - (2 * j) break return diff # Driver codea = [3, 1, 4, 2, 2, 1]n = len(a) print(\"The minimum difference between \" \"2 sets is \", findMin(a, n)) # This code is contributed by Tokir Manva",
"e": 15280,
"s": 13857,
"text": null
},
{
"code": "// A Recursive C# program to solve// minimum sum partition problem.using System; class GFG { // Returns the minimum value of // the difference of the two sets. static int findMin(int[] arr, int n) { // Calculate sum of all elements int sum = 0; for (int i = 0; i < n; i++) sum += arr[i]; // Create an array to store // results of subproblems bool[, ] dp = new bool[n + 1, sum + 1]; // Initialize first column as true. // 0 sum is possible with all elements. for (int i = 0; i <= n; i++) dp[i, 0] = true; // Initialize top row, except dp[0,0], // as false. With 0 elements, no other // sum except 0 is possible for (int i = 1; i <= sum; i++) dp[0, i] = false; // Fill the partition table // in bottom up manner for (int i = 1; i <= n; i++) { for (int j = 1; j <= sum; j++) { // If i'th element is excluded dp[i, j] = dp[i - 1, j]; // If i'th element is included if (arr[i - 1] <= j) dp[i, j] |= dp[i - 1, j - arr[i - 1]]; } } // Initialize difference of two sums. int diff = int.MaxValue; // Find the largest j such that dp[n,j] // is true where j loops from sum/2 t0 0 for (int j = sum / 2; j >= 0; j--) { // Find the if (dp[n, j] == true) { diff = sum - 2 * j; break; } } return diff; } // Driver code public static void Main(String[] args) { int[] arr = { 3, 1, 4, 2, 2, 1 }; int n = arr.Length; Console.WriteLine(\"The minimum difference \" + \"between 2 sets is \" + findMin(arr, n)); }} // This code is contributed by Rajput-Ji",
"e": 17186,
"s": 15280,
"text": null
},
{
"code": "<script> // A Recursive JavaScript program to solve minimum sum partition// problem. // Returns the minimum value of the difference of the two sets.function findMin(arr, n){ // Calculate sum of all elements let sum = 0; for (let i = 0; i < n; i++) sum += arr[i]; // Create an array to store results of subproblems let dp = new Array(n + 1); // Initialize first column as true. 0 sum is possible // with all elements. for (let i = 0; i <= n; i++) { dp[i] = new Array(sum + 1); for(let j = 0; j <= sum; j++) { if(j == 0) dp[i][j] = true; } } // Initialize top row, except dp[0][0], as false. With // 0 elements, no other sum except 0 is possible for (let i = 1; i <= sum; i++) dp[0][i] = false; // Fill the partition table in bottom up manner for (let i=1; i<=n; i++) { for (let j=1; j<=sum; j++) { // If i'th element is excluded dp[i][j] = dp[i-1][j]; // If i'th element is included if (arr[i-1] <= j) dp[i][j] |= dp[i-1][j-arr[i-1]]; } } // Initialize difference of two sums. let diff = Number.MAX_VALUE; // Find the largest j such that dp[n][j] // is true where j loops from sum/2 t0 0 for (let j=Math.floor(sum/2); j>=0; j--) { // Find the if (dp[n][j] == true) { diff = sum-2*j; break; } } return diff;} // Driver program to test above function let arr = [ 3, 1, 4, 2, 2, 1 ]; let n = arr.length; document.write( \"The minimum difference between 2 sets is \" + findMin(arr, n)); // This code is contributed by Dharanendra L V. </script>",
"e": 18944,
"s": 17186,
"text": null
},
{
"code": null,
"e": 18953,
"s": 18944,
"text": "Output: "
},
{
"code": null,
"e": 18996,
"s": 18953,
"text": "The minimum difference between 2 sets is 1"
},
{
"code": null,
"e": 19093,
"s": 18996,
"text": "Time Complexity = O(n*sum) where n is the number of elements and sum is the sum of all elements."
},
{
"code": null,
"e": 19141,
"s": 19093,
"text": "Dynamic Programming with less Space Complexity:"
},
{
"code": null,
"e": 19222,
"s": 19141,
"text": "Instead of using 2D array we can solve this problem using 1D array dp[sum/2+1] ."
},
{
"code": null,
"e": 19340,
"s": 19222,
"text": "lets say sum of elements of set 1 is x than sum of elements of set 2 will be sm-x (sm is sum of all elements of arr)."
},
{
"code": null,
"e": 19377,
"s": 19340,
"text": "So we have to minimize abs(sm-2*x). "
},
{
"code": null,
"e": 19574,
"s": 19377,
"text": "So for minimizing difference between two sets, we need to know a number that is just less than sum/2 (sum is sum of all elements in array) and can be generated by addition of elements from array. "
},
{
"code": null,
"e": 19578,
"s": 19574,
"text": "C++"
},
{
"code": null,
"e": 19583,
"s": 19578,
"text": "Java"
},
{
"code": null,
"e": 19591,
"s": 19583,
"text": "Python3"
},
{
"code": null,
"e": 19594,
"s": 19591,
"text": "C#"
},
{
"code": null,
"e": 19605,
"s": 19594,
"text": "Javascript"
},
{
"code": "#include <iostream>using namespace std; int minDifference(int arr[], int n){ int sum = 0; for (int i = 0; i < n; i++) sum += arr[i]; int y = sum / 2 + 1; // dp[i] gives whether is it possible to get i as sum of // elements dd is helper variable // we use dd to ignoring duplicates bool dp[y], dd[y]; // Initialising dp and dd for (int i = 0; i < y; i++) { dp[i] = dd[i] = false; } // sum = 0 is possible dd[0] = true; for (int i = 0; i < n; i++) { // updating dd[k] as true if k can be formed using // elements from 1 to i+1 for (int j = 0; j + arr[i] < y; j++) { if (dp[j]) dd[j + arr[i]] = true; } // updating dd for (int j = 0; j < y; j++) { if (dd[j]) dp[j] = true; dd[j] = false; // reset dd } } // checking the number from sum/2 to 1 which is possible // to get as sum for (int i = y - 1; i >= 0; i--) { if (dp[i]) return (sum - 2 * i); // since i is possible to form then another number // is sum-i // so mindifference is sum-i-i }}int main(){ int arr[] = { 1, 6, 11, 5 }; int n = sizeof(arr) / sizeof(arr[0]); cout << \"The Minimum difference of 2 sets is \" << minDifference(arr, n) << '\\n'; return 0;}",
"e": 20958,
"s": 19605,
"text": null
},
{
"code": "import java.util.*; class GFG { static int minDifference(int arr[], int n) { int sum = 0; for (int i = 0; i < n; i++) sum += arr[i]; int y = sum / 2 + 1; // dp[i] gives whether is it possible to get i as // sum of elements dd is helper variable we use dd // to ignoring duplicates boolean dp[] = new boolean[y], dd[] = new boolean[y]; // Initialising dp and dd for (int i = 0; i < y; i++) { dp[i] = dd[i] = false; } // sum = 0 is possible dd[0] = true; for (int i = 0; i < n; i++) { // updating dd[k] as true if k can be formed // using elements from 1 to i+1 for (int j = 0; j + arr[i] < y; j++) { if (dp[j]) dd[j + arr[i]] = true; } // updating dd for (int j = 0; j < y; j++) { if (dd[j]) dp[j] = true; dd[j] = false; // reset dd } } // checking the number from sum/2 to 1 which is // possible to get as sum for (int i = y - 1; i >= 0; i--) { if (dp[i]) return (sum - 2 * i); // since i is possible to form then another // number is sum-i so mindifference is sum-i-i } return 0; } public static void main(String[] args) { int arr[] = { 1, 6, 11, 5 }; int n = arr.length; System.out.print( \"The Minimum difference of 2 sets is \" + minDifference(arr, n) + '\\n'); }} // This code is contributed by umadevi9616",
"e": 22635,
"s": 20958,
"text": null
},
{
"code": "def minDifference(arr, n): sum = 0; for i in range(n): sum += arr[i]; y = sum // 2 + 1; # dp[i] gives whether is it possible to get i as # sum of elements dd is helper variable we use dd # to ignoring duplicates dp = [False for i in range(y)] dd = [False for i in range(y)] # Initialising dp and dd # sum = 0 is possible dd[0] = True; for i in range(n): # updating dd[k] as True if k can be formed # using elements from 1 to i+1 for j in range(y): if (j + arr[i] < y and dp[j]): dd[j + arr[i]] = True; # updating dd for j in range(y): if (dd[j]): dp[j] = True; dd[j] = False; # reset dd # checking the number from sum/2 to 1 which is # possible to get as sum for i in range(y-1, 0, -1): if (dp[i]): return (sum - 2 * i); # since i is possible to form then another # number is sum-i so mindifference is sum-i-i return 0; if __name__ == '__main__': arr = [ 1, 6, 11, 5 ]; n = len(arr); print(\"The Minimum difference of 2 sets is \", minDifference(arr, n)); # This code is contributed by umadevi9616",
"e": 23878,
"s": 22635,
"text": null
},
{
"code": "using System; public class GFG { static int minDifference(int []arr, int n) { int sum = 0; for (int i = 0; i < n; i++) sum += arr[i]; int y = sum / 2 + 1; // dp[i] gives whether is it possible to get i as // sum of elements dd is helper variable we use dd // to ignoring duplicates bool []dp = new bool[y];bool []dd = new bool[y]; // Initialising dp and dd for (int i = 0; i < y; i++) { dp[i] = dd[i] = false; } // sum = 0 is possible dd[0] = true; for (int i = 0; i < n; i++) { // updating dd[k] as true if k can be formed // using elements from 1 to i+1 for (int j = 0; j + arr[i] < y; j++) { if (dp[j]) dd[j + arr[i]] = true; } // updating dd for (int j = 0; j < y; j++) { if (dd[j]) dp[j] = true; dd[j] = false; // reset dd } } // checking the number from sum/2 to 1 which is // possible to get as sum for (int i = y - 1; i >= 0; i--) { if (dp[i]) return (sum - 2 * i); // since i is possible to form then another // number is sum-i so mindifference is sum-i-i } return 0; } public static void Main(String[] args) { int []arr = { 1, 6, 11, 5 }; int n = arr.Length; Console.Write( \"The Minimum difference of 2 sets is \" + minDifference(arr, n) + '\\n'); }} // This code contributed by gauravrajput1",
"e": 25509,
"s": 23878,
"text": null
},
{
"code": "<script> function minDifference(arr , n) { var sum = 0; for (var i = 0; i < n; i++) sum += arr[i]; var y = parseInt(sum / 2) + 1; // dp[i] gives whether is it possible to get i as // sum of elements dd is helper variable we use dd // to ignoring duplicates var dp = Array(y).fill(false), dd = Array(y).fill(false); // Initialising dp and dd for (var i = 0; i < y; i++) { dp[i] = dd[i] = false; } // sum = 0 is possible dd[0] = true; for ( var i = 0; i < n; i++) { // updating dd[k] as true if k can be formed // using elements from 1 to i+1 for (var j = 0; j + arr[i] < y; j++) { if (dp[j]) dd[j + arr[i]] = true; } // updating dd for (var j = 0; j < y; j++) { if (dd[j]) dp[j] = true; dd[j] = false; // reset dd } } // checking the number from sum/2 to 1 which is // possible to get as sum for (var i = y - 1; i >= 0; i--) { if (dp[i]) return (sum - 2 * i); // since i is possible to form then another // number is sum-i so mindifference is sum-i-i } return 0; } var arr = [ 1, 6, 11, 5 ]; var n = arr.length; document.write(\"The Minimum difference of 2 sets is \" + minDifference(arr, n) + '\\n'); // This code is contributed by gauravrajput1</script>",
"e": 27101,
"s": 25509,
"text": null
},
{
"code": null,
"e": 27142,
"s": 27104,
"text": "The Minimum difference of 2 sets is 1"
},
{
"code": null,
"e": 27193,
"s": 27144,
"text": "Time Complexity: O(n*sum)Auxiliary Space: O(sum)"
},
{
"code": null,
"e": 27484,
"s": 27195,
"text": "Note that the above solution is in Pseudo Polynomial Time (time complexity is dependent on the numeric value of input).This article is contributed by Abhiraj Smit. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 27499,
"s": 27486,
"text": "nitin mittal"
},
{
"code": null,
"e": 27513,
"s": 27499,
"text": "draculemihawk"
},
{
"code": null,
"e": 27523,
"s": 27513,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 27529,
"s": 27523,
"text": "ukasp"
},
{
"code": null,
"e": 27537,
"s": 27529,
"text": "rag2127"
},
{
"code": null,
"e": 27553,
"s": 27537,
"text": "dharanendralv23"
},
{
"code": null,
"e": 27564,
"s": 27553,
"text": "mehtabalam"
},
{
"code": null,
"e": 27575,
"s": 27564,
"text": "dinijain99"
},
{
"code": null,
"e": 27587,
"s": 27575,
"text": "umadevi9616"
},
{
"code": null,
"e": 27601,
"s": 27587,
"text": "GauravRajput1"
},
{
"code": null,
"e": 27610,
"s": 27601,
"text": "rkbhola5"
},
{
"code": null,
"e": 27620,
"s": 27610,
"text": "sanskar84"
},
{
"code": null,
"e": 27627,
"s": 27620,
"text": "Amazon"
},
{
"code": null,
"e": 27635,
"s": 27627,
"text": "Samsung"
},
{
"code": null,
"e": 27655,
"s": 27635,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 27662,
"s": 27655,
"text": "Amazon"
},
{
"code": null,
"e": 27670,
"s": 27662,
"text": "Samsung"
},
{
"code": null,
"e": 27690,
"s": 27670,
"text": "Dynamic Programming"
}
] |
Zombie Processes and their Prevention
|
05 Nov, 2021
Prerequisites: fork() in C, Zombie ProcessZombie state: When a process is created in UNIX using fork() system call, the address space of the Parent process is replicated. If the parent process calls wait() system call, then the execution of the parent is suspended until the child is terminated. At the termination of the child, a ‘SIGCHLD’ signal is generated which is delivered to the parent by the kernel. Parent, on receipt of ‘SIGCHLD’ reads the status of the child from the process table. Even though the child is terminated, there is an entry in the process table corresponding to the child where the status is stored. When the parent collects the status, this entry is deleted. Thus, all the traces of the child process are removed from the system. If the parent decides not to wait for the child’s termination and executes its subsequent task, then at the termination of the child, the exit status is not read. Hence, there remains an entry in the process table even after the termination of the child. This state of the child process is known as the Zombie state.
C
// A C program to demonstrate working of// fork() and process table entries.#include<stdio.h>#include<unistd.h>#include<sys/wait.h>#include<sys/types.h> int main(){ int i; int pid = fork(); if (pid == 0) { for (i=0; i<20; i++) printf("I am Child\n"); } else { printf("I am Parent\n"); while(1); }}
Output :
Now check the process table using the following command in the terminal$ ps -eaf
Here the entry [a.out] defunct shows the zombie process.
Why do we need to prevent the creation of the Zombie process? There is one process table per system. The size of the process table is finite. If too many zombie processes are generated, then the process table will be full. That is, the system will not be able to generate any new process, then the system will come to a standstill. Hence, we need to prevent the creation of zombie processes.
1. Using wait() system call: When the parent process calls wait(), after the creation of a child, it indicates that, it will wait for the child to complete and it will reap the exit status of the child. The parent process is suspended(waits in a waiting queue) until the child is terminated. It must be understood that during this period, the parent process does nothing just wait.
C
// A C program to demonstrate working of// fork()/wait() and Zombie processes#include<stdio.h>#include<unistd.h>#include<sys/wait.h>#include<sys/types.h> int main(){ int i; int pid = fork(); if (pid==0) { for (i=0; i<20; i++) printf("I am Child\n"); } else { wait(NULL); printf("I am Parent\n"); while(1); }}
2. By ignoring the SIGCHLD signal: When a child is terminated, a corresponding SIGCHLD signal is delivered to the parent, if we call the ‘signal(SIGCHLD,SIG_IGN)’, then the SIGCHLD signal is ignored by the system, and the child process entry is deleted from the process table. Thus, no zombie is created. However, in this case, the parent cannot know about the exit status of the child.
C
// A C program to demonstrate ignoring// SIGCHLD signal to prevent Zombie processes#include<stdio.h>#include<unistd.h>#include<sys/wait.h>#include<sys/types.h> int main(){ int i; int pid = fork(); if (pid == 0) for (i=0; i<20; i++) printf("I am Child\n"); else { signal(SIGCHLD,SIG_IGN); printf("I am Parent\n"); while(1); }}
3. By using a signal handler: The parent process installs a signal handler for the SIGCHLD signal. The signal handler calls wait() system call within it. In this scenario, when the child terminated, the SIGCHLD is delivered to the parent. On receipt of SIGCHLD, the corresponding handler is activated, which in turn calls the wait() system call. Hence, the parent collects the exit status almost immediately and the child entry in the process table is cleared. Thus no zombie is created.
C
// A C program to demonstrate handling of// SIGCHLD signal to prevent Zombie processes.#include<stdio.h>#include<unistd.h>#include<sys/wait.h>#include<sys/types.h> void func(int signum){ wait(NULL);} int main(){ int i; int pid = fork(); if (pid == 0) for (i=0; i<20; i++) printf("I am Child\n"); else { signal(SIGCHLD, func); printf("I am Parent\n"); while(1); }}
Output:
Here no any [a.out] defunct i.e. no Zombie process is created.
This article is contributed by Kishlay Verma. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. 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.
sagar0719kumar
shubhammalpani
Pushpender007
Processes & Threads
system-programming
C Language
Linux-Unix
Operating Systems
Operating Systems
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Substring in C++
Function Pointer in C
Left Shift and Right Shift Operators in C/C++
Different Methods to Reverse a String in C++
std::string class in C++
Sed Command in Linux/Unix with examples
AWK command in Unix/Linux with examples
grep command in Unix/Linux
cut command in Linux with examples
cp command in Linux with examples
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n05 Nov, 2021"
},
{
"code": null,
"e": 1129,
"s": 54,
"text": "Prerequisites: fork() in C, Zombie ProcessZombie state: When a process is created in UNIX using fork() system call, the address space of the Parent process is replicated. If the parent process calls wait() system call, then the execution of the parent is suspended until the child is terminated. At the termination of the child, a ‘SIGCHLD’ signal is generated which is delivered to the parent by the kernel. Parent, on receipt of ‘SIGCHLD’ reads the status of the child from the process table. Even though the child is terminated, there is an entry in the process table corresponding to the child where the status is stored. When the parent collects the status, this entry is deleted. Thus, all the traces of the child process are removed from the system. If the parent decides not to wait for the child’s termination and executes its subsequent task, then at the termination of the child, the exit status is not read. Hence, there remains an entry in the process table even after the termination of the child. This state of the child process is known as the Zombie state. "
},
{
"code": null,
"e": 1131,
"s": 1129,
"text": "C"
},
{
"code": "// A C program to demonstrate working of// fork() and process table entries.#include<stdio.h>#include<unistd.h>#include<sys/wait.h>#include<sys/types.h> int main(){ int i; int pid = fork(); if (pid == 0) { for (i=0; i<20; i++) printf(\"I am Child\\n\"); } else { printf(\"I am Parent\\n\"); while(1); }}",
"e": 1486,
"s": 1131,
"text": null
},
{
"code": null,
"e": 1496,
"s": 1486,
"text": "Output : "
},
{
"code": null,
"e": 1577,
"s": 1496,
"text": "Now check the process table using the following command in the terminal$ ps -eaf"
},
{
"code": null,
"e": 1634,
"s": 1577,
"text": "Here the entry [a.out] defunct shows the zombie process."
},
{
"code": null,
"e": 2027,
"s": 1634,
"text": "Why do we need to prevent the creation of the Zombie process? There is one process table per system. The size of the process table is finite. If too many zombie processes are generated, then the process table will be full. That is, the system will not be able to generate any new process, then the system will come to a standstill. Hence, we need to prevent the creation of zombie processes. "
},
{
"code": null,
"e": 2409,
"s": 2027,
"text": "1. Using wait() system call: When the parent process calls wait(), after the creation of a child, it indicates that, it will wait for the child to complete and it will reap the exit status of the child. The parent process is suspended(waits in a waiting queue) until the child is terminated. It must be understood that during this period, the parent process does nothing just wait."
},
{
"code": null,
"e": 2411,
"s": 2409,
"text": "C"
},
{
"code": "// A C program to demonstrate working of// fork()/wait() and Zombie processes#include<stdio.h>#include<unistd.h>#include<sys/wait.h>#include<sys/types.h> int main(){ int i; int pid = fork(); if (pid==0) { for (i=0; i<20; i++) printf(\"I am Child\\n\"); } else { wait(NULL); printf(\"I am Parent\\n\"); while(1); }}",
"e": 2783,
"s": 2411,
"text": null
},
{
"code": null,
"e": 3170,
"s": 2783,
"text": "2. By ignoring the SIGCHLD signal: When a child is terminated, a corresponding SIGCHLD signal is delivered to the parent, if we call the ‘signal(SIGCHLD,SIG_IGN)’, then the SIGCHLD signal is ignored by the system, and the child process entry is deleted from the process table. Thus, no zombie is created. However, in this case, the parent cannot know about the exit status of the child."
},
{
"code": null,
"e": 3172,
"s": 3170,
"text": "C"
},
{
"code": "// A C program to demonstrate ignoring// SIGCHLD signal to prevent Zombie processes#include<stdio.h>#include<unistd.h>#include<sys/wait.h>#include<sys/types.h> int main(){ int i; int pid = fork(); if (pid == 0) for (i=0; i<20; i++) printf(\"I am Child\\n\"); else { signal(SIGCHLD,SIG_IGN); printf(\"I am Parent\\n\"); while(1); }}",
"e": 3555,
"s": 3172,
"text": null
},
{
"code": null,
"e": 4043,
"s": 3555,
"text": "3. By using a signal handler: The parent process installs a signal handler for the SIGCHLD signal. The signal handler calls wait() system call within it. In this scenario, when the child terminated, the SIGCHLD is delivered to the parent. On receipt of SIGCHLD, the corresponding handler is activated, which in turn calls the wait() system call. Hence, the parent collects the exit status almost immediately and the child entry in the process table is cleared. Thus no zombie is created."
},
{
"code": null,
"e": 4045,
"s": 4043,
"text": "C"
},
{
"code": "// A C program to demonstrate handling of// SIGCHLD signal to prevent Zombie processes.#include<stdio.h>#include<unistd.h>#include<sys/wait.h>#include<sys/types.h> void func(int signum){ wait(NULL);} int main(){ int i; int pid = fork(); if (pid == 0) for (i=0; i<20; i++) printf(\"I am Child\\n\"); else { signal(SIGCHLD, func); printf(\"I am Parent\\n\"); while(1); }}",
"e": 4469,
"s": 4045,
"text": null
},
{
"code": null,
"e": 4477,
"s": 4469,
"text": "Output:"
},
{
"code": null,
"e": 4540,
"s": 4477,
"text": "Here no any [a.out] defunct i.e. no Zombie process is created."
},
{
"code": null,
"e": 4962,
"s": 4540,
"text": "This article is contributed by Kishlay Verma. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. 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": 4977,
"s": 4962,
"text": "sagar0719kumar"
},
{
"code": null,
"e": 4992,
"s": 4977,
"text": "shubhammalpani"
},
{
"code": null,
"e": 5006,
"s": 4992,
"text": "Pushpender007"
},
{
"code": null,
"e": 5026,
"s": 5006,
"text": "Processes & Threads"
},
{
"code": null,
"e": 5045,
"s": 5026,
"text": "system-programming"
},
{
"code": null,
"e": 5056,
"s": 5045,
"text": "C Language"
},
{
"code": null,
"e": 5067,
"s": 5056,
"text": "Linux-Unix"
},
{
"code": null,
"e": 5085,
"s": 5067,
"text": "Operating Systems"
},
{
"code": null,
"e": 5103,
"s": 5085,
"text": "Operating Systems"
},
{
"code": null,
"e": 5201,
"s": 5103,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 5218,
"s": 5201,
"text": "Substring in C++"
},
{
"code": null,
"e": 5240,
"s": 5218,
"text": "Function Pointer in C"
},
{
"code": null,
"e": 5286,
"s": 5240,
"text": "Left Shift and Right Shift Operators in C/C++"
},
{
"code": null,
"e": 5331,
"s": 5286,
"text": "Different Methods to Reverse a String in C++"
},
{
"code": null,
"e": 5356,
"s": 5331,
"text": "std::string class in C++"
},
{
"code": null,
"e": 5396,
"s": 5356,
"text": "Sed Command in Linux/Unix with examples"
},
{
"code": null,
"e": 5436,
"s": 5396,
"text": "AWK command in Unix/Linux with examples"
},
{
"code": null,
"e": 5463,
"s": 5436,
"text": "grep command in Unix/Linux"
},
{
"code": null,
"e": 5498,
"s": 5463,
"text": "cut command in Linux with examples"
}
] |
matplotlib.patches.Rectangle in Python
|
27 Apr, 2020
Matplotlib is an amazing visualization library in Python for 2D plots of arrays. Matplotlib is a multi-platform data visualization library built on NumPy arrays and designed to work with the broader SciPy stack.
The matplotlib.patches.Rectangle class is used to rectangle patch to a plot with lower left at xy = (x, y) with specified width, height and rotation angle.
Syntax: class matplotlib.patches.Rectangle(xy, width, height, angle=0.0, **kwargs)
Parameters:
xy: Lower left point to start the rectangle plotting
width : width of the rectangle
height: Height of the rectangle.
angle: Angle of rotation of the rectangle.
The below table has a list of valid kwargs;
Example 1:
import numpy as npimport matplotlib.pyplot as pltfrom matplotlib.patches import Rectangle # The imageX = np.arange(16).reshape(4, 4) # highlight some feature in the# middle boxes.fig = plt.figure() ax = fig.add_subplot(111)ax.imshow(X, cmap = plt.cm.gray, interpolation ='nearest')ax.add_patch( Rectangle((0.5, 0.5), 2, 2, fc ='none', ec ='g', lw = 10) ) plt.show()
Output:Example 2:
import matplotlibimport matplotlib.pyplot as plt fig = plt.figure()ax = fig.add_subplot(111) rect1 = matplotlib.patches.Rectangle((-200, -100), 400, 200, color ='green') rect2 = matplotlib.patches.Rectangle((0, 150), 300, 20, color ='pink') rect3 = matplotlib.patches.Rectangle((-300, -50), 40, 200, color ='yellow') ax.add_patch(rect1)ax.add_patch(rect2)ax.add_patch(rect3) plt.xlim([-400, 400])plt.ylim([-400, 400]) plt.show()
Output:
Matplotlib patches-class
Python-matplotlib
Python
Write From Home
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to iterate through Excel rows in Python?
Enumerate() in Python
Python Dictionary
Python OOPs Concepts
Different ways to create Pandas Dataframe
Convert integer to string in Python
Convert string to integer in Python
Python infinity
Matplotlib.pyplot.title() in Python
How to set input type date in dd-mm-yyyy format using HTML ?
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n27 Apr, 2020"
},
{
"code": null,
"e": 240,
"s": 28,
"text": "Matplotlib is an amazing visualization library in Python for 2D plots of arrays. Matplotlib is a multi-platform data visualization library built on NumPy arrays and designed to work with the broader SciPy stack."
},
{
"code": null,
"e": 396,
"s": 240,
"text": "The matplotlib.patches.Rectangle class is used to rectangle patch to a plot with lower left at xy = (x, y) with specified width, height and rotation angle."
},
{
"code": null,
"e": 479,
"s": 396,
"text": "Syntax: class matplotlib.patches.Rectangle(xy, width, height, angle=0.0, **kwargs)"
},
{
"code": null,
"e": 491,
"s": 479,
"text": "Parameters:"
},
{
"code": null,
"e": 544,
"s": 491,
"text": "xy: Lower left point to start the rectangle plotting"
},
{
"code": null,
"e": 575,
"s": 544,
"text": "width : width of the rectangle"
},
{
"code": null,
"e": 608,
"s": 575,
"text": "height: Height of the rectangle."
},
{
"code": null,
"e": 651,
"s": 608,
"text": "angle: Angle of rotation of the rectangle."
},
{
"code": null,
"e": 695,
"s": 651,
"text": "The below table has a list of valid kwargs;"
},
{
"code": null,
"e": 706,
"s": 695,
"text": "Example 1:"
},
{
"code": "import numpy as npimport matplotlib.pyplot as pltfrom matplotlib.patches import Rectangle # The imageX = np.arange(16).reshape(4, 4) # highlight some feature in the# middle boxes.fig = plt.figure() ax = fig.add_subplot(111)ax.imshow(X, cmap = plt.cm.gray, interpolation ='nearest')ax.add_patch( Rectangle((0.5, 0.5), 2, 2, fc ='none', ec ='g', lw = 10) ) plt.show()",
"e": 1180,
"s": 706,
"text": null
},
{
"code": null,
"e": 1198,
"s": 1180,
"text": "Output:Example 2:"
},
{
"code": "import matplotlibimport matplotlib.pyplot as plt fig = plt.figure()ax = fig.add_subplot(111) rect1 = matplotlib.patches.Rectangle((-200, -100), 400, 200, color ='green') rect2 = matplotlib.patches.Rectangle((0, 150), 300, 20, color ='pink') rect3 = matplotlib.patches.Rectangle((-300, -50), 40, 200, color ='yellow') ax.add_patch(rect1)ax.add_patch(rect2)ax.add_patch(rect3) plt.xlim([-400, 400])plt.ylim([-400, 400]) plt.show()",
"e": 1852,
"s": 1198,
"text": null
},
{
"code": null,
"e": 1860,
"s": 1852,
"text": "Output:"
},
{
"code": null,
"e": 1885,
"s": 1860,
"text": "Matplotlib patches-class"
},
{
"code": null,
"e": 1903,
"s": 1885,
"text": "Python-matplotlib"
},
{
"code": null,
"e": 1910,
"s": 1903,
"text": "Python"
},
{
"code": null,
"e": 1926,
"s": 1910,
"text": "Write From Home"
},
{
"code": null,
"e": 2024,
"s": 1926,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2069,
"s": 2024,
"text": "How to iterate through Excel rows in Python?"
},
{
"code": null,
"e": 2091,
"s": 2069,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 2109,
"s": 2091,
"text": "Python Dictionary"
},
{
"code": null,
"e": 2130,
"s": 2109,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 2172,
"s": 2130,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 2208,
"s": 2172,
"text": "Convert integer to string in Python"
},
{
"code": null,
"e": 2244,
"s": 2208,
"text": "Convert string to integer in Python"
},
{
"code": null,
"e": 2260,
"s": 2244,
"text": "Python infinity"
},
{
"code": null,
"e": 2296,
"s": 2260,
"text": "Matplotlib.pyplot.title() in Python"
}
] |
How to set the opacity of background image in CSS ?
|
26 Mar, 2021
In this article, we are going to see how to set the opacity of a background image in CSS. Opacity can be defined as the quality of lacking transparency. It can be used to define the amount of content to be visible.
Approach: We can use the opacity property in CSS which is used to change the opacity of an element. The value of the property can be set in a range of 0 to 1, where “0” is fully transparent and “1” is opaque. Any decimal value can be used in between to set the opacity accordingly.
Syntax:
opacity: value;
Example: In this example, we will set a background image to the <div> and use the opacity property to set the opacity of this image. The opacity is set to 0.2 so that the background is made transparent and the text on top of the image is clearly visible.
HTML
<!DOCTYPE html><html> <head> <title> How to change opacity of background image in CSS ? </title> <style> #GFG { height: 100vh; display: flex; align-items: center; justify-content: center; } #GFG::before { content: ""; position: absolute; top: 0px; right: 0px; bottom: 0px; left: 0px; /* Specify the background image to be used */ background-image: url('https://media.geeksforgeeks.org/wp-content/uploads/20210313130410/exbg.png'); background-size: cover; /* Specify the background image */ opacity: 0.2; } </style></head> <body> <div id="GFG"> <h2>Background image with opacity</h2> </div></body> </html>
Output:
CSS-Properties
CSS-Questions
HTML-Questions
HTML-Tags
Picked
CSS
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to set space between the flexbox ?
Design a Tribute Page using HTML & CSS
Build a Survey Form using HTML and CSS
Form validation using jQuery
Design a web page using HTML and CSS
REST API (Introduction)
Hide or show elements in HTML using display property
How to set the default value for an HTML <select> element ?
How to set input type date in dd-mm-yyyy format using HTML ?
HTTP headers | Content-Type
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n26 Mar, 2021"
},
{
"code": null,
"e": 243,
"s": 28,
"text": "In this article, we are going to see how to set the opacity of a background image in CSS. Opacity can be defined as the quality of lacking transparency. It can be used to define the amount of content to be visible."
},
{
"code": null,
"e": 525,
"s": 243,
"text": "Approach: We can use the opacity property in CSS which is used to change the opacity of an element. The value of the property can be set in a range of 0 to 1, where “0” is fully transparent and “1” is opaque. Any decimal value can be used in between to set the opacity accordingly."
},
{
"code": null,
"e": 533,
"s": 525,
"text": "Syntax:"
},
{
"code": null,
"e": 549,
"s": 533,
"text": "opacity: value;"
},
{
"code": null,
"e": 804,
"s": 549,
"text": "Example: In this example, we will set a background image to the <div> and use the opacity property to set the opacity of this image. The opacity is set to 0.2 so that the background is made transparent and the text on top of the image is clearly visible."
},
{
"code": null,
"e": 809,
"s": 804,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <title> How to change opacity of background image in CSS ? </title> <style> #GFG { height: 100vh; display: flex; align-items: center; justify-content: center; } #GFG::before { content: \"\"; position: absolute; top: 0px; right: 0px; bottom: 0px; left: 0px; /* Specify the background image to be used */ background-image: url('https://media.geeksforgeeks.org/wp-content/uploads/20210313130410/exbg.png'); background-size: cover; /* Specify the background image */ opacity: 0.2; } </style></head> <body> <div id=\"GFG\"> <h2>Background image with opacity</h2> </div></body> </html>",
"e": 1657,
"s": 809,
"text": null
},
{
"code": null,
"e": 1665,
"s": 1657,
"text": "Output:"
},
{
"code": null,
"e": 1680,
"s": 1665,
"text": "CSS-Properties"
},
{
"code": null,
"e": 1694,
"s": 1680,
"text": "CSS-Questions"
},
{
"code": null,
"e": 1709,
"s": 1694,
"text": "HTML-Questions"
},
{
"code": null,
"e": 1719,
"s": 1709,
"text": "HTML-Tags"
},
{
"code": null,
"e": 1726,
"s": 1719,
"text": "Picked"
},
{
"code": null,
"e": 1730,
"s": 1726,
"text": "CSS"
},
{
"code": null,
"e": 1735,
"s": 1730,
"text": "HTML"
},
{
"code": null,
"e": 1752,
"s": 1735,
"text": "Web Technologies"
},
{
"code": null,
"e": 1757,
"s": 1752,
"text": "HTML"
},
{
"code": null,
"e": 1855,
"s": 1757,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1894,
"s": 1855,
"text": "How to set space between the flexbox ?"
},
{
"code": null,
"e": 1933,
"s": 1894,
"text": "Design a Tribute Page using HTML & CSS"
},
{
"code": null,
"e": 1972,
"s": 1933,
"text": "Build a Survey Form using HTML and CSS"
},
{
"code": null,
"e": 2001,
"s": 1972,
"text": "Form validation using jQuery"
},
{
"code": null,
"e": 2038,
"s": 2001,
"text": "Design a web page using HTML and CSS"
},
{
"code": null,
"e": 2062,
"s": 2038,
"text": "REST API (Introduction)"
},
{
"code": null,
"e": 2115,
"s": 2062,
"text": "Hide or show elements in HTML using display property"
},
{
"code": null,
"e": 2175,
"s": 2115,
"text": "How to set the default value for an HTML <select> element ?"
},
{
"code": null,
"e": 2236,
"s": 2175,
"text": "How to set input type date in dd-mm-yyyy format using HTML ?"
}
] |
Python EasyGUI – Showing Image in a Button Box
|
05 Sep, 2020
In this article we will see how we can add or show image in the button box. Button box is used to display a window having multiple buttons in EasyGUI, it can be used where there is condition to select one among lot of buttons for example buttons in lift at a time user can opt only one option, below is how the normal button box looks like
When we invoke the buttonbox function (or other functions that display a button box, such as msgbox, indexbox, ynbox, etc.), we can specify the keyword argument image=img where img is the filename of an image. The file can be .gif. Usually, we can use other images such as .png.
In order to do this we will use buttonbox method
Syntax : buttonbox(text, title, image=img, choices=button_list)
Argument : It takes 4 arguments, first string i.e text to be displayed, second string i.e title of the window and third and forth is keyword argument which is image source and the button choices
Return : It returns the text of the button that the user selected
Example :In this we will create a button box with a image, and user will be allowed to select any button and message will appear according to the message, below is the implementation
# importing easygui modulefrom easygui import * # message to be displayedtext = "Message to be displayed on the window GfG" # window titletitle = "Window Title GfG" # button listbutton_list = [] # button 1button1 = "Average" # second buttonbutton2 = "Good" # third buttonbutton3 = "Very Good" # appending button to the button listbutton_list.append(button1)button_list.append(button2)button_list.append(button3) img = "gfg.png" # creating a button boxoutput = buttonbox(text, title, image = img, choices = button_list) # title for the message boxtitle = "Message Box" # message message = "You selected : " + output # creating a message box msg = msgbox(message, title)
Output :
Another Example :
# importing easygui modulefrom easygui import * # message to be displayedtext = "How much do you like the image given below" # window titletitle = "Window Title GfG" # button listbutton_list = [] # button 1button1 = "Average" # second buttonbutton2 = "Good" # third buttonbutton3 = "Very Good" # appending button to the button listbutton_list.append(button1)button_list.append(button2)button_list.append(button3) # a image of a dogimg = "dog_image.png" # creating a button boxoutput = buttonbox(text, title, image = img, choices = button_list) # title for the message boxtitle = "Message Box" # message message = "You selected : " + output # creating a message box msg = msgbox(message, title)
Output :
Python-EasyGUI
Python-gui
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": 28,
"s": 0,
"text": "\n05 Sep, 2020"
},
{
"code": null,
"e": 368,
"s": 28,
"text": "In this article we will see how we can add or show image in the button box. Button box is used to display a window having multiple buttons in EasyGUI, it can be used where there is condition to select one among lot of buttons for example buttons in lift at a time user can opt only one option, below is how the normal button box looks like"
},
{
"code": null,
"e": 647,
"s": 368,
"text": "When we invoke the buttonbox function (or other functions that display a button box, such as msgbox, indexbox, ynbox, etc.), we can specify the keyword argument image=img where img is the filename of an image. The file can be .gif. Usually, we can use other images such as .png."
},
{
"code": null,
"e": 696,
"s": 647,
"text": "In order to do this we will use buttonbox method"
},
{
"code": null,
"e": 760,
"s": 696,
"text": "Syntax : buttonbox(text, title, image=img, choices=button_list)"
},
{
"code": null,
"e": 955,
"s": 760,
"text": "Argument : It takes 4 arguments, first string i.e text to be displayed, second string i.e title of the window and third and forth is keyword argument which is image source and the button choices"
},
{
"code": null,
"e": 1021,
"s": 955,
"text": "Return : It returns the text of the button that the user selected"
},
{
"code": null,
"e": 1204,
"s": 1021,
"text": "Example :In this we will create a button box with a image, and user will be allowed to select any button and message will appear according to the message, below is the implementation"
},
{
"code": "# importing easygui modulefrom easygui import * # message to be displayedtext = \"Message to be displayed on the window GfG\" # window titletitle = \"Window Title GfG\" # button listbutton_list = [] # button 1button1 = \"Average\" # second buttonbutton2 = \"Good\" # third buttonbutton3 = \"Very Good\" # appending button to the button listbutton_list.append(button1)button_list.append(button2)button_list.append(button3) img = \"gfg.png\" # creating a button boxoutput = buttonbox(text, title, image = img, choices = button_list) # title for the message boxtitle = \"Message Box\" # message message = \"You selected : \" + output # creating a message box msg = msgbox(message, title)",
"e": 1885,
"s": 1204,
"text": null
},
{
"code": null,
"e": 1894,
"s": 1885,
"text": "Output :"
},
{
"code": null,
"e": 1912,
"s": 1894,
"text": "Another Example :"
},
{
"code": "# importing easygui modulefrom easygui import * # message to be displayedtext = \"How much do you like the image given below\" # window titletitle = \"Window Title GfG\" # button listbutton_list = [] # button 1button1 = \"Average\" # second buttonbutton2 = \"Good\" # third buttonbutton3 = \"Very Good\" # appending button to the button listbutton_list.append(button1)button_list.append(button2)button_list.append(button3) # a image of a dogimg = \"dog_image.png\" # creating a button boxoutput = buttonbox(text, title, image = img, choices = button_list) # title for the message boxtitle = \"Message Box\" # message message = \"You selected : \" + output # creating a message box msg = msgbox(message, title)",
"e": 2618,
"s": 1912,
"text": null
},
{
"code": null,
"e": 2627,
"s": 2618,
"text": "Output :"
},
{
"code": null,
"e": 2642,
"s": 2627,
"text": "Python-EasyGUI"
},
{
"code": null,
"e": 2653,
"s": 2642,
"text": "Python-gui"
},
{
"code": null,
"e": 2660,
"s": 2653,
"text": "Python"
},
{
"code": null,
"e": 2758,
"s": 2660,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2790,
"s": 2758,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 2817,
"s": 2790,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 2838,
"s": 2817,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 2861,
"s": 2838,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 2892,
"s": 2861,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 2948,
"s": 2892,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 2990,
"s": 2948,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 3032,
"s": 2990,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 3071,
"s": 3032,
"text": "Python | Get unique values from a list"
}
] |
Types in Julia | Set 1
|
26 Mar, 2020
Types in Julia are basically the data elements of various different sizes and functionality. Every value(not variable) in a program is bound to be of some type. Variables are simply names bound to some values. Defining a value’s type is done either by the programmer or by the compiler itself. It is always considered feasible to define the type of the value before executing the source code in order to achieve fast execution and making your code less prone to errors.
Example: Consider the following three values:
10 -> Integer, 10.5 -> Float, 10/3 -> Rational
Each value here is of a different type. The integer value is different from a float value and from the rational value and similarly, the other two values are different from each other. Now, if we have to add these three values or perform some other operation on these values then it will be a difficulty because the values are not of the same type. In order to add these values, we need to convert the other two values to be of the same type as the third one. Type System is basically divided into two categories, based on the time of its definition. These are:
Static Type SystemDynamic Type System
Static Type System
Dynamic Type System
Static Type System: In a static type system, every executable program expression is defined with a type prior to its execution. This is done at the programmer’s end and is feasible for faster execution speed of the code.Dynamic Type System: In a dynamic type system, the compiler has to decide the type of the values at the time of code compilation. This will result in the code to take some extra time for execution.
Julia uses Dynamic Typed System to write variable values but it also accepts statically typed definitions to provide advantage of indicating certain values are of specific types. By default, Julia assigns the untyped values with any type required. Thus the programmer can write any Julia function without ever defining the types explicitly. But, providing explicit type to the value results in better code readability and also it makes it easier to find errors in the code. Hence, it is not necessary to use the Type system in Julia but using it will make the code clearer, simpler, faster and robust.
Types in Julia are declared with the help of the :: operator. This operator is read as ‘is an instance of’ when appended to a value or an expression. It can be used anywhere in the program to show that the value on the left-hand side is an instance of the type defined on the right side of the :: operator.Types are declared to make a proof of the assertion to confirm that the program is working fine and to provide the compiler some extra information about the type of the expressions and values which will result in faster and more efficient code.
Now, you might think that what if the programmer is unaware of the type and assigns a wrong type to the value or expression. This is handled by an exception in Julia. If the value on the left side is not of the type that is declared on the right side, an exception is generated and the code execution will stop there. Because the compiler expects the computed value on the left side to be of the type specified on the right side. The exception raised will state the expected type from the left side(as defined) and what is actually being produced.Example:
In the above snippet, it can be seen that when the expression on the left side is defined with a Float type, then it generates an Error on execution because the computed value on the left was expected to be of Float64 type as declared but it is of the type Int64. Later when the Type system was changed to Int, it computed the value on the left side and produced the output.
Using Type definition with Assignment operator: When used with the assignment operator, the :: operator if used to make the variable on the left-hand side a typed value, then it will restrict that variable to always hold the value of the same type, just like the statically typed variables in C language. Every value assigned to the variable, if not of the same type will be converted to the same type with the use of the convert function.Example:
Note: Declaration of Typed variable is limited to local variables only. For now, Julia doesn’t allows to Type global variables.
Declaration of Type for functions is also allowed in Julia. This will result in the function to always convert and return the computed value in the form of the specified Type.Example:
function Addition(x, y)::Float64 return x + yend Addition(1, 2)
In the above code, the function should return the Integer value but due to type declaration of the function, the output of the computed value is converted into Float64(desired type).
Julia allows every object to have a type, but it is not certain to have instances of all the types. The types that can have instances are referred to be as concrete types. Concrete types are not allowed to have any subtypes. Subtypes are the sub-entities of a Type. If a type can be further divided into different types, then those parts are called subtypes. For ex- Strings, Rational, bool, etc.Abstract types are those whose subtypes exist. For ex- Any, Number, etc. Though we can’t create objects of the Abstract types but with the help of Abstract types, a programmer can write codes that can work with any of the subtypes of the specified type.Example:
function Addition(x::Number) return x + 1end
The above code can accept a number of any subtype, i.e. it will accept Float64, Int64, etc. and will return the output in the same form. Because here, x is typed with ::Number, so x must be subtype of Number. It will generate an error if the value of x is something other than a subtype of Number like String, array, etc.
Subtypes of a type can be written with the use of <: symbol. This symbol means that the left side is a subtype of the right side. It can also be used in an expression to test if the left side operand is a subtype of the right operand. It will return true for the same and false if it is not a subtype of the specified type.Example:
Abstract types can be used to provide default implementations to concrete types. If we take an example in which the default implementation is of Any type. Then the compiler will assign the respective subtypes to the values as per the need of the computation.
function Addition(x, y) return x + yendAddition(1, 2)
On execution of the above code, the compiler will auto-assign the type of the arguments passed as the type of the values in the function.
function Addition(x::Int, y::Int) return x + yendAddition(1, 2)
Concrete types can be further divided into two types:
Primitive Types
Composite Types
Primitive Types in Julia are the concrete types whose value is in the form of bits. Integers and Float values are an example of Primitive types. Julia has a predefined set of standard primitive types but it also allows to create your own types.Syntax for declaring a primitive type:
primitive type end
primitive type <: end
Examples for Primitive Types are Int8, Int16, Int64, Float16, Float32, String, etc.
Abstract types can not be used to store values in the memory, the compiler will automatically assign a primitive type to the value. If we check for the size of the Abstract type Integer, then it will raise an error because Integer doesn’t have a fixed size, but we can check for the size of its Primitive types i.e. Int8, Int16, Int64, etc.
Composite types in Julia are a collection of named fields which can be individually treated as single values of specific types. Composite types can be declared with the use of struct keyword.Syntax:
struct
Field_name1
Field_name2::Type
Field_name3::Type
end
Here, the fields which are not specified with any type are set with the default type Any. The object of this Composite type can be created with the use of constructors.Example:
# Creating composite typesstruct Geeks x y::Int64 z::Float64end # creating object with constructorobject1 = Geeks("Hello", 10, 10.5)
As we can see that in the above code, the composite type is created with the use of struct keyword and all the fields are individually of Primitive types. If we check the type of the object created with the use of the constructor, then it shows the struct that has been created.
Note: Composite types created with the use of struct keyword are immutable, which means they cannot be modified after their creation.
The composite types defined with the use of struct are of immutable types as explained above. But, Julia also allows creating Composite types of Mutable types, which means that the value of its field can be modified even after their creation. This is done by the use of keyword mutable struct. If a composite type is declared with mutable struct instead of struct, then the value of its instances can be modified anytime.
mutable struct
Field_name1
Field_name2::Type
Field_name3::Type
end
Example:
# Creating composite types # with mutable structstruct Geeks x y::Int64 z::Float64end # creating object with constructorobject1 = Geeks("Hello", 10, 10.5)
Values of a mutable struct can be modified just by passing the new value to the field.
Julia-Basics
Julia
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n26 Mar, 2020"
},
{
"code": null,
"e": 498,
"s": 28,
"text": "Types in Julia are basically the data elements of various different sizes and functionality. Every value(not variable) in a program is bound to be of some type. Variables are simply names bound to some values. Defining a value’s type is done either by the programmer or by the compiler itself. It is always considered feasible to define the type of the value before executing the source code in order to achieve fast execution and making your code less prone to errors."
},
{
"code": null,
"e": 544,
"s": 498,
"text": "Example: Consider the following three values:"
},
{
"code": null,
"e": 606,
"s": 544,
"text": " 10 -> Integer, 10.5 -> Float, 10/3 -> Rational"
},
{
"code": null,
"e": 1168,
"s": 606,
"text": "Each value here is of a different type. The integer value is different from a float value and from the rational value and similarly, the other two values are different from each other. Now, if we have to add these three values or perform some other operation on these values then it will be a difficulty because the values are not of the same type. In order to add these values, we need to convert the other two values to be of the same type as the third one. Type System is basically divided into two categories, based on the time of its definition. These are:"
},
{
"code": null,
"e": 1206,
"s": 1168,
"text": "Static Type SystemDynamic Type System"
},
{
"code": null,
"e": 1225,
"s": 1206,
"text": "Static Type System"
},
{
"code": null,
"e": 1245,
"s": 1225,
"text": "Dynamic Type System"
},
{
"code": null,
"e": 1663,
"s": 1245,
"text": "Static Type System: In a static type system, every executable program expression is defined with a type prior to its execution. This is done at the programmer’s end and is feasible for faster execution speed of the code.Dynamic Type System: In a dynamic type system, the compiler has to decide the type of the values at the time of code compilation. This will result in the code to take some extra time for execution."
},
{
"code": null,
"e": 2265,
"s": 1663,
"text": "Julia uses Dynamic Typed System to write variable values but it also accepts statically typed definitions to provide advantage of indicating certain values are of specific types. By default, Julia assigns the untyped values with any type required. Thus the programmer can write any Julia function without ever defining the types explicitly. But, providing explicit type to the value results in better code readability and also it makes it easier to find errors in the code. Hence, it is not necessary to use the Type system in Julia but using it will make the code clearer, simpler, faster and robust."
},
{
"code": null,
"e": 2816,
"s": 2265,
"text": "Types in Julia are declared with the help of the :: operator. This operator is read as ‘is an instance of’ when appended to a value or an expression. It can be used anywhere in the program to show that the value on the left-hand side is an instance of the type defined on the right side of the :: operator.Types are declared to make a proof of the assertion to confirm that the program is working fine and to provide the compiler some extra information about the type of the expressions and values which will result in faster and more efficient code."
},
{
"code": null,
"e": 3372,
"s": 2816,
"text": "Now, you might think that what if the programmer is unaware of the type and assigns a wrong type to the value or expression. This is handled by an exception in Julia. If the value on the left side is not of the type that is declared on the right side, an exception is generated and the code execution will stop there. Because the compiler expects the computed value on the left side to be of the type specified on the right side. The exception raised will state the expected type from the left side(as defined) and what is actually being produced.Example:"
},
{
"code": null,
"e": 3747,
"s": 3372,
"text": "In the above snippet, it can be seen that when the expression on the left side is defined with a Float type, then it generates an Error on execution because the computed value on the left was expected to be of Float64 type as declared but it is of the type Int64. Later when the Type system was changed to Int, it computed the value on the left side and produced the output."
},
{
"code": null,
"e": 4195,
"s": 3747,
"text": "Using Type definition with Assignment operator: When used with the assignment operator, the :: operator if used to make the variable on the left-hand side a typed value, then it will restrict that variable to always hold the value of the same type, just like the statically typed variables in C language. Every value assigned to the variable, if not of the same type will be converted to the same type with the use of the convert function.Example:"
},
{
"code": null,
"e": 4323,
"s": 4195,
"text": "Note: Declaration of Typed variable is limited to local variables only. For now, Julia doesn’t allows to Type global variables."
},
{
"code": null,
"e": 4507,
"s": 4323,
"text": "Declaration of Type for functions is also allowed in Julia. This will result in the function to always convert and return the computed value in the form of the specified Type.Example:"
},
{
"code": "function Addition(x, y)::Float64 return x + yend Addition(1, 2)",
"e": 4575,
"s": 4507,
"text": null
},
{
"code": null,
"e": 4758,
"s": 4575,
"text": "In the above code, the function should return the Integer value but due to type declaration of the function, the output of the computed value is converted into Float64(desired type)."
},
{
"code": null,
"e": 5416,
"s": 4758,
"text": "Julia allows every object to have a type, but it is not certain to have instances of all the types. The types that can have instances are referred to be as concrete types. Concrete types are not allowed to have any subtypes. Subtypes are the sub-entities of a Type. If a type can be further divided into different types, then those parts are called subtypes. For ex- Strings, Rational, bool, etc.Abstract types are those whose subtypes exist. For ex- Any, Number, etc. Though we can’t create objects of the Abstract types but with the help of Abstract types, a programmer can write codes that can work with any of the subtypes of the specified type.Example:"
},
{
"code": "function Addition(x::Number) return x + 1end",
"e": 5464,
"s": 5416,
"text": null
},
{
"code": null,
"e": 5786,
"s": 5464,
"text": "The above code can accept a number of any subtype, i.e. it will accept Float64, Int64, etc. and will return the output in the same form. Because here, x is typed with ::Number, so x must be subtype of Number. It will generate an error if the value of x is something other than a subtype of Number like String, array, etc."
},
{
"code": null,
"e": 6118,
"s": 5786,
"text": "Subtypes of a type can be written with the use of <: symbol. This symbol means that the left side is a subtype of the right side. It can also be used in an expression to test if the left side operand is a subtype of the right operand. It will return true for the same and false if it is not a subtype of the specified type.Example:"
},
{
"code": null,
"e": 6377,
"s": 6118,
"text": "Abstract types can be used to provide default implementations to concrete types. If we take an example in which the default implementation is of Any type. Then the compiler will assign the respective subtypes to the values as per the need of the computation."
},
{
"code": "function Addition(x, y) return x + yendAddition(1, 2)",
"e": 6434,
"s": 6377,
"text": null
},
{
"code": null,
"e": 6572,
"s": 6434,
"text": "On execution of the above code, the compiler will auto-assign the type of the arguments passed as the type of the values in the function."
},
{
"code": "function Addition(x::Int, y::Int) return x + yendAddition(1, 2)",
"e": 6639,
"s": 6572,
"text": null
},
{
"code": null,
"e": 6693,
"s": 6639,
"text": "Concrete types can be further divided into two types:"
},
{
"code": null,
"e": 6709,
"s": 6693,
"text": "Primitive Types"
},
{
"code": null,
"e": 6725,
"s": 6709,
"text": "Composite Types"
},
{
"code": null,
"e": 7008,
"s": 6725,
"text": "Primitive Types in Julia are the concrete types whose value is in the form of bits. Integers and Float values are an example of Primitive types. Julia has a predefined set of standard primitive types but it also allows to create your own types.Syntax for declaring a primitive type:"
},
{
"code": null,
"e": 7053,
"s": 7008,
"text": "primitive type end\nprimitive type <: end\n"
},
{
"code": null,
"e": 7137,
"s": 7053,
"text": "Examples for Primitive Types are Int8, Int16, Int64, Float16, Float32, String, etc."
},
{
"code": null,
"e": 7478,
"s": 7137,
"text": "Abstract types can not be used to store values in the memory, the compiler will automatically assign a primitive type to the value. If we check for the size of the Abstract type Integer, then it will raise an error because Integer doesn’t have a fixed size, but we can check for the size of its Primitive types i.e. Int8, Int16, Int64, etc."
},
{
"code": null,
"e": 7677,
"s": 7478,
"text": "Composite types in Julia are a collection of named fields which can be individually treated as single values of specific types. Composite types can be declared with the use of struct keyword.Syntax:"
},
{
"code": null,
"e": 7750,
"s": 7677,
"text": "struct \n Field_name1\n Field_name2::Type\n Field_name3::Type\nend\n"
},
{
"code": null,
"e": 7927,
"s": 7750,
"text": "Here, the fields which are not specified with any type are set with the default type Any. The object of this Composite type can be created with the use of constructors.Example:"
},
{
"code": "# Creating composite typesstruct Geeks x y::Int64 z::Float64end # creating object with constructorobject1 = Geeks(\"Hello\", 10, 10.5)",
"e": 8070,
"s": 7927,
"text": null
},
{
"code": null,
"e": 8349,
"s": 8070,
"text": "As we can see that in the above code, the composite type is created with the use of struct keyword and all the fields are individually of Primitive types. If we check the type of the object created with the use of the constructor, then it shows the struct that has been created."
},
{
"code": null,
"e": 8483,
"s": 8349,
"text": "Note: Composite types created with the use of struct keyword are immutable, which means they cannot be modified after their creation."
},
{
"code": null,
"e": 8905,
"s": 8483,
"text": "The composite types defined with the use of struct are of immutable types as explained above. But, Julia also allows creating Composite types of Mutable types, which means that the value of its field can be modified even after their creation. This is done by the use of keyword mutable struct. If a composite type is declared with mutable struct instead of struct, then the value of its instances can be modified anytime."
},
{
"code": null,
"e": 8986,
"s": 8905,
"text": "mutable struct \n Field_name1\n Field_name2::Type\n Field_name3::Type\nend\n"
},
{
"code": null,
"e": 8995,
"s": 8986,
"text": "Example:"
},
{
"code": "# Creating composite types # with mutable structstruct Geeks x y::Int64 z::Float64end # creating object with constructorobject1 = Geeks(\"Hello\", 10, 10.5)",
"e": 9160,
"s": 8995,
"text": null
},
{
"code": null,
"e": 9247,
"s": 9160,
"text": "Values of a mutable struct can be modified just by passing the new value to the field."
},
{
"code": null,
"e": 9260,
"s": 9247,
"text": "Julia-Basics"
},
{
"code": null,
"e": 9266,
"s": 9260,
"text": "Julia"
}
] |
SWING - JMenuBar Class
|
The JMenuBar class provides an implementation of a menu bar.
Following is the declaration for javax.swing.JMenuBar class −
public class JMenuBar
extends JComponent
implements Accessible, MenuElement
JMenuBar()
Creates a new menu bar.
JMenu add(JMenu c)
Appends the specified menu to the end of the menu bar.
void addNotify()
Overrides JComponent.addNotify to register this menu bar with the current keyboard manager.
AccessibleContext getAccessibleContext()
Gets the AccessibleContext associated with this JMenuBar.
Component getComponent()
Implemented to be a MenuElement.
Component getComponentAtIndex(int i)
Deprecated. Replaced by getComponent(int i)
int getComponentIndex(Component c)
Returns the index of the specified component.
JMenu getHelpMenu()
Gets the help menu for the menu bar.
Insets getMargin()
Returns the margin between the menubar's border and its menus.
JMenu getMenu(int index)
Returns the menu at the specified position in the menu bar.
int getMenuCount()
Returns the number of items in the menu bar.
SingleSelectionModel getSelectionModel()
Returns the model object that handles single selections.
MenuElement[] getSubElements()
Implemented to be a MenuElement. Returns the menus in this menu bar.
MenuBarUI getUI()
Returns the menubar's current UI.
String getUIClassID()
Returns the name of the L&F class that renders this component.
boolean isBorderPainted()
Returns true if the menu bars border should be painted.
boolean isSelected()
Returns true if the menu bar currently has a component selected.
void menuSelectionChanged(boolean isIncluded)
Implemented to be a MenuElement, does nothing.
protected void paintBorder(Graphics g)
Paints the menubar's border, if the BorderPainted property is true.
protected String paramString()
Returns a string representation of this JMenuBar.
protected boolean processKeyBinding(KeyStroke ks, KeyEvent e, int condition, boolean pressed)
Subclassed to check all the child menus.
void processKeyEvent(KeyEvent e, MenuElement[] path, MenuSelectionManager manager)
Implemented to be a MenuElement, does nothing.
void processMouseEvent(MouseEvent event, MenuElement[] path, MenuSelectionManager manager)
Implemented to be a MenuElement, does nothing.
void removeNotify()
Overrides JComponent.removeNotify to unregister this menu bar with the current keyboard manager.
void setBorderPainted(boolean b)
Sets whether the border should be painted.
void setHelpMenu(JMenu menu)
Sets the help menu that appears when the user selects the "help" option in the menu bar.
void setMargin(Insets m)
Sets the margin between the menubar's border and its menus.
void setSelected(Component sel)
Sets the currently selected component, producing a change to the selection model.
void setSelectionModel(SingleSelectionModel model)
Sets the model object to handle single selections.
void setUI(MenuBarUI ui)
Sets the L&F object that renders this component.
void updateUI()
Resets the UI property with a value from the current look and feel.
This class inherits methods from the following classes −
javax.swing.JComponent
java.awt.Container
java.awt.Component
java.lang.Object
Create the following Java program using any editor of your choice in say D:/ > SWING > com > tutorialspoint > gui >
SwingMenuDemo.java
package com.tutorialspoint.gui;
import java.awt.*;
import java.awt.event.*;
public class SwingMenuDemo {
private JFrame mainFrame;
private JLabel headerLabel;
private JLabel statusLabel;
private JPanel controlPanel;
public SwingMenuDemo(){
prepareGUI();
}
public static void main(String[] args){
SwingMenuDemo swingMenuDemo = new SwingMenuDemo();
swingMenuDemo.showMenuDemo();
}
private void prepareGUI(){
mainFrame = new JFrame("Java SWING Examples");
mainFrame.setSize(400,400);
mainFrame.setLayout(new GridLayout(3, 1));
headerLabel = new JLabel("",JLabel.CENTER );
statusLabel = new JLabel("",JLabel.CENTER);
statusLabel.setSize(350,100);
mainFrame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent windowEvent){
System.exit(0);
}
});
controlPanel = new JPanel();
controlPanel.setLayout(new FlowLayout());
mainFrame.add(headerLabel);
mainFrame.add(controlPanel);
mainFrame.add(statusLabel);
mainFrame.setVisible(true);
}
private void showMenuDemo(){
//create a menu bar
final JMenuBar menuBar = new JMenuBar();
//create menus
JMenu fileMenu = new JMenu("File");
JMenu editMenu = new JMenu("Edit");
final JMenu aboutMenu = new JMenu("About");
final JMenu linkMenu = new JMenu("Links");
//create menu items
JMenuItem newMenuItem = new JMenuItem("New");
newMenuItem.setMnemonic(KeyEvent.VK_N);
newMenuItem.setActionCommand("New");
JMenuItem openMenuItem = new JMenuItem("Open");
openMenuItem.setActionCommand("Open");
JMenuItem saveMenuItem = new JMenuItem("Save");
saveMenuItem.setActionCommand("Save");
JMenuItem exitMenuItem = new JMenuItem("Exit");
exitMenuItem.setActionCommand("Exit");
JMenuItem cutMenuItem = new JMenuItem("Cut");
cutMenuItem.setActionCommand("Cut");
JMenuItem copyMenuItem = new JMenuItem("Copy");
copyMenuItem.setActionCommand("Copy");
JMenuItem pasteMenuItem = new JMenuItem("Paste");
pasteMenuItem.setActionCommand("Paste");
MenuItemListener menuItemListener = new MenuItemListener();
newMenuItem.addActionListener(menuItemListener);
openMenuItem.addActionListener(menuItemListener);
saveMenuItem.addActionListener(menuItemListener);
exitMenuItem.addActionListener(menuItemListener);
cutMenuItem.addActionListener(menuItemListener);
copyMenuItem.addActionListener(menuItemListener);
pasteMenuItem.addActionListener(menuItemListener);
final JCheckBoxMenuItem showWindowMenu = new JCheckBoxMenuItem("Show About", true);
showWindowMenu.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
if(showWindowMenu.getState()){
menuBar.add(aboutMenu);
} else {
menuBar.remove(aboutMenu);
}
}
});
final JRadioButtonMenuItem showLinksMenu = new JRadioButtonMenuItem(
"Show Links", true);
showLinksMenu.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
if(menuBar.getMenu(3)!= null){
menuBar.remove(linkMenu);
mainFrame.repaint();
} else {
menuBar.add(linkMenu);
mainFrame.repaint();
}
}
});
//add menu items to menus
fileMenu.add(newMenuItem);
fileMenu.add(openMenuItem);
fileMenu.add(saveMenuItem);
fileMenu.addSeparator();
fileMenu.add(showWindowMenu);
fileMenu.addSeparator();
fileMenu.add(showLinksMenu);
fileMenu.addSeparator();
fileMenu.add(exitMenuItem);
editMenu.add(cutMenuItem);
editMenu.add(copyMenuItem);
editMenu.add(pasteMenuItem);
//add menu to menubar
menuBar.add(fileMenu);
menuBar.add(editMenu);
menuBar.add(aboutMenu);
menuBar.add(linkMenu);
//add menubar to the frame
mainFrame.setJMenuBar(menuBar);
mainFrame.setVisible(true);
}
class MenuItemListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
statusLabel.setText(e.getActionCommand() + " JMenuItem clicked.");
}
}
}
Compile the program using the command prompt. Go to D:/ > SWING and type the following command.
D:\SWING>javac com\tutorialspoint\gui\SwingMenuDemo.java
If no error occurs, it means the compilation is successful. Run the program using the following command.
D:\SWING>java com.tutorialspoint.gui.SwingMenuDemo
Verify the following output.
|
[
{
"code": null,
"e": 1958,
"s": 1897,
"text": "The JMenuBar class provides an implementation of a menu bar."
},
{
"code": null,
"e": 2020,
"s": 1958,
"text": "Following is the declaration for javax.swing.JMenuBar class −"
},
{
"code": null,
"e": 2106,
"s": 2020,
"text": "public class JMenuBar\n extends JComponent\n implements Accessible, MenuElement\n"
},
{
"code": null,
"e": 2117,
"s": 2106,
"text": "JMenuBar()"
},
{
"code": null,
"e": 2141,
"s": 2117,
"text": "Creates a new menu bar."
},
{
"code": null,
"e": 2160,
"s": 2141,
"text": "JMenu add(JMenu c)"
},
{
"code": null,
"e": 2215,
"s": 2160,
"text": "Appends the specified menu to the end of the menu bar."
},
{
"code": null,
"e": 2232,
"s": 2215,
"text": "void addNotify()"
},
{
"code": null,
"e": 2324,
"s": 2232,
"text": "Overrides JComponent.addNotify to register this menu bar with the current keyboard manager."
},
{
"code": null,
"e": 2365,
"s": 2324,
"text": "AccessibleContext\tgetAccessibleContext()"
},
{
"code": null,
"e": 2423,
"s": 2365,
"text": "Gets the AccessibleContext associated with this JMenuBar."
},
{
"code": null,
"e": 2448,
"s": 2423,
"text": "Component getComponent()"
},
{
"code": null,
"e": 2481,
"s": 2448,
"text": "Implemented to be a MenuElement."
},
{
"code": null,
"e": 2518,
"s": 2481,
"text": "Component getComponentAtIndex(int i)"
},
{
"code": null,
"e": 2562,
"s": 2518,
"text": "Deprecated. Replaced by getComponent(int i)"
},
{
"code": null,
"e": 2597,
"s": 2562,
"text": "int getComponentIndex(Component c)"
},
{
"code": null,
"e": 2643,
"s": 2597,
"text": "Returns the index of the specified component."
},
{
"code": null,
"e": 2663,
"s": 2643,
"text": "JMenu getHelpMenu()"
},
{
"code": null,
"e": 2700,
"s": 2663,
"text": "Gets the help menu for the menu bar."
},
{
"code": null,
"e": 2719,
"s": 2700,
"text": "Insets getMargin()"
},
{
"code": null,
"e": 2782,
"s": 2719,
"text": "Returns the margin between the menubar's border and its menus."
},
{
"code": null,
"e": 2807,
"s": 2782,
"text": "JMenu getMenu(int index)"
},
{
"code": null,
"e": 2867,
"s": 2807,
"text": "Returns the menu at the specified position in the menu bar."
},
{
"code": null,
"e": 2886,
"s": 2867,
"text": "int getMenuCount()"
},
{
"code": null,
"e": 2931,
"s": 2886,
"text": "Returns the number of items in the menu bar."
},
{
"code": null,
"e": 2972,
"s": 2931,
"text": "SingleSelectionModel getSelectionModel()"
},
{
"code": null,
"e": 3029,
"s": 2972,
"text": "Returns the model object that handles single selections."
},
{
"code": null,
"e": 3060,
"s": 3029,
"text": "MenuElement[] getSubElements()"
},
{
"code": null,
"e": 3129,
"s": 3060,
"text": "Implemented to be a MenuElement. Returns the menus in this menu bar."
},
{
"code": null,
"e": 3147,
"s": 3129,
"text": "MenuBarUI getUI()"
},
{
"code": null,
"e": 3181,
"s": 3147,
"text": "Returns the menubar's current UI."
},
{
"code": null,
"e": 3203,
"s": 3181,
"text": "String getUIClassID()"
},
{
"code": null,
"e": 3266,
"s": 3203,
"text": "Returns the name of the L&F class that renders this component."
},
{
"code": null,
"e": 3292,
"s": 3266,
"text": "boolean isBorderPainted()"
},
{
"code": null,
"e": 3348,
"s": 3292,
"text": "Returns true if the menu bars border should be painted."
},
{
"code": null,
"e": 3369,
"s": 3348,
"text": "boolean isSelected()"
},
{
"code": null,
"e": 3434,
"s": 3369,
"text": "Returns true if the menu bar currently has a component selected."
},
{
"code": null,
"e": 3480,
"s": 3434,
"text": "void menuSelectionChanged(boolean isIncluded)"
},
{
"code": null,
"e": 3527,
"s": 3480,
"text": "Implemented to be a MenuElement, does nothing."
},
{
"code": null,
"e": 3566,
"s": 3527,
"text": "protected void paintBorder(Graphics g)"
},
{
"code": null,
"e": 3634,
"s": 3566,
"text": "Paints the menubar's border, if the BorderPainted property is true."
},
{
"code": null,
"e": 3665,
"s": 3634,
"text": "protected String paramString()"
},
{
"code": null,
"e": 3715,
"s": 3665,
"text": "Returns a string representation of this JMenuBar."
},
{
"code": null,
"e": 3809,
"s": 3715,
"text": "protected boolean processKeyBinding(KeyStroke ks, KeyEvent e, int condition, boolean pressed)"
},
{
"code": null,
"e": 3850,
"s": 3809,
"text": "Subclassed to check all the child menus."
},
{
"code": null,
"e": 3933,
"s": 3850,
"text": "void processKeyEvent(KeyEvent e, MenuElement[] path, MenuSelectionManager manager)"
},
{
"code": null,
"e": 3980,
"s": 3933,
"text": "Implemented to be a MenuElement, does nothing."
},
{
"code": null,
"e": 4071,
"s": 3980,
"text": "void processMouseEvent(MouseEvent event, MenuElement[] path, MenuSelectionManager manager)"
},
{
"code": null,
"e": 4118,
"s": 4071,
"text": "Implemented to be a MenuElement, does nothing."
},
{
"code": null,
"e": 4138,
"s": 4118,
"text": "void removeNotify()"
},
{
"code": null,
"e": 4235,
"s": 4138,
"text": "Overrides JComponent.removeNotify to unregister this menu bar with the current keyboard manager."
},
{
"code": null,
"e": 4268,
"s": 4235,
"text": "void setBorderPainted(boolean b)"
},
{
"code": null,
"e": 4311,
"s": 4268,
"text": "Sets whether the border should be painted."
},
{
"code": null,
"e": 4340,
"s": 4311,
"text": "void setHelpMenu(JMenu menu)"
},
{
"code": null,
"e": 4429,
"s": 4340,
"text": "Sets the help menu that appears when the user selects the \"help\" option in the menu bar."
},
{
"code": null,
"e": 4454,
"s": 4429,
"text": "void setMargin(Insets m)"
},
{
"code": null,
"e": 4514,
"s": 4454,
"text": "Sets the margin between the menubar's border and its menus."
},
{
"code": null,
"e": 4546,
"s": 4514,
"text": "void setSelected(Component sel)"
},
{
"code": null,
"e": 4628,
"s": 4546,
"text": "Sets the currently selected component, producing a change to the selection model."
},
{
"code": null,
"e": 4679,
"s": 4628,
"text": "void setSelectionModel(SingleSelectionModel model)"
},
{
"code": null,
"e": 4730,
"s": 4679,
"text": "Sets the model object to handle single selections."
},
{
"code": null,
"e": 4755,
"s": 4730,
"text": "void setUI(MenuBarUI ui)"
},
{
"code": null,
"e": 4804,
"s": 4755,
"text": "Sets the L&F object that renders this component."
},
{
"code": null,
"e": 4820,
"s": 4804,
"text": "void updateUI()"
},
{
"code": null,
"e": 4888,
"s": 4820,
"text": "Resets the UI property with a value from the current look and feel."
},
{
"code": null,
"e": 4945,
"s": 4888,
"text": "This class inherits methods from the following classes −"
},
{
"code": null,
"e": 4968,
"s": 4945,
"text": "javax.swing.JComponent"
},
{
"code": null,
"e": 4987,
"s": 4968,
"text": "java.awt.Container"
},
{
"code": null,
"e": 5006,
"s": 4987,
"text": "java.awt.Component"
},
{
"code": null,
"e": 5023,
"s": 5006,
"text": "java.lang.Object"
},
{
"code": null,
"e": 5139,
"s": 5023,
"text": "Create the following Java program using any editor of your choice in say D:/ > SWING > com > tutorialspoint > gui >"
},
{
"code": null,
"e": 5158,
"s": 5139,
"text": "SwingMenuDemo.java"
},
{
"code": null,
"e": 9685,
"s": 5158,
"text": "package com.tutorialspoint.gui;\n\nimport java.awt.*;\nimport java.awt.event.*;\n\npublic class SwingMenuDemo {\n private JFrame mainFrame;\n private JLabel headerLabel;\n private JLabel statusLabel;\n private JPanel controlPanel; \n\n public SwingMenuDemo(){\n prepareGUI();\n }\n public static void main(String[] args){\n SwingMenuDemo swingMenuDemo = new SwingMenuDemo(); \n swingMenuDemo.showMenuDemo();\n }\n private void prepareGUI(){\n mainFrame = new JFrame(\"Java SWING Examples\");\n mainFrame.setSize(400,400);\n mainFrame.setLayout(new GridLayout(3, 1));\n\n headerLabel = new JLabel(\"\",JLabel.CENTER );\n statusLabel = new JLabel(\"\",JLabel.CENTER); \n statusLabel.setSize(350,100);\n \n mainFrame.addWindowListener(new WindowAdapter() {\n public void windowClosing(WindowEvent windowEvent){\n System.exit(0);\n } \n }); \n controlPanel = new JPanel();\n controlPanel.setLayout(new FlowLayout());\n\n mainFrame.add(headerLabel);\n mainFrame.add(controlPanel);\n mainFrame.add(statusLabel);\n mainFrame.setVisible(true); \n }\n private void showMenuDemo(){\n //create a menu bar\n final JMenuBar menuBar = new JMenuBar();\n\n //create menus\n JMenu fileMenu = new JMenu(\"File\");\n JMenu editMenu = new JMenu(\"Edit\"); \n final JMenu aboutMenu = new JMenu(\"About\");\n final JMenu linkMenu = new JMenu(\"Links\");\n \n //create menu items\n JMenuItem newMenuItem = new JMenuItem(\"New\");\n newMenuItem.setMnemonic(KeyEvent.VK_N);\n newMenuItem.setActionCommand(\"New\");\n\n JMenuItem openMenuItem = new JMenuItem(\"Open\");\n openMenuItem.setActionCommand(\"Open\");\n\n JMenuItem saveMenuItem = new JMenuItem(\"Save\");\n saveMenuItem.setActionCommand(\"Save\");\n\n JMenuItem exitMenuItem = new JMenuItem(\"Exit\");\n exitMenuItem.setActionCommand(\"Exit\");\n\n JMenuItem cutMenuItem = new JMenuItem(\"Cut\");\n cutMenuItem.setActionCommand(\"Cut\");\n\n JMenuItem copyMenuItem = new JMenuItem(\"Copy\");\n copyMenuItem.setActionCommand(\"Copy\");\n\n JMenuItem pasteMenuItem = new JMenuItem(\"Paste\");\n pasteMenuItem.setActionCommand(\"Paste\");\n\n MenuItemListener menuItemListener = new MenuItemListener();\n\n newMenuItem.addActionListener(menuItemListener);\n openMenuItem.addActionListener(menuItemListener);\n saveMenuItem.addActionListener(menuItemListener);\n exitMenuItem.addActionListener(menuItemListener);\n cutMenuItem.addActionListener(menuItemListener);\n copyMenuItem.addActionListener(menuItemListener);\n pasteMenuItem.addActionListener(menuItemListener);\n\n final JCheckBoxMenuItem showWindowMenu = new JCheckBoxMenuItem(\"Show About\", true);\n showWindowMenu.addItemListener(new ItemListener() {\n public void itemStateChanged(ItemEvent e) {\n \n if(showWindowMenu.getState()){\n menuBar.add(aboutMenu);\n } else {\n menuBar.remove(aboutMenu);\n }\n }\n });\n final JRadioButtonMenuItem showLinksMenu = new JRadioButtonMenuItem(\n \"Show Links\", true);\n showLinksMenu.addItemListener(new ItemListener() {\n public void itemStateChanged(ItemEvent e) {\n \n if(menuBar.getMenu(3)!= null){\n menuBar.remove(linkMenu);\n mainFrame.repaint();\n } else { \n menuBar.add(linkMenu);\n mainFrame.repaint();\n }\n }\n });\n //add menu items to menus\n fileMenu.add(newMenuItem);\n fileMenu.add(openMenuItem);\n fileMenu.add(saveMenuItem);\n fileMenu.addSeparator();\n fileMenu.add(showWindowMenu);\n fileMenu.addSeparator();\n fileMenu.add(showLinksMenu); \n fileMenu.addSeparator();\n fileMenu.add(exitMenuItem); \n \n editMenu.add(cutMenuItem);\n editMenu.add(copyMenuItem);\n editMenu.add(pasteMenuItem);\n\n //add menu to menubar\n menuBar.add(fileMenu);\n menuBar.add(editMenu);\n menuBar.add(aboutMenu); \n menuBar.add(linkMenu);\n\n //add menubar to the frame\n mainFrame.setJMenuBar(menuBar);\n mainFrame.setVisible(true); \n }\n class MenuItemListener implements ActionListener {\n public void actionPerformed(ActionEvent e) { \n statusLabel.setText(e.getActionCommand() + \" JMenuItem clicked.\");\n } \n }\n}"
},
{
"code": null,
"e": 9781,
"s": 9685,
"text": "Compile the program using the command prompt. Go to D:/ > SWING and type the following command."
},
{
"code": null,
"e": 9839,
"s": 9781,
"text": "D:\\SWING>javac com\\tutorialspoint\\gui\\SwingMenuDemo.java\n"
},
{
"code": null,
"e": 9944,
"s": 9839,
"text": "If no error occurs, it means the compilation is successful. Run the program using the following command."
},
{
"code": null,
"e": 9996,
"s": 9944,
"text": "D:\\SWING>java com.tutorialspoint.gui.SwingMenuDemo\n"
}
] |
Counter Type in Cassandra - GeeksforGeeks
|
27 Dec, 2019
In this article, we will discuss how to create counter type column in Cassandra and what are the restriction while using the counter column as a data type into the table and we will see how we can update the Counter Column by using an Update Query. let’s discuss one by one.
The counter is a special column used to store a number that this changed increments. For example, you might use a counter column to count the number of times a page is viewed. So, we can define a counter in a dedicated table only and use that counter datatype.
Restriction on the counter column:
Counter column cannot index, delete or re-add a counter column.
All non-counter columns in the table must be defined as a part of the primary key.
To load data in a counter column or to increase or decrease the value of the counter, use the update command.
Now, we are going to create table with a Counter column. let’s have a look.
Create table View_Counts
(
count_view counter,
name varchar,
blog_name text,
primary key(name, blog_name)
);
Let’s see the table schema.
describe table View_Counts;
Output:
Now, we are going to insert value for the counter column with the help of the Update clause.Let’s have a look.
update View_counts set count_view = count_view+1
where name = 'Ashish'and blog_name = 'cassandra';
Let’s see the result.
select *
from View_Counts;
Output:
Now, we are going to update the value for the counter column with the help of the Update clause.Let’s have a look.
update View_counts set count_view = count_view + 4
where name = 'Ashish'and blog_name = 'cassandra';
Let’s see the result.
select *
from View_Counts;
Output:
We can also decrement the value for the counter column with the help of the Update clause. let’s have a look.
update View_counts set count_view = count_view - 4
where name = 'Ashish'and blog_name = 'cassandra';
Let’s see the result.
select *
from View_Counts;
Output:
Cassandra rejects using time star or using TTL in the command to update a counter column. So, let’s create a View_Counts table. So, we created count_view and this is a counter value of type counter. This is very important and we have a name and blog_name and we can see that the primary key is to have a name and blog_name.
If we will try to create a similar table, let’s say – copy_View_Counts and the primary key will be the only name, we’ll get an error. Because cannot mix counter and non-counter columns in the same table if they are not primary key. let’s have a look.
Let’s understand with an example.
Create table copy_View_Counts
(
count_view counter,
name varchar,
blog_name text,
primary key(name)
);
Here, All non-counter columns must be part of the primary key. but, the only name is the only part of primary column that’s why it is giving an error. let’s have a look.
Let’s see the result.
select *
from View_Counts;
Output:
Apache
DBMS
DBMS
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Introduction of 4th and 5th Normal form in DBMS
Deadlock in DBMS
Difference between 2NF and 3NF in DBMS
Anomalies in Relational Model
Cartesian Product Operation in Relational Algebra
Difference between Where and Having Clause in SQL
Cosine Similarity
SQL | DROP, TRUNCATE
KDD Process in Data Mining
Second Normal Form (2NF)
|
[
{
"code": null,
"e": 23913,
"s": 23885,
"text": "\n27 Dec, 2019"
},
{
"code": null,
"e": 24188,
"s": 23913,
"text": "In this article, we will discuss how to create counter type column in Cassandra and what are the restriction while using the counter column as a data type into the table and we will see how we can update the Counter Column by using an Update Query. let’s discuss one by one."
},
{
"code": null,
"e": 24449,
"s": 24188,
"text": "The counter is a special column used to store a number that this changed increments. For example, you might use a counter column to count the number of times a page is viewed. So, we can define a counter in a dedicated table only and use that counter datatype."
},
{
"code": null,
"e": 24484,
"s": 24449,
"text": "Restriction on the counter column:"
},
{
"code": null,
"e": 24548,
"s": 24484,
"text": "Counter column cannot index, delete or re-add a counter column."
},
{
"code": null,
"e": 24631,
"s": 24548,
"text": "All non-counter columns in the table must be defined as a part of the primary key."
},
{
"code": null,
"e": 24741,
"s": 24631,
"text": "To load data in a counter column or to increase or decrease the value of the counter, use the update command."
},
{
"code": null,
"e": 24817,
"s": 24741,
"text": "Now, we are going to create table with a Counter column. let’s have a look."
},
{
"code": null,
"e": 24938,
"s": 24817,
"text": "Create table View_Counts \n (\n count_view counter,\n name varchar,\n blog_name text,\n primary key(name, blog_name)\n ); "
},
{
"code": null,
"e": 24966,
"s": 24938,
"text": "Let’s see the table schema."
},
{
"code": null,
"e": 24995,
"s": 24966,
"text": "describe table View_Counts; "
},
{
"code": null,
"e": 25003,
"s": 24995,
"text": "Output:"
},
{
"code": null,
"e": 25114,
"s": 25003,
"text": "Now, we are going to insert value for the counter column with the help of the Update clause.Let’s have a look."
},
{
"code": null,
"e": 25217,
"s": 25114,
"text": "update View_counts set count_view = count_view+1 \nwhere name = 'Ashish'and blog_name = 'cassandra'; "
},
{
"code": null,
"e": 25239,
"s": 25217,
"text": "Let’s see the result."
},
{
"code": null,
"e": 25268,
"s": 25239,
"text": "select * \nfrom View_Counts; "
},
{
"code": null,
"e": 25276,
"s": 25268,
"text": "Output:"
},
{
"code": null,
"e": 25391,
"s": 25276,
"text": "Now, we are going to update the value for the counter column with the help of the Update clause.Let’s have a look."
},
{
"code": null,
"e": 25495,
"s": 25391,
"text": "update View_counts set count_view = count_view + 4 \nwhere name = 'Ashish'and blog_name = 'cassandra'; "
},
{
"code": null,
"e": 25517,
"s": 25495,
"text": "Let’s see the result."
},
{
"code": null,
"e": 25546,
"s": 25517,
"text": "select * \nfrom View_Counts; "
},
{
"code": null,
"e": 25554,
"s": 25546,
"text": "Output:"
},
{
"code": null,
"e": 25664,
"s": 25554,
"text": "We can also decrement the value for the counter column with the help of the Update clause. let’s have a look."
},
{
"code": null,
"e": 25768,
"s": 25664,
"text": "update View_counts set count_view = count_view - 4 \nwhere name = 'Ashish'and blog_name = 'cassandra'; "
},
{
"code": null,
"e": 25790,
"s": 25768,
"text": "Let’s see the result."
},
{
"code": null,
"e": 25819,
"s": 25790,
"text": "select * \nfrom View_Counts; "
},
{
"code": null,
"e": 25827,
"s": 25819,
"text": "Output:"
},
{
"code": null,
"e": 26151,
"s": 25827,
"text": "Cassandra rejects using time star or using TTL in the command to update a counter column. So, let’s create a View_Counts table. So, we created count_view and this is a counter value of type counter. This is very important and we have a name and blog_name and we can see that the primary key is to have a name and blog_name."
},
{
"code": null,
"e": 26402,
"s": 26151,
"text": "If we will try to create a similar table, let’s say – copy_View_Counts and the primary key will be the only name, we’ll get an error. Because cannot mix counter and non-counter columns in the same table if they are not primary key. let’s have a look."
},
{
"code": null,
"e": 26436,
"s": 26402,
"text": "Let’s understand with an example."
},
{
"code": null,
"e": 26550,
"s": 26436,
"text": "Create table copy_View_Counts\n (\n count_view counter,\n name varchar,\n blog_name text,\n primary key(name)\n ); "
},
{
"code": null,
"e": 26720,
"s": 26550,
"text": "Here, All non-counter columns must be part of the primary key. but, the only name is the only part of primary column that’s why it is giving an error. let’s have a look."
},
{
"code": null,
"e": 26742,
"s": 26720,
"text": "Let’s see the result."
},
{
"code": null,
"e": 26771,
"s": 26742,
"text": "select * \nfrom View_Counts; "
},
{
"code": null,
"e": 26779,
"s": 26771,
"text": "Output:"
},
{
"code": null,
"e": 26786,
"s": 26779,
"text": "Apache"
},
{
"code": null,
"e": 26791,
"s": 26786,
"text": "DBMS"
},
{
"code": null,
"e": 26796,
"s": 26791,
"text": "DBMS"
},
{
"code": null,
"e": 26894,
"s": 26796,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26903,
"s": 26894,
"text": "Comments"
},
{
"code": null,
"e": 26916,
"s": 26903,
"text": "Old Comments"
},
{
"code": null,
"e": 26964,
"s": 26916,
"text": "Introduction of 4th and 5th Normal form in DBMS"
},
{
"code": null,
"e": 26981,
"s": 26964,
"text": "Deadlock in DBMS"
},
{
"code": null,
"e": 27020,
"s": 26981,
"text": "Difference between 2NF and 3NF in DBMS"
},
{
"code": null,
"e": 27050,
"s": 27020,
"text": "Anomalies in Relational Model"
},
{
"code": null,
"e": 27100,
"s": 27050,
"text": "Cartesian Product Operation in Relational Algebra"
},
{
"code": null,
"e": 27150,
"s": 27100,
"text": "Difference between Where and Having Clause in SQL"
},
{
"code": null,
"e": 27168,
"s": 27150,
"text": "Cosine Similarity"
},
{
"code": null,
"e": 27189,
"s": 27168,
"text": "SQL | DROP, TRUNCATE"
},
{
"code": null,
"e": 27216,
"s": 27189,
"text": "KDD Process in Data Mining"
}
] |
HTML5 - Microdata
|
Microdata is a standardized way to provide additional semantics in your web pages.
Microdata lets you define your own customized elements and start embedding custom properties in your web pages. At a high level, microdata consists of a group of name-value pairs.
The groups are called items, and each name-value pair is a property. Items and properties are represented by regular elements.
To create an item, the itemscope attribute is used.
To create an item, the itemscope attribute is used.
To add a property to an item, the itemprop attribute is used on one of the item's descendants.
To add a property to an item, the itemprop attribute is used on one of the item's descendants.
Here there are two items, each of which has the property "name" −
<html>
<body>
<div itemscope>
<p>My name is <span itemprop = "name">Zara</span>.</p>
</div>
<div itemscope>
<p>My name is <span itemprop = "name">Nuha</span>.</p>
</div>
</body>
</html>
It will produce the following result −
My name is Zara.
My name is Nuha.
Properties generally have values that are strings but it can have following data types −
Microdata introduces five global attributes which would be available for any element to use and give context for machines about your data.
itemscope
This is used to create an item. The itemscope attribute is a Boolean attribute that tells that there is Microdata on this page, and this is where it starts.
itemtype
This attribute is a valid URL which defines the item and provides the context for the properties.
itemid
This attribute is global identifier for the item.
itemprop
This attribute defines a property of the item.
itemref
This attribute gives a list of additional elements to crawl to find the name-value pairs of the item.
Properties generally have values that are strings as mentioned in above example but they can also have values that are URLs. Following example has one property, "image", whose value is a URL −
<div itemscope>
<img itemprop = "image" src = "tp-logo.gif" alt = "TutorialsPoint">
</div>
Properties can also have values that are dates, times, or dates and times. This is achieved using the time element and its datetime attribute.
<html>
<body>
<div itemscope>
My birthday is:
<time itemprop = "birthday" datetime = "1971-05-08">
Aug 5th 1971
</time>
</div>
</body>
</html>
It will produce the following result −
Properties can also themselves be groups of name-value pairs, by putting the itemscope attribute on the element that declares the property.
If a browser supports the HTML5 microdata API, there will be a getItems() function on the global document object. If browser doesn't support microdata, the getItems() function will be undefined.
function supports_microdata_api() {
return !!document.getItems;
}
Modernizr does not yet support checking for the microdata API, so you’ll need to use the function like the one listed above.
The HTML5 microdata standard includes both HTML markup (primarily for search engines) and a set of DOM functions (primarily for browsers).
You can include microdata markup in your web pages, and search engines that don't understand the microdata attributes will just ignore them. But if you need to access or manipulate microdata through the DOM, you'll need to check whether the browser supports the microdata DOM API.
To define microdata vocabulary you need a namespace URL which points to a working web page. For example https://data-vocabulary.org/Person can be used as the namespace for a personal microdata vocabulary with the following named properties −
name − Person name as a simple string
name − Person name as a simple string
Photo − A URL to a picture of the person.
Photo − A URL to a picture of the person.
URL − A website belonging to the person.
URL − A website belonging to the person.
Using about properties a person microdata could be as follows −
<html>
<body>
<div itemscope>
<section itemscope itemtype = "http://data-vocabulary.org/Person">
<h1 itemprop = "name">Gopal K Varma</h1>
<p>
<img itemprop = "photo"
src = "http://www.tutorialspoint.com/green/images/logo.png">
</p>
<a itemprop = "url" href = "#">Site</a>
</section>
</div>
</body>
</html>
It will produce the following result −
Google supports microdata as part of their Rich Snippets program. When Google's web crawler parses your page and finds microdata properties that conform to the http://datavocabulary.org/Person vocabulary, it parses out those properties and stores them alongside the rest of the page data.
You can test above example using Rich Snippets Testing Tool using http://www.tutorialspoint.com/html5/microdata.htm
For further development on Microdata you can always refer to HTML5 Microdata.
19 Lectures
2 hours
Anadi Sharma
16 Lectures
1.5 hours
Anadi Sharma
18 Lectures
1.5 hours
Frahaan Hussain
57 Lectures
5.5 hours
DigiFisk (Programming Is Fun)
54 Lectures
6 hours
DigiFisk (Programming Is Fun)
45 Lectures
5.5 hours
DigiFisk (Programming Is Fun)
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2691,
"s": 2608,
"text": "Microdata is a standardized way to provide additional semantics in your web pages."
},
{
"code": null,
"e": 2871,
"s": 2691,
"text": "Microdata lets you define your own customized elements and start embedding custom properties in your web pages. At a high level, microdata consists of a group of name-value pairs."
},
{
"code": null,
"e": 2998,
"s": 2871,
"text": "The groups are called items, and each name-value pair is a property. Items and properties are represented by regular elements."
},
{
"code": null,
"e": 3050,
"s": 2998,
"text": "To create an item, the itemscope attribute is used."
},
{
"code": null,
"e": 3102,
"s": 3050,
"text": "To create an item, the itemscope attribute is used."
},
{
"code": null,
"e": 3197,
"s": 3102,
"text": "To add a property to an item, the itemprop attribute is used on one of the item's descendants."
},
{
"code": null,
"e": 3292,
"s": 3197,
"text": "To add a property to an item, the itemprop attribute is used on one of the item's descendants."
},
{
"code": null,
"e": 3358,
"s": 3292,
"text": "Here there are two items, each of which has the property \"name\" −"
},
{
"code": null,
"e": 3613,
"s": 3358,
"text": "<html>\n <body>\n \n <div itemscope>\n <p>My name is <span itemprop = \"name\">Zara</span>.</p>\n </div>\n \n <div itemscope>\n <p>My name is <span itemprop = \"name\">Nuha</span>.</p>\n </div>\n \n </body>\n</html>"
},
{
"code": null,
"e": 3652,
"s": 3613,
"text": "It will produce the following result −"
},
{
"code": null,
"e": 3669,
"s": 3652,
"text": "My name is Zara."
},
{
"code": null,
"e": 3686,
"s": 3669,
"text": "My name is Nuha."
},
{
"code": null,
"e": 3775,
"s": 3686,
"text": "Properties generally have values that are strings but it can have following data types −"
},
{
"code": null,
"e": 3914,
"s": 3775,
"text": "Microdata introduces five global attributes which would be available for any element to use and give context for machines about your data."
},
{
"code": null,
"e": 3924,
"s": 3914,
"text": "itemscope"
},
{
"code": null,
"e": 4081,
"s": 3924,
"text": "This is used to create an item. The itemscope attribute is a Boolean attribute that tells that there is Microdata on this page, and this is where it starts."
},
{
"code": null,
"e": 4090,
"s": 4081,
"text": "itemtype"
},
{
"code": null,
"e": 4188,
"s": 4090,
"text": "This attribute is a valid URL which defines the item and provides the context for the properties."
},
{
"code": null,
"e": 4195,
"s": 4188,
"text": "itemid"
},
{
"code": null,
"e": 4245,
"s": 4195,
"text": "This attribute is global identifier for the item."
},
{
"code": null,
"e": 4254,
"s": 4245,
"text": "itemprop"
},
{
"code": null,
"e": 4301,
"s": 4254,
"text": "This attribute defines a property of the item."
},
{
"code": null,
"e": 4309,
"s": 4301,
"text": "itemref"
},
{
"code": null,
"e": 4411,
"s": 4309,
"text": "This attribute gives a list of additional elements to crawl to find the name-value pairs of the item."
},
{
"code": null,
"e": 4604,
"s": 4411,
"text": "Properties generally have values that are strings as mentioned in above example but they can also have values that are URLs. Following example has one property, \"image\", whose value is a URL −"
},
{
"code": null,
"e": 4698,
"s": 4604,
"text": "<div itemscope>\n <img itemprop = \"image\" src = \"tp-logo.gif\" alt = \"TutorialsPoint\">\n</div>"
},
{
"code": null,
"e": 4841,
"s": 4698,
"text": "Properties can also have values that are dates, times, or dates and times. This is achieved using the time element and its datetime attribute."
},
{
"code": null,
"e": 5055,
"s": 4841,
"text": "<html>\n <body>\n \n <div itemscope>\n My birthday is:\n <time itemprop = \"birthday\" datetime = \"1971-05-08\">\n Aug 5th 1971\n </time>\n </div>\n \n </body>\n</html>"
},
{
"code": null,
"e": 5094,
"s": 5055,
"text": "It will produce the following result −"
},
{
"code": null,
"e": 5234,
"s": 5094,
"text": "Properties can also themselves be groups of name-value pairs, by putting the itemscope attribute on the element that declares the property."
},
{
"code": null,
"e": 5429,
"s": 5234,
"text": "If a browser supports the HTML5 microdata API, there will be a getItems() function on the global document object. If browser doesn't support microdata, the getItems() function will be undefined."
},
{
"code": null,
"e": 5498,
"s": 5429,
"text": "function supports_microdata_api() {\n return !!document.getItems;\n}"
},
{
"code": null,
"e": 5623,
"s": 5498,
"text": "Modernizr does not yet support checking for the microdata API, so you’ll need to use the function like the one listed above."
},
{
"code": null,
"e": 5762,
"s": 5623,
"text": "The HTML5 microdata standard includes both HTML markup (primarily for search engines) and a set of DOM functions (primarily for browsers)."
},
{
"code": null,
"e": 6043,
"s": 5762,
"text": "You can include microdata markup in your web pages, and search engines that don't understand the microdata attributes will just ignore them. But if you need to access or manipulate microdata through the DOM, you'll need to check whether the browser supports the microdata DOM API."
},
{
"code": null,
"e": 6285,
"s": 6043,
"text": "To define microdata vocabulary you need a namespace URL which points to a working web page. For example https://data-vocabulary.org/Person can be used as the namespace for a personal microdata vocabulary with the following named properties −"
},
{
"code": null,
"e": 6323,
"s": 6285,
"text": "name − Person name as a simple string"
},
{
"code": null,
"e": 6361,
"s": 6323,
"text": "name − Person name as a simple string"
},
{
"code": null,
"e": 6403,
"s": 6361,
"text": "Photo − A URL to a picture of the person."
},
{
"code": null,
"e": 6445,
"s": 6403,
"text": "Photo − A URL to a picture of the person."
},
{
"code": null,
"e": 6486,
"s": 6445,
"text": "URL − A website belonging to the person."
},
{
"code": null,
"e": 6527,
"s": 6486,
"text": "URL − A website belonging to the person."
},
{
"code": null,
"e": 6591,
"s": 6527,
"text": "Using about properties a person microdata could be as follows −"
},
{
"code": null,
"e": 7049,
"s": 6591,
"text": "<html>\n <body>\n \n <div itemscope>\n <section itemscope itemtype = \"http://data-vocabulary.org/Person\">\n <h1 itemprop = \"name\">Gopal K Varma</h1>\n \n <p>\n <img itemprop = \"photo\" \n src = \"http://www.tutorialspoint.com/green/images/logo.png\">\n </p>\n \n <a itemprop = \"url\" href = \"#\">Site</a>\n </section>\n </div>\n \n </body>\n</html>"
},
{
"code": null,
"e": 7088,
"s": 7049,
"text": "It will produce the following result −"
},
{
"code": null,
"e": 7380,
"s": 7091,
"text": "Google supports microdata as part of their Rich Snippets program. When Google's web crawler parses your page and finds microdata properties that conform to the http://datavocabulary.org/Person vocabulary, it parses out those properties and stores them alongside the rest of the page data."
},
{
"code": null,
"e": 7496,
"s": 7380,
"text": "You can test above example using Rich Snippets Testing Tool using http://www.tutorialspoint.com/html5/microdata.htm"
},
{
"code": null,
"e": 7575,
"s": 7496,
"text": "For further development on Microdata you can always refer to HTML5 Microdata."
},
{
"code": null,
"e": 7608,
"s": 7575,
"text": "\n 19 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 7622,
"s": 7608,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 7657,
"s": 7622,
"text": "\n 16 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 7671,
"s": 7657,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 7706,
"s": 7671,
"text": "\n 18 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 7723,
"s": 7706,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 7758,
"s": 7723,
"text": "\n 57 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 7789,
"s": 7758,
"text": " DigiFisk (Programming Is Fun)"
},
{
"code": null,
"e": 7822,
"s": 7789,
"text": "\n 54 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 7853,
"s": 7822,
"text": " DigiFisk (Programming Is Fun)"
},
{
"code": null,
"e": 7888,
"s": 7853,
"text": "\n 45 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 7919,
"s": 7888,
"text": " DigiFisk (Programming Is Fun)"
},
{
"code": null,
"e": 7926,
"s": 7919,
"text": " Print"
},
{
"code": null,
"e": 7937,
"s": 7926,
"text": " Add Notes"
}
] |
How can I find non-ASCII characters in MySQL?
|
Non ASCII characters are characters such as the pound symbol(£), trademark symbol, plusminus
symbol etc. To find the non-ASCII characters from the table, the following steps are required −
First a table is created with the help of the create command which is given as follows −
mysql> CREATE table NonASciiDemo
-> (
-> NonAScii varchar(100)
-> );
Query OK, 0 rows affected (0.61 sec)
After that the records are inserted into the table with the help of the insert command which is as
follows −
mysql> INSERT into NonASciiDemo values('-,-');
Query OK, 1 row affected (0.18 sec)
mysql> INSERT into NonASciiDemo values(' ');
Query OK, 1 row affected (0.23 sec)
mysql> INSERT into NonASciiDemo values('£');
Query OK, 1 row affected (0.30 sec)
mysql> INSERT into NonASciiDemo values('123abcd£');
Query OK, 1 row affected (0.24 sec)
Four records are inserted into the table as shown above in which two records contain non ASCII
characters and two records contain ASCII characters.
To display allthe records, select command is used as follows −
SELECT * from NonASciiDemo;
The following is the output
+----------+
| NonAScii |
+----------+
| -,- |
| |
| £ |
| 123abcd£ |
+----------+
4 rows in set (0.00 sec)
The syntax to find the non ASCII characters is given as follows −
SELECT * FROM yourTableName WHERE NOT HEX(yourColumnName) REGEXP '^([0-7][0-
9A-F])*$';
The query to get the non ASCII characters using the above syntax is given as follows −
mysql> SELECT * FROM NonASciiDemo WHERE NOT HEX(NonAScii) REGEXP '^([0-7][0-9AF])*$';
The following is the output of the above query −
+----------+
| NonAScii |
+----------+
| £ |
| 123abcd£ |
+----------+
2 rows in set (0.00 sec)
|
[
{
"code": null,
"e": 1251,
"s": 1062,
"text": "Non ASCII characters are characters such as the pound symbol(£), trademark symbol, plusminus\nsymbol etc. To find the non-ASCII characters from the table, the following steps are required −"
},
{
"code": null,
"e": 1340,
"s": 1251,
"text": "First a table is created with the help of the create command which is given as follows −"
},
{
"code": null,
"e": 1446,
"s": 1340,
"text": "mysql> CREATE table NonASciiDemo\n-> (\n-> NonAScii varchar(100)\n-> );\nQuery OK, 0 rows affected (0.61 sec)"
},
{
"code": null,
"e": 1555,
"s": 1446,
"text": "After that the records are inserted into the table with the help of the insert command which is as\nfollows −"
},
{
"code": null,
"e": 1892,
"s": 1555,
"text": "mysql> INSERT into NonASciiDemo values('-,-');\nQuery OK, 1 row affected (0.18 sec)\n\nmysql> INSERT into NonASciiDemo values(' ');\nQuery OK, 1 row affected (0.23 sec)\n\nmysql> INSERT into NonASciiDemo values('£');\nQuery OK, 1 row affected (0.30 sec)\n\nmysql> INSERT into NonASciiDemo values('123abcd£');\nQuery OK, 1 row affected (0.24 sec)"
},
{
"code": null,
"e": 2040,
"s": 1892,
"text": "Four records are inserted into the table as shown above in which two records contain non ASCII\ncharacters and two records contain ASCII characters."
},
{
"code": null,
"e": 2103,
"s": 2040,
"text": "To display allthe records, select command is used as follows −"
},
{
"code": null,
"e": 2132,
"s": 2103,
"text": "SELECT * from NonASciiDemo;\n"
},
{
"code": null,
"e": 2160,
"s": 2132,
"text": "The following is the output"
},
{
"code": null,
"e": 2289,
"s": 2160,
"text": "+----------+\n| NonAScii |\n+----------+\n| -,- |\n| |\n| £ |\n| 123abcd£ |\n+----------+\n4 rows in set (0.00 sec)"
},
{
"code": null,
"e": 2355,
"s": 2289,
"text": "The syntax to find the non ASCII characters is given as follows −"
},
{
"code": null,
"e": 2443,
"s": 2355,
"text": "SELECT * FROM yourTableName WHERE NOT HEX(yourColumnName) REGEXP '^([0-7][0-\n9A-F])*$';"
},
{
"code": null,
"e": 2530,
"s": 2443,
"text": "The query to get the non ASCII characters using the above syntax is given as follows −"
},
{
"code": null,
"e": 2617,
"s": 2530,
"text": "mysql> SELECT * FROM NonASciiDemo WHERE NOT HEX(NonAScii) REGEXP '^([0-7][0-9AF])*$';\n"
},
{
"code": null,
"e": 2666,
"s": 2617,
"text": "The following is the output of the above query −"
},
{
"code": null,
"e": 2769,
"s": 2666,
"text": "+----------+\n| NonAScii |\n+----------+\n| £ |\n| 123abcd£ |\n+----------+\n2 rows in set (0.00 sec)"
}
] |
Puppeteer - Device Emulation
|
We can run tests with mobile configurations in Puppeteer and check the responsive property of a webpage. The list of devices that the Puppeteer supports can be obtained from the Chrome DevTools. Right-click on a page opened in the Chrome browser, then select Inspect.
Then, click on the Toggle Device Toolbar.
Click on the dropdown - Responsive to get the list of devices.
To emulate a device, we have to use the method emulate() and the device to be emulated is passed as a parameter to this method. The syntax for this method is as follows −
const m = puppeteer.devices['iPhone X']
//emulate iPhoneX
await page.emulate(m)
Let us emulate the device iPhone X using the emulate function in Puppeteer.
To begin, follow Steps 1 to 2 from the Chapter of Basic Test on Puppeteer which are as follows −
Step 1 − Create a new file within the directory where the node_modules folder is created (location where the Puppeteer and Puppeteer core have been installed).
The details on Puppeteer installation is discussed in the Chapter of Puppeteer Installation.
Right-click on the folder where the node_modules folder is created, then click on the New file button.
Step 2 − Enter a filename, say testcase1.js.
Step 3 − Add the below code within the testcase1.js file created.
//Puppeteer library
const puppeteer = require('puppeteer')
//launch browser in headed mode
puppeteer.launch({headless:false}).then(async browser => {
//browser new page
const page = await browser.newPage()
//set device to iPhone X
const m = puppeteer.devices['iPhone X']
//emulate iPhoneX
await page.emulate(m)
//launch URL
await page.goto('https://www.tutorialspoint.com/index.htm')
//capture screenshot of emulated device
await page.screenshot({ path: 'iPhoneDevice.png'})
//browser close
await browser.close()
})
Step 4 − Execute the code with the command given below −
node <filename>
So in our example, we shall run the following command −
node testcase1.js
After the command has been successfully executed, a new file called the iPhoneDevice.png gets created within the page directory. It contains the captured screenshot of the emulated webpage for the iPhone X device.
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 3018,
"s": 2750,
"text": "We can run tests with mobile configurations in Puppeteer and check the responsive property of a webpage. The list of devices that the Puppeteer supports can be obtained from the Chrome DevTools. Right-click on a page opened in the Chrome browser, then select Inspect."
},
{
"code": null,
"e": 3060,
"s": 3018,
"text": "Then, click on the Toggle Device Toolbar."
},
{
"code": null,
"e": 3123,
"s": 3060,
"text": "Click on the dropdown - Responsive to get the list of devices."
},
{
"code": null,
"e": 3294,
"s": 3123,
"text": "To emulate a device, we have to use the method emulate() and the device to be emulated is passed as a parameter to this method. The syntax for this method is as follows −"
},
{
"code": null,
"e": 3375,
"s": 3294,
"text": "const m = puppeteer.devices['iPhone X']\n//emulate iPhoneX\nawait page.emulate(m)\n"
},
{
"code": null,
"e": 3451,
"s": 3375,
"text": "Let us emulate the device iPhone X using the emulate function in Puppeteer."
},
{
"code": null,
"e": 3548,
"s": 3451,
"text": "To begin, follow Steps 1 to 2 from the Chapter of Basic Test on Puppeteer which are as follows −"
},
{
"code": null,
"e": 3708,
"s": 3548,
"text": "Step 1 − Create a new file within the directory where the node_modules folder is created (location where the Puppeteer and Puppeteer core have been installed)."
},
{
"code": null,
"e": 3801,
"s": 3708,
"text": "The details on Puppeteer installation is discussed in the Chapter of Puppeteer Installation."
},
{
"code": null,
"e": 3904,
"s": 3801,
"text": "Right-click on the folder where the node_modules folder is created, then click on the New file button."
},
{
"code": null,
"e": 3949,
"s": 3904,
"text": "Step 2 − Enter a filename, say testcase1.js."
},
{
"code": null,
"e": 4015,
"s": 3949,
"text": "Step 3 − Add the below code within the testcase1.js file created."
},
{
"code": null,
"e": 4567,
"s": 4015,
"text": "//Puppeteer library\nconst puppeteer = require('puppeteer')\n//launch browser in headed mode\npuppeteer.launch({headless:false}).then(async browser => {\n //browser new page\n const page = await browser.newPage()\n //set device to iPhone X\n const m = puppeteer.devices['iPhone X']\n //emulate iPhoneX\n await page.emulate(m)\n //launch URL\n await page.goto('https://www.tutorialspoint.com/index.htm')\n //capture screenshot of emulated device\n await page.screenshot({ path: 'iPhoneDevice.png'})\n //browser close\n await browser.close()\n})"
},
{
"code": null,
"e": 4624,
"s": 4567,
"text": "Step 4 − Execute the code with the command given below −"
},
{
"code": null,
"e": 4641,
"s": 4624,
"text": "node <filename>\n"
},
{
"code": null,
"e": 4697,
"s": 4641,
"text": "So in our example, we shall run the following command −"
},
{
"code": null,
"e": 4716,
"s": 4697,
"text": "node testcase1.js\n"
},
{
"code": null,
"e": 4930,
"s": 4716,
"text": "After the command has been successfully executed, a new file called the iPhoneDevice.png gets created within the page directory. It contains the captured screenshot of the emulated webpage for the iPhone X device."
},
{
"code": null,
"e": 4937,
"s": 4930,
"text": " Print"
},
{
"code": null,
"e": 4948,
"s": 4937,
"text": " Add Notes"
}
] |
Which event occurs when a value is added to an input box in JavaScript? - GeeksforGeeks
|
11 Feb, 2022
JavaScript has events to provide a dynamic interface to a webpage. These events are hooked to elements in the Document Object Model (DOM). These events by default use bubbling propagation i.e, upwards in the DOM from children to parent. We can bind events either as inline or in an external script. There are multiple events associated with Javascript which include onClick(), onChange(), onmouseleave(), onmouseout(), onmouseover(), onload etc.
In this article, we will specifically learn about the event that occurs when a value is added in an input box in JavaScript.
oninput() event: The oninput() event occurs when a value is added to an input box. We enter a value using the keyboard. So we can associate certain keyboard events when a value is added in an input box using the keyboard.
These events may include:
onkeypress: When the user presse a key that produces a character value.
onkeyup: Whenever a key is released after pressing.
onkeydown: When the user has pressed down the key. It will occur even if the key pressed does not produce a character value.
We can also associate onChange events when a value is added in an input box using the keyboard.
onChange: This event detects the change in the value of any element listing to this event.
Example 1: Below is an example that shows the usage of these events.
HTML
<!DOCTYPE html><html> <head> <title>GFG events</title></head> <body id="GFG"> <form> <label>Type Something</label> <input type="text" onChange=invokingOnChangeEvent() oninput=invokingOnInputEvent() onkeydown=invokingOnKeyDownEvent() onkeyup=invokingOnKeyUpEvent() onkeypress=invokingOnKeyPressEvent()> </input> </form> <script> function invokingOnInputEvent(event) { console.log("onInput event occurred") } function invokingOnChangeEvent(event) { console.log("onChange event occurred") } function invokingOnKeyPressEvent(event) { console.log("onKeyPress event occurred") } function invokingOnKeyUpEvent(event) { console.log("onKeyUp event occurred") } function invokingOnKeyDownEvent(event) { console.log("onKeyDown event occurred") } </script></body> </html>
Output:
Example 2: This example will change the background color on an event occurring
HTML
<!DOCTYPE html><html> <head> <title>GFG events</title></head> <body id="GFG"> <form> <label> Type Something</label> <input type="text" onChange=invokingOnChangeEvent() oninput=invokingOnInputEvent() onkeydown=invokingOnKeyDownEvent() onkeyup=invokingOnKeyUpEvent() onkeypress=invokingOnKeyPressEvent()> </input> </form> <script> function invokingOnInputEvent(event) { console.log("onInput event occurred") document.getElementById("GFG") .style.backgroundColor = 'red'; } function invokingOnChangeEvent(event) { console.log("onChange event occurred") document.getElementById("GFG") .style.backgroundColor = 'green'; } function invokingOnKeyPressEvent(event) { console.log("onKeyPress event occurred") document.getElementById("GFG") .style.backgroundColor = 'yellow'; } function invokingOnKeyUpEvent(event) { console.log("onKeyUp event occurred") document.getElementById("GFG") .style.backgroundColor = 'pink'; } function invokingOnKeyDownEvent(event) { console.log("onKeyDown event occurred") document.getElementById("GFG") .style.backgroundColor = 'orange'; } </script></body> </html>
Output:
germanshephered48
JavaScript-Events
JavaScript-Questions
Picked
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
How to create a link in JavaScript ?
How to Show Images on Click using HTML ?
How to remove an HTML element using JavaScript ?
Remove elements from a JavaScript Array
Express.js express.Router() Function
Installation of Node.js on Linux
How to set input type date in dd-mm-yyyy format using HTML ?
How to create footer to stay at the bottom of a Web page?
How to float three div side by side using CSS?
|
[
{
"code": null,
"e": 24909,
"s": 24881,
"text": "\n11 Feb, 2022"
},
{
"code": null,
"e": 25356,
"s": 24909,
"text": "JavaScript has events to provide a dynamic interface to a webpage. These events are hooked to elements in the Document Object Model (DOM). These events by default use bubbling propagation i.e, upwards in the DOM from children to parent. We can bind events either as inline or in an external script. There are multiple events associated with Javascript which include onClick(), onChange(), onmouseleave(), onmouseout(), onmouseover(), onload etc."
},
{
"code": null,
"e": 25481,
"s": 25356,
"text": "In this article, we will specifically learn about the event that occurs when a value is added in an input box in JavaScript."
},
{
"code": null,
"e": 25703,
"s": 25481,
"text": "oninput() event: The oninput() event occurs when a value is added to an input box. We enter a value using the keyboard. So we can associate certain keyboard events when a value is added in an input box using the keyboard."
},
{
"code": null,
"e": 25729,
"s": 25703,
"text": "These events may include:"
},
{
"code": null,
"e": 25801,
"s": 25729,
"text": "onkeypress: When the user presse a key that produces a character value."
},
{
"code": null,
"e": 25853,
"s": 25801,
"text": "onkeyup: Whenever a key is released after pressing."
},
{
"code": null,
"e": 25978,
"s": 25853,
"text": "onkeydown: When the user has pressed down the key. It will occur even if the key pressed does not produce a character value."
},
{
"code": null,
"e": 26074,
"s": 25978,
"text": "We can also associate onChange events when a value is added in an input box using the keyboard."
},
{
"code": null,
"e": 26165,
"s": 26074,
"text": "onChange: This event detects the change in the value of any element listing to this event."
},
{
"code": null,
"e": 26234,
"s": 26165,
"text": "Example 1: Below is an example that shows the usage of these events."
},
{
"code": null,
"e": 26239,
"s": 26234,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <title>GFG events</title></head> <body id=\"GFG\"> <form> <label>Type Something</label> <input type=\"text\" onChange=invokingOnChangeEvent() oninput=invokingOnInputEvent() onkeydown=invokingOnKeyDownEvent() onkeyup=invokingOnKeyUpEvent() onkeypress=invokingOnKeyPressEvent()> </input> </form> <script> function invokingOnInputEvent(event) { console.log(\"onInput event occurred\") } function invokingOnChangeEvent(event) { console.log(\"onChange event occurred\") } function invokingOnKeyPressEvent(event) { console.log(\"onKeyPress event occurred\") } function invokingOnKeyUpEvent(event) { console.log(\"onKeyUp event occurred\") } function invokingOnKeyDownEvent(event) { console.log(\"onKeyDown event occurred\") } </script></body> </html>",
"e": 27224,
"s": 26239,
"text": null
},
{
"code": null,
"e": 27232,
"s": 27224,
"text": "Output:"
},
{
"code": null,
"e": 27311,
"s": 27232,
"text": "Example 2: This example will change the background color on an event occurring"
},
{
"code": null,
"e": 27316,
"s": 27311,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <title>GFG events</title></head> <body id=\"GFG\"> <form> <label> Type Something</label> <input type=\"text\" onChange=invokingOnChangeEvent() oninput=invokingOnInputEvent() onkeydown=invokingOnKeyDownEvent() onkeyup=invokingOnKeyUpEvent() onkeypress=invokingOnKeyPressEvent()> </input> </form> <script> function invokingOnInputEvent(event) { console.log(\"onInput event occurred\") document.getElementById(\"GFG\") .style.backgroundColor = 'red'; } function invokingOnChangeEvent(event) { console.log(\"onChange event occurred\") document.getElementById(\"GFG\") .style.backgroundColor = 'green'; } function invokingOnKeyPressEvent(event) { console.log(\"onKeyPress event occurred\") document.getElementById(\"GFG\") .style.backgroundColor = 'yellow'; } function invokingOnKeyUpEvent(event) { console.log(\"onKeyUp event occurred\") document.getElementById(\"GFG\") .style.backgroundColor = 'pink'; } function invokingOnKeyDownEvent(event) { console.log(\"onKeyDown event occurred\") document.getElementById(\"GFG\") .style.backgroundColor = 'orange'; } </script></body> </html>",
"e": 28753,
"s": 27316,
"text": null
},
{
"code": null,
"e": 28761,
"s": 28753,
"text": "Output:"
},
{
"code": null,
"e": 28779,
"s": 28761,
"text": "germanshephered48"
},
{
"code": null,
"e": 28797,
"s": 28779,
"text": "JavaScript-Events"
},
{
"code": null,
"e": 28818,
"s": 28797,
"text": "JavaScript-Questions"
},
{
"code": null,
"e": 28825,
"s": 28818,
"text": "Picked"
},
{
"code": null,
"e": 28836,
"s": 28825,
"text": "JavaScript"
},
{
"code": null,
"e": 28853,
"s": 28836,
"text": "Web Technologies"
},
{
"code": null,
"e": 28951,
"s": 28853,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28960,
"s": 28951,
"text": "Comments"
},
{
"code": null,
"e": 28973,
"s": 28960,
"text": "Old Comments"
},
{
"code": null,
"e": 29034,
"s": 28973,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 29071,
"s": 29034,
"text": "How to create a link in JavaScript ?"
},
{
"code": null,
"e": 29112,
"s": 29071,
"text": "How to Show Images on Click using HTML ?"
},
{
"code": null,
"e": 29161,
"s": 29112,
"text": "How to remove an HTML element using JavaScript ?"
},
{
"code": null,
"e": 29201,
"s": 29161,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 29238,
"s": 29201,
"text": "Express.js express.Router() Function"
},
{
"code": null,
"e": 29271,
"s": 29238,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 29332,
"s": 29271,
"text": "How to set input type date in dd-mm-yyyy format using HTML ?"
},
{
"code": null,
"e": 29390,
"s": 29332,
"text": "How to create footer to stay at the bottom of a Web page?"
}
] |
Electron - Webview
|
The webview tag is used to embed the 'guest' content like web pages in your Electron app. This content is contained within the webview container. An embedded page within your app controls how this content will be displayed.
The webview runs in a separate process than your app. To ensure security from malicious content, the webview doesn't have same permissions as your web page. This keeps your app safe from the embedded content. All interactions between your app and the embedded page will be asynchronous.
Let us consider an example to understand the embedding of an external webpage in our Electron app. We will embed the tutorialspoint website in our app on the right side. Create a new main.js file with the following content −
const {app, BrowserWindow} = require('electron')
const url = require('url')
const path = require('path')
let win
function createWindow() {
win = new BrowserWindow({width: 800, height: 600})
win.loadURL(url.format ({
pathname: path.join(__dirname, 'index.html'),
protocol: 'file:',
slashes: true
}))
}
app.on('ready', createWindow)
Now that we have set up our main process, let us create the HTML file that will embed the tutorialspoint website. Create a file called index.html with the following content −
<!DOCTYPE html>
<html>
<head>
<meta charset = "UTF-8">
<title>Menus</title>
</head>
<body>
<div>
<div>
<h2>We have the website embedded below!</h2>
</div>
<webview id = "foo" src = "https://www.tutorialspoint.com/" style =
"width:400px; height:480px;">
<div class = "indicator"></div>
</webview>
</div>
<script type = "text/javascript">
// Event handlers for loading events.
// Use these to handle loading screens, transitions, etc
onload = () => {
const webview = document.getElementById('foo')
const indicator = document.querySelector('.indicator')
const loadstart = () => {
indicator.innerText = 'loading...'
}
const loadstop = () => {
indicator.innerText = ''
}
webview.addEventListener('did-start-loading', loadstart)
webview.addEventListener('did-stop-loading', loadstop)
}
</script>
</body>
</html>
Run the app using the following command −
$ electron ./main.js
The above command will generate the following output −
The webview tag can be used for other resources as well. The webview element has a list of events that it emits listed on the official docs. You can use these events to improve the functionality depending on the things that take place in the webview.
Whenever you are embedding scripts or other resources from the Internet, it is advisable to use webview. This is recommended as it comes with great security benefits and does not hinder normal behaviour.
251 Lectures
35.5 hours
Gowthami Swarna
9 Lectures
41 mins
Ashraf Said
8 Lectures
32 mins
Ashraf Said
25 Lectures
1 hours
Ashraf Said
17 Lectures
1 hours
Ashraf Said
8 Lectures
25 mins
Ashraf Said
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2289,
"s": 2065,
"text": "The webview tag is used to embed the 'guest' content like web pages in your Electron app. This content is contained within the webview container. An embedded page within your app controls how this content will be displayed."
},
{
"code": null,
"e": 2576,
"s": 2289,
"text": "The webview runs in a separate process than your app. To ensure security from malicious content, the webview doesn't have same permissions as your web page. This keeps your app safe from the embedded content. All interactions between your app and the embedded page will be asynchronous."
},
{
"code": null,
"e": 2801,
"s": 2576,
"text": "Let us consider an example to understand the embedding of an external webpage in our Electron app. We will embed the tutorialspoint website in our app on the right side. Create a new main.js file with the following content −"
},
{
"code": null,
"e": 3162,
"s": 2801,
"text": "const {app, BrowserWindow} = require('electron')\nconst url = require('url')\nconst path = require('path')\n\nlet win\n\nfunction createWindow() {\n win = new BrowserWindow({width: 800, height: 600})\n win.loadURL(url.format ({\n pathname: path.join(__dirname, 'index.html'),\n protocol: 'file:',\n slashes: true\n }))\n}\n\napp.on('ready', createWindow)"
},
{
"code": null,
"e": 3337,
"s": 3162,
"text": "Now that we have set up our main process, let us create the HTML file that will embed the tutorialspoint website. Create a file called index.html with the following content −"
},
{
"code": null,
"e": 4440,
"s": 3337,
"text": "<!DOCTYPE html>\n<html>\n <head>\n <meta charset = \"UTF-8\">\n <title>Menus</title>\n </head>\n \n <body>\n <div>\n <div>\n <h2>We have the website embedded below!</h2>\n </div>\n <webview id = \"foo\" src = \"https://www.tutorialspoint.com/\" style = \n \"width:400px; height:480px;\">\n <div class = \"indicator\"></div>\n </webview>\n </div>\n \n <script type = \"text/javascript\">\n // Event handlers for loading events.\n // Use these to handle loading screens, transitions, etc\n onload = () => {\n const webview = document.getElementById('foo')\n const indicator = document.querySelector('.indicator')\n\n const loadstart = () => {\n indicator.innerText = 'loading...'\n }\n\n const loadstop = () => {\n indicator.innerText = ''\n }\n\n webview.addEventListener('did-start-loading', loadstart)\n webview.addEventListener('did-stop-loading', loadstop)\n }\n </script>\n </body>\n</html>"
},
{
"code": null,
"e": 4482,
"s": 4440,
"text": "Run the app using the following command −"
},
{
"code": null,
"e": 4504,
"s": 4482,
"text": "$ electron ./main.js\n"
},
{
"code": null,
"e": 4559,
"s": 4504,
"text": "The above command will generate the following output −"
},
{
"code": null,
"e": 4810,
"s": 4559,
"text": "The webview tag can be used for other resources as well. The webview element has a list of events that it emits listed on the official docs. You can use these events to improve the functionality depending on the things that take place in the webview."
},
{
"code": null,
"e": 5014,
"s": 4810,
"text": "Whenever you are embedding scripts or other resources from the Internet, it is advisable to use webview. This is recommended as it comes with great security benefits and does not hinder normal behaviour."
},
{
"code": null,
"e": 5051,
"s": 5014,
"text": "\n 251 Lectures \n 35.5 hours \n"
},
{
"code": null,
"e": 5068,
"s": 5051,
"text": " Gowthami Swarna"
},
{
"code": null,
"e": 5099,
"s": 5068,
"text": "\n 9 Lectures \n 41 mins\n"
},
{
"code": null,
"e": 5112,
"s": 5099,
"text": " Ashraf Said"
},
{
"code": null,
"e": 5143,
"s": 5112,
"text": "\n 8 Lectures \n 32 mins\n"
},
{
"code": null,
"e": 5156,
"s": 5143,
"text": " Ashraf Said"
},
{
"code": null,
"e": 5189,
"s": 5156,
"text": "\n 25 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 5202,
"s": 5189,
"text": " Ashraf Said"
},
{
"code": null,
"e": 5235,
"s": 5202,
"text": "\n 17 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 5248,
"s": 5235,
"text": " Ashraf Said"
},
{
"code": null,
"e": 5279,
"s": 5248,
"text": "\n 8 Lectures \n 25 mins\n"
},
{
"code": null,
"e": 5292,
"s": 5279,
"text": " Ashraf Said"
},
{
"code": null,
"e": 5299,
"s": 5292,
"text": " Print"
},
{
"code": null,
"e": 5310,
"s": 5299,
"text": " Add Notes"
}
] |
How to set selected item of Spinner by value instead of by position on Android?
|
This example demonstrates how do I set the selected item of Spinner by value instead of by position on Android.
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.
Step 2 − Add the following code to res/layout/activity_main.xml.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="16dp"
tools:context=".MainActivity">
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:onClick="SelectSpinnerValue"
android:text="Select Cristiano Ronaldo" />
<Spinner
android:id="@+id/spinner"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/button"
android:layout_centerInParent="true"
android:layout_marginTop="10dp" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="40dp"
android:text="Set selected item of Spinner by value instead of by position on Android"
android:textAlignment="center"
android:textSize="24sp"
android:textStyle="bold|italic" />
</RelativeLayout>
Step 3 − Add the following code to src/MainActivity.java
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class MainActivity extends AppCompatActivity {
Spinner spinner;
String[] FootBallPlayers = new String[]{"Lionel Messi", "Eden Hazard", "Cristiano Ronaldo", "Neymar Jr", "Gareth Bale", "David Bekham"};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
spinner = findViewById(R.id.spinner);
final List<String> plantsList = new ArrayList<>(Arrays.asList(FootBallPlayers));
final ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<>(this, R.layout.support_simple_spinner_dropdown_item, plantsList);
spinnerArrayAdapter.setDropDownViewResource(R.layout.spinner_value);
spinner.setAdapter(spinnerArrayAdapter);
}
public void SelectSpinnerValue(View view) {
spinner.setSelection(2);
}
}
Step 4 − Create a layout resource file (spinner_value.xml) and add the following code:
<?xml version="1.0" encoding="utf-8"?>
<TextView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="10dp"
android:textStyle="italic"
android:fontFamily="sans-serif-medium" />
Step 5 − Add the following code to androidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="app.com.sample">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen −
Click here to download the project code.
|
[
{
"code": null,
"e": 1174,
"s": 1062,
"text": "This example demonstrates how do I set the selected item of Spinner by value instead of by position on Android."
},
{
"code": null,
"e": 1303,
"s": 1174,
"text": "Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project."
},
{
"code": null,
"e": 1368,
"s": 1303,
"text": "Step 2 − Add the following code to res/layout/activity_main.xml."
},
{
"code": null,
"e": 2541,
"s": 1368,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<RelativeLayout\nxmlns:android=\"http://schemas.android.com/apk/res/android\"\n xmlns:tools=\"http://schemas.android.com/tools\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n android:padding=\"16dp\"\n tools:context=\".MainActivity\">\n <Button\n android:id=\"@+id/button\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_centerInParent=\"true\"\n android:onClick=\"SelectSpinnerValue\"\n android:text=\"Select Cristiano Ronaldo\" />\n <Spinner\n android:id=\"@+id/spinner\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_below=\"@id/button\"\n android:layout_centerInParent=\"true\"\n android:layout_marginTop=\"10dp\" />\n <TextView\n android:layout_width=\"match_parent\"\n android:layout_height=\"wrap_content\"\n android:layout_marginTop=\"40dp\"\n android:text=\"Set selected item of Spinner by value instead of by position on Android\"\n android:textAlignment=\"center\"\n android:textSize=\"24sp\"\n android:textStyle=\"bold|italic\" />\n</RelativeLayout>"
},
{
"code": null,
"e": 2598,
"s": 2541,
"text": "Step 3 − Add the following code to src/MainActivity.java"
},
{
"code": null,
"e": 3696,
"s": 2598,
"text": "import androidx.appcompat.app.AppCompatActivity;\nimport android.os.Bundle;\nimport android.view.View;\nimport android.widget.ArrayAdapter;\nimport android.widget.Spinner;\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.List;\npublic class MainActivity extends AppCompatActivity {\n Spinner spinner;\n String[] FootBallPlayers = new String[]{\"Lionel Messi\", \"Eden Hazard\", \"Cristiano Ronaldo\", \"Neymar Jr\", \"Gareth Bale\", \"David Bekham\"};\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n spinner = findViewById(R.id.spinner);\n final List<String> plantsList = new ArrayList<>(Arrays.asList(FootBallPlayers));\n final ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<>(this, R.layout.support_simple_spinner_dropdown_item, plantsList);\n spinnerArrayAdapter.setDropDownViewResource(R.layout.spinner_value);\n spinner.setAdapter(spinnerArrayAdapter);\n }\n public void SelectSpinnerValue(View view) {\n spinner.setSelection(2);\n }\n}"
},
{
"code": null,
"e": 3783,
"s": 3696,
"text": "Step 4 − Create a layout resource file (spinner_value.xml) and add the following code:"
},
{
"code": null,
"e": 4074,
"s": 3783,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<TextView\n xmlns:android=\"http://schemas.android.com/apk/res/android\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"wrap_content\"\n android:padding=\"10dp\"\n android:textStyle=\"italic\"\n android:fontFamily=\"sans-serif-medium\" />"
},
{
"code": null,
"e": 4129,
"s": 4074,
"text": "Step 5 − Add the following code to androidManifest.xml"
},
{
"code": null,
"e": 4799,
"s": 4129,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\" package=\"app.com.sample\">\n <application\n android:allowBackup=\"true\"\n android:icon=\"@mipmap/ic_launcher\"\n android:label=\"@string/app_name\"\n android:roundIcon=\"@mipmap/ic_launcher_round\"\n android:supportsRtl=\"true\"\n android:theme=\"@style/AppTheme\">\n <activity android:name=\".MainActivity\">\n <intent-filter>\n <action android:name=\"android.intent.action.MAIN\" />\n <category android:name=\"android.intent.category.LAUNCHER\" />\n </intent-filter>\n </activity>\n </application>\n</manifest>"
},
{
"code": null,
"e": 5146,
"s": 4799,
"text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen −"
},
{
"code": null,
"e": 5187,
"s": 5146,
"text": "Click here to download the project code."
}
] |
Prolog - Examples of Cuts
|
In this section, we will see some examples of cuts in prolog. Let us consider, we want to find the maximum of two elements. So we will check these two conditions.
If X > Y, then Max := X
If X > Y, then Max := X
if X <= Y, then Max := Y
if X <= Y, then Max := Y
Now from these two lines, we can understand that these two statements are mutually exclusive, so when one is true, another one must be false. In such cases we can use the cut. So let us see the program.
We can also define a predicate where we use the two cases using disjunction (OR logic). So when first one satisfies, it does not check for the second one, otherwise, it will check for the second statement.
max(X,Y,X) :- X >= Y,!.
max(X,Y,Y) :- X < Y.
max_find(X,Y,Max) :- X >= Y,!, Max = X; Max = Y.
| ?- [cut_example].
1 1 Call: [cut_example] ?
compiling D:/TP Prolog/Sample_Codes/cut_example.pl for byte code...
D:/TP Prolog/Sample_Codes/cut_example.pl compiled, 3 lines read - 1195 bytes written, 43 ms
1 1 Exit: [cut_example] ?
yes
{trace}
| ?- max(10,20,Max).
1 1 Call: max(10,20,_23) ?
2 2 Call: 10>=20 ?
2 2 Fail: 10>=20 ?
2 2 Call: 10<20 ?
2 2 Exit: 10<20 ?
1 1 Exit: max(10,20,20) ?
Max = 20
yes
{trace}
| ?- max_find(20,10,Max).
1 1 Call: max_find(20,10,_23) ?
2 2 Call: 20>=10 ?
2 2 Exit: 20>=10 ?
1 1 Exit: max_find(20,10,20) ?
Max = 20
yes
{trace}
| ?-
Let us see another example, where we will use list. In this program we will try to insert an element into a list, if it is not present in the list before. And if the list has the element before we will simply cut it. For the membership checking also, if the item is at the head part, we should not check further, so cut it, otherwise check into the tail part.
list_member(X,[X|_]) :- !.
list_member(X,[_|TAIL]) :- list_member(X,TAIL).
list_append(A,T,T) :- list_member(A,T),!.
list_append(A,T,[A|T]).
| ?- [cut_example].
compiling D:/TP Prolog/Sample_Codes/cut_example.pl for byte code...
D:/TP Prolog/Sample_Codes/cut_example.pl compiled, 9 lines read - 1954 bytes written, 15 ms
yes
| ?- trace.
The debugger will first creep -- showing everything (trace)
yes
{trace}
| ?- list_append(a,[a,b,c,d,e], L).
1 1 Call: list_append(a,[a,b,c,d,e],_33) ?
2 2 Call: list_member(a,[a,b,c,d,e]) ?
2 2 Exit: list_member(a,[a,b,c,d,e]) ?
1 1 Exit: list_append(a,[a,b,c,d,e],[a,b,c,d,e]) ?
L = [a,b,c,d,e]
yes
{trace}
| ?- list_append(k,[a,b,c,d,e], L).
1 1 Call: list_append(k,[a,b,c,d,e],_33) ?
2 2 Call: list_member(k,[a,b,c,d,e]) ?
3 3 Call: list_member(k,[b,c,d,e]) ?
4 4 Call: list_member(k,[c,d,e]) ?
5 5 Call: list_member(k,[d,e]) ?
6 6 Call: list_member(k,[e]) ?
7 7 Call: list_member(k,[]) ?
7 7 Fail: list_member(k,[]) ?
6 6 Fail: list_member(k,[e]) ?
5 5 Fail: list_member(k,[d,e]) ?
4 4 Fail: list_member(k,[c,d,e]) ?
3 3 Fail: list_member(k,[b,c,d,e]) ?
2 2 Fail: list_member(k,[a,b,c,d,e]) ?
1 1 Exit: list_append(k,[a,b,c,d,e],[k,a,b,c,d,e]) ?
L = [k,a,b,c,d,e]
(16 ms) yes
{trace}
| ?-
65 Lectures
5 hours
Arnab Chakraborty
78 Lectures
7 hours
Arnab Chakraborty
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2255,
"s": 2092,
"text": "In this section, we will see some examples of cuts in prolog. Let us consider, we want to find the maximum of two elements. So we will check these two conditions."
},
{
"code": null,
"e": 2279,
"s": 2255,
"text": "If X > Y, then Max := X"
},
{
"code": null,
"e": 2303,
"s": 2279,
"text": "If X > Y, then Max := X"
},
{
"code": null,
"e": 2328,
"s": 2303,
"text": "if X <= Y, then Max := Y"
},
{
"code": null,
"e": 2353,
"s": 2328,
"text": "if X <= Y, then Max := Y"
},
{
"code": null,
"e": 2556,
"s": 2353,
"text": "Now from these two lines, we can understand that these two statements are mutually exclusive, so when one is true, another one must be false. In such cases we can use the cut. So let us see the program."
},
{
"code": null,
"e": 2762,
"s": 2556,
"text": "We can also define a predicate where we use the two cases using disjunction (OR logic). So when first one satisfies, it does not check for the second one, otherwise, it will check for the second statement."
},
{
"code": null,
"e": 2857,
"s": 2762,
"text": "max(X,Y,X) :- X >= Y,!.\nmax(X,Y,Y) :- X < Y.\n\nmax_find(X,Y,Max) :- X >= Y,!, Max = X; Max = Y."
},
{
"code": null,
"e": 3498,
"s": 2857,
"text": "| ?- [cut_example].\n 1 1 Call: [cut_example] ?\ncompiling D:/TP Prolog/Sample_Codes/cut_example.pl for byte code...\nD:/TP Prolog/Sample_Codes/cut_example.pl compiled, 3 lines read - 1195 bytes written, 43 ms\n 1 1 Exit: [cut_example] ?\nyes\n{trace}\n| ?- max(10,20,Max).\n 1 1 Call: max(10,20,_23) ?\n 2 2 Call: 10>=20 ?\n 2 2 Fail: 10>=20 ?\n 2 2 Call: 10<20 ?\n 2 2 Exit: 10<20 ?\n 1 1 Exit: max(10,20,20) ?\nMax = 20\n\nyes\n{trace}\n| ?- max_find(20,10,Max).\n 1 1 Call: max_find(20,10,_23) ?\n 2 2 Call: 20>=10 ?\n 2 2 Exit: 20>=10 ?\n 1 1 Exit: max_find(20,10,20) ?\nMax = 20\n\nyes\n{trace}\n| ?-\n"
},
{
"code": null,
"e": 3858,
"s": 3498,
"text": "Let us see another example, where we will use list. In this program we will try to insert an element into a list, if it is not present in the list before. And if the list has the element before we will simply cut it. For the membership checking also, if the item is at the head part, we should not check further, so cut it, otherwise check into the tail part."
},
{
"code": null,
"e": 4000,
"s": 3858,
"text": "list_member(X,[X|_]) :- !.\nlist_member(X,[_|TAIL]) :- list_member(X,TAIL).\n\nlist_append(A,T,T) :- list_member(A,T),!.\nlist_append(A,T,[A|T])."
},
{
"code": null,
"e": 5216,
"s": 4000,
"text": "| ?- [cut_example].\ncompiling D:/TP Prolog/Sample_Codes/cut_example.pl for byte code...\nD:/TP Prolog/Sample_Codes/cut_example.pl compiled, 9 lines read - 1954 bytes written, 15 ms\n\nyes\n| ?- trace.\nThe debugger will first creep -- showing everything (trace)\n\nyes\n{trace}\n| ?- list_append(a,[a,b,c,d,e], L).\n 1 1 Call: list_append(a,[a,b,c,d,e],_33) ?\n 2 2 Call: list_member(a,[a,b,c,d,e]) ?\n 2 2 Exit: list_member(a,[a,b,c,d,e]) ?\n 1 1 Exit: list_append(a,[a,b,c,d,e],[a,b,c,d,e]) ?\n \nL = [a,b,c,d,e]\n\nyes\n{trace}\n| ?- list_append(k,[a,b,c,d,e], L).\n 1 1 Call: list_append(k,[a,b,c,d,e],_33) ?\n 2 2 Call: list_member(k,[a,b,c,d,e]) ?\n 3 3 Call: list_member(k,[b,c,d,e]) ?\n 4 4 Call: list_member(k,[c,d,e]) ?\n 5 5 Call: list_member(k,[d,e]) ?\n 6 6 Call: list_member(k,[e]) ?\n 7 7 Call: list_member(k,[]) ?\n 7 7 Fail: list_member(k,[]) ?\n 6 6 Fail: list_member(k,[e]) ?\n 5 5 Fail: list_member(k,[d,e]) ?\n 4 4 Fail: list_member(k,[c,d,e]) ?\n 3 3 Fail: list_member(k,[b,c,d,e]) ?\n 2 2 Fail: list_member(k,[a,b,c,d,e]) ?\n 1 1 Exit: list_append(k,[a,b,c,d,e],[k,a,b,c,d,e]) ?\n \nL = [k,a,b,c,d,e]\n\n(16 ms) yes\n{trace}\n| ?-\n"
},
{
"code": null,
"e": 5249,
"s": 5216,
"text": "\n 65 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 5268,
"s": 5249,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 5301,
"s": 5268,
"text": "\n 78 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 5320,
"s": 5301,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 5327,
"s": 5320,
"text": " Print"
},
{
"code": null,
"e": 5338,
"s": 5327,
"text": " Add Notes"
}
] |
scipy stats.cauchy() | Python - GeeksforGeeks
|
20 Mar, 2019
scipy.stats.cauchy() is an cauchy continuous random variable that is defined with a standard format and some shape parameters to complete its specification.
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 : cauchy continuous random variable
Code #1 : Creating cauchy continuous random variable
# importing scipyfrom scipy.stats import cauchy numargs = cauchy.numargs[] = [0.6, ] * numargsrv = cauchy() print ("RV : \n", rv)
Output :
RV :
<scipy.stats._distn_infrastructure.rv_frozen object at 0x000002948548C6D8>
Code #2 : cauchy random variates and probability distribution function.
import numpy as npquantile = np.arange (0.01, 1, 0.1) import numpy as npimport matplotlib.pyplot as plt distribution = np.linspace(0, np.minimum(rv.dist.b, 5))print("Distribution : \n", distribution) plot = plt.plot(distribution, rv.pdf(distribution))
Output :
Random Variates :
[ 2.73388202 4.88389383 -4.89271415 4.63864536 -0.36933865 1.51521875
1.43853452 -0.69619917 -0.68358229 4.13179831]
Probability Distribution :
[0.31827806 0.31450438 0.30486533 0.29040223 0.27250226 0.25260685
0.23198738 0.21162814 0.19220451 0.17412061]
Code #3 : Graphical Representation.
import numpy as npimport matplotlib.pyplot as plt distribution = np.linspace(0, np.minimum(rv.dist.b, 5))print("Distribution : \n", distribution) plot = plt.plot(distribution, rv.pdf(distribution))
Output :
Distribution :
Distribution :
[0. 0.10204082 0.20408163 0.30612245 0.40816327 0.51020408
0.6122449 0.71428571 0.81632653 0.91836735 1.02040816 1.12244898
1.2244898 1.32653061 1.42857143 1.53061224 1.63265306 1.73469388
1.83673469 1.93877551 2.04081633 2.14285714 2.24489796 2.34693878
2.44897959 2.55102041 2.65306122 2.75510204 2.85714286 2.95918367
3.06122449 3.16326531 3.26530612 3.36734694 3.46938776 3.57142857
3.67346939 3.7755102 3.87755102 3.97959184 4.08163265 4.18367347
4.28571429 4.3877551 4.48979592 4.59183673 4.69387755 4.79591837
4.89795918 5. ]
Code #4 : Varying Positional Arguments
import matplotlib.pyplot as pltimport numpy as np x = np.linspace(0, 1.0, 100) # Varying positional argumentsy1 = cauchy.pdf(x, 2.75, 2.75)y2 = cauchy.pdf(x, 3.25, 3.25)plt.plot(x, y1, "*", x, y2, "r--")
Output :
Python scipy-stats-functions
Python-scipy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Python String | replace()
*args and **kwargs in Python
Reading and Writing to text files in Python
Create a Pandas DataFrame from Lists
Convert integer to string in Python
Check if element exists in list in Python
sum() function in Python
|
[
{
"code": null,
"e": 25421,
"s": 25393,
"text": "\n20 Mar, 2019"
},
{
"code": null,
"e": 25578,
"s": 25421,
"text": "scipy.stats.cauchy() is an cauchy continuous random variable that is defined with a standard format and some shape parameters to complete its specification."
},
{
"code": null,
"e": 25936,
"s": 25578,
"text": "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’)."
},
{
"code": null,
"e": 25980,
"s": 25936,
"text": "Results : cauchy continuous random variable"
},
{
"code": null,
"e": 26033,
"s": 25980,
"text": "Code #1 : Creating cauchy continuous random variable"
},
{
"code": "# importing scipyfrom scipy.stats import cauchy numargs = cauchy.numargs[] = [0.6, ] * numargsrv = cauchy() print (\"RV : \\n\", rv) ",
"e": 26166,
"s": 26033,
"text": null
},
{
"code": null,
"e": 26175,
"s": 26166,
"text": "Output :"
},
{
"code": null,
"e": 26258,
"s": 26175,
"text": "RV : \n <scipy.stats._distn_infrastructure.rv_frozen object at 0x000002948548C6D8>\n"
},
{
"code": null,
"e": 26330,
"s": 26258,
"text": "Code #2 : cauchy random variates and probability distribution function."
},
{
"code": "import numpy as npquantile = np.arange (0.01, 1, 0.1) import numpy as npimport matplotlib.pyplot as plt distribution = np.linspace(0, np.minimum(rv.dist.b, 5))print(\"Distribution : \\n\", distribution) plot = plt.plot(distribution, rv.pdf(distribution))",
"e": 26585,
"s": 26330,
"text": null
},
{
"code": null,
"e": 26594,
"s": 26585,
"text": "Output :"
},
{
"code": null,
"e": 26880,
"s": 26594,
"text": "Random Variates : \n [ 2.73388202 4.88389383 -4.89271415 4.63864536 -0.36933865 1.51521875\n 1.43853452 -0.69619917 -0.68358229 4.13179831]\n\nProbability Distribution : \n [0.31827806 0.31450438 0.30486533 0.29040223 0.27250226 0.25260685\n 0.23198738 0.21162814 0.19220451 0.17412061]"
},
{
"code": null,
"e": 26916,
"s": 26880,
"text": "Code #3 : Graphical Representation."
},
{
"code": "import numpy as npimport matplotlib.pyplot as plt distribution = np.linspace(0, np.minimum(rv.dist.b, 5))print(\"Distribution : \\n\", distribution) plot = plt.plot(distribution, rv.pdf(distribution))",
"e": 27116,
"s": 26916,
"text": null
},
{
"code": null,
"e": 27125,
"s": 27116,
"text": "Output :"
},
{
"code": null,
"e": 27718,
"s": 27125,
"text": "Distribution : \nDistribution : \n [0. 0.10204082 0.20408163 0.30612245 0.40816327 0.51020408\n 0.6122449 0.71428571 0.81632653 0.91836735 1.02040816 1.12244898\n 1.2244898 1.32653061 1.42857143 1.53061224 1.63265306 1.73469388\n 1.83673469 1.93877551 2.04081633 2.14285714 2.24489796 2.34693878\n 2.44897959 2.55102041 2.65306122 2.75510204 2.85714286 2.95918367\n 3.06122449 3.16326531 3.26530612 3.36734694 3.46938776 3.57142857\n 3.67346939 3.7755102 3.87755102 3.97959184 4.08163265 4.18367347\n 4.28571429 4.3877551 4.48979592 4.59183673 4.69387755 4.79591837\n 4.89795918 5. ]"
},
{
"code": null,
"e": 27757,
"s": 27718,
"text": "Code #4 : Varying Positional Arguments"
},
{
"code": "import matplotlib.pyplot as pltimport numpy as np x = np.linspace(0, 1.0, 100) # Varying positional argumentsy1 = cauchy.pdf(x, 2.75, 2.75)y2 = cauchy.pdf(x, 3.25, 3.25)plt.plot(x, y1, \"*\", x, y2, \"r--\")",
"e": 27963,
"s": 27757,
"text": null
},
{
"code": null,
"e": 27972,
"s": 27963,
"text": "Output :"
},
{
"code": null,
"e": 28001,
"s": 27972,
"text": "Python scipy-stats-functions"
},
{
"code": null,
"e": 28014,
"s": 28001,
"text": "Python-scipy"
},
{
"code": null,
"e": 28021,
"s": 28014,
"text": "Python"
},
{
"code": null,
"e": 28119,
"s": 28021,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28151,
"s": 28119,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 28173,
"s": 28151,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 28215,
"s": 28173,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 28241,
"s": 28215,
"text": "Python String | replace()"
},
{
"code": null,
"e": 28270,
"s": 28241,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 28314,
"s": 28270,
"text": "Reading and Writing to text files in Python"
},
{
"code": null,
"e": 28351,
"s": 28314,
"text": "Create a Pandas DataFrame from Lists"
},
{
"code": null,
"e": 28387,
"s": 28351,
"text": "Convert integer to string in Python"
},
{
"code": null,
"e": 28429,
"s": 28387,
"text": "Check if element exists in list in Python"
}
] |
random.getstate() in Python - GeeksforGeeks
|
27 Jul, 2021
random() module is used to generate random numbers in Python. Not actually random, rather this is used to generate pseudo-random numbers. That implies that these randomly generated numbers can be determined.
The getstate() method of the random module returns an object with the current internal state of the random number generator. This object can be passed to the setstate() method to restore the state. There are no parameters passed in this method.Example 1:
Python3
import random # remember this statestate = random.getstate() # print 10 random numbersprint(random.sample(range(20), k = 10)) # restore staterandom.setstate(state) # print same first 5 random numbers# as aboveprint(random.sample(range(20), k = 5))
Output:
[16, 1, 0, 11, 19, 3, 7, 5, 10, 13]
[16, 1, 0, 11, 19]
Example 2:
Python3
import random list1 = [1, 2, 3, 4, 5, 6] # Get the statestate = random.getstate() # prints a random value from the listprint(random.choice(list1)) # Set the staterandom.setstate(state) # prints the same random value# from the listprint(random.choice(list1))
Output:
3
3
akshaysingh98088
Python-random
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe
Python Dictionary
Taking input in Python
How to Install PIP on Windows ?
Read a file line by line in Python
Enumerate() in Python
Different ways to create Pandas Dataframe
|
[
{
"code": null,
"e": 25047,
"s": 25019,
"text": "\n27 Jul, 2021"
},
{
"code": null,
"e": 25256,
"s": 25047,
"text": "random() module is used to generate random numbers in Python. Not actually random, rather this is used to generate pseudo-random numbers. That implies that these randomly generated numbers can be determined. "
},
{
"code": null,
"e": 25512,
"s": 25256,
"text": "The getstate() method of the random module returns an object with the current internal state of the random number generator. This object can be passed to the setstate() method to restore the state. There are no parameters passed in this method.Example 1: "
},
{
"code": null,
"e": 25520,
"s": 25512,
"text": "Python3"
},
{
"code": "import random # remember this statestate = random.getstate() # print 10 random numbersprint(random.sample(range(20), k = 10)) # restore staterandom.setstate(state) # print same first 5 random numbers# as aboveprint(random.sample(range(20), k = 5))",
"e": 25769,
"s": 25520,
"text": null
},
{
"code": null,
"e": 25778,
"s": 25769,
"text": "Output: "
},
{
"code": null,
"e": 25833,
"s": 25778,
"text": "[16, 1, 0, 11, 19, 3, 7, 5, 10, 13]\n[16, 1, 0, 11, 19]"
},
{
"code": null,
"e": 25846,
"s": 25833,
"text": "Example 2: "
},
{
"code": null,
"e": 25854,
"s": 25846,
"text": "Python3"
},
{
"code": "import random list1 = [1, 2, 3, 4, 5, 6] # Get the statestate = random.getstate() # prints a random value from the listprint(random.choice(list1)) # Set the staterandom.setstate(state) # prints the same random value# from the listprint(random.choice(list1))",
"e": 26122,
"s": 25854,
"text": null
},
{
"code": null,
"e": 26131,
"s": 26122,
"text": "Output: "
},
{
"code": null,
"e": 26135,
"s": 26131,
"text": "3\n3"
},
{
"code": null,
"e": 26154,
"s": 26137,
"text": "akshaysingh98088"
},
{
"code": null,
"e": 26168,
"s": 26154,
"text": "Python-random"
},
{
"code": null,
"e": 26175,
"s": 26168,
"text": "Python"
},
{
"code": null,
"e": 26273,
"s": 26175,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26301,
"s": 26273,
"text": "Read JSON file using Python"
},
{
"code": null,
"e": 26351,
"s": 26301,
"text": "Adding new column to existing DataFrame in Pandas"
},
{
"code": null,
"e": 26373,
"s": 26351,
"text": "Python map() function"
},
{
"code": null,
"e": 26417,
"s": 26373,
"text": "How to get column names in Pandas dataframe"
},
{
"code": null,
"e": 26435,
"s": 26417,
"text": "Python Dictionary"
},
{
"code": null,
"e": 26458,
"s": 26435,
"text": "Taking input in Python"
},
{
"code": null,
"e": 26490,
"s": 26458,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 26525,
"s": 26490,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 26547,
"s": 26525,
"text": "Enumerate() in Python"
}
] |
Ratio Manipulations in C++ | Set 1 (Arithmetic) - GeeksforGeeks
|
18 Jan, 2022
C++ allows us to perform addition, subtraction, multiplication, and division operations on fractions. One method of adding ratios is discussed in the following article – Program to add two fractions. The method used here is tedious and lengthy, so to overcome that a better method was introduced in C++. The <ratio> header file in C++ allows us to manipulate ratios using various inbuilt template alias. The header file was introduced from C++ 11 onwards.
In this article, we will be discussing the Arithmetic Ratio Manipulations in C++. The following functions are used:
ratio_add
ratio_subtract
ratio_multiply
ratio_divide
1) ratio_add: This template alias is used to add two ratios and return the result in the simplest form. It returns two-member constants, num, and den denoting numerator and denominator.
2) ratio_subtract: This template alias is used to subtract two ratios and return the result in the simplest form. It returns two-member constants, num, and den denoting numerator and denominator. It subtracts ratio2 from ratio1.
CPP
// C++ program to demonstrate the working of// ratio_add and ratio_subtract#include <iostream>#include <ratio> // for ratio manipulationusing namespace std;int main(){ // Declaring ratios typedef ratio<5, 4> ratio1; typedef ratio<3, 4> ratio2; // Summing two ratios typedef ratio_add<ratio1, ratio2> sum; // Subtracting two ratios typedef ratio_subtract<ratio1, ratio2> diff; // printing sum of ratios cout << "The sum of ratios is : "; cout << sum::num << "/" << sum::den; cout << endl; // printing difference of ratios cout << "The difference of ratios is : "; cout << diff::num << "/" << diff::den; cout << endl; return 0;}
The sum of ratios is : 2/1
The difference of ratios is : 1/2
3. ratio_multiply: This template alias is used to multiply two ratios and return the result in the simplest form. It returns two-member constants, num, and den denoting numerator and denominator.
4. ratio_divide: This template alias is used to divide two ratios and return the result in the simplest form. It returns two-member constants, num, and den denoting numerator and denominator. It divides ratio1 by ratio2.
CPP
// C++ program to demonstrate the working of// ratio_multiply and ratio_divide#include <iostream>#include <ratio> // for ratio manipulationusing namespace std;int main(){ // Declaring ratios typedef ratio<5, 4> ratio1; typedef ratio<3, 4> ratio2; // Multiplying two ratios typedef ratio_multiply<ratio1, ratio2> prod; // Dividing two ratios typedef ratio_divide<ratio1, ratio2> div; // printing product of ratios cout << "The product of ratios is : "; cout << prod::num << "/" << prod::den; cout << endl; // printing division of ratios cout << "The division of ratios is : "; cout << div::num << "/" << div::den; cout << endl; return 0;}
The product of ratios is : 15/16
The division of ratios is : 5/3
For Next Set Refer to this article:
Ratio Manipulations in C++ | Set 2 (Comparison)
This article is contributed by Manjeet Singh. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. 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.
akshaysingh98088
anshikajain26
CPP-Library
C Language
C++
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Substring in C++
Left Shift and Right Shift Operators in C/C++
Function Pointer in C
Core Dump (Segmentation fault) in C/C++
rand() and srand() in C/C++
Vector in C++ STL
Inheritance in C++
Initialize a vector in C++ (6 different ways)
Map in C++ Standard Template Library (STL)
C++ Classes and Objects
|
[
{
"code": null,
"e": 25860,
"s": 25832,
"text": "\n18 Jan, 2022"
},
{
"code": null,
"e": 26316,
"s": 25860,
"text": "C++ allows us to perform addition, subtraction, multiplication, and division operations on fractions. One method of adding ratios is discussed in the following article – Program to add two fractions. The method used here is tedious and lengthy, so to overcome that a better method was introduced in C++. The <ratio> header file in C++ allows us to manipulate ratios using various inbuilt template alias. The header file was introduced from C++ 11 onwards."
},
{
"code": null,
"e": 26432,
"s": 26316,
"text": "In this article, we will be discussing the Arithmetic Ratio Manipulations in C++. The following functions are used:"
},
{
"code": null,
"e": 26442,
"s": 26432,
"text": "ratio_add"
},
{
"code": null,
"e": 26457,
"s": 26442,
"text": "ratio_subtract"
},
{
"code": null,
"e": 26472,
"s": 26457,
"text": "ratio_multiply"
},
{
"code": null,
"e": 26485,
"s": 26472,
"text": "ratio_divide"
},
{
"code": null,
"e": 26671,
"s": 26485,
"text": "1) ratio_add: This template alias is used to add two ratios and return the result in the simplest form. It returns two-member constants, num, and den denoting numerator and denominator."
},
{
"code": null,
"e": 26901,
"s": 26671,
"text": "2) ratio_subtract: This template alias is used to subtract two ratios and return the result in the simplest form. It returns two-member constants, num, and den denoting numerator and denominator. It subtracts ratio2 from ratio1. "
},
{
"code": null,
"e": 26905,
"s": 26901,
"text": "CPP"
},
{
"code": "// C++ program to demonstrate the working of// ratio_add and ratio_subtract#include <iostream>#include <ratio> // for ratio manipulationusing namespace std;int main(){ // Declaring ratios typedef ratio<5, 4> ratio1; typedef ratio<3, 4> ratio2; // Summing two ratios typedef ratio_add<ratio1, ratio2> sum; // Subtracting two ratios typedef ratio_subtract<ratio1, ratio2> diff; // printing sum of ratios cout << \"The sum of ratios is : \"; cout << sum::num << \"/\" << sum::den; cout << endl; // printing difference of ratios cout << \"The difference of ratios is : \"; cout << diff::num << \"/\" << diff::den; cout << endl; return 0;}",
"e": 27585,
"s": 26905,
"text": null
},
{
"code": null,
"e": 27646,
"s": 27585,
"text": "The sum of ratios is : 2/1\nThe difference of ratios is : 1/2"
},
{
"code": null,
"e": 27842,
"s": 27646,
"text": "3. ratio_multiply: This template alias is used to multiply two ratios and return the result in the simplest form. It returns two-member constants, num, and den denoting numerator and denominator."
},
{
"code": null,
"e": 28064,
"s": 27842,
"text": "4. ratio_divide: This template alias is used to divide two ratios and return the result in the simplest form. It returns two-member constants, num, and den denoting numerator and denominator. It divides ratio1 by ratio2. "
},
{
"code": null,
"e": 28068,
"s": 28064,
"text": "CPP"
},
{
"code": "// C++ program to demonstrate the working of// ratio_multiply and ratio_divide#include <iostream>#include <ratio> // for ratio manipulationusing namespace std;int main(){ // Declaring ratios typedef ratio<5, 4> ratio1; typedef ratio<3, 4> ratio2; // Multiplying two ratios typedef ratio_multiply<ratio1, ratio2> prod; // Dividing two ratios typedef ratio_divide<ratio1, ratio2> div; // printing product of ratios cout << \"The product of ratios is : \"; cout << prod::num << \"/\" << prod::den; cout << endl; // printing division of ratios cout << \"The division of ratios is : \"; cout << div::num << \"/\" << div::den; cout << endl; return 0;}",
"e": 28759,
"s": 28068,
"text": null
},
{
"code": null,
"e": 28824,
"s": 28759,
"text": "The product of ratios is : 15/16\nThe division of ratios is : 5/3"
},
{
"code": null,
"e": 28860,
"s": 28824,
"text": "For Next Set Refer to this article:"
},
{
"code": null,
"e": 28908,
"s": 28860,
"text": "Ratio Manipulations in C++ | Set 2 (Comparison)"
},
{
"code": null,
"e": 29331,
"s": 28908,
"text": "This article is contributed by Manjeet Singh. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. 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": 29348,
"s": 29331,
"text": "akshaysingh98088"
},
{
"code": null,
"e": 29362,
"s": 29348,
"text": "anshikajain26"
},
{
"code": null,
"e": 29374,
"s": 29362,
"text": "CPP-Library"
},
{
"code": null,
"e": 29385,
"s": 29374,
"text": "C Language"
},
{
"code": null,
"e": 29389,
"s": 29385,
"text": "C++"
},
{
"code": null,
"e": 29393,
"s": 29389,
"text": "CPP"
},
{
"code": null,
"e": 29491,
"s": 29393,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29508,
"s": 29491,
"text": "Substring in C++"
},
{
"code": null,
"e": 29554,
"s": 29508,
"text": "Left Shift and Right Shift Operators in C/C++"
},
{
"code": null,
"e": 29576,
"s": 29554,
"text": "Function Pointer in C"
},
{
"code": null,
"e": 29616,
"s": 29576,
"text": "Core Dump (Segmentation fault) in C/C++"
},
{
"code": null,
"e": 29644,
"s": 29616,
"text": "rand() and srand() in C/C++"
},
{
"code": null,
"e": 29662,
"s": 29644,
"text": "Vector in C++ STL"
},
{
"code": null,
"e": 29681,
"s": 29662,
"text": "Inheritance in C++"
},
{
"code": null,
"e": 29727,
"s": 29681,
"text": "Initialize a vector in C++ (6 different ways)"
},
{
"code": null,
"e": 29770,
"s": 29727,
"text": "Map in C++ Standard Template Library (STL)"
}
] |
How to Hide Axis Text Ticks or Tick Labels in Matplotlib? - GeeksforGeeks
|
17 Dec, 2020
Prerequisites: Matplotlib
The Matplotlib library by default shows the axis ticks and tick labels. Sometimes it is necessary to hide these axis ticks and tick labels. This article discusses some methods by which this can be done.
xticks(ticks=None, labels=None, **kwargs)– used to get and set the current tick locations and labels of the x-axis.
yticks(ticks=None, labels=None, **kwargs)- used to get and set the current tick locations and labels of the y-axis.
set_visible(boolean)- sets visibility
Method 1:
The functions xticks() and yticks() are used to denote positions using which a data point is supposed to be displayed. They take a list as argument. Thus, axis text ticks or tick labels can be disabled by setting the xticks and yticks to an empty list as shown below:
plt.xticks([])
plt.yticks([])
Example 1:
Python3
import matplotlib.pyplot as plt x1 = [5, 8, 10]y1 = [12, 16, 8]x2 = [6, 9, 12]y2 = [14, 10, 8] plt.plot(x1, y1, 'g', linewidth=7)plt.plot(x2, y2, 'b', linewidth=7) plt.title('Disabling xticks and yticks', fontsize=20) plt.xlabel('X axis', fontsize=15)plt.ylabel('Y axis', fontsize=15) # disabling xticks by Setting xticks to an empty listplt.xticks([]) # disabling yticks by setting yticks to an empty listplt.yticks([]) plt.show()
Output:
Method 2:
By default, in matplotlib library, plots are plotted on a white background. Therefore, setting the color of tick labels as white can make the axis tick labels as hidden. For this only color attribute needs to passed with w (represents white) as a value to xticks() and yticks() function. Implementation is given below:
Example 2:
Python3
import matplotlib.pyplot as plt plt.plot([5, 10, 20], [20, 10, 50], color='g') plt.xlabel("X Label")plt.ylabel("Y Label") # xticks color whiteplt.xticks(color='w') # yticks color whiteplt.yticks(color='w') plt.show()
Output:
Method 3:
Null Locator is a type of tick locator which makes the axis ticks and tick labels disappear. Simply passing NullLocator() function will be enough.
Example3:
Python3
import numpy as npimport matplotlib.ticker as ticker ax = plt.axes() x = np.random.rand(100)ax.plot(x, color='g') ax.xaxis.set_major_locator(ticker.NullLocator())ax.yaxis.set_major_locator(ticker.NullLocator())
Output:
Method 4:
Observe the syntax of xticks() and yticks() carefully, if even just a space is passed to them along with the data the output will be our desired result.
Example 4:
Python3
import matplotlib.pyplot as plt x = [5, 8, 15, 20, 30]y = [15, 10, 8, 20, 15]plt.plot(x, y, color='g', linewidth=5) # x-label as blankplt.xticks(x, " ") # y-label as blankplt.yticks(y, " ") plt.show()
Output:
Method 5:
This method is just a modification of method 4. Instead of passing an empty string, assign label as space in the functions itself.
Example 5:
Python3
import matplotlib.pyplot as plt x = [5, 8, 15, 20, 30]y = [15, 10, 8, 20, 15]plt.plot(x, y, color='g', linewidth=5) plt.xticks(x, labels=" ")plt.yticks(y, labels=" ") plt.show()
Output:
Method 6:
Using set_visibile() we can also set visibility of tick labels as False, that will not make them appear in our plot. This method hides labels as well as ticks, so if some requirement needs ticks to be displayed this isn’t the option to for, multiple methods shown above would stand ideal though.
Example 6:
Python3
import matplotlib.pyplot as plt x = [5, 8, 15, 20, 30]y = [15, 10, 8, 20, 15]plt.plot(x, y, color='g', linewidth=5) # getting current axesa = plt.gca() # set visibility of x-axis as Falsexax = a.axes.get_xaxis()xax = xax.set_visible(False) # set visibility of y-axis as Falseyax = a.axes.get_yaxis()yax = yax.set_visible(False) plt.show()
Output:
Picked
Python-matplotlib
Technical Scripter 2020
Python
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
Python String | replace()
*args and **kwargs in Python
Reading and Writing to text files in Python
Create a Pandas DataFrame from Lists
|
[
{
"code": null,
"e": 25539,
"s": 25511,
"text": "\n17 Dec, 2020"
},
{
"code": null,
"e": 25565,
"s": 25539,
"text": "Prerequisites: Matplotlib"
},
{
"code": null,
"e": 25768,
"s": 25565,
"text": "The Matplotlib library by default shows the axis ticks and tick labels. Sometimes it is necessary to hide these axis ticks and tick labels. This article discusses some methods by which this can be done."
},
{
"code": null,
"e": 25884,
"s": 25768,
"text": "xticks(ticks=None, labels=None, **kwargs)– used to get and set the current tick locations and labels of the x-axis."
},
{
"code": null,
"e": 26000,
"s": 25884,
"text": "yticks(ticks=None, labels=None, **kwargs)- used to get and set the current tick locations and labels of the y-axis."
},
{
"code": null,
"e": 26038,
"s": 26000,
"text": "set_visible(boolean)- sets visibility"
},
{
"code": null,
"e": 26049,
"s": 26038,
"text": "Method 1: "
},
{
"code": null,
"e": 26317,
"s": 26049,
"text": "The functions xticks() and yticks() are used to denote positions using which a data point is supposed to be displayed. They take a list as argument. Thus, axis text ticks or tick labels can be disabled by setting the xticks and yticks to an empty list as shown below:"
},
{
"code": null,
"e": 26347,
"s": 26317,
"text": "plt.xticks([])\nplt.yticks([])"
},
{
"code": null,
"e": 26358,
"s": 26347,
"text": "Example 1:"
},
{
"code": null,
"e": 26366,
"s": 26358,
"text": "Python3"
},
{
"code": "import matplotlib.pyplot as plt x1 = [5, 8, 10]y1 = [12, 16, 8]x2 = [6, 9, 12]y2 = [14, 10, 8] plt.plot(x1, y1, 'g', linewidth=7)plt.plot(x2, y2, 'b', linewidth=7) plt.title('Disabling xticks and yticks', fontsize=20) plt.xlabel('X axis', fontsize=15)plt.ylabel('Y axis', fontsize=15) # disabling xticks by Setting xticks to an empty listplt.xticks([]) # disabling yticks by setting yticks to an empty listplt.yticks([]) plt.show()",
"e": 26809,
"s": 26366,
"text": null
},
{
"code": null,
"e": 26817,
"s": 26809,
"text": "Output:"
},
{
"code": null,
"e": 26827,
"s": 26817,
"text": "Method 2:"
},
{
"code": null,
"e": 27146,
"s": 26827,
"text": "By default, in matplotlib library, plots are plotted on a white background. Therefore, setting the color of tick labels as white can make the axis tick labels as hidden. For this only color attribute needs to passed with w (represents white) as a value to xticks() and yticks() function. Implementation is given below:"
},
{
"code": null,
"e": 27157,
"s": 27146,
"text": "Example 2:"
},
{
"code": null,
"e": 27165,
"s": 27157,
"text": "Python3"
},
{
"code": "import matplotlib.pyplot as plt plt.plot([5, 10, 20], [20, 10, 50], color='g') plt.xlabel(\"X Label\")plt.ylabel(\"Y Label\") # xticks color whiteplt.xticks(color='w') # yticks color whiteplt.yticks(color='w') plt.show()",
"e": 27387,
"s": 27165,
"text": null
},
{
"code": null,
"e": 27396,
"s": 27387,
"text": "Output: "
},
{
"code": null,
"e": 27406,
"s": 27396,
"text": "Method 3:"
},
{
"code": null,
"e": 27553,
"s": 27406,
"text": "Null Locator is a type of tick locator which makes the axis ticks and tick labels disappear. Simply passing NullLocator() function will be enough."
},
{
"code": null,
"e": 27563,
"s": 27553,
"text": "Example3:"
},
{
"code": null,
"e": 27571,
"s": 27563,
"text": "Python3"
},
{
"code": "import numpy as npimport matplotlib.ticker as ticker ax = plt.axes() x = np.random.rand(100)ax.plot(x, color='g') ax.xaxis.set_major_locator(ticker.NullLocator())ax.yaxis.set_major_locator(ticker.NullLocator())",
"e": 27785,
"s": 27571,
"text": null
},
{
"code": null,
"e": 27793,
"s": 27785,
"text": "Output:"
},
{
"code": null,
"e": 27804,
"s": 27793,
"text": "Method 4: "
},
{
"code": null,
"e": 27957,
"s": 27804,
"text": "Observe the syntax of xticks() and yticks() carefully, if even just a space is passed to them along with the data the output will be our desired result."
},
{
"code": null,
"e": 27969,
"s": 27957,
"text": "Example 4: "
},
{
"code": null,
"e": 27977,
"s": 27969,
"text": "Python3"
},
{
"code": "import matplotlib.pyplot as plt x = [5, 8, 15, 20, 30]y = [15, 10, 8, 20, 15]plt.plot(x, y, color='g', linewidth=5) # x-label as blankplt.xticks(x, \" \") # y-label as blankplt.yticks(y, \" \") plt.show()",
"e": 28182,
"s": 27977,
"text": null
},
{
"code": null,
"e": 28190,
"s": 28182,
"text": "Output:"
},
{
"code": null,
"e": 28200,
"s": 28190,
"text": "Method 5:"
},
{
"code": null,
"e": 28331,
"s": 28200,
"text": "This method is just a modification of method 4. Instead of passing an empty string, assign label as space in the functions itself."
},
{
"code": null,
"e": 28342,
"s": 28331,
"text": "Example 5:"
},
{
"code": null,
"e": 28350,
"s": 28342,
"text": "Python3"
},
{
"code": "import matplotlib.pyplot as plt x = [5, 8, 15, 20, 30]y = [15, 10, 8, 20, 15]plt.plot(x, y, color='g', linewidth=5) plt.xticks(x, labels=\" \")plt.yticks(y, labels=\" \") plt.show()",
"e": 28531,
"s": 28350,
"text": null
},
{
"code": null,
"e": 28539,
"s": 28531,
"text": "Output:"
},
{
"code": null,
"e": 28549,
"s": 28539,
"text": "Method 6:"
},
{
"code": null,
"e": 28845,
"s": 28549,
"text": "Using set_visibile() we can also set visibility of tick labels as False, that will not make them appear in our plot. This method hides labels as well as ticks, so if some requirement needs ticks to be displayed this isn’t the option to for, multiple methods shown above would stand ideal though."
},
{
"code": null,
"e": 28856,
"s": 28845,
"text": "Example 6:"
},
{
"code": null,
"e": 28864,
"s": 28856,
"text": "Python3"
},
{
"code": "import matplotlib.pyplot as plt x = [5, 8, 15, 20, 30]y = [15, 10, 8, 20, 15]plt.plot(x, y, color='g', linewidth=5) # getting current axesa = plt.gca() # set visibility of x-axis as Falsexax = a.axes.get_xaxis()xax = xax.set_visible(False) # set visibility of y-axis as Falseyax = a.axes.get_yaxis()yax = yax.set_visible(False) plt.show()",
"e": 29208,
"s": 28864,
"text": null
},
{
"code": null,
"e": 29216,
"s": 29208,
"text": "Output:"
},
{
"code": null,
"e": 29223,
"s": 29216,
"text": "Picked"
},
{
"code": null,
"e": 29241,
"s": 29223,
"text": "Python-matplotlib"
},
{
"code": null,
"e": 29265,
"s": 29241,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 29272,
"s": 29265,
"text": "Python"
},
{
"code": null,
"e": 29291,
"s": 29272,
"text": "Technical Scripter"
},
{
"code": null,
"e": 29389,
"s": 29291,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29407,
"s": 29389,
"text": "Python Dictionary"
},
{
"code": null,
"e": 29442,
"s": 29407,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 29474,
"s": 29442,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 29496,
"s": 29474,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 29538,
"s": 29496,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 29568,
"s": 29538,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 29594,
"s": 29568,
"text": "Python String | replace()"
},
{
"code": null,
"e": 29623,
"s": 29594,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 29667,
"s": 29623,
"text": "Reading and Writing to text files in Python"
}
] |
Find the duplicate characters in a string in O(1) space - GeeksforGeeks
|
29 Jan, 2022
Given a string str, the task is to find all the duplicate characters present in a given string in lexicographical order without using any additional data structure.
Examples:
Input: str = “geeksforgeeks” Output: e g k s Explanation: Frequency of character ‘g’ = 2 Frequency of character ‘e’ = 4 Frequency of character ‘k’ = 2 Frequency of character ‘s’ = 2 Therefore, the required output is e g k s.
Input: str = “apple” Output: p Explanation: Frequency of character ‘p’ = 2. Therefore, the required output is p.
Approach: Follow the steps below to solve the problem:
Initialize a variable, say first, where ith bit of first check if the character (i + ‘a’) present in the string at least once or not.
Initialize a variable, say second, where ith bit of second check if the character (i + ‘a’) present in the string at least twice or not.
Iterate over the characters of the string. For every ith character, check if str[i] has already occurred in the string or not. If found to be true, then set the (str[i] – ‘a’)th bit of second.
Otherwise, set (str[i] – ‘a’)th bit of first.
Finally, iterate over the range [0, 25] and check if ith bit of both first and second is set or not. If found to be true, then print (i + ‘a’).
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program to implement// the above approach#include <bits/stdc++.h>using namespace std; // Function to find duplicate characters// in string without using any additional// data structurevoid findDuplicate(string str, int N){ // Check if (i + 'a') is present // in str at least once or not. int first = 0; // Check if (i + 'a') is present // in str at least twice or not. int second = 0; // Iterate over the characters // of the string str for (int i = 0; i < N; i++) { // If str[i] has already occurred in str if (first & (1 << (str[i] - 'a'))) { // Set (str[i] - 'a')-th bit of second second = second | (1 << (str[i] - 'a')); } else { // Set (str[i] - 'a')-th bit of second first = first | (1 << (str[i] - 'a')); } } // Iterate over the range [0, 25] for (int i = 0; i < 26; i++) { // If i-th bit of both first // and second is Set if ((first & (1 << i)) && (second & (1 << i))) { cout << char(i + 'a') << " "; } }} // Driver Codeint main(){ string str = "geeksforgeeks"; int N = str.length(); findDuplicate(str, N);}
// Java program for the above approachpublic class GFG{ // Function to find duplicate characters // in string without using any additional // data structure static void findDuplicate(String str, int N) { // Check if (i + 'a') is present // in str at least once or not. int first = 0; // Check if (i + 'a') is present // in str at least twice or not. int second = 0; // Iterate over the characters // of the string str for (int i = 0; i < N; i++) { // If str[i] has already occurred in str if ((first & (1 << (str.charAt(i) - 'a'))) != 0) { // Set (str[i] - 'a')-th bit of second second = second | (1 << (str.charAt(i) - 'a')); } else { // Set (str[i] - 'a')-th bit of second first = first | (1 << (str.charAt(i) - 'a')); } } // Iterate over the range [0, 25] for (int i = 0; i < 26; i++) { // If i-th bit of both first // and second is Set if (((first & (1 << i)) & (second & (1 << i))) != 0) { System.out.print((char)(i + 'a') + " "); } } } // Driver Code static public void main(String args[]) { String str = "geeksforgeeks"; int N = str.length(); findDuplicate(str, N); }} // This code is contributed by AnkThon.
# Python 3 code added. program to implement# the above approach # Function to find duplicate characters# in string without using any additional# data structuredef findDuplicate(str1, N): # Check if (i + 'a') is present # in str1 at least once or not. first = 0 # Check if (i + 'a') is present # in str1 at least twice or not. second = 0 # Iterate over the characters # of the string str1 for i in range(N): # If str1[i] has already occurred in str1 if (first & (1 << (ord(str1[i]) - 97))): # Set (str1[i] - 'a')-th bit of second second = second | (1 << (ord(str1[i]) - 97)) else: # Set (str1[i] - 'a')-th bit of second first = first | (1 << (ord(str1[i]) - 97)) # Iterate over the range [0, 25] for i in range(26): # If i-th bit of both first # and second is Set if ((first & (1 << i)) and (second & (1 << i))): print(chr(i + 97), end = " ") # Driver Codeif __name__ == '__main__': str1 = "geeksforgeeks" N = len(str1) findDuplicate(str1, N) # This code is contributed by SURENDRA_GANGWAR.
// C# program for the above approachusing System;class GFG{ // Function to find duplicate characters // in string without using any additional // data structure static void findDuplicate(string str, int N) { // Check if (i + 'a') is present // in str at least once or not. int first = 0; // Check if (i + 'a') is present // in str at least twice or not. int second = 0; // Iterate over the characters // of the string str for (int i = 0; i < N; i++) { // If str[i] has already occurred in str if ((first & (1 << (str[i] - 'a'))) != 0) { // Set (str[i] - 'a')-th bit of second second = second | (1 << (str[i] - 'a')); } else { // Set (str[i] - 'a')-th bit of second first = first | (1 << (str[i] - 'a')); } } // Iterate over the range [0, 25] for (int i = 0; i < 26; i++) { // If i-th bit of both first // and second is Set if (((first & (1 << i)) & (second & (1 << i))) != 0) { Console.Write((char)(i + 'a') + " "); } } } // Driver Code static public void Main() { string str = "geeksforgeeks"; int N = str.Length; findDuplicate(str, N); }} // This code is contributed by susmitakundugoaldanga.
<script> // Javascript program for the above approach // Function to find duplicate characters// in string without using any additional// data structurefunction findDuplicate(str, N){ // Check if (i + 'a') is present // in str at least once or not. let first = 0; // Check if (i + 'a') is present // in str at least twice or not. let second = 0; // Iterate over the characters // of the string str for(let i = 0; i < N; i++) { // If str[i] has already occurred in str if ((first & (1 << (str[i].charCodeAt() - 'a'.charCodeAt()))) != 0) { // Set (str[i] - 'a')-th bit of second second = second | (1 << (str[i].charCodeAt() - 'a'.charCodeAt())); } else { // Set (str[i] - 'a')-th bit of second first = first | (1 << (str[i].charCodeAt() - 'a'.charCodeAt())); } } // Iterate over the range [0, 25] for(let i = 0; i < 26; i++) { // If i-th bit of both first // and second is Set if (((first & (1 << i)) & (second & (1 << i))) != 0) { document.write(String.fromCharCode( i + 'a'.charCodeAt()) + " "); } }} // Driver codelet str = "geeksforgeeks";let N = str.length; findDuplicate(str, N); // This code is contributed by divyesh072019 </script>
e g k s
Time Complexity: O(N)Auxiliary Space: O(1)
SURENDRA_GANGWAR
susmitakundugoaldanga
ankthon
divyesh072019
simmytarika5
surinderdawra388
frequency-counting
Searching
Strings
Searching
Strings
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Search an element in a sorted and rotated array
Program to find largest element in an array
Given an array of size n and a number k, find all elements that appear more than n/k times
k largest(or smallest) elements in an array
Median of two sorted arrays of different sizes
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
Longest Common Subsequence | DP-4
|
[
{
"code": null,
"e": 26253,
"s": 26225,
"text": "\n29 Jan, 2022"
},
{
"code": null,
"e": 26418,
"s": 26253,
"text": "Given a string str, the task is to find all the duplicate characters present in a given string in lexicographical order without using any additional data structure."
},
{
"code": null,
"e": 26428,
"s": 26418,
"text": "Examples:"
},
{
"code": null,
"e": 26653,
"s": 26428,
"text": "Input: str = “geeksforgeeks” Output: e g k s Explanation: Frequency of character ‘g’ = 2 Frequency of character ‘e’ = 4 Frequency of character ‘k’ = 2 Frequency of character ‘s’ = 2 Therefore, the required output is e g k s."
},
{
"code": null,
"e": 26766,
"s": 26653,
"text": "Input: str = “apple” Output: p Explanation: Frequency of character ‘p’ = 2. Therefore, the required output is p."
},
{
"code": null,
"e": 26821,
"s": 26766,
"text": "Approach: Follow the steps below to solve the problem:"
},
{
"code": null,
"e": 26955,
"s": 26821,
"text": "Initialize a variable, say first, where ith bit of first check if the character (i + ‘a’) present in the string at least once or not."
},
{
"code": null,
"e": 27092,
"s": 26955,
"text": "Initialize a variable, say second, where ith bit of second check if the character (i + ‘a’) present in the string at least twice or not."
},
{
"code": null,
"e": 27285,
"s": 27092,
"text": "Iterate over the characters of the string. For every ith character, check if str[i] has already occurred in the string or not. If found to be true, then set the (str[i] – ‘a’)th bit of second."
},
{
"code": null,
"e": 27331,
"s": 27285,
"text": "Otherwise, set (str[i] – ‘a’)th bit of first."
},
{
"code": null,
"e": 27475,
"s": 27331,
"text": "Finally, iterate over the range [0, 25] and check if ith bit of both first and second is set or not. If found to be true, then print (i + ‘a’)."
},
{
"code": null,
"e": 27526,
"s": 27475,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 27530,
"s": 27526,
"text": "C++"
},
{
"code": null,
"e": 27535,
"s": 27530,
"text": "Java"
},
{
"code": null,
"e": 27543,
"s": 27535,
"text": "Python3"
},
{
"code": null,
"e": 27546,
"s": 27543,
"text": "C#"
},
{
"code": null,
"e": 27557,
"s": 27546,
"text": "Javascript"
},
{
"code": "// C++ program to implement// the above approach#include <bits/stdc++.h>using namespace std; // Function to find duplicate characters// in string without using any additional// data structurevoid findDuplicate(string str, int N){ // Check if (i + 'a') is present // in str at least once or not. int first = 0; // Check if (i + 'a') is present // in str at least twice or not. int second = 0; // Iterate over the characters // of the string str for (int i = 0; i < N; i++) { // If str[i] has already occurred in str if (first & (1 << (str[i] - 'a'))) { // Set (str[i] - 'a')-th bit of second second = second | (1 << (str[i] - 'a')); } else { // Set (str[i] - 'a')-th bit of second first = first | (1 << (str[i] - 'a')); } } // Iterate over the range [0, 25] for (int i = 0; i < 26; i++) { // If i-th bit of both first // and second is Set if ((first & (1 << i)) && (second & (1 << i))) { cout << char(i + 'a') << \" \"; } }} // Driver Codeint main(){ string str = \"geeksforgeeks\"; int N = str.length(); findDuplicate(str, N);}",
"e": 28798,
"s": 27557,
"text": null
},
{
"code": "// Java program for the above approachpublic class GFG{ // Function to find duplicate characters // in string without using any additional // data structure static void findDuplicate(String str, int N) { // Check if (i + 'a') is present // in str at least once or not. int first = 0; // Check if (i + 'a') is present // in str at least twice or not. int second = 0; // Iterate over the characters // of the string str for (int i = 0; i < N; i++) { // If str[i] has already occurred in str if ((first & (1 << (str.charAt(i) - 'a'))) != 0) { // Set (str[i] - 'a')-th bit of second second = second | (1 << (str.charAt(i) - 'a')); } else { // Set (str[i] - 'a')-th bit of second first = first | (1 << (str.charAt(i) - 'a')); } } // Iterate over the range [0, 25] for (int i = 0; i < 26; i++) { // If i-th bit of both first // and second is Set if (((first & (1 << i)) & (second & (1 << i))) != 0) { System.out.print((char)(i + 'a') + \" \"); } } } // Driver Code static public void main(String args[]) { String str = \"geeksforgeeks\"; int N = str.length(); findDuplicate(str, N); }} // This code is contributed by AnkThon.",
"e": 30108,
"s": 28798,
"text": null
},
{
"code": "# Python 3 code added. program to implement# the above approach # Function to find duplicate characters# in string without using any additional# data structuredef findDuplicate(str1, N): # Check if (i + 'a') is present # in str1 at least once or not. first = 0 # Check if (i + 'a') is present # in str1 at least twice or not. second = 0 # Iterate over the characters # of the string str1 for i in range(N): # If str1[i] has already occurred in str1 if (first & (1 << (ord(str1[i]) - 97))): # Set (str1[i] - 'a')-th bit of second second = second | (1 << (ord(str1[i]) - 97)) else: # Set (str1[i] - 'a')-th bit of second first = first | (1 << (ord(str1[i]) - 97)) # Iterate over the range [0, 25] for i in range(26): # If i-th bit of both first # and second is Set if ((first & (1 << i)) and (second & (1 << i))): print(chr(i + 97), end = \" \") # Driver Codeif __name__ == '__main__': str1 = \"geeksforgeeks\" N = len(str1) findDuplicate(str1, N) # This code is contributed by SURENDRA_GANGWAR.",
"e": 31272,
"s": 30108,
"text": null
},
{
"code": "// C# program for the above approachusing System;class GFG{ // Function to find duplicate characters // in string without using any additional // data structure static void findDuplicate(string str, int N) { // Check if (i + 'a') is present // in str at least once or not. int first = 0; // Check if (i + 'a') is present // in str at least twice or not. int second = 0; // Iterate over the characters // of the string str for (int i = 0; i < N; i++) { // If str[i] has already occurred in str if ((first & (1 << (str[i] - 'a'))) != 0) { // Set (str[i] - 'a')-th bit of second second = second | (1 << (str[i] - 'a')); } else { // Set (str[i] - 'a')-th bit of second first = first | (1 << (str[i] - 'a')); } } // Iterate over the range [0, 25] for (int i = 0; i < 26; i++) { // If i-th bit of both first // and second is Set if (((first & (1 << i)) & (second & (1 << i))) != 0) { Console.Write((char)(i + 'a') + \" \"); } } } // Driver Code static public void Main() { string str = \"geeksforgeeks\"; int N = str.Length; findDuplicate(str, N); }} // This code is contributed by susmitakundugoaldanga.",
"e": 32558,
"s": 31272,
"text": null
},
{
"code": "<script> // Javascript program for the above approach // Function to find duplicate characters// in string without using any additional// data structurefunction findDuplicate(str, N){ // Check if (i + 'a') is present // in str at least once or not. let first = 0; // Check if (i + 'a') is present // in str at least twice or not. let second = 0; // Iterate over the characters // of the string str for(let i = 0; i < N; i++) { // If str[i] has already occurred in str if ((first & (1 << (str[i].charCodeAt() - 'a'.charCodeAt()))) != 0) { // Set (str[i] - 'a')-th bit of second second = second | (1 << (str[i].charCodeAt() - 'a'.charCodeAt())); } else { // Set (str[i] - 'a')-th bit of second first = first | (1 << (str[i].charCodeAt() - 'a'.charCodeAt())); } } // Iterate over the range [0, 25] for(let i = 0; i < 26; i++) { // If i-th bit of both first // and second is Set if (((first & (1 << i)) & (second & (1 << i))) != 0) { document.write(String.fromCharCode( i + 'a'.charCodeAt()) + \" \"); } }} // Driver codelet str = \"geeksforgeeks\";let N = str.length; findDuplicate(str, N); // This code is contributed by divyesh072019 </script>",
"e": 34069,
"s": 32558,
"text": null
},
{
"code": null,
"e": 34077,
"s": 34069,
"text": "e g k s"
},
{
"code": null,
"e": 34122,
"s": 34079,
"text": "Time Complexity: O(N)Auxiliary Space: O(1)"
},
{
"code": null,
"e": 34139,
"s": 34122,
"text": "SURENDRA_GANGWAR"
},
{
"code": null,
"e": 34161,
"s": 34139,
"text": "susmitakundugoaldanga"
},
{
"code": null,
"e": 34169,
"s": 34161,
"text": "ankthon"
},
{
"code": null,
"e": 34183,
"s": 34169,
"text": "divyesh072019"
},
{
"code": null,
"e": 34196,
"s": 34183,
"text": "simmytarika5"
},
{
"code": null,
"e": 34213,
"s": 34196,
"text": "surinderdawra388"
},
{
"code": null,
"e": 34232,
"s": 34213,
"text": "frequency-counting"
},
{
"code": null,
"e": 34242,
"s": 34232,
"text": "Searching"
},
{
"code": null,
"e": 34250,
"s": 34242,
"text": "Strings"
},
{
"code": null,
"e": 34260,
"s": 34250,
"text": "Searching"
},
{
"code": null,
"e": 34268,
"s": 34260,
"text": "Strings"
},
{
"code": null,
"e": 34366,
"s": 34268,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 34414,
"s": 34366,
"text": "Search an element in a sorted and rotated array"
},
{
"code": null,
"e": 34458,
"s": 34414,
"text": "Program to find largest element in an array"
},
{
"code": null,
"e": 34549,
"s": 34458,
"text": "Given an array of size n and a number k, find all elements that appear more than n/k times"
},
{
"code": null,
"e": 34593,
"s": 34549,
"text": "k largest(or smallest) elements in an array"
},
{
"code": null,
"e": 34640,
"s": 34593,
"text": "Median of two sorted arrays of different sizes"
},
{
"code": null,
"e": 34686,
"s": 34640,
"text": "Write a program to reverse an array or string"
},
{
"code": null,
"e": 34711,
"s": 34686,
"text": "Reverse a string in Java"
},
{
"code": null,
"e": 34771,
"s": 34711,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 34786,
"s": 34771,
"text": "C++ Data Types"
}
] |
Java Swing | JToolBar - GeeksforGeeks
|
09 Sep, 2021
JToolBar is a part of Java Swing package. JToolBar is an implementation of toolbar. The JToolBar is a group of commonly used components such as buttons or drop down menu. JToolBar can be dragged to different locations by the user
Constructors of the class are:
JToolBar() : creates a new toolbar with horizontal orientationJToolBar(int o) : creates a new toolbar with specified orientationJToolBar(String n) : creates a new toolbar with specified nameJToolBar(String n, int o) : creates a new toolbar with specified name and orientation.
JToolBar() : creates a new toolbar with horizontal orientation
JToolBar(int o) : creates a new toolbar with specified orientation
JToolBar(String n) : creates a new toolbar with specified name
JToolBar(String n, int o) : creates a new toolbar with specified name and orientation.
Commonly used methods :
addSeparator() : adds the separator to the end of toolbarsetFloatable(boolean b) : if true is passed then the toolbar can be dragged to other locations or else not .setLayout(LayoutManager m) : set layout of the toolbarsetOrientation(int o) : sets the orientation of toolbaradd(Component c) : adds component to the toolbargetMargin() : returns the margin of the toolbarsetMargin(Insets m) : sets the margin of the toolbar to the insets givengetOrientation() : returns the orientation of the toolbarupdateUI() : Notification from the UIFactory that the Look and feel has changed.setUI(ToolBarUI u) : Sets the Look and feel object that renders this component.setRollover(boolean b) : Sets the rollover state of this toolbarto boolean b.setFloatable(boolean b) :the boolean b decides whether the position of toolbar can be changed or notsetBorderPainted(boolean b): decides whether border should be painted or not.paintBorder(Graphics g) : paint the toolbar’s borderisRollover() : Returns the rollover state.isFloatable() : returns the floatable property.isBorderPainted() : returns whether border is painted or notgetComponentIndex(Component c) : Returns the index of the specified component.getComponentAtIndex(int i) :Returns the component at the specified index.addSeparator(Dimension size) :Appends a separator of a specified dimension.addSeparator() :Appends a separator of default size.add(Action a) : adds a new JButton that follows the specified action.paramString() : returns a string representation of this JToolBar.getUIClassID() : returns the name of the Look and feel class that renders this component.getAccessibleContext() : gets the AccessibleContext associated with this JToolBar.
addSeparator() : adds the separator to the end of toolbar
setFloatable(boolean b) : if true is passed then the toolbar can be dragged to other locations or else not .
setLayout(LayoutManager m) : set layout of the toolbar
setOrientation(int o) : sets the orientation of toolbar
add(Component c) : adds component to the toolbar
getMargin() : returns the margin of the toolbar
setMargin(Insets m) : sets the margin of the toolbar to the insets given
getOrientation() : returns the orientation of the toolbar
updateUI() : Notification from the UIFactory that the Look and feel has changed.
setUI(ToolBarUI u) : Sets the Look and feel object that renders this component.
setRollover(boolean b) : Sets the rollover state of this toolbarto boolean b.
setFloatable(boolean b) :the boolean b decides whether the position of toolbar can be changed or not
setBorderPainted(boolean b): decides whether border should be painted or not.
paintBorder(Graphics g) : paint the toolbar’s border
isRollover() : Returns the rollover state.
isFloatable() : returns the floatable property.
isBorderPainted() : returns whether border is painted or not
getComponentIndex(Component c) : Returns the index of the specified component.
getComponentAtIndex(int i) :Returns the component at the specified index.
addSeparator(Dimension size) :Appends a separator of a specified dimension.
addSeparator() :Appends a separator of default size.
add(Action a) : adds a new JButton that follows the specified action.
paramString() : returns a string representation of this JToolBar.
getUIClassID() : returns the name of the Look and feel class that renders this component.
getAccessibleContext() : gets the AccessibleContext associated with this JToolBar.
The Following programs will illustrate the use of toolbar.1. Program to create a simple toolbar and add buttons and combobox to it.
Java
// Java Program to create a simple toolbar and add buttons and combobox to it.import java.awt.*;import javax.swing.*;import java.awt.event.*;public class Tool extends JFrame { // toolbar static JToolBar tb; // buttons static JButton b1, b2; // create a frame static JFrame f; // create a combo box static JComboBox x; public static void main() { // create a frame f = new JFrame("Toolbar demo"); // set layout for frame f.setLayout(new BorderLayout()); // create a toolbar tb = new JToolBar(); // create a panel JPanel p = new JPanel(); // create a combobox x = new JComboBox(new String[] { "item 1", "item 2", "item 3" }); // create new buttons b1 = new JButton("button 1"); b2 = new JButton("button 2"); // add buttons p.add(b1); p.add(b2); // add menu to menu bar p.add(x); tb.add(p); // add toolbar to frame f.add(tb, BorderLayout.NORTH); // set the size of the frame f.setSize(500, 500); f.setVisible(true); }}
Output :
2. Program to create a toolbar and add action listener to its components .
Java
// Java Program to create a toolbar and add action listener to its components .import java.awt.*;import javax.swing.*;import java.awt.event.*;public class Tool extends JFrame implements ActionListener, ItemListener { // toolbar static JToolBar tb; // buttons static JButton b1, b2; // create a frame static JFrame f; // create a combo box static JComboBox x; // create a label static JLabel l, l1; public static void main() { // create a object of class Tool to = new Tool(); // create a label l = new JLabel("nothing selected"); l1 = new JLabel("nothing selected"); // create a frame f = new JFrame("Toolbar demo"); // set layout for frame f.setLayout(new BorderLayout()); // create a toolbar tb = new JToolBar(); // create a panel JPanel p = new JPanel(); // create a combobox x = new JComboBox(new String[] { "item 1", "item 2", "item 3" }); // add actionListener x.addItemListener(to); // create new buttons b1 = new JButton("button 1"); b2 = new JButton("button 2"); // add ActionListener to it b1.addActionListener(to); b2.addActionListener(to); // add buttons p.add(b1); p.add(b2); // add menu to menu bar p.add(x); tb.add(p); // create a panel JPanel p1 = new JPanel(); p1.add(l); p1.add(l1); // add toolbar to frame f.add(tb, BorderLayout.NORTH); f.add(p1, BorderLayout.CENTER); // set the size of the frame f.setSize(500, 500); f.setVisible(true); } // if button is pressed public void actionPerformed(ActionEvent e) { l.setText(e.getActionCommand() + " selected."); } // if combo box is selected public void itemStateChanged(ItemEvent e) { l1.setText(x.getSelectedItem() + " selected."); }}
Output :
3. Program to create a vertical toolbar and add action listener to its components .
Java
import java.awt.*;import javax.swing.*;import java.awt.event.*;public class Tool extends JFrame implements ActionListener, ItemListener { // toolbar static JToolBar tb; // buttons static JButton b1, b2; // create a frame static JFrame f; // create a combo box static JComboBox x; // create a label static JLabel l, l1; public static void main() { // create a object of class Tool to = new Tool(); // create a label l = new JLabel("nothing selected"); l1 = new JLabel("nothing selected"); // create a frame f = new JFrame("Toolbar demo"); // set layout for frame f.setLayout(new BorderLayout()); // create a toolbar tb = new JToolBar("toolbar"); // set orientation tb.setOrientation(SwingConstants.VERTICAL); // create a panel JPanel p = new JPanel(); // set layout p.setLayout(new BoxLayout(p, BoxLayout.Y_AXIS)); // create a combobox x = new JComboBox(new String[] { "item 1", "item 2", "item 3" }); // add actionListener x.addItemListener(to); // create new buttons b1 = new JButton("button 1"); b2 = new JButton("button 2"); // add ActionListener to it b1.addActionListener(to); b2.addActionListener(to); // add buttons p.add(b1); p.add(b2); // add menu to menu bar p.add(x); tb.add(p); // create a panel JPanel p1 = new JPanel(); p1.add(l); p1.add(l1); // add toolbar to frame f.add(tb, BorderLayout.WEST); f.add(p1, BorderLayout.CENTER); // set the size of the frame f.setSize(500, 500); f.setVisible(true); } // if button is pressed public void actionPerformed(ActionEvent e) { l.setText(e.getActionCommand() + " selected."); } // if combo box is selected public void itemStateChanged(ItemEvent e) { l1.setText(x.getSelectedItem() + " selected."); }}
Output :
Note : The following programs might not run in an online compiler please use an Offline IDE
sweetyty
sumitgumber28
java-swing
Java
Programming Language
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Object Oriented Programming (OOPs) Concept in Java
HashMap in Java with Examples
Stream In Java
Interfaces in Java
How to iterate any Map in Java
Modulo Operator (%) in C/C++ with Examples
Arrow operator -> in C/C++ with Examples
Differences between Procedural and Object Oriented Programming
Structures in C++
Top 10 Programming Languages to Learn in 2022
|
[
{
"code": null,
"e": 25671,
"s": 25643,
"text": "\n09 Sep, 2021"
},
{
"code": null,
"e": 25902,
"s": 25671,
"text": "JToolBar is a part of Java Swing package. JToolBar is an implementation of toolbar. The JToolBar is a group of commonly used components such as buttons or drop down menu. JToolBar can be dragged to different locations by the user "
},
{
"code": null,
"e": 25934,
"s": 25902,
"text": "Constructors of the class are: "
},
{
"code": null,
"e": 26211,
"s": 25934,
"text": "JToolBar() : creates a new toolbar with horizontal orientationJToolBar(int o) : creates a new toolbar with specified orientationJToolBar(String n) : creates a new toolbar with specified nameJToolBar(String n, int o) : creates a new toolbar with specified name and orientation."
},
{
"code": null,
"e": 26274,
"s": 26211,
"text": "JToolBar() : creates a new toolbar with horizontal orientation"
},
{
"code": null,
"e": 26341,
"s": 26274,
"text": "JToolBar(int o) : creates a new toolbar with specified orientation"
},
{
"code": null,
"e": 26404,
"s": 26341,
"text": "JToolBar(String n) : creates a new toolbar with specified name"
},
{
"code": null,
"e": 26491,
"s": 26404,
"text": "JToolBar(String n, int o) : creates a new toolbar with specified name and orientation."
},
{
"code": null,
"e": 26517,
"s": 26491,
"text": "Commonly used methods : "
},
{
"code": null,
"e": 28214,
"s": 26517,
"text": "addSeparator() : adds the separator to the end of toolbarsetFloatable(boolean b) : if true is passed then the toolbar can be dragged to other locations or else not .setLayout(LayoutManager m) : set layout of the toolbarsetOrientation(int o) : sets the orientation of toolbaradd(Component c) : adds component to the toolbargetMargin() : returns the margin of the toolbarsetMargin(Insets m) : sets the margin of the toolbar to the insets givengetOrientation() : returns the orientation of the toolbarupdateUI() : Notification from the UIFactory that the Look and feel has changed.setUI(ToolBarUI u) : Sets the Look and feel object that renders this component.setRollover(boolean b) : Sets the rollover state of this toolbarto boolean b.setFloatable(boolean b) :the boolean b decides whether the position of toolbar can be changed or notsetBorderPainted(boolean b): decides whether border should be painted or not.paintBorder(Graphics g) : paint the toolbar’s borderisRollover() : Returns the rollover state.isFloatable() : returns the floatable property.isBorderPainted() : returns whether border is painted or notgetComponentIndex(Component c) : Returns the index of the specified component.getComponentAtIndex(int i) :Returns the component at the specified index.addSeparator(Dimension size) :Appends a separator of a specified dimension.addSeparator() :Appends a separator of default size.add(Action a) : adds a new JButton that follows the specified action.paramString() : returns a string representation of this JToolBar.getUIClassID() : returns the name of the Look and feel class that renders this component.getAccessibleContext() : gets the AccessibleContext associated with this JToolBar."
},
{
"code": null,
"e": 28272,
"s": 28214,
"text": "addSeparator() : adds the separator to the end of toolbar"
},
{
"code": null,
"e": 28382,
"s": 28272,
"text": "setFloatable(boolean b) : if true is passed then the toolbar can be dragged to other locations or else not ."
},
{
"code": null,
"e": 28437,
"s": 28382,
"text": "setLayout(LayoutManager m) : set layout of the toolbar"
},
{
"code": null,
"e": 28493,
"s": 28437,
"text": "setOrientation(int o) : sets the orientation of toolbar"
},
{
"code": null,
"e": 28542,
"s": 28493,
"text": "add(Component c) : adds component to the toolbar"
},
{
"code": null,
"e": 28590,
"s": 28542,
"text": "getMargin() : returns the margin of the toolbar"
},
{
"code": null,
"e": 28663,
"s": 28590,
"text": "setMargin(Insets m) : sets the margin of the toolbar to the insets given"
},
{
"code": null,
"e": 28721,
"s": 28663,
"text": "getOrientation() : returns the orientation of the toolbar"
},
{
"code": null,
"e": 28802,
"s": 28721,
"text": "updateUI() : Notification from the UIFactory that the Look and feel has changed."
},
{
"code": null,
"e": 28882,
"s": 28802,
"text": "setUI(ToolBarUI u) : Sets the Look and feel object that renders this component."
},
{
"code": null,
"e": 28960,
"s": 28882,
"text": "setRollover(boolean b) : Sets the rollover state of this toolbarto boolean b."
},
{
"code": null,
"e": 29061,
"s": 28960,
"text": "setFloatable(boolean b) :the boolean b decides whether the position of toolbar can be changed or not"
},
{
"code": null,
"e": 29139,
"s": 29061,
"text": "setBorderPainted(boolean b): decides whether border should be painted or not."
},
{
"code": null,
"e": 29192,
"s": 29139,
"text": "paintBorder(Graphics g) : paint the toolbar’s border"
},
{
"code": null,
"e": 29235,
"s": 29192,
"text": "isRollover() : Returns the rollover state."
},
{
"code": null,
"e": 29283,
"s": 29235,
"text": "isFloatable() : returns the floatable property."
},
{
"code": null,
"e": 29344,
"s": 29283,
"text": "isBorderPainted() : returns whether border is painted or not"
},
{
"code": null,
"e": 29423,
"s": 29344,
"text": "getComponentIndex(Component c) : Returns the index of the specified component."
},
{
"code": null,
"e": 29497,
"s": 29423,
"text": "getComponentAtIndex(int i) :Returns the component at the specified index."
},
{
"code": null,
"e": 29573,
"s": 29497,
"text": "addSeparator(Dimension size) :Appends a separator of a specified dimension."
},
{
"code": null,
"e": 29626,
"s": 29573,
"text": "addSeparator() :Appends a separator of default size."
},
{
"code": null,
"e": 29696,
"s": 29626,
"text": "add(Action a) : adds a new JButton that follows the specified action."
},
{
"code": null,
"e": 29762,
"s": 29696,
"text": "paramString() : returns a string representation of this JToolBar."
},
{
"code": null,
"e": 29852,
"s": 29762,
"text": "getUIClassID() : returns the name of the Look and feel class that renders this component."
},
{
"code": null,
"e": 29935,
"s": 29852,
"text": "getAccessibleContext() : gets the AccessibleContext associated with this JToolBar."
},
{
"code": null,
"e": 30069,
"s": 29935,
"text": "The Following programs will illustrate the use of toolbar.1. Program to create a simple toolbar and add buttons and combobox to it. "
},
{
"code": null,
"e": 30074,
"s": 30069,
"text": "Java"
},
{
"code": "// Java Program to create a simple toolbar and add buttons and combobox to it.import java.awt.*;import javax.swing.*;import java.awt.event.*;public class Tool extends JFrame { // toolbar static JToolBar tb; // buttons static JButton b1, b2; // create a frame static JFrame f; // create a combo box static JComboBox x; public static void main() { // create a frame f = new JFrame(\"Toolbar demo\"); // set layout for frame f.setLayout(new BorderLayout()); // create a toolbar tb = new JToolBar(); // create a panel JPanel p = new JPanel(); // create a combobox x = new JComboBox(new String[] { \"item 1\", \"item 2\", \"item 3\" }); // create new buttons b1 = new JButton(\"button 1\"); b2 = new JButton(\"button 2\"); // add buttons p.add(b1); p.add(b2); // add menu to menu bar p.add(x); tb.add(p); // add toolbar to frame f.add(tb, BorderLayout.NORTH); // set the size of the frame f.setSize(500, 500); f.setVisible(true); }}",
"e": 31206,
"s": 30074,
"text": null
},
{
"code": null,
"e": 31216,
"s": 31206,
"text": "Output : "
},
{
"code": null,
"e": 31292,
"s": 31216,
"text": "2. Program to create a toolbar and add action listener to its components . "
},
{
"code": null,
"e": 31297,
"s": 31292,
"text": "Java"
},
{
"code": "// Java Program to create a toolbar and add action listener to its components .import java.awt.*;import javax.swing.*;import java.awt.event.*;public class Tool extends JFrame implements ActionListener, ItemListener { // toolbar static JToolBar tb; // buttons static JButton b1, b2; // create a frame static JFrame f; // create a combo box static JComboBox x; // create a label static JLabel l, l1; public static void main() { // create a object of class Tool to = new Tool(); // create a label l = new JLabel(\"nothing selected\"); l1 = new JLabel(\"nothing selected\"); // create a frame f = new JFrame(\"Toolbar demo\"); // set layout for frame f.setLayout(new BorderLayout()); // create a toolbar tb = new JToolBar(); // create a panel JPanel p = new JPanel(); // create a combobox x = new JComboBox(new String[] { \"item 1\", \"item 2\", \"item 3\" }); // add actionListener x.addItemListener(to); // create new buttons b1 = new JButton(\"button 1\"); b2 = new JButton(\"button 2\"); // add ActionListener to it b1.addActionListener(to); b2.addActionListener(to); // add buttons p.add(b1); p.add(b2); // add menu to menu bar p.add(x); tb.add(p); // create a panel JPanel p1 = new JPanel(); p1.add(l); p1.add(l1); // add toolbar to frame f.add(tb, BorderLayout.NORTH); f.add(p1, BorderLayout.CENTER); // set the size of the frame f.setSize(500, 500); f.setVisible(true); } // if button is pressed public void actionPerformed(ActionEvent e) { l.setText(e.getActionCommand() + \" selected.\"); } // if combo box is selected public void itemStateChanged(ItemEvent e) { l1.setText(x.getSelectedItem() + \" selected.\"); }}",
"e": 33272,
"s": 31297,
"text": null
},
{
"code": null,
"e": 33282,
"s": 33272,
"text": "Output : "
},
{
"code": null,
"e": 33367,
"s": 33282,
"text": "3. Program to create a vertical toolbar and add action listener to its components . "
},
{
"code": null,
"e": 33372,
"s": 33367,
"text": "Java"
},
{
"code": "import java.awt.*;import javax.swing.*;import java.awt.event.*;public class Tool extends JFrame implements ActionListener, ItemListener { // toolbar static JToolBar tb; // buttons static JButton b1, b2; // create a frame static JFrame f; // create a combo box static JComboBox x; // create a label static JLabel l, l1; public static void main() { // create a object of class Tool to = new Tool(); // create a label l = new JLabel(\"nothing selected\"); l1 = new JLabel(\"nothing selected\"); // create a frame f = new JFrame(\"Toolbar demo\"); // set layout for frame f.setLayout(new BorderLayout()); // create a toolbar tb = new JToolBar(\"toolbar\"); // set orientation tb.setOrientation(SwingConstants.VERTICAL); // create a panel JPanel p = new JPanel(); // set layout p.setLayout(new BoxLayout(p, BoxLayout.Y_AXIS)); // create a combobox x = new JComboBox(new String[] { \"item 1\", \"item 2\", \"item 3\" }); // add actionListener x.addItemListener(to); // create new buttons b1 = new JButton(\"button 1\"); b2 = new JButton(\"button 2\"); // add ActionListener to it b1.addActionListener(to); b2.addActionListener(to); // add buttons p.add(b1); p.add(b2); // add menu to menu bar p.add(x); tb.add(p); // create a panel JPanel p1 = new JPanel(); p1.add(l); p1.add(l1); // add toolbar to frame f.add(tb, BorderLayout.WEST); f.add(p1, BorderLayout.CENTER); // set the size of the frame f.setSize(500, 500); f.setVisible(true); } // if button is pressed public void actionPerformed(ActionEvent e) { l.setText(e.getActionCommand() + \" selected.\"); } // if combo box is selected public void itemStateChanged(ItemEvent e) { l1.setText(x.getSelectedItem() + \" selected.\"); }}",
"e": 35432,
"s": 33372,
"text": null
},
{
"code": null,
"e": 35442,
"s": 35432,
"text": "Output : "
},
{
"code": null,
"e": 35535,
"s": 35442,
"text": "Note : The following programs might not run in an online compiler please use an Offline IDE "
},
{
"code": null,
"e": 35544,
"s": 35535,
"text": "sweetyty"
},
{
"code": null,
"e": 35558,
"s": 35544,
"text": "sumitgumber28"
},
{
"code": null,
"e": 35569,
"s": 35558,
"text": "java-swing"
},
{
"code": null,
"e": 35574,
"s": 35569,
"text": "Java"
},
{
"code": null,
"e": 35595,
"s": 35574,
"text": "Programming Language"
},
{
"code": null,
"e": 35600,
"s": 35595,
"text": "Java"
},
{
"code": null,
"e": 35698,
"s": 35600,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 35749,
"s": 35698,
"text": "Object Oriented Programming (OOPs) Concept in Java"
},
{
"code": null,
"e": 35779,
"s": 35749,
"text": "HashMap in Java with Examples"
},
{
"code": null,
"e": 35794,
"s": 35779,
"text": "Stream In Java"
},
{
"code": null,
"e": 35813,
"s": 35794,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 35844,
"s": 35813,
"text": "How to iterate any Map in Java"
},
{
"code": null,
"e": 35887,
"s": 35844,
"text": "Modulo Operator (%) in C/C++ with Examples"
},
{
"code": null,
"e": 35928,
"s": 35887,
"text": "Arrow operator -> in C/C++ with Examples"
},
{
"code": null,
"e": 35991,
"s": 35928,
"text": "Differences between Procedural and Object Oriented Programming"
},
{
"code": null,
"e": 36009,
"s": 35991,
"text": "Structures in C++"
}
] |
K Dimensional Tree | Set 2 (Find Minimum) - GeeksforGeeks
|
03 Nov, 2020
We strongly recommend to refer below post as a prerequisite of this.
K Dimensional Tree | Set 1 (Search and Insert)
In this post find minimum is discussed. The operation is to find minimum in the given dimension. This is especially needed in delete operation.
For example, consider below KD Tree, if given dimension is x, then output should be 5 and if given dimensions is y, then output should be 12.
In KD tree, points are divided dimension by dimension. For example, root divides keys by dimension 0, level next to root divides by dimension 1, next level by dimension 2 if k is more then 2 (else by dimension 0), and so on.
To find minimum we traverse nodes starting from root. If dimension of current level is same as given dimension, then required minimum lies on left side if there is left child. This is same as Binary Search Tree Minimum.Above is simple, what to do when current level’s dimension is different. When dimension of current level is different, minimum may be either in left subtree or right subtree or current node may also be minimum. So we take minimum of three and return. This is different from Binary Search tree.
Below is C++ implementation of find minimum operation.
// A C++ program to demonstrate find minimum on KD tree#include <bits/stdc++.h>using namespace std; const int k = 2; // A structure to represent node of kd treestruct Node { int point[k]; // To store k dimensional point Node *left, *right;}; // A method to create a node of K D treestruct Node* newNode(int arr[]){ struct Node* temp = new Node; for (int i = 0; i < k; i++) temp->point[i] = arr[i]; temp->left = temp->right = NULL; return temp;} // Inserts a new node and returns root of modified tree// The parameter depth is used to decide axis of comparisonNode* insertRec(Node* root, int point[], unsigned depth){ // Tree is empty? if (root == NULL) return newNode(point); // Calculate current dimension (cd) of comparison unsigned cd = depth % k; // Compare the new point with root on current dimension 'cd' // and decide the left or right subtree if (point[cd] < (root->point[cd])) root->left = insertRec(root->left, point, depth + 1); else root->right = insertRec(root->right, point, depth + 1); return root;} // Function to insert a new point with given point in// KD Tree and return new root. It mainly uses above recursive// function "insertRec()"Node* insert(Node* root, int point[]){ return insertRec(root, point, 0);} // A utility function to find minimum of three integersint min(int x, int y, int z){ return min(x, min(y, z));} // Recursively finds minimum of d'th dimension in KD tree// The parameter depth is used to determine current axis.int findMinRec(Node* root, int d, unsigned depth){ // Base cases if (root == NULL) return INT_MAX; // Current dimension is computed using current depth and total // dimensions (k) unsigned cd = depth % k; // Compare point with root with respect to cd (Current dimension) if (cd == d) { if (root->left == NULL) return root->point[d]; return min(root->point[d], findMinRec(root->left, d, depth + 1)); } // If current dimension is different then minimum can be anywhere // in this subtree return min(root->point[d], findMinRec(root->left, d, depth + 1), findMinRec(root->right, d, depth + 1));} // A wrapper over findMinRec(). Returns minimum of d'th dimensionint findMin(Node* root, int d){ // Pass current level or depth as 0 return findMinRec(root, d, 0);} // Driver program to test above functionsint main(){ struct Node* root = NULL; int points[][k] = { { 30, 40 }, { 5, 25 }, { 70, 70 }, { 10, 12 }, { 50, 30 }, { 35, 45 } }; int n = sizeof(points) / sizeof(points[0]); for (int i = 0; i < n; i++) root = insert(root, points[i]); cout << "Minimum of 0'th dimension is " << findMin(root, 0) << endl; cout << "Minimum of 1'th dimension is " << findMin(root, 1) << endl; return 0;}
Output:
Minimum of 0'th dimension is 5
Minimum of 1'th dimension is 12
YouTubeGeeksforGeeks507K subscribersK-Dimensional Tree [Find Minimum] | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 4:16•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=oRwYNAEuNK8" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>Source:https://www.cs.umd.edu/class/spring2008/cmsc420/L19.kd-trees.pdf
This article is contributed by Ashish Gupta. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
mayurpothuri
xmyqsh
Advanced Data Structure
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Decision Tree Introduction with example
AVL Tree | Set 2 (Deletion)
Ordered Set and GNU C++ PBDS
Red-Black Tree | Set 2 (Insert)
Disjoint Set Data Structures
Design a data structure that supports insert, delete, search and getRandom in constant time
Binary Indexed Tree or Fenwick Tree
Insert Operation in B-Tree
Design a Chess Game
|
[
{
"code": null,
"e": 26383,
"s": 26355,
"text": "\n03 Nov, 2020"
},
{
"code": null,
"e": 26452,
"s": 26383,
"text": "We strongly recommend to refer below post as a prerequisite of this."
},
{
"code": null,
"e": 26499,
"s": 26452,
"text": "K Dimensional Tree | Set 1 (Search and Insert)"
},
{
"code": null,
"e": 26643,
"s": 26499,
"text": "In this post find minimum is discussed. The operation is to find minimum in the given dimension. This is especially needed in delete operation."
},
{
"code": null,
"e": 26785,
"s": 26643,
"text": "For example, consider below KD Tree, if given dimension is x, then output should be 5 and if given dimensions is y, then output should be 12."
},
{
"code": null,
"e": 27010,
"s": 26785,
"text": "In KD tree, points are divided dimension by dimension. For example, root divides keys by dimension 0, level next to root divides by dimension 1, next level by dimension 2 if k is more then 2 (else by dimension 0), and so on."
},
{
"code": null,
"e": 27523,
"s": 27010,
"text": "To find minimum we traverse nodes starting from root. If dimension of current level is same as given dimension, then required minimum lies on left side if there is left child. This is same as Binary Search Tree Minimum.Above is simple, what to do when current level’s dimension is different. When dimension of current level is different, minimum may be either in left subtree or right subtree or current node may also be minimum. So we take minimum of three and return. This is different from Binary Search tree."
},
{
"code": null,
"e": 27578,
"s": 27523,
"text": "Below is C++ implementation of find minimum operation."
},
{
"code": "// A C++ program to demonstrate find minimum on KD tree#include <bits/stdc++.h>using namespace std; const int k = 2; // A structure to represent node of kd treestruct Node { int point[k]; // To store k dimensional point Node *left, *right;}; // A method to create a node of K D treestruct Node* newNode(int arr[]){ struct Node* temp = new Node; for (int i = 0; i < k; i++) temp->point[i] = arr[i]; temp->left = temp->right = NULL; return temp;} // Inserts a new node and returns root of modified tree// The parameter depth is used to decide axis of comparisonNode* insertRec(Node* root, int point[], unsigned depth){ // Tree is empty? if (root == NULL) return newNode(point); // Calculate current dimension (cd) of comparison unsigned cd = depth % k; // Compare the new point with root on current dimension 'cd' // and decide the left or right subtree if (point[cd] < (root->point[cd])) root->left = insertRec(root->left, point, depth + 1); else root->right = insertRec(root->right, point, depth + 1); return root;} // Function to insert a new point with given point in// KD Tree and return new root. It mainly uses above recursive// function \"insertRec()\"Node* insert(Node* root, int point[]){ return insertRec(root, point, 0);} // A utility function to find minimum of three integersint min(int x, int y, int z){ return min(x, min(y, z));} // Recursively finds minimum of d'th dimension in KD tree// The parameter depth is used to determine current axis.int findMinRec(Node* root, int d, unsigned depth){ // Base cases if (root == NULL) return INT_MAX; // Current dimension is computed using current depth and total // dimensions (k) unsigned cd = depth % k; // Compare point with root with respect to cd (Current dimension) if (cd == d) { if (root->left == NULL) return root->point[d]; return min(root->point[d], findMinRec(root->left, d, depth + 1)); } // If current dimension is different then minimum can be anywhere // in this subtree return min(root->point[d], findMinRec(root->left, d, depth + 1), findMinRec(root->right, d, depth + 1));} // A wrapper over findMinRec(). Returns minimum of d'th dimensionint findMin(Node* root, int d){ // Pass current level or depth as 0 return findMinRec(root, d, 0);} // Driver program to test above functionsint main(){ struct Node* root = NULL; int points[][k] = { { 30, 40 }, { 5, 25 }, { 70, 70 }, { 10, 12 }, { 50, 30 }, { 35, 45 } }; int n = sizeof(points) / sizeof(points[0]); for (int i = 0; i < n; i++) root = insert(root, points[i]); cout << \"Minimum of 0'th dimension is \" << findMin(root, 0) << endl; cout << \"Minimum of 1'th dimension is \" << findMin(root, 1) << endl; return 0;}",
"e": 30461,
"s": 27578,
"text": null
},
{
"code": null,
"e": 30469,
"s": 30461,
"text": "Output:"
},
{
"code": null,
"e": 30532,
"s": 30469,
"text": "Minimum of 0'th dimension is 5\nMinimum of 1'th dimension is 12"
},
{
"code": null,
"e": 31435,
"s": 30532,
"text": "YouTubeGeeksforGeeks507K subscribersK-Dimensional Tree [Find Minimum] | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 4:16•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=oRwYNAEuNK8\" target=\"_blank\">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>Source:https://www.cs.umd.edu/class/spring2008/cmsc420/L19.kd-trees.pdf"
},
{
"code": null,
"e": 31604,
"s": 31435,
"text": "This article is contributed by Ashish Gupta. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above"
},
{
"code": null,
"e": 31617,
"s": 31604,
"text": "mayurpothuri"
},
{
"code": null,
"e": 31624,
"s": 31617,
"text": "xmyqsh"
},
{
"code": null,
"e": 31648,
"s": 31624,
"text": "Advanced Data Structure"
},
{
"code": null,
"e": 31746,
"s": 31648,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31786,
"s": 31746,
"text": "Decision Tree Introduction with example"
},
{
"code": null,
"e": 31814,
"s": 31786,
"text": "AVL Tree | Set 2 (Deletion)"
},
{
"code": null,
"e": 31843,
"s": 31814,
"text": "Ordered Set and GNU C++ PBDS"
},
{
"code": null,
"e": 31875,
"s": 31843,
"text": "Red-Black Tree | Set 2 (Insert)"
},
{
"code": null,
"e": 31904,
"s": 31875,
"text": "Disjoint Set Data Structures"
},
{
"code": null,
"e": 31996,
"s": 31904,
"text": "Design a data structure that supports insert, delete, search and getRandom in constant time"
},
{
"code": null,
"e": 32032,
"s": 31996,
"text": "Binary Indexed Tree or Fenwick Tree"
},
{
"code": null,
"e": 32059,
"s": 32032,
"text": "Insert Operation in B-Tree"
}
] |
Python | Thresholding techniques using OpenCV | Set-3 (Otsu Thresholding) - GeeksforGeeks
|
29 May, 2019
In the previous posts, Simple Thresholding and Adaptive Thresholding were explained. In Simple Thresholding, the global value of threshold was used which remained constant throughout. In Adaptive thresholding, the threshold value is calculated for smaller regions with different threshold values for different regions with respect to the change in lighting.
In Otsu Thresholding, a value of the threshold isn’t chosen but is determined automatically. A bimodal image (two distinct image values) is considered. The histogram generated contains two peaks. So, a generic condition would be to choose a threshold value that lies in the middle of both the histogram peak values.
We use the Traditional cv2.threshold function and use cv2.THRESH_OTSU as an extra flag.
Syntax: cv2.threshold(source, thresholdValue, maxVal, thresholdingTechnique)
Parameters:-> source: Input Image array (must be in Grayscale).-> thresholdValue: Value of Threshold below and above which pixel values will change accordingly.-> maxVal: Maximum value that can be assigned to a pixel.-> thresholdingTechnique: The type of thresholding to be applied.
Below is the Python code explaining Otsu Thresholding Technique –
# Python program to illustrate# Otsu thresholding type on an image # organizing importsimport cv2 import numpy as np # path to input image is specified and# image is loaded with imread commandimage1 = cv2.imread('input1.jpg') # cv2.cvtColor is applied over the# image input with applied parameters# to convert the image in grayscaleimg = cv2.cvtColor(image1, cv2.COLOR_BGR2GRAY) # applying Otsu thresholding# as an extra flag in binary # thresholding ret, thresh1 = cv2.threshold(img, 120, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU) # the window showing output image # with the corresponding thresholding # techniques applied to the input image cv2.imshow('Otsu Threshold', thresh1) # De-allocate any associated memory usage if cv2.waitKey(0) & 0xff == 27: cv2.destroyAllWindows()
Input:
Output:
The calculation accepts that the picture contains two classes of pixels following foreground and background pixels, it at that point ascertains the ideal limit isolating the two classes with the goal that their consolidated spread is insignificant.
Image-Processing
OpenCV
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
Python String | replace()
|
[
{
"code": null,
"e": 42651,
"s": 42623,
"text": "\n29 May, 2019"
},
{
"code": null,
"e": 43009,
"s": 42651,
"text": "In the previous posts, Simple Thresholding and Adaptive Thresholding were explained. In Simple Thresholding, the global value of threshold was used which remained constant throughout. In Adaptive thresholding, the threshold value is calculated for smaller regions with different threshold values for different regions with respect to the change in lighting."
},
{
"code": null,
"e": 43325,
"s": 43009,
"text": "In Otsu Thresholding, a value of the threshold isn’t chosen but is determined automatically. A bimodal image (two distinct image values) is considered. The histogram generated contains two peaks. So, a generic condition would be to choose a threshold value that lies in the middle of both the histogram peak values."
},
{
"code": null,
"e": 43413,
"s": 43325,
"text": "We use the Traditional cv2.threshold function and use cv2.THRESH_OTSU as an extra flag."
},
{
"code": null,
"e": 43490,
"s": 43413,
"text": "Syntax: cv2.threshold(source, thresholdValue, maxVal, thresholdingTechnique)"
},
{
"code": null,
"e": 43773,
"s": 43490,
"text": "Parameters:-> source: Input Image array (must be in Grayscale).-> thresholdValue: Value of Threshold below and above which pixel values will change accordingly.-> maxVal: Maximum value that can be assigned to a pixel.-> thresholdingTechnique: The type of thresholding to be applied."
},
{
"code": null,
"e": 43839,
"s": 43773,
"text": "Below is the Python code explaining Otsu Thresholding Technique –"
},
{
"code": "# Python program to illustrate# Otsu thresholding type on an image # organizing importsimport cv2 import numpy as np # path to input image is specified and# image is loaded with imread commandimage1 = cv2.imread('input1.jpg') # cv2.cvtColor is applied over the# image input with applied parameters# to convert the image in grayscaleimg = cv2.cvtColor(image1, cv2.COLOR_BGR2GRAY) # applying Otsu thresholding# as an extra flag in binary # thresholding ret, thresh1 = cv2.threshold(img, 120, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU) # the window showing output image # with the corresponding thresholding # techniques applied to the input image cv2.imshow('Otsu Threshold', thresh1) # De-allocate any associated memory usage if cv2.waitKey(0) & 0xff == 27: cv2.destroyAllWindows() ",
"e": 44739,
"s": 43839,
"text": null
},
{
"code": null,
"e": 44746,
"s": 44739,
"text": "Input:"
},
{
"code": null,
"e": 44754,
"s": 44746,
"text": "Output:"
},
{
"code": null,
"e": 45003,
"s": 44754,
"text": "The calculation accepts that the picture contains two classes of pixels following foreground and background pixels, it at that point ascertains the ideal limit isolating the two classes with the goal that their consolidated spread is insignificant."
},
{
"code": null,
"e": 45020,
"s": 45003,
"text": "Image-Processing"
},
{
"code": null,
"e": 45027,
"s": 45020,
"text": "OpenCV"
},
{
"code": null,
"e": 45034,
"s": 45027,
"text": "Python"
},
{
"code": null,
"e": 45132,
"s": 45034,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 45160,
"s": 45132,
"text": "Read JSON file using Python"
},
{
"code": null,
"e": 45210,
"s": 45160,
"text": "Adding new column to existing DataFrame in Pandas"
},
{
"code": null,
"e": 45232,
"s": 45210,
"text": "Python map() function"
},
{
"code": null,
"e": 45276,
"s": 45232,
"text": "How to get column names in Pandas dataframe"
},
{
"code": null,
"e": 45311,
"s": 45276,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 45343,
"s": 45311,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 45365,
"s": 45343,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 45407,
"s": 45365,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 45437,
"s": 45407,
"text": "Iterate over a list in Python"
}
] |
stringstream in C++ and its applications - GeeksforGeeks
|
30 Jan, 2022
A stringstream associates a string object with a stream allowing you to read from the string as if it were a stream (like cin). To use stringstream, we need to include sstream header file. The stringstream class is extremely useful in parsing input.
Basic methods are:
clear()- To clear the stream.str()- To get and set string object whose content is present in the stream. operator <<- Add a string to the stringstream object. operator >>- Read something from the stringstream object.
clear()- To clear the stream.
str()- To get and set string object whose content is present in the stream.
operator <<- Add a string to the stringstream object.
operator >>- Read something from the stringstream object.
Examples:
1. Count the number of words in a string-
Examples-
Input: Asipu Pawan KumarOutput: 3
Input: Geeks For Geeks IdeOutput: 4
Below is the C++ program to implement the above approach-
C++
// C++ program to count words in // a string using stringstream.#include <iostream>#include <sstream>#include<string>using namespace std; int countWords(string str){ // Breaking input into word // using string stream // Used for breaking words stringstream s(str); // To store individual words string word; int count = 0; while (s >> word) count++; return count;} // Driver codeint main(){ string s = "geeks for geeks geeks " "contribution placements"; cout << " Number of words are: " << countWords(s); return 0;}
Number of words are: 6
2. Print frequencies of individual words in a string-
Examples-
Input: Geeks For Geeks Quiz Geeks Quiz Practice PracticeOutput: For -> 1 Geeks -> 3 Practice -> 2 Quiz -> 2
Input: Word String Frequency StringOutput: Frequency -> 1 String -> 2 Word -> 1
Below is the C++ program to implement the above approach-
C++
// C++ program to demonstrate use// of stringstream to count// frequencies of words.#include <bits/stdc++.h>#include <iostream>#include <sstream>#include<string>using namespace std; void printFrequency(string st){ // Each word it mapped to // it's frequency map<string, int>FW; // Used for breaking words stringstream ss(st); // To store individual words string Word; while (ss >> Word) FW[Word]++; map<string, int>::iterator m; for (m = FW.begin(); m != FW.end(); m++) cout << m->first << "-> " << m->second << "\n";} // Driver codeint main(){ string s = "Geeks For Geeks Ide"; printFrequency(s); return 0;}
For-> 1
Geeks-> 2
Ide-> 1
3. Removing spaces from a string using Stringstream4. Converting Strings to Numbers in C/C++
This article is contributed by ASIPU PAWAN KUMAR. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. 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.
ghurarpit110
cpp-string
cpp-stringstream
C++
Strings
Strings
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Vector in C++ STL
Initialize a vector in C++ (6 different ways)
std::sort() in C++ STL
Bitwise Operators in C/C++
Virtual Function in C++
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
Longest Common Subsequence | DP-4
Check for Balanced Brackets in an expression (well-formedness) using Stack
|
[
{
"code": null,
"e": 28207,
"s": 28179,
"text": "\n30 Jan, 2022"
},
{
"code": null,
"e": 28458,
"s": 28207,
"text": "A stringstream associates a string object with a stream allowing you to read from the string as if it were a stream (like cin). To use stringstream, we need to include sstream header file. The stringstream class is extremely useful in parsing input. "
},
{
"code": null,
"e": 28477,
"s": 28458,
"text": "Basic methods are:"
},
{
"code": null,
"e": 28694,
"s": 28477,
"text": "clear()- To clear the stream.str()- To get and set string object whose content is present in the stream. operator <<- Add a string to the stringstream object. operator >>- Read something from the stringstream object."
},
{
"code": null,
"e": 28724,
"s": 28694,
"text": "clear()- To clear the stream."
},
{
"code": null,
"e": 28801,
"s": 28724,
"text": "str()- To get and set string object whose content is present in the stream. "
},
{
"code": null,
"e": 28856,
"s": 28801,
"text": "operator <<- Add a string to the stringstream object. "
},
{
"code": null,
"e": 28914,
"s": 28856,
"text": "operator >>- Read something from the stringstream object."
},
{
"code": null,
"e": 28924,
"s": 28914,
"text": "Examples:"
},
{
"code": null,
"e": 28966,
"s": 28924,
"text": "1. Count the number of words in a string-"
},
{
"code": null,
"e": 28976,
"s": 28966,
"text": "Examples-"
},
{
"code": null,
"e": 29010,
"s": 28976,
"text": "Input: Asipu Pawan KumarOutput: 3"
},
{
"code": null,
"e": 29046,
"s": 29010,
"text": "Input: Geeks For Geeks IdeOutput: 4"
},
{
"code": null,
"e": 29104,
"s": 29046,
"text": "Below is the C++ program to implement the above approach-"
},
{
"code": null,
"e": 29108,
"s": 29104,
"text": "C++"
},
{
"code": "// C++ program to count words in // a string using stringstream.#include <iostream>#include <sstream>#include<string>using namespace std; int countWords(string str){ // Breaking input into word // using string stream // Used for breaking words stringstream s(str); // To store individual words string word; int count = 0; while (s >> word) count++; return count;} // Driver codeint main(){ string s = \"geeks for geeks geeks \" \"contribution placements\"; cout << \" Number of words are: \" << countWords(s); return 0;}",
"e": 29687,
"s": 29108,
"text": null
},
{
"code": null,
"e": 29711,
"s": 29687,
"text": " Number of words are: 6"
},
{
"code": null,
"e": 29765,
"s": 29711,
"text": "2. Print frequencies of individual words in a string-"
},
{
"code": null,
"e": 29775,
"s": 29765,
"text": "Examples-"
},
{
"code": null,
"e": 29919,
"s": 29775,
"text": "Input: Geeks For Geeks Quiz Geeks Quiz Practice PracticeOutput: For -> 1 Geeks -> 3 Practice -> 2 Quiz -> 2"
},
{
"code": null,
"e": 30030,
"s": 29919,
"text": "Input: Word String Frequency StringOutput: Frequency -> 1 String -> 2 Word -> 1 "
},
{
"code": null,
"e": 30088,
"s": 30030,
"text": "Below is the C++ program to implement the above approach-"
},
{
"code": null,
"e": 30092,
"s": 30088,
"text": "C++"
},
{
"code": "// C++ program to demonstrate use// of stringstream to count// frequencies of words.#include <bits/stdc++.h>#include <iostream>#include <sstream>#include<string>using namespace std; void printFrequency(string st){ // Each word it mapped to // it's frequency map<string, int>FW; // Used for breaking words stringstream ss(st); // To store individual words string Word; while (ss >> Word) FW[Word]++; map<string, int>::iterator m; for (m = FW.begin(); m != FW.end(); m++) cout << m->first << \"-> \" << m->second << \"\\n\";} // Driver codeint main(){ string s = \"Geeks For Geeks Ide\"; printFrequency(s); return 0;}",
"e": 30774,
"s": 30092,
"text": null
},
{
"code": null,
"e": 30801,
"s": 30774,
"text": "For-> 1\nGeeks-> 2\nIde-> 1\n"
},
{
"code": null,
"e": 30894,
"s": 30801,
"text": "3. Removing spaces from a string using Stringstream4. Converting Strings to Numbers in C/C++"
},
{
"code": null,
"e": 31319,
"s": 30894,
"text": "This article is contributed by ASIPU PAWAN KUMAR. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. 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": 31332,
"s": 31319,
"text": "ghurarpit110"
},
{
"code": null,
"e": 31343,
"s": 31332,
"text": "cpp-string"
},
{
"code": null,
"e": 31360,
"s": 31343,
"text": "cpp-stringstream"
},
{
"code": null,
"e": 31364,
"s": 31360,
"text": "C++"
},
{
"code": null,
"e": 31372,
"s": 31364,
"text": "Strings"
},
{
"code": null,
"e": 31380,
"s": 31372,
"text": "Strings"
},
{
"code": null,
"e": 31384,
"s": 31380,
"text": "CPP"
},
{
"code": null,
"e": 31482,
"s": 31384,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31500,
"s": 31482,
"text": "Vector in C++ STL"
},
{
"code": null,
"e": 31546,
"s": 31500,
"text": "Initialize a vector in C++ (6 different ways)"
},
{
"code": null,
"e": 31569,
"s": 31546,
"text": "std::sort() in C++ STL"
},
{
"code": null,
"e": 31596,
"s": 31569,
"text": "Bitwise Operators in C/C++"
},
{
"code": null,
"e": 31620,
"s": 31596,
"text": "Virtual Function in C++"
},
{
"code": null,
"e": 31666,
"s": 31620,
"text": "Write a program to reverse an array or string"
},
{
"code": null,
"e": 31691,
"s": 31666,
"text": "Reverse a string in Java"
},
{
"code": null,
"e": 31751,
"s": 31691,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 31785,
"s": 31751,
"text": "Longest Common Subsequence | DP-4"
}
] |
Dart Programming - Substring Method
|
Returns the substring of this string that extends from startIndex, inclusive, to endIndex, exclusive.
substring(int startIndex, [ int endIndex ])
startIndex − the index to start extracting from(inclusive).
startIndex − the index to start extracting from(inclusive).
endIndex − the index to stop extracting (exclusive).
endIndex − the index to stop extracting (exclusive).
Note − Indexes are zero based, i.e., the first character will have the index 0 and so on.
Returns a string.
void main() {
String str1 = "Hello World";
print("New String: ${str1.substring(6)}");
// from index 6 to the last index
print("New String: ${str1.substring(2,6)}");
// from index 2 to the 6th index
}
It will produce the following output −.
New String: World
New String: llo
44 Lectures
4.5 hours
Sriyank Siddhartha
34 Lectures
4 hours
Sriyank Siddhartha
69 Lectures
4 hours
Frahaan Hussain
117 Lectures
10 hours
Frahaan Hussain
22 Lectures
1.5 hours
Pranjal Srivastava
34 Lectures
3 hours
Pranjal Srivastava
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2627,
"s": 2525,
"text": "Returns the substring of this string that extends from startIndex, inclusive, to endIndex, exclusive."
},
{
"code": null,
"e": 2672,
"s": 2627,
"text": "substring(int startIndex, [ int endIndex ])\n"
},
{
"code": null,
"e": 2732,
"s": 2672,
"text": "startIndex − the index to start extracting from(inclusive)."
},
{
"code": null,
"e": 2792,
"s": 2732,
"text": "startIndex − the index to start extracting from(inclusive)."
},
{
"code": null,
"e": 2845,
"s": 2792,
"text": "endIndex − the index to stop extracting (exclusive)."
},
{
"code": null,
"e": 2898,
"s": 2845,
"text": "endIndex − the index to stop extracting (exclusive)."
},
{
"code": null,
"e": 2988,
"s": 2898,
"text": "Note − Indexes are zero based, i.e., the first character will have the index 0 and so on."
},
{
"code": null,
"e": 3006,
"s": 2988,
"text": "Returns a string."
},
{
"code": null,
"e": 3236,
"s": 3006,
"text": "void main() { \n String str1 = \"Hello World\"; \n print(\"New String: ${str1.substring(6)}\"); \n \n // from index 6 to the last index \n print(\"New String: ${str1.substring(2,6)}\"); \n \n // from index 2 to the 6th index \n} "
},
{
"code": null,
"e": 3276,
"s": 3236,
"text": "It will produce the following output −."
},
{
"code": null,
"e": 3313,
"s": 3276,
"text": "New String: World \nNew String: llo \n"
},
{
"code": null,
"e": 3348,
"s": 3313,
"text": "\n 44 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 3368,
"s": 3348,
"text": " Sriyank Siddhartha"
},
{
"code": null,
"e": 3401,
"s": 3368,
"text": "\n 34 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 3421,
"s": 3401,
"text": " Sriyank Siddhartha"
},
{
"code": null,
"e": 3454,
"s": 3421,
"text": "\n 69 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 3471,
"s": 3454,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 3506,
"s": 3471,
"text": "\n 117 Lectures \n 10 hours \n"
},
{
"code": null,
"e": 3523,
"s": 3506,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 3558,
"s": 3523,
"text": "\n 22 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 3578,
"s": 3558,
"text": " Pranjal Srivastava"
},
{
"code": null,
"e": 3611,
"s": 3578,
"text": "\n 34 Lectures \n 3 hours \n"
},
{
"code": null,
"e": 3631,
"s": 3611,
"text": " Pranjal Srivastava"
},
{
"code": null,
"e": 3638,
"s": 3631,
"text": " Print"
},
{
"code": null,
"e": 3649,
"s": 3638,
"text": " Add Notes"
}
] |
How to Locate Dark Web Hacker Forums for Security Research | by Mitchell Telatnik | Towards Data Science
|
To most users, Google is the gateway to exploring the internet. However, the deep web contains pages that cannot be indexed by Google. Within this space, lies the dark web — anonymized websites, often called hidden services, dealing in criminal activity from drugs to hacking to human trafficking.
Conducting security research on the dark web can be difficult. Website URLs on the dark web do not follow conventions and are often a random string of letters and numbers followed by the .onion subdomain. These websites require the TOR browser to resolve, and cannot be accessed through traditional browsers such as Chrome or Safari.
In addition, traditional search engines such as Google do not exist on the dark web. Instead, website URLs are either exchanged person to person (online or in-person) or collected into a simple Html directory. This can make it difficult to find hacker forums on the dark web — specifically forums where serious individuals gather.
Some forums can be found on the dark web directories listed above. These can be found on the dark web or even the surface web (the web we all know and that this article is hosted on). However, because these forums are easy to find, they often attract amateurs in the community. In order to locate more relevant forums for security research, the snowball sampling method can be used to crawl the darknet.
Snowball sampling is a method that can be used to locate hidden services on the dark web for security research including data collection and CTI streams. Snowball sampling is a web crawler architecture that takes a root URL and crawls the website for outgoing links to other websites. This process is then continued for each gathered link for a set depth. This crawler will return a large list of URLs to dark web websites that it gathered.
This method is very similar to the way early search engine web crawlers worked. A key example of this can be found in the 1998 paper “The Anatomy of a Large-Scale Hypertextual Web Search Engine” by Sergey Brin and Lawrence Page — the founders of Google.
Snowball sampling works well when applied to forums on the dark web. Users will often link to other forums in forum posts and comments — an example of the exchange on URLs from person to person that was mentioned earlier. By starting with a hacker forum found on a directory (or one you already know of), more serious and security-relevant forums can be quickly located.
In order to develop the dark web crawler, you need to set up your environment. It may be useful to read my article on how to scrape the dark web to better understand the process. It will also be useful in scraping data from the dark web forums you have identified. This article assumes you are using the OSX operating system. However, if you are using Linex or Windows many aspects should still be applicable.
The TOR browser is a browser that uses the TOR network and will allow us to resolve websites using a .onion subdomain. The TOR browser can be downloaded here.
Running a VPN while crawling the dark web can provide you additional security. A virtual private network (VPN) is not required but highly recommended.
For this article, I assume you already have python installed on your machine with an IDE of your choice. If not, many tutorials can be found online.
Pandas is a data manipulation Python package. Pandas will be used to store and export the data scraped to a csv file. Pandas can be installed using pip by typing the following command into your terminal:
pip install pandas
Selenium is a browser automation Python package. Selenium will be used to crawl the websites and extract data. Selenium can be installed using pip by typing the following command into your terminal:
pip install selenium
For selenium to automate a browser, it requires a driver. Because the TOR browser is running off of Firefox, we will be using Mozilla’s Geckodriver. You can download the driver here. After downloading, extract the driver and move it to your ~/.local/bin folder.
The location of the TOR browser’s Firefox binary will also be needed. To find this, right-click on the TOR browser in your applications folder and click on show contents. Then navigate to the Firefox binary and copy the full path. Save this path somewhere for later use.
This implementation will get you started creating a snowball sampling dark web crawler of depth 1. Because the website structure of the forums differs from each other, it can be difficult to automate the crawler beyond depth 1.
First, import the web driver and FirefoxBinary from selenium. Also import pandas as pd and re.
from selenium import webdriverfrom selenium.webdriver.firefox.firefox_binary import FirefoxBinaryimport pandas as pdimport re
Create a variable “binary” and set it to the path of the Firefox binary you saved earlier.
binary = FirefoxBinary(*path to your firefox binary*)
Set the web driver up to use Firefox and pass the binary variable.
driver = webdriver.Firefox(firefox_binary = binary)
Create a variable “starting_node” and set it to the URL of the starting forum.
starting_node = *your url*
Create an empty list “found_nodes”.
found_nodes = []
You will now need to automate your crawler to scrape the text of the forum posts, comments, or both. This process will differ from forum to forum. I recommend reading my article “How to Scrape the Dark Web” for some guidance and the Selenium documentation can be found here.
Compile a regex expression that can be used to identify onion links in the strings.
p = re.compile('\S+onion')
For each string (post text or comment text) search for onion URLs and add them to the list “found_nodes”.
for post in posts: nodes = p.findall(post) found_nodes.append(nodes)
The list “found_nodes” will contain the onion links found from the starting node. This algorithm can then be either repeated for each found link or stopped at a depth of 1.
Snowball sampling is a good method for discovering dark web hacker forums and other hidden services. In addition, services found through this method are generally more useful for security research than those found on directories since serious members of hacker communities generally do not congregate on well-advertised sites.
There are some areas of improvement in this implementation, however. Following this implementation of snowball sampling requires each found node to be manually visited and inspected for content. Not only can this be a time-consuming process, but it can also be dangerous to visit unknown onion links. Automatically determining website content through post context would greatly improve this crawler.
I want to reiterate that scraping the dark web can be dangerous. Make sure you take the necessary safety precautions. Please continue to research safe browsing on the dark web. I am not responsible for any harm that occurs.
|
[
{
"code": null,
"e": 470,
"s": 172,
"text": "To most users, Google is the gateway to exploring the internet. However, the deep web contains pages that cannot be indexed by Google. Within this space, lies the dark web — anonymized websites, often called hidden services, dealing in criminal activity from drugs to hacking to human trafficking."
},
{
"code": null,
"e": 804,
"s": 470,
"text": "Conducting security research on the dark web can be difficult. Website URLs on the dark web do not follow conventions and are often a random string of letters and numbers followed by the .onion subdomain. These websites require the TOR browser to resolve, and cannot be accessed through traditional browsers such as Chrome or Safari."
},
{
"code": null,
"e": 1135,
"s": 804,
"text": "In addition, traditional search engines such as Google do not exist on the dark web. Instead, website URLs are either exchanged person to person (online or in-person) or collected into a simple Html directory. This can make it difficult to find hacker forums on the dark web — specifically forums where serious individuals gather."
},
{
"code": null,
"e": 1539,
"s": 1135,
"text": "Some forums can be found on the dark web directories listed above. These can be found on the dark web or even the surface web (the web we all know and that this article is hosted on). However, because these forums are easy to find, they often attract amateurs in the community. In order to locate more relevant forums for security research, the snowball sampling method can be used to crawl the darknet."
},
{
"code": null,
"e": 1980,
"s": 1539,
"text": "Snowball sampling is a method that can be used to locate hidden services on the dark web for security research including data collection and CTI streams. Snowball sampling is a web crawler architecture that takes a root URL and crawls the website for outgoing links to other websites. This process is then continued for each gathered link for a set depth. This crawler will return a large list of URLs to dark web websites that it gathered."
},
{
"code": null,
"e": 2234,
"s": 1980,
"text": "This method is very similar to the way early search engine web crawlers worked. A key example of this can be found in the 1998 paper “The Anatomy of a Large-Scale Hypertextual Web Search Engine” by Sergey Brin and Lawrence Page — the founders of Google."
},
{
"code": null,
"e": 2605,
"s": 2234,
"text": "Snowball sampling works well when applied to forums on the dark web. Users will often link to other forums in forum posts and comments — an example of the exchange on URLs from person to person that was mentioned earlier. By starting with a hacker forum found on a directory (or one you already know of), more serious and security-relevant forums can be quickly located."
},
{
"code": null,
"e": 3015,
"s": 2605,
"text": "In order to develop the dark web crawler, you need to set up your environment. It may be useful to read my article on how to scrape the dark web to better understand the process. It will also be useful in scraping data from the dark web forums you have identified. This article assumes you are using the OSX operating system. However, if you are using Linex or Windows many aspects should still be applicable."
},
{
"code": null,
"e": 3174,
"s": 3015,
"text": "The TOR browser is a browser that uses the TOR network and will allow us to resolve websites using a .onion subdomain. The TOR browser can be downloaded here."
},
{
"code": null,
"e": 3325,
"s": 3174,
"text": "Running a VPN while crawling the dark web can provide you additional security. A virtual private network (VPN) is not required but highly recommended."
},
{
"code": null,
"e": 3474,
"s": 3325,
"text": "For this article, I assume you already have python installed on your machine with an IDE of your choice. If not, many tutorials can be found online."
},
{
"code": null,
"e": 3678,
"s": 3474,
"text": "Pandas is a data manipulation Python package. Pandas will be used to store and export the data scraped to a csv file. Pandas can be installed using pip by typing the following command into your terminal:"
},
{
"code": null,
"e": 3697,
"s": 3678,
"text": "pip install pandas"
},
{
"code": null,
"e": 3896,
"s": 3697,
"text": "Selenium is a browser automation Python package. Selenium will be used to crawl the websites and extract data. Selenium can be installed using pip by typing the following command into your terminal:"
},
{
"code": null,
"e": 3917,
"s": 3896,
"text": "pip install selenium"
},
{
"code": null,
"e": 4179,
"s": 3917,
"text": "For selenium to automate a browser, it requires a driver. Because the TOR browser is running off of Firefox, we will be using Mozilla’s Geckodriver. You can download the driver here. After downloading, extract the driver and move it to your ~/.local/bin folder."
},
{
"code": null,
"e": 4450,
"s": 4179,
"text": "The location of the TOR browser’s Firefox binary will also be needed. To find this, right-click on the TOR browser in your applications folder and click on show contents. Then navigate to the Firefox binary and copy the full path. Save this path somewhere for later use."
},
{
"code": null,
"e": 4678,
"s": 4450,
"text": "This implementation will get you started creating a snowball sampling dark web crawler of depth 1. Because the website structure of the forums differs from each other, it can be difficult to automate the crawler beyond depth 1."
},
{
"code": null,
"e": 4773,
"s": 4678,
"text": "First, import the web driver and FirefoxBinary from selenium. Also import pandas as pd and re."
},
{
"code": null,
"e": 4899,
"s": 4773,
"text": "from selenium import webdriverfrom selenium.webdriver.firefox.firefox_binary import FirefoxBinaryimport pandas as pdimport re"
},
{
"code": null,
"e": 4990,
"s": 4899,
"text": "Create a variable “binary” and set it to the path of the Firefox binary you saved earlier."
},
{
"code": null,
"e": 5044,
"s": 4990,
"text": "binary = FirefoxBinary(*path to your firefox binary*)"
},
{
"code": null,
"e": 5111,
"s": 5044,
"text": "Set the web driver up to use Firefox and pass the binary variable."
},
{
"code": null,
"e": 5163,
"s": 5111,
"text": "driver = webdriver.Firefox(firefox_binary = binary)"
},
{
"code": null,
"e": 5242,
"s": 5163,
"text": "Create a variable “starting_node” and set it to the URL of the starting forum."
},
{
"code": null,
"e": 5269,
"s": 5242,
"text": "starting_node = *your url*"
},
{
"code": null,
"e": 5305,
"s": 5269,
"text": "Create an empty list “found_nodes”."
},
{
"code": null,
"e": 5322,
"s": 5305,
"text": "found_nodes = []"
},
{
"code": null,
"e": 5597,
"s": 5322,
"text": "You will now need to automate your crawler to scrape the text of the forum posts, comments, or both. This process will differ from forum to forum. I recommend reading my article “How to Scrape the Dark Web” for some guidance and the Selenium documentation can be found here."
},
{
"code": null,
"e": 5681,
"s": 5597,
"text": "Compile a regex expression that can be used to identify onion links in the strings."
},
{
"code": null,
"e": 5708,
"s": 5681,
"text": "p = re.compile('\\S+onion')"
},
{
"code": null,
"e": 5814,
"s": 5708,
"text": "For each string (post text or comment text) search for onion URLs and add them to the list “found_nodes”."
},
{
"code": null,
"e": 5885,
"s": 5814,
"text": "for post in posts: nodes = p.findall(post) found_nodes.append(nodes)"
},
{
"code": null,
"e": 6058,
"s": 5885,
"text": "The list “found_nodes” will contain the onion links found from the starting node. This algorithm can then be either repeated for each found link or stopped at a depth of 1."
},
{
"code": null,
"e": 6385,
"s": 6058,
"text": "Snowball sampling is a good method for discovering dark web hacker forums and other hidden services. In addition, services found through this method are generally more useful for security research than those found on directories since serious members of hacker communities generally do not congregate on well-advertised sites."
},
{
"code": null,
"e": 6785,
"s": 6385,
"text": "There are some areas of improvement in this implementation, however. Following this implementation of snowball sampling requires each found node to be manually visited and inspected for content. Not only can this be a time-consuming process, but it can also be dangerous to visit unknown onion links. Automatically determining website content through post context would greatly improve this crawler."
}
] |
How to create SVG graphics using JavaScript?
|
All modern browsers support SVG and you can easily create it using JavaScript. Google Chrome and Firefox both support SVG.
With JavaScript, create a blank SVG document object model (DOM). Using attributes, create a shape like a circle or a rectangle.
var mySvg = "http://www.w3.org/2000/svg";
var myDoc = evt.target.ownerDocument;
var myShape = svgDocument.createElementNS(mySvg, "circle");
myShape.setAttributeNS(null, "cx", 40);
myShape.setAttributeNS(null, "cy", 40);
myShape.setAttributeNS(null, "r", 30);
myShape.setAttributeNS(null, "fill", "yellow");
|
[
{
"code": null,
"e": 1185,
"s": 1062,
"text": "All modern browsers support SVG and you can easily create it using JavaScript. Google Chrome and Firefox both support SVG."
},
{
"code": null,
"e": 1313,
"s": 1185,
"text": "With JavaScript, create a blank SVG document object model (DOM). Using attributes, create a shape like a circle or a rectangle."
},
{
"code": null,
"e": 1623,
"s": 1313,
"text": "var mySvg = \"http://www.w3.org/2000/svg\";\nvar myDoc = evt.target.ownerDocument;\n\nvar myShape = svgDocument.createElementNS(mySvg, \"circle\");\n\nmyShape.setAttributeNS(null, \"cx\", 40);\nmyShape.setAttributeNS(null, \"cy\", 40);\nmyShape.setAttributeNS(null, \"r\", 30);\n\nmyShape.setAttributeNS(null, \"fill\", \"yellow\");"
}
] |
Int32.GetHashCode Method in C# with Examples - GeeksforGeeks
|
04 Apr, 2019
Int32.GetHashCode method is used to get the HashCode for the current Int32 instance.
Syntax: public override int GetHashCode ();
Return Value: This method returns a 32-bit signed integer hash code.
Below programs illustrate the use of the above discussed-method:
Example 1:
// C# program to illustrate the// Int32.GetHashCode() Methodusing System; class GFG { // Main Method public static void Main() { // Taking Int32 variable int val = 32523; // Getting the hash code for Int32 // using GetHashCode() method int result = val.GetHashCode(); // Display the hashcode Console.WriteLine("HashCode for Int32 is: {0}", result); }}
HashCode for Int32 is: 32523
Example 2:
// C# program to illustrate the// Int32.GetHashCode() Methodusing System; class GFG { // Main Method public static void Main() { // using result() Method result(Int32.MinValue); result(Int32.MaxValue); } // result() method public static void result(int val) { // using GetHashCode() method int code = val.GetHashCode(); // Display the hashcode Console.WriteLine("HashCode for {0} is {1}", val, code); }}
HashCode for -2147483648 is -2147483648
HashCode for 2147483647 is 2147483647
Reference:
https://docs.microsoft.com/en-us/dotnet/api/system.int32.gethashcode?view=netframework-4.7.2
CSharp-Int32-Struct
CSharp-method
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Program to calculate Electricity Bill
C# Dictionary with examples
C# | How to insert an element in an Array?
HashSet in C# with Examples
Introduction to .NET Framework
Linked List Implementation in C#
C# | Data Types
C# | Replace() Method
Lambda Expressions in C#
Main Method in C#
|
[
{
"code": null,
"e": 23879,
"s": 23851,
"text": "\n04 Apr, 2019"
},
{
"code": null,
"e": 23964,
"s": 23879,
"text": "Int32.GetHashCode method is used to get the HashCode for the current Int32 instance."
},
{
"code": null,
"e": 24008,
"s": 23964,
"text": "Syntax: public override int GetHashCode ();"
},
{
"code": null,
"e": 24077,
"s": 24008,
"text": "Return Value: This method returns a 32-bit signed integer hash code."
},
{
"code": null,
"e": 24142,
"s": 24077,
"text": "Below programs illustrate the use of the above discussed-method:"
},
{
"code": null,
"e": 24153,
"s": 24142,
"text": "Example 1:"
},
{
"code": "// C# program to illustrate the// Int32.GetHashCode() Methodusing System; class GFG { // Main Method public static void Main() { // Taking Int32 variable int val = 32523; // Getting the hash code for Int32 // using GetHashCode() method int result = val.GetHashCode(); // Display the hashcode Console.WriteLine(\"HashCode for Int32 is: {0}\", result); }}",
"e": 24621,
"s": 24153,
"text": null
},
{
"code": null,
"e": 24651,
"s": 24621,
"text": "HashCode for Int32 is: 32523\n"
},
{
"code": null,
"e": 24662,
"s": 24651,
"text": "Example 2:"
},
{
"code": "// C# program to illustrate the// Int32.GetHashCode() Methodusing System; class GFG { // Main Method public static void Main() { // using result() Method result(Int32.MinValue); result(Int32.MaxValue); } // result() method public static void result(int val) { // using GetHashCode() method int code = val.GetHashCode(); // Display the hashcode Console.WriteLine(\"HashCode for {0} is {1}\", val, code); }}",
"e": 25188,
"s": 24662,
"text": null
},
{
"code": null,
"e": 25267,
"s": 25188,
"text": "HashCode for -2147483648 is -2147483648\nHashCode for 2147483647 is 2147483647\n"
},
{
"code": null,
"e": 25278,
"s": 25267,
"text": "Reference:"
},
{
"code": null,
"e": 25371,
"s": 25278,
"text": "https://docs.microsoft.com/en-us/dotnet/api/system.int32.gethashcode?view=netframework-4.7.2"
},
{
"code": null,
"e": 25391,
"s": 25371,
"text": "CSharp-Int32-Struct"
},
{
"code": null,
"e": 25405,
"s": 25391,
"text": "CSharp-method"
},
{
"code": null,
"e": 25408,
"s": 25405,
"text": "C#"
},
{
"code": null,
"e": 25506,
"s": 25408,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25515,
"s": 25506,
"text": "Comments"
},
{
"code": null,
"e": 25528,
"s": 25515,
"text": "Old Comments"
},
{
"code": null,
"e": 25566,
"s": 25528,
"text": "Program to calculate Electricity Bill"
},
{
"code": null,
"e": 25594,
"s": 25566,
"text": "C# Dictionary with examples"
},
{
"code": null,
"e": 25637,
"s": 25594,
"text": "C# | How to insert an element in an Array?"
},
{
"code": null,
"e": 25665,
"s": 25637,
"text": "HashSet in C# with Examples"
},
{
"code": null,
"e": 25696,
"s": 25665,
"text": "Introduction to .NET Framework"
},
{
"code": null,
"e": 25729,
"s": 25696,
"text": "Linked List Implementation in C#"
},
{
"code": null,
"e": 25745,
"s": 25729,
"text": "C# | Data Types"
},
{
"code": null,
"e": 25767,
"s": 25745,
"text": "C# | Replace() Method"
},
{
"code": null,
"e": 25792,
"s": 25767,
"text": "Lambda Expressions in C#"
}
] |
Difference Between CSS Display and Visibility
|
We can hide or remove an element in a HTML document with CSS Visibility and CSS Display properties respectively. To the user, there might not seem any difference in using any of the two properties, but there is.
CSS Display − none does not render the element on the document and thus not allocating it any space.
CSS Visibility − hidden does renders the element on the document and even the space is allocated but it is not made visible to the user.
Let’s see an example for CSS Display none −
Live Demo
<!DOCTYPE html>
<html>
<head>
<title>CSS Display None</title>
<style>
form {
width:70%;
margin: 0 auto;
text-align: center;
}
* {
padding: 2px;
margin:5px;
box-sizing: border-box;
}
input[type="button"] {
border-radius: 10px;
}
.child{
display: inline-block;
height: 40px;
width: 40px;
color: white;
border: 4px solid black;
}
.child:nth-of-type(1){
background-color: #FF8A00;
}
.child:nth-of-type(2){
background-color: #F44336;
}
.child:nth-of-type(3){
background-color: #C303C3;
}
.child:nth-of-type(4){
background-color: #4CAF50;
}
.child:nth-of-type(5){
background-color: #03A9F4;
}
.child:nth-of-type(6){
background-color: #FEDC11;
}
</style>
</head>
<body>
<form>
<fieldset>
<legend>CSS-Display-None</legend>
<div id="container">
<div class="child"></div><div class="child primary"></div><div class="child"></div><div class="child"></div><div class="child primary"></div><div class="child primary"></div>
</div><br>
<input type="button" value="Hide Primary Colors" onclick="displayNone()">
</fieldset>
</form>
<script>
var primaryColor = document.getElementsByClassName('primary');
function displayNone(){
for(var i=0; i<3; i++)
primaryColor[i].style.display = 'none';
}
</script>
</body>
</html>
This will produce the following output −
Before clicking ‘Hide Primary Colors’ button −
After clicking ‘Hide Primary Colors’ button −
Let’s see an example of CSS Visibility hidden −
Live Demo
<!DOCTYPE html>
<html>
<head>
<title>CSS Visibility hidden</title>
<style>
form {
width:70%;
margin: 0 auto;
text-align: center;
}
* {
padding: 2px;
margin:5px;
box-sizing: border-box;
}
input[type="button"] {
border-radius: 10px;
}
.child{
display: inline-block;
height: 40px;
width: 40px;
color: white;
border: 4px solid black;
}
.child:nth-of-type(1){
background-color: #FF8A00;
}
.child:nth-of-type(2){
background-color: #F44336;
}
.child:nth-of-type(3){
background-color: #C303C3;
}
.child:nth-of-type(4){
background-color: #4CAF50;
}
.child:nth-of-type(5){
background-color: #03A9F4;
}
.child:nth-of-type(6){
background-color: #FEDC11;
}
</style>
</head>
<body>
<form>
<fieldset>
<legend>CSS-Visibility-hidden</legend>
<div id="container">
<div class="child"></div><div class="child primary"></div><div class="child"></div><div class="child"></div><div class="child primary"></div><div class="child primary"></div>
</div><br>
<input type="button" value="Hide Primary Colors" onclick="visibilityHidden()">
</fieldset>
</form>
<script>
var primaryColor = document.getElementsByClassName('primary');
function visibilityHidden(){
for(var i=0; i<3; i++)
primaryColor[i].style.visibility = 'hidden';
}
</script>
</body>
</html>
This will produce the following output −
Before clicking ‘Hide Primary Colors’ button −
After clicking ‘Hide Primary Colors’ button −
|
[
{
"code": null,
"e": 1274,
"s": 1062,
"text": "We can hide or remove an element in a HTML document with CSS Visibility and CSS Display properties respectively. To the user, there might not seem any difference in using any of the two properties, but there is."
},
{
"code": null,
"e": 1375,
"s": 1274,
"text": "CSS Display − none does not render the element on the document and thus not allocating it any space."
},
{
"code": null,
"e": 1512,
"s": 1375,
"text": "CSS Visibility − hidden does renders the element on the document and even the space is allocated but it is not made visible to the user."
},
{
"code": null,
"e": 1556,
"s": 1512,
"text": "Let’s see an example for CSS Display none −"
},
{
"code": null,
"e": 1567,
"s": 1556,
"text": " Live Demo"
},
{
"code": null,
"e": 2830,
"s": 1567,
"text": "<!DOCTYPE html>\n<html>\n<head>\n<title>CSS Display None</title>\n<style>\nform {\n width:70%;\n margin: 0 auto;\n text-align: center;\n}\n* {\n padding: 2px;\n margin:5px;\n box-sizing: border-box;\n}\ninput[type=\"button\"] {\n border-radius: 10px;\n}\n.child{\n display: inline-block;\n height: 40px;\n width: 40px;\n color: white;\n border: 4px solid black;\n}\n.child:nth-of-type(1){\n background-color: #FF8A00;\n}\n.child:nth-of-type(2){\n background-color: #F44336;\n}\n.child:nth-of-type(3){\n background-color: #C303C3;\n}\n.child:nth-of-type(4){\n background-color: #4CAF50;\n}\n.child:nth-of-type(5){\n background-color: #03A9F4;\n}\n.child:nth-of-type(6){\n background-color: #FEDC11;\n}\n</style>\n</head>\n<body>\n<form>\n<fieldset>\n<legend>CSS-Display-None</legend>\n<div id=\"container\">\n<div class=\"child\"></div><div class=\"child primary\"></div><div class=\"child\"></div><div class=\"child\"></div><div class=\"child primary\"></div><div class=\"child primary\"></div>\n</div><br>\n<input type=\"button\" value=\"Hide Primary Colors\" onclick=\"displayNone()\">\n</fieldset>\n</form>\n<script>\nvar primaryColor = document.getElementsByClassName('primary');\nfunction displayNone(){\n for(var i=0; i<3; i++)\n primaryColor[i].style.display = 'none';\n}\n</script>\n</body>\n</html>"
},
{
"code": null,
"e": 2871,
"s": 2830,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2918,
"s": 2871,
"text": "Before clicking ‘Hide Primary Colors’ button −"
},
{
"code": null,
"e": 2964,
"s": 2918,
"text": "After clicking ‘Hide Primary Colors’ button −"
},
{
"code": null,
"e": 3012,
"s": 2964,
"text": "Let’s see an example of CSS Visibility hidden −"
},
{
"code": null,
"e": 3023,
"s": 3012,
"text": " Live Demo"
},
{
"code": null,
"e": 4311,
"s": 3023,
"text": "<!DOCTYPE html>\n<html>\n<head>\n<title>CSS Visibility hidden</title>\n<style>\nform {\n width:70%;\n margin: 0 auto;\n text-align: center;\n}\n* {\n padding: 2px;\n margin:5px;\n box-sizing: border-box;\n}\ninput[type=\"button\"] {\n border-radius: 10px;\n}\n.child{\n display: inline-block;\n height: 40px;\n width: 40px;\n color: white;\n border: 4px solid black;\n}\n.child:nth-of-type(1){\n background-color: #FF8A00;\n}\n.child:nth-of-type(2){\n background-color: #F44336;\n}\n.child:nth-of-type(3){\n background-color: #C303C3;\n}\n.child:nth-of-type(4){\n background-color: #4CAF50;\n}\n.child:nth-of-type(5){\n background-color: #03A9F4;\n}\n.child:nth-of-type(6){\n background-color: #FEDC11;\n}\n</style>\n</head>\n<body>\n<form>\n<fieldset>\n<legend>CSS-Visibility-hidden</legend>\n<div id=\"container\">\n<div class=\"child\"></div><div class=\"child primary\"></div><div class=\"child\"></div><div class=\"child\"></div><div class=\"child primary\"></div><div class=\"child primary\"></div>\n</div><br>\n<input type=\"button\" value=\"Hide Primary Colors\" onclick=\"visibilityHidden()\">\n</fieldset>\n</form>\n<script>\nvar primaryColor = document.getElementsByClassName('primary');\nfunction visibilityHidden(){\n for(var i=0; i<3; i++)\n primaryColor[i].style.visibility = 'hidden';\n}\n</script>\n</body>\n</html>"
},
{
"code": null,
"e": 4352,
"s": 4311,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 4399,
"s": 4352,
"text": "Before clicking ‘Hide Primary Colors’ button −"
},
{
"code": null,
"e": 4445,
"s": 4399,
"text": "After clicking ‘Hide Primary Colors’ button −"
}
] |
Tryit Editor v3.7
|
CSS Style Images
Tryit: Image hover - Slide in from top
|
[
{
"code": null,
"e": 26,
"s": 9,
"text": "CSS Style Images"
}
] |
How to print new line in Java?
|
The java.io.PrintStream.println() method prints an array of characters and then terminate the line. This method behaves as though it invokes print(char[]) and then println().
Using this method you can print the data on the console.
import java.io.*;
public class PrintStreamDemo {
public static void main(String[] args) {
char[] c = {'a', 'b', 'c'};
// create print stream object
PrintStream ps = new PrintStream(System.out);
// print an array and change line
ps.println(c);
ps.print("New Line");
// flush the stream
ps.flush();
}
}
abc
New Line
|
[
{
"code": null,
"e": 1237,
"s": 1062,
"text": "The java.io.PrintStream.println() method prints an array of characters and then terminate the line. This method behaves as though it invokes print(char[]) and then println()."
},
{
"code": null,
"e": 1294,
"s": 1237,
"text": "Using this method you can print the data on the console."
},
{
"code": null,
"e": 1670,
"s": 1294,
"text": "import java.io.*;\npublic class PrintStreamDemo {\n public static void main(String[] args) {\n char[] c = {'a', 'b', 'c'};\n \n // create print stream object\n PrintStream ps = new PrintStream(System.out);\n \n // print an array and change line\n ps.println(c);\n ps.print(\"New Line\");\n \n // flush the stream\n ps.flush();\n }\n}"
},
{
"code": null,
"e": 1684,
"s": 1670,
"text": "abc\nNew Line\n"
}
] |
MySQL SELECT to sum a column value with previous value
|
For this, you can use a session variable. Let us first create a table −
mysql> create table DemoTable809(Price int);
Query OK, 0 rows affected (0.53 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable809 values(40);
Query OK, 1 row affected (0.17 sec)
mysql> insert into DemoTable809 values(50);
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable809 values(60);
Query OK, 1 row affected (0.12 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable809;
This will produce the following output −
+-------+
| Price |
+-------+
| 40 |
| 50 |
| 60 |
+-------+
3 rows in set (0.00 sec)
Following is the query to sum a column value with a previous value −
mysql> select @currentSum:=@currentSum+Price from DemoTable809;
This will produce the following output −
+--------------------------------+
| @currentSum:=@currentSum+Price |
+--------------------------------+
| 40 |
| 90 |
| 150 |
+--------------------------------+
3 rows in set (0.00 sec)
|
[
{
"code": null,
"e": 1134,
"s": 1062,
"text": "For this, you can use a session variable. Let us first create a table −"
},
{
"code": null,
"e": 1216,
"s": 1134,
"text": "mysql> create table DemoTable809(Price int);\nQuery OK, 0 rows affected (0.53 sec)"
},
{
"code": null,
"e": 1272,
"s": 1216,
"text": "Insert some records in the table using insert command −"
},
{
"code": null,
"e": 1512,
"s": 1272,
"text": "mysql> insert into DemoTable809 values(40);\nQuery OK, 1 row affected (0.17 sec)\nmysql> insert into DemoTable809 values(50);\nQuery OK, 1 row affected (0.14 sec)\nmysql> insert into DemoTable809 values(60);\nQuery OK, 1 row affected (0.12 sec)"
},
{
"code": null,
"e": 1572,
"s": 1512,
"text": "Display all records from the table using select statement −"
},
{
"code": null,
"e": 1606,
"s": 1572,
"text": "mysql> select *from DemoTable809;"
},
{
"code": null,
"e": 1647,
"s": 1606,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 1742,
"s": 1647,
"text": "+-------+\n| Price |\n+-------+\n| 40 |\n| 50 |\n| 60 |\n+-------+\n3 rows in set (0.00 sec)"
},
{
"code": null,
"e": 1811,
"s": 1742,
"text": "Following is the query to sum a column value with a previous value −"
},
{
"code": null,
"e": 1875,
"s": 1811,
"text": "mysql> select @currentSum:=@currentSum+Price from DemoTable809;"
},
{
"code": null,
"e": 1916,
"s": 1875,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2186,
"s": 1916,
"text": "+--------------------------------+\n| @currentSum:=@currentSum+Price |\n+--------------------------------+\n| 40 |\n| 90 |\n| 150 |\n+--------------------------------+\n3 rows in set (0.00 sec)"
}
] |
Statistics in Python — Using ANOVA for Feature Selection | by Wei-Meng Lee | Towards Data Science
|
In my previous article, I talked about using the chi-square statistics to select features from a dataset for machine learning. The chi-square test is used when both your independent and dependent variables are all categorical variables. However, what if your independent variable is categorical and your dependent variable is numerical? In this case, you have to use another statistic test known as ANOVA — Analysis of Variance.
And so in this article, our discussion will revolve around ANOVA and how you use it in machine learning for feature selection. Like all my previous articles, I will use a concrete example to explain the concept.
Before we get started, it is useful to summarize the different methods for feature selection that we have discussed so far :
If you need a refresher on Pearson correlation, Spearman’s rank correlation, and Chi-Square, I suggest you go and check them out now (see the links below) and come back to this article once you are done. Some of the concepts discussed in this article is similar to that of the chi-square test, and so I recommend you check that out.
towardsdatascience.com
towardsdatascience.com
towardsdatascience.com
ANOVA is used for testing two variables, where:
one is a categorical variable
another is a numerical variable
ANOVA is used when the categorical variable has at least 3 groups (i.e three different unique values).
If you want to compare just two groups, use the t-test. I will cover t-test in another article.
ANOVA lets you know if your numerical variable changes according to the level of the categorical variable.
ANOVA uses the f-tests to statistically test the equality of means. F-tests are named after its test statistic, F, which was named in honor of Sir Ronald Fisher.
Here are some examples that makes it easier to understand when you can use ANOVA.
You have a dataset containing information of a group of people pertaining to their social media usage and the number of hours they sleep:
You want to find out if the amount of social media usage (categorical variable) has a direct impact on the number of hours of sleep (numerical variable).
You have a dataset containing three different brands of medication and the number of days for the medication to take effect:
You want to find out if there is a direct relationship between a specific brand and its effectiveness.
ANOVA checks whether there is equal variance between groups of categorical feature with respect to the numerical response.
If there is equal variance between groups, it means this feature has no impact on the response and hence it (the categorical variable) cannot be considered for model training.
The best way to understand ANOVA is to use an example. In the following example, I use a fictitious dataset where I recorded the reaction time of a group of people when they are given a specific type of drink.
I have a sample dataset named drinks.csv containing the following content:
team,drink_type,reaction_time1,water,142,water,253,water,234,water,275,water,286,water,217,water,268,water,309,water,3110,water,341,coke,25 2,coke,263,coke,274,coke,295,coke,256,coke,237,coke,228,coke,279,coke,2910,coke,211,coffee,82,coffee,203,coffee,264,coffee,365,coffee,396,coffee,237,coffee,258,coffee,289,coffee,2710,coffee,25
There are 10 teams in all — each team comprises of 3 persons. Each person in the team is given three different types of drinks — water, coke, and coffee. After consuming the drink, they were asked to perform some activities and their reaction time recorded. The aim of this experiment is to determine if the drinks have any effect on a person’s reaction time.
Let’s first load the dataset into a Pandas DataFrame:
import pandas as pddf = pd.read_csv('drinks.csv')
Record the observation size, which we will make use of later:
observation_size = df.shape[0] # number of observations
It is useful to visualize the distribution of the data using a Boxplot:
_ = df.boxplot('reaction_time', by='drink_type')
You can see that the three types of drinks have about the same median reaction time.
To facilitate the calculation for ANOVA, we need to pivot the dataframe:
df = df.pivot(columns='drink_type', index='team')display(df)
The columns represent the three different types of drinks and the rows represents the 10 teams. We will also use this chance to record the number of items in each group, as well as the number of groups, which we will make use of later:
n = df.shape[0] # 10; number of items in each groupk = df.shape[1] # 3; number of groups
You now define your null hypothesis and alternate hypothesis, just like the chi-square test. They are:
H0 (Null hypothesis) — that there is no difference among group means.
H1 (Alternate hypothesis) — that at least one group differs significantly from the overall mean of the dependent variable.
We are now ready to begin our calculations for ANOVA. First, let’s find the mean for each group:
df.loc['Group Means'] = df.mean()df
From here, you can now calculate the overall mean:
overall_mean = df.iloc[-1].mean()overall_mean # 25.666666666666668
Now that we have calculated the overall mean, we can proceed to calculate the following:
Sum of squares of all observation — SS_total
Sum of squares within — SS_within
Sum of squares between — SS_between
The sum of squares of all observation is calculated by deducting each observation from the overall mean, and then summing all the squares of the differences:
Programmatically, SS_total is computed as:
SS_total = (((df.iloc[:-1] - overall_mean)**2).sum()).sum()SS_total # 1002.6666666666667
The sum of squares within is the sum of squared deviations of scores around their group’s mean:
Programmatically, SS_within is computed as:
SS_within = (((df.iloc[:-1] - df.iloc[-1])**2).sum()).sum() SS_within # 1001.4
Next we calculate the sum of squares of the group means from the overall mean:
Programmatically, SS_between is computed as:
SS_between = (n * (df.iloc[-1] - overall_mean)**2).sum()SS_between # 1.266666666666667
You can verify that:
SS_total = SS_between + SS_within
With all the values computed, you can now complete the ANOVA table. Recall you have the following variables:
You can compute the various degrees of freedoms as follows:
df_total = observation_size - 1 # 29df_within = observation_size - k # 27df_between = k - 1 # 2
From the above, compute the various mean squared values:
mean_sq_between = SS_between / (k - 1) # 0.6333333333333335mean_sq_within = \ SS_within / (observation_size - k) # 37.08888888888889
Finally, you can calculate the F-value, which is the ratio of two variances:
F = mean_sq_between / mean_sq_within # 0.017076093469143204
Recall earlier that I mentioned ANOVA uses the f-tests to statistically test the equality of means.
Once the F-value is obtained, you now have to refer to the f-distribution table (see http://www.socr.ucla.edu/Applets.dir/F_Table.html for one example) to obtain the f-critical value. The f-distribution table is organized based on the α value (usually 0.05). So you need to first locate the table based on α=0.05:
Next, observe that the columns of the f-distribution table is based on df1 while the rows are based on df2. You can get your df1 and df2 from the previous variables that we have created:
df1 = df_between # 2df2 = df_within # 27
Using the values of df1 and df2, you can now locate the f-critical value by locating the df1 column and df2 row:
From the above figure, you can see that the f-critical value is 3.3541. Using this value, you can now decide if you will accept or reject the null hypothesis using the F-distribution curve:
Since the f-value (0.0171, which is what we can calculated) is less than the f-critical value in the f-distribution table, we accept the null hypothesis — this means there is no variance in different groups — all the means are the same.
For machine learning, this feature — drink_type, should not be included for training as it seems the different types of drinks have no effect on the reaction time.
You should only include a feature for training only if you reject the null hypothesis as this means that the values in the drink types have an effect on the reaction time.
In the previous section, we manually calculated the f-value for our dataset. Actually, there is an easier way — use the stats module’s f_oneway() function to calculate the f-value and p-value:
import scipy.stats as statsfvalue, pvalue = stats.f_oneway( df.iloc[:-1,0], df.iloc[:-1,1], df.iloc[:-1,2])print(fvalue, pvalue) # 0.0170760934691432 0.9830794846682348
The f_oneway() function takes the groups as input and returns the ANOVA F and p-value:
In the above, the f-value is 0.0170760934691432 (identical to the one we calculated manually) and the p-value is 0.9830794846682348.
Observe that the f_oneway() function takes in a variable number of arguments:
If you have many groups, it would be quite tedious to pass in the values of all the groups one by one. So, there is an easier way:
fvalue, pvalue = stats.f_oneway( *df.iloc[:-1,0:3].T.values)
I will leave the above as an exercise for you to understand how it works.
Another way to calculate the f-value is to use the statsmodel module. You first build the model using the ols() function, and then call the fit() function on the instance of the model. Finally, you call the anova_lm() function on the fitted model and specify the type of ANOVA test to perform on it:
There are 3 types of ANOVA tests to perform, but their discussion is beyond the scope of this article.
import pandas as pdimport statsmodels.api as smfrom statsmodels.formula.api import olsdf = pd.read_csv('drinks.csv')model = ols('reaction_time ~ drink_type', data=df).fit()sm.stats.anova_lm(model, typ=2)
The above code snippet produces the following result, which is the same as the f-value that we calculated earlier (0.017076):
The anova_lm() function also returns the p-value (0.983079). You can make use of the following rules to determine if the categorical variable has any influence on the numerical variable:
if p < 0.05, this means that the categorical variable has significant influence on the numerical variable
if p > 0.05, this means that the categorical variable has no significant influence on the numerical variable
Since the p-value is now 0.983079 (>0.05), this means that the drink_type has no significant influence on the reaction_time.
In this article, I have explained how ANOVA helps to determine if a categorical variable has influence on a numerical variable. So far the ANOVA test that we have discussed is known as the one-way ANOVA test. There are a few variations of ANOVA:
One-way ANOVA— used to check how a numerical variable responds to the levels of one independent categorical variables
Two-way ANOVA —used to check how a numerical variable responds to the levels of two independent categorical variables
Multi-way ANOVA — used to check how a numerical variable responds to the levels of multiple independent categorical variables
Using a two-way ANOVA or multi-way ANOVA, you can investigate the combined impact of two (or more) independent categorical variables on one dependent numerical variable.
I hope you find this article useful. Stay tuned for the next article!
|
[
{
"code": null,
"e": 601,
"s": 172,
"text": "In my previous article, I talked about using the chi-square statistics to select features from a dataset for machine learning. The chi-square test is used when both your independent and dependent variables are all categorical variables. However, what if your independent variable is categorical and your dependent variable is numerical? In this case, you have to use another statistic test known as ANOVA — Analysis of Variance."
},
{
"code": null,
"e": 813,
"s": 601,
"text": "And so in this article, our discussion will revolve around ANOVA and how you use it in machine learning for feature selection. Like all my previous articles, I will use a concrete example to explain the concept."
},
{
"code": null,
"e": 938,
"s": 813,
"text": "Before we get started, it is useful to summarize the different methods for feature selection that we have discussed so far :"
},
{
"code": null,
"e": 1271,
"s": 938,
"text": "If you need a refresher on Pearson correlation, Spearman’s rank correlation, and Chi-Square, I suggest you go and check them out now (see the links below) and come back to this article once you are done. Some of the concepts discussed in this article is similar to that of the chi-square test, and so I recommend you check that out."
},
{
"code": null,
"e": 1294,
"s": 1271,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 1317,
"s": 1294,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 1340,
"s": 1317,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 1388,
"s": 1340,
"text": "ANOVA is used for testing two variables, where:"
},
{
"code": null,
"e": 1418,
"s": 1388,
"text": "one is a categorical variable"
},
{
"code": null,
"e": 1450,
"s": 1418,
"text": "another is a numerical variable"
},
{
"code": null,
"e": 1553,
"s": 1450,
"text": "ANOVA is used when the categorical variable has at least 3 groups (i.e three different unique values)."
},
{
"code": null,
"e": 1649,
"s": 1553,
"text": "If you want to compare just two groups, use the t-test. I will cover t-test in another article."
},
{
"code": null,
"e": 1756,
"s": 1649,
"text": "ANOVA lets you know if your numerical variable changes according to the level of the categorical variable."
},
{
"code": null,
"e": 1918,
"s": 1756,
"text": "ANOVA uses the f-tests to statistically test the equality of means. F-tests are named after its test statistic, F, which was named in honor of Sir Ronald Fisher."
},
{
"code": null,
"e": 2000,
"s": 1918,
"text": "Here are some examples that makes it easier to understand when you can use ANOVA."
},
{
"code": null,
"e": 2138,
"s": 2000,
"text": "You have a dataset containing information of a group of people pertaining to their social media usage and the number of hours they sleep:"
},
{
"code": null,
"e": 2292,
"s": 2138,
"text": "You want to find out if the amount of social media usage (categorical variable) has a direct impact on the number of hours of sleep (numerical variable)."
},
{
"code": null,
"e": 2417,
"s": 2292,
"text": "You have a dataset containing three different brands of medication and the number of days for the medication to take effect:"
},
{
"code": null,
"e": 2520,
"s": 2417,
"text": "You want to find out if there is a direct relationship between a specific brand and its effectiveness."
},
{
"code": null,
"e": 2643,
"s": 2520,
"text": "ANOVA checks whether there is equal variance between groups of categorical feature with respect to the numerical response."
},
{
"code": null,
"e": 2819,
"s": 2643,
"text": "If there is equal variance between groups, it means this feature has no impact on the response and hence it (the categorical variable) cannot be considered for model training."
},
{
"code": null,
"e": 3029,
"s": 2819,
"text": "The best way to understand ANOVA is to use an example. In the following example, I use a fictitious dataset where I recorded the reaction time of a group of people when they are given a specific type of drink."
},
{
"code": null,
"e": 3104,
"s": 3029,
"text": "I have a sample dataset named drinks.csv containing the following content:"
},
{
"code": null,
"e": 3437,
"s": 3104,
"text": "team,drink_type,reaction_time1,water,142,water,253,water,234,water,275,water,286,water,217,water,268,water,309,water,3110,water,341,coke,25 2,coke,263,coke,274,coke,295,coke,256,coke,237,coke,228,coke,279,coke,2910,coke,211,coffee,82,coffee,203,coffee,264,coffee,365,coffee,396,coffee,237,coffee,258,coffee,289,coffee,2710,coffee,25"
},
{
"code": null,
"e": 3797,
"s": 3437,
"text": "There are 10 teams in all — each team comprises of 3 persons. Each person in the team is given three different types of drinks — water, coke, and coffee. After consuming the drink, they were asked to perform some activities and their reaction time recorded. The aim of this experiment is to determine if the drinks have any effect on a person’s reaction time."
},
{
"code": null,
"e": 3851,
"s": 3797,
"text": "Let’s first load the dataset into a Pandas DataFrame:"
},
{
"code": null,
"e": 3901,
"s": 3851,
"text": "import pandas as pddf = pd.read_csv('drinks.csv')"
},
{
"code": null,
"e": 3963,
"s": 3901,
"text": "Record the observation size, which we will make use of later:"
},
{
"code": null,
"e": 4021,
"s": 3963,
"text": "observation_size = df.shape[0] # number of observations"
},
{
"code": null,
"e": 4093,
"s": 4021,
"text": "It is useful to visualize the distribution of the data using a Boxplot:"
},
{
"code": null,
"e": 4142,
"s": 4093,
"text": "_ = df.boxplot('reaction_time', by='drink_type')"
},
{
"code": null,
"e": 4227,
"s": 4142,
"text": "You can see that the three types of drinks have about the same median reaction time."
},
{
"code": null,
"e": 4300,
"s": 4227,
"text": "To facilitate the calculation for ANOVA, we need to pivot the dataframe:"
},
{
"code": null,
"e": 4361,
"s": 4300,
"text": "df = df.pivot(columns='drink_type', index='team')display(df)"
},
{
"code": null,
"e": 4597,
"s": 4361,
"text": "The columns represent the three different types of drinks and the rows represents the 10 teams. We will also use this chance to record the number of items in each group, as well as the number of groups, which we will make use of later:"
},
{
"code": null,
"e": 4690,
"s": 4597,
"text": "n = df.shape[0] # 10; number of items in each groupk = df.shape[1] # 3; number of groups"
},
{
"code": null,
"e": 4793,
"s": 4690,
"text": "You now define your null hypothesis and alternate hypothesis, just like the chi-square test. They are:"
},
{
"code": null,
"e": 4863,
"s": 4793,
"text": "H0 (Null hypothesis) — that there is no difference among group means."
},
{
"code": null,
"e": 4986,
"s": 4863,
"text": "H1 (Alternate hypothesis) — that at least one group differs significantly from the overall mean of the dependent variable."
},
{
"code": null,
"e": 5083,
"s": 4986,
"text": "We are now ready to begin our calculations for ANOVA. First, let’s find the mean for each group:"
},
{
"code": null,
"e": 5119,
"s": 5083,
"text": "df.loc['Group Means'] = df.mean()df"
},
{
"code": null,
"e": 5170,
"s": 5119,
"text": "From here, you can now calculate the overall mean:"
},
{
"code": null,
"e": 5240,
"s": 5170,
"text": "overall_mean = df.iloc[-1].mean()overall_mean # 25.666666666666668"
},
{
"code": null,
"e": 5329,
"s": 5240,
"text": "Now that we have calculated the overall mean, we can proceed to calculate the following:"
},
{
"code": null,
"e": 5374,
"s": 5329,
"text": "Sum of squares of all observation — SS_total"
},
{
"code": null,
"e": 5408,
"s": 5374,
"text": "Sum of squares within — SS_within"
},
{
"code": null,
"e": 5444,
"s": 5408,
"text": "Sum of squares between — SS_between"
},
{
"code": null,
"e": 5602,
"s": 5444,
"text": "The sum of squares of all observation is calculated by deducting each observation from the overall mean, and then summing all the squares of the differences:"
},
{
"code": null,
"e": 5645,
"s": 5602,
"text": "Programmatically, SS_total is computed as:"
},
{
"code": null,
"e": 5736,
"s": 5645,
"text": "SS_total = (((df.iloc[:-1] - overall_mean)**2).sum()).sum()SS_total # 1002.6666666666667"
},
{
"code": null,
"e": 5832,
"s": 5736,
"text": "The sum of squares within is the sum of squared deviations of scores around their group’s mean:"
},
{
"code": null,
"e": 5876,
"s": 5832,
"text": "Programmatically, SS_within is computed as:"
},
{
"code": null,
"e": 5958,
"s": 5876,
"text": "SS_within = (((df.iloc[:-1] - df.iloc[-1])**2).sum()).sum() SS_within # 1001.4"
},
{
"code": null,
"e": 6037,
"s": 5958,
"text": "Next we calculate the sum of squares of the group means from the overall mean:"
},
{
"code": null,
"e": 6082,
"s": 6037,
"text": "Programmatically, SS_between is computed as:"
},
{
"code": null,
"e": 6172,
"s": 6082,
"text": "SS_between = (n * (df.iloc[-1] - overall_mean)**2).sum()SS_between # 1.266666666666667"
},
{
"code": null,
"e": 6193,
"s": 6172,
"text": "You can verify that:"
},
{
"code": null,
"e": 6227,
"s": 6193,
"text": "SS_total = SS_between + SS_within"
},
{
"code": null,
"e": 6336,
"s": 6227,
"text": "With all the values computed, you can now complete the ANOVA table. Recall you have the following variables:"
},
{
"code": null,
"e": 6396,
"s": 6336,
"text": "You can compute the various degrees of freedoms as follows:"
},
{
"code": null,
"e": 6525,
"s": 6396,
"text": "df_total = observation_size - 1 # 29df_within = observation_size - k # 27df_between = k - 1 # 2"
},
{
"code": null,
"e": 6582,
"s": 6525,
"text": "From the above, compute the various mean squared values:"
},
{
"code": null,
"e": 6728,
"s": 6582,
"text": "mean_sq_between = SS_between / (k - 1) # 0.6333333333333335mean_sq_within = \\ SS_within / (observation_size - k) # 37.08888888888889"
},
{
"code": null,
"e": 6805,
"s": 6728,
"text": "Finally, you can calculate the F-value, which is the ratio of two variances:"
},
{
"code": null,
"e": 6872,
"s": 6805,
"text": "F = mean_sq_between / mean_sq_within # 0.017076093469143204"
},
{
"code": null,
"e": 6972,
"s": 6872,
"text": "Recall earlier that I mentioned ANOVA uses the f-tests to statistically test the equality of means."
},
{
"code": null,
"e": 7286,
"s": 6972,
"text": "Once the F-value is obtained, you now have to refer to the f-distribution table (see http://www.socr.ucla.edu/Applets.dir/F_Table.html for one example) to obtain the f-critical value. The f-distribution table is organized based on the α value (usually 0.05). So you need to first locate the table based on α=0.05:"
},
{
"code": null,
"e": 7473,
"s": 7286,
"text": "Next, observe that the columns of the f-distribution table is based on df1 while the rows are based on df2. You can get your df1 and df2 from the previous variables that we have created:"
},
{
"code": null,
"e": 7521,
"s": 7473,
"text": "df1 = df_between # 2df2 = df_within # 27"
},
{
"code": null,
"e": 7634,
"s": 7521,
"text": "Using the values of df1 and df2, you can now locate the f-critical value by locating the df1 column and df2 row:"
},
{
"code": null,
"e": 7824,
"s": 7634,
"text": "From the above figure, you can see that the f-critical value is 3.3541. Using this value, you can now decide if you will accept or reject the null hypothesis using the F-distribution curve:"
},
{
"code": null,
"e": 8061,
"s": 7824,
"text": "Since the f-value (0.0171, which is what we can calculated) is less than the f-critical value in the f-distribution table, we accept the null hypothesis — this means there is no variance in different groups — all the means are the same."
},
{
"code": null,
"e": 8225,
"s": 8061,
"text": "For machine learning, this feature — drink_type, should not be included for training as it seems the different types of drinks have no effect on the reaction time."
},
{
"code": null,
"e": 8397,
"s": 8225,
"text": "You should only include a feature for training only if you reject the null hypothesis as this means that the values in the drink types have an effect on the reaction time."
},
{
"code": null,
"e": 8590,
"s": 8397,
"text": "In the previous section, we manually calculated the f-value for our dataset. Actually, there is an easier way — use the stats module’s f_oneway() function to calculate the f-value and p-value:"
},
{
"code": null,
"e": 8773,
"s": 8590,
"text": "import scipy.stats as statsfvalue, pvalue = stats.f_oneway( df.iloc[:-1,0], df.iloc[:-1,1], df.iloc[:-1,2])print(fvalue, pvalue) # 0.0170760934691432 0.9830794846682348"
},
{
"code": null,
"e": 8860,
"s": 8773,
"text": "The f_oneway() function takes the groups as input and returns the ANOVA F and p-value:"
},
{
"code": null,
"e": 8993,
"s": 8860,
"text": "In the above, the f-value is 0.0170760934691432 (identical to the one we calculated manually) and the p-value is 0.9830794846682348."
},
{
"code": null,
"e": 9071,
"s": 8993,
"text": "Observe that the f_oneway() function takes in a variable number of arguments:"
},
{
"code": null,
"e": 9202,
"s": 9071,
"text": "If you have many groups, it would be quite tedious to pass in the values of all the groups one by one. So, there is an easier way:"
},
{
"code": null,
"e": 9266,
"s": 9202,
"text": "fvalue, pvalue = stats.f_oneway( *df.iloc[:-1,0:3].T.values)"
},
{
"code": null,
"e": 9340,
"s": 9266,
"text": "I will leave the above as an exercise for you to understand how it works."
},
{
"code": null,
"e": 9640,
"s": 9340,
"text": "Another way to calculate the f-value is to use the statsmodel module. You first build the model using the ols() function, and then call the fit() function on the instance of the model. Finally, you call the anova_lm() function on the fitted model and specify the type of ANOVA test to perform on it:"
},
{
"code": null,
"e": 9743,
"s": 9640,
"text": "There are 3 types of ANOVA tests to perform, but their discussion is beyond the scope of this article."
},
{
"code": null,
"e": 9947,
"s": 9743,
"text": "import pandas as pdimport statsmodels.api as smfrom statsmodels.formula.api import olsdf = pd.read_csv('drinks.csv')model = ols('reaction_time ~ drink_type', data=df).fit()sm.stats.anova_lm(model, typ=2)"
},
{
"code": null,
"e": 10073,
"s": 9947,
"text": "The above code snippet produces the following result, which is the same as the f-value that we calculated earlier (0.017076):"
},
{
"code": null,
"e": 10260,
"s": 10073,
"text": "The anova_lm() function also returns the p-value (0.983079). You can make use of the following rules to determine if the categorical variable has any influence on the numerical variable:"
},
{
"code": null,
"e": 10366,
"s": 10260,
"text": "if p < 0.05, this means that the categorical variable has significant influence on the numerical variable"
},
{
"code": null,
"e": 10475,
"s": 10366,
"text": "if p > 0.05, this means that the categorical variable has no significant influence on the numerical variable"
},
{
"code": null,
"e": 10600,
"s": 10475,
"text": "Since the p-value is now 0.983079 (>0.05), this means that the drink_type has no significant influence on the reaction_time."
},
{
"code": null,
"e": 10846,
"s": 10600,
"text": "In this article, I have explained how ANOVA helps to determine if a categorical variable has influence on a numerical variable. So far the ANOVA test that we have discussed is known as the one-way ANOVA test. There are a few variations of ANOVA:"
},
{
"code": null,
"e": 10964,
"s": 10846,
"text": "One-way ANOVA— used to check how a numerical variable responds to the levels of one independent categorical variables"
},
{
"code": null,
"e": 11082,
"s": 10964,
"text": "Two-way ANOVA —used to check how a numerical variable responds to the levels of two independent categorical variables"
},
{
"code": null,
"e": 11208,
"s": 11082,
"text": "Multi-way ANOVA — used to check how a numerical variable responds to the levels of multiple independent categorical variables"
},
{
"code": null,
"e": 11378,
"s": 11208,
"text": "Using a two-way ANOVA or multi-way ANOVA, you can investigate the combined impact of two (or more) independent categorical variables on one dependent numerical variable."
}
] |
UPDATE column to append data into it in MySQL?
|
To achieve this, the following is the syntax.
UPDATE yourTableName set
yourColumnName=concat(ifnull(yourColumnName,””),’anyValue1,anyValue2,anyValue);
To understand the above syntax, let us first create a table. The query to create a table is as follows -
mysql> create table AppendDataDemo
-> (
-> StudentId int,
-> StudentName varchar(100),
-> StudentAge int
-> );
Query OK, 0 rows affected (1.54 sec)
Insert some records in the table using insert command. The query is as follows.
mysql> insert into AppendDataDemo values(101,'John',23);
Query OK, 1 row affected (0.24 sec)
mysql> insert into AppendDataDemo values(102,null,24);
Query OK, 1 row affected (0.74 sec)
mysql> insert into AppendDataDemo values(103,'Mike',26);
Query OK, 1 row affected (0.12 sec)
Display all records from the table using select statement. The query is as follows.
mysql> select *from AppendDataDemo;
The following is the output.
+-----------+-------------+------------+
| StudentId | StudentName | StudentAge |
+-----------+-------------+------------+
| 101 | John | 23 |
| 102 | NULL | 24 |
| 103 | Mike | 26 |
+-----------+-------------+------------+
3 rows in set (0.00 sec)
The following is the query to update the column StudentName and append “Carol, Sam, Maria” to its data.
mysql> update AppendDataDemo set StudentName=concat(ifnull(StudentName,""), ' Carol,Sam,Maria');
Query OK, 3 rows affected (0.14 sec)
Rows matched: 3 Changed: 3 Warnings: 0
Check the table records from the table using select statement. The query is as follows.
mysql> select *from AppendDataDemo;
The following is the output displaying appened data.
+-----------+----------------------+------------+
| StudentId | StudentName | StudentAge |
+-----------+----------------------+------------+
| 101 | John Carol,Sam,Maria | 23 |
| 102 | Carol,Sam,Maria | 24 |
| 103 | Mike Carol,Sam,Maria | 26 |
+-----------+----------------------+------------+
3 rows in set (0.03 sec)
|
[
{
"code": null,
"e": 1108,
"s": 1062,
"text": "To achieve this, the following is the syntax."
},
{
"code": null,
"e": 1213,
"s": 1108,
"text": "UPDATE yourTableName set\nyourColumnName=concat(ifnull(yourColumnName,””),’anyValue1,anyValue2,anyValue);"
},
{
"code": null,
"e": 1318,
"s": 1213,
"text": "To understand the above syntax, let us first create a table. The query to create a table is as follows -"
},
{
"code": null,
"e": 1466,
"s": 1318,
"text": "mysql> create table AppendDataDemo\n-> (\n-> StudentId int,\n-> StudentName varchar(100),\n-> StudentAge int\n-> );\nQuery OK, 0 rows affected (1.54 sec)"
},
{
"code": null,
"e": 1546,
"s": 1466,
"text": "Insert some records in the table using insert command. The query is as follows."
},
{
"code": null,
"e": 1825,
"s": 1546,
"text": "mysql> insert into AppendDataDemo values(101,'John',23);\nQuery OK, 1 row affected (0.24 sec)\n\nmysql> insert into AppendDataDemo values(102,null,24);\nQuery OK, 1 row affected (0.74 sec)\n\nmysql> insert into AppendDataDemo values(103,'Mike',26);\nQuery OK, 1 row affected (0.12 sec)"
},
{
"code": null,
"e": 1909,
"s": 1825,
"text": "Display all records from the table using select statement. The query is as follows."
},
{
"code": null,
"e": 1945,
"s": 1909,
"text": "mysql> select *from AppendDataDemo;"
},
{
"code": null,
"e": 1974,
"s": 1945,
"text": "The following is the output."
},
{
"code": null,
"e": 2286,
"s": 1974,
"text": "+-----------+-------------+------------+\n| StudentId | StudentName | StudentAge |\n+-----------+-------------+------------+\n| 101 | John | 23 |\n| 102 | NULL | 24 |\n| 103 | Mike | 26 |\n+-----------+-------------+------------+\n3 rows in set (0.00 sec)"
},
{
"code": null,
"e": 2390,
"s": 2286,
"text": "The following is the query to update the column StudentName and append “Carol, Sam, Maria” to its data."
},
{
"code": null,
"e": 2563,
"s": 2390,
"text": "mysql> update AppendDataDemo set StudentName=concat(ifnull(StudentName,\"\"), ' Carol,Sam,Maria');\nQuery OK, 3 rows affected (0.14 sec)\nRows matched: 3 Changed: 3 Warnings: 0"
},
{
"code": null,
"e": 2651,
"s": 2563,
"text": "Check the table records from the table using select statement. The query is as follows."
},
{
"code": null,
"e": 2687,
"s": 2651,
"text": "mysql> select *from AppendDataDemo;"
},
{
"code": null,
"e": 2740,
"s": 2687,
"text": "The following is the output displaying appened data."
},
{
"code": null,
"e": 3115,
"s": 2740,
"text": "+-----------+----------------------+------------+\n| StudentId | StudentName | StudentAge |\n+-----------+----------------------+------------+\n| 101 | John Carol,Sam,Maria | 23 |\n| 102 | Carol,Sam,Maria | 24 |\n| 103 | Mike Carol,Sam,Maria | 26 |\n+-----------+----------------------+------------+\n3 rows in set (0.03 sec)"
}
] |
C++ String Library - operator+=
|
It extends the string by appending additional characters at the end of its current value.
Following is the declaration for std::string::operator+=
string& operator+= (const string& str);
string& operator+= (const string& str);
str − It is a string object.
str − It is a string object.
c − It is a character object.
c − It is a character object.
It returns *this.
if an exception is thrown, there are no changes in the string.
In below example for std::string::operator+=.
#include <iostream>
#include <string>
int main () {
std::string name ("Sairamkrishna");
std::string family ("Mammahe");
name += " Prasad. ";
name += family;
name += '\n';
std::cout << name;
return 0;
}
Sairamkrishna Prasad. Mammahe
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2693,
"s": 2603,
"text": "It extends the string by appending additional characters at the end of its current value."
},
{
"code": null,
"e": 2750,
"s": 2693,
"text": "Following is the declaration for std::string::operator+="
},
{
"code": null,
"e": 2790,
"s": 2750,
"text": "string& operator+= (const string& str);"
},
{
"code": null,
"e": 2830,
"s": 2790,
"text": "string& operator+= (const string& str);"
},
{
"code": null,
"e": 2859,
"s": 2830,
"text": "str − It is a string object."
},
{
"code": null,
"e": 2888,
"s": 2859,
"text": "str − It is a string object."
},
{
"code": null,
"e": 2918,
"s": 2888,
"text": "c − It is a character object."
},
{
"code": null,
"e": 2948,
"s": 2918,
"text": "c − It is a character object."
},
{
"code": null,
"e": 2966,
"s": 2948,
"text": "It returns *this."
},
{
"code": null,
"e": 3029,
"s": 2966,
"text": "if an exception is thrown, there are no changes in the string."
},
{
"code": null,
"e": 3075,
"s": 3029,
"text": "In below example for std::string::operator+=."
},
{
"code": null,
"e": 3300,
"s": 3075,
"text": "#include <iostream>\n#include <string>\n\nint main () {\n std::string name (\"Sairamkrishna\");\n std::string family (\"Mammahe\");\n name += \" Prasad. \";\n name += family;\n name += '\\n';\n\n std::cout << name;\n return 0;\n}"
},
{
"code": null,
"e": 3331,
"s": 3300,
"text": "Sairamkrishna Prasad. Mammahe\n"
},
{
"code": null,
"e": 3338,
"s": 3331,
"text": " Print"
},
{
"code": null,
"e": 3349,
"s": 3338,
"text": " Add Notes"
}
] |
Lodash _.isNull() Method - GeeksforGeeks
|
05 Sep, 2020
Lodash is a JavaScript library that works on the top of underscore.js. Lodash helps in working with arrays, strings, objects, numbers, etc.
The _.isNull() method is used to find whether the value of the object is null. If the value is null then returns true otherwise it returns false.
Syntax:
_.isNull(value)
Parameters: This method accepts a single parameter as mentioned above and described below:
value: This parameter holds the value to check.
Return Value: This method returns true if the value is null, else false.
Example 1: Here, const _ = require(‘lodash’) is used to import the lodash library into the file.
Javascript
// Requiring the lodash library const _ = require("lodash"); // Use of _.isNull() // method let gfg = _.isNull(null); // Printing the output console.log(gfg);
Output:
true
Example 2:
Javascript
// Requiring the lodash library const _ = require("lodash"); // Use of _.isNull() // method let gfg = _.isNull(void 0); // Printing the output console.log(gfg);
Output:
false
Example 3:
Javascript
// Requiring the lodash library const _ = require("lodash"); // Use of _.isNull() // method let gfg = _.isNull(NaN); // Printing the output console.log(gfg);
Output:
false
JavaScript-Lodash
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?
Remove elements from a JavaScript Array
How to get selected value in dropdown list using JavaScript ?
Top 10 Front End Developer Skills That You Need in 2022
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
|
[
{
"code": null,
"e": 24909,
"s": 24881,
"text": "\n05 Sep, 2020"
},
{
"code": null,
"e": 25049,
"s": 24909,
"text": "Lodash is a JavaScript library that works on the top of underscore.js. Lodash helps in working with arrays, strings, objects, numbers, etc."
},
{
"code": null,
"e": 25195,
"s": 25049,
"text": "The _.isNull() method is used to find whether the value of the object is null. If the value is null then returns true otherwise it returns false."
},
{
"code": null,
"e": 25203,
"s": 25195,
"text": "Syntax:"
},
{
"code": null,
"e": 25219,
"s": 25203,
"text": "_.isNull(value)"
},
{
"code": null,
"e": 25310,
"s": 25219,
"text": "Parameters: This method accepts a single parameter as mentioned above and described below:"
},
{
"code": null,
"e": 25358,
"s": 25310,
"text": "value: This parameter holds the value to check."
},
{
"code": null,
"e": 25431,
"s": 25358,
"text": "Return Value: This method returns true if the value is null, else false."
},
{
"code": null,
"e": 25528,
"s": 25431,
"text": "Example 1: Here, const _ = require(‘lodash’) is used to import the lodash library into the file."
},
{
"code": null,
"e": 25539,
"s": 25528,
"text": "Javascript"
},
{
"code": "// Requiring the lodash library const _ = require(\"lodash\"); // Use of _.isNull() // method let gfg = _.isNull(null); // Printing the output console.log(gfg);",
"e": 25715,
"s": 25539,
"text": null
},
{
"code": null,
"e": 25723,
"s": 25715,
"text": "Output:"
},
{
"code": null,
"e": 25728,
"s": 25723,
"text": "true"
},
{
"code": null,
"e": 25741,
"s": 25728,
"text": "Example 2: "
},
{
"code": null,
"e": 25752,
"s": 25741,
"text": "Javascript"
},
{
"code": "// Requiring the lodash library const _ = require(\"lodash\"); // Use of _.isNull() // method let gfg = _.isNull(void 0); // Printing the output console.log(gfg);",
"e": 25930,
"s": 25752,
"text": null
},
{
"code": null,
"e": 25938,
"s": 25930,
"text": "Output:"
},
{
"code": null,
"e": 25944,
"s": 25938,
"text": "false"
},
{
"code": null,
"e": 25957,
"s": 25944,
"text": "Example 3: "
},
{
"code": null,
"e": 25968,
"s": 25957,
"text": "Javascript"
},
{
"code": "// Requiring the lodash library const _ = require(\"lodash\"); // Use of _.isNull() // method let gfg = _.isNull(NaN); // Printing the output console.log(gfg);",
"e": 26143,
"s": 25968,
"text": null
},
{
"code": null,
"e": 26151,
"s": 26143,
"text": "Output:"
},
{
"code": null,
"e": 26157,
"s": 26151,
"text": "false"
},
{
"code": null,
"e": 26175,
"s": 26157,
"text": "JavaScript-Lodash"
},
{
"code": null,
"e": 26186,
"s": 26175,
"text": "JavaScript"
},
{
"code": null,
"e": 26203,
"s": 26186,
"text": "Web Technologies"
},
{
"code": null,
"e": 26301,
"s": 26203,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26310,
"s": 26301,
"text": "Comments"
},
{
"code": null,
"e": 26323,
"s": 26310,
"text": "Old Comments"
},
{
"code": null,
"e": 26384,
"s": 26323,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 26425,
"s": 26384,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 26479,
"s": 26425,
"text": "How to get character array from string in JavaScript?"
},
{
"code": null,
"e": 26519,
"s": 26479,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 26581,
"s": 26519,
"text": "How to get selected value in dropdown list using JavaScript ?"
},
{
"code": null,
"e": 26637,
"s": 26581,
"text": "Top 10 Front End Developer Skills That You Need in 2022"
},
{
"code": null,
"e": 26670,
"s": 26637,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 26732,
"s": 26670,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 26775,
"s": 26732,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
Running Docker Container as a Non Root User
|
When you run an application inside a Docker Container, by default it has access to all the root privileges. You might have noticed that when you open an Ubuntu Docker Container Bash, you are logged in as the root user by default. This can prove to be a major concern in terms of security of the application. Any outsider can misuse this and hack the entire Container along with all the other files and applications running inside the Docker Container. Hence, it becomes very important to perform most of the trivial operations as a non root user wherever possible.
In this article, we will be discussing two methods to access the Docker Container as a Non Root User.
Adding a User to the Docker Group
Adding a User to the Docker Group
You can try to run Docker Containers as a Non Root User by adding Users to the Docker Group. If there is no Docker group, you can always create one.
You can create a Docker Group using the following command.
sudo groupadd docker
If there is already a Docker group in your local machine, the output of the below command would be −
groupadd: group 'docker' already exists
After you have created the Docker Group, you can now add Non Root Users using the following command.
sudo usermod −aG docker [non−root user]
To verify the group membership, you need to re−login to your Docker.
Using Dockerfile
Using Dockerfile
Another simpler solution to access a Docker Container using Non Root User, is to specify the instructions in the Dockerfile. Docker allows you to add the User using the −u flag along with the useradd command and then using the USER instruction, you can decide which user you want to be logged in as when you start the Docker Container.
Look at the Dockerfile below.
#Pull the base image as Ubuntu
FROM ubuntu:latest
#Add a user with userid 8877 and name nonroot
RUN useradd −u 8877 nonroot
#Run Container as nonroot
USER nonroot
In the above Dockerfile, Ubuntu is the base Docker Image pulled from the Docker registry. The useradd command along with the -u flag adds a user with the specified name and Id using the Docker RUN instruction. The USER instruction is used to specify which user to be logged in while running the Docker Container associated with the image.
To build the Docker Image using the above Dockerfile, you can use the following Docker Build command.
sudo docker build −t my−image .
Run the Docker Container associated with the Docker Image.
sudo docker run −it my−image bash
This opens the bash of the ubuntu Container. To verify that you have been logged in as a non−root user, you can use the id command.
id
You will find that the Docker Container’s user and group are now changed to the Non−Root user that you had specified in the Dockerfile.
Majority of the Docker Users either forget or don’t find it necessary to change their user privileges and switch to Non Root user. It is a bad practice and always poses a threat when the application is deployed and made public. Not only it poses a threat to that particular application, but also through the application, hackers can manipulate the entire filesystem of the Docker Container inside which the application is running along with other important applications that might be deployed inside the same Docker Container.
In this article, we saw two different methods through which you can switch the current user as a non root user. The process discussed in Method 2 is better and widely used due to the fact that almost all the Docker applications require a Dockerfile to maintain the Container and using two simple additional statements, you can make the switch.
|
[
{
"code": null,
"e": 1627,
"s": 1062,
"text": "When you run an application inside a Docker Container, by default it has access to all the root privileges. You might have noticed that when you open an Ubuntu Docker Container Bash, you are logged in as the root user by default. This can prove to be a major concern in terms of security of the application. Any outsider can misuse this and hack the entire Container along with all the other files and applications running inside the Docker Container. Hence, it becomes very important to perform most of the trivial operations as a non root user wherever possible."
},
{
"code": null,
"e": 1729,
"s": 1627,
"text": "In this article, we will be discussing two methods to access the Docker Container as a Non Root User."
},
{
"code": null,
"e": 1764,
"s": 1729,
"text": " Adding a User to the Docker Group"
},
{
"code": null,
"e": 1799,
"s": 1764,
"text": " Adding a User to the Docker Group"
},
{
"code": null,
"e": 1948,
"s": 1799,
"text": "You can try to run Docker Containers as a Non Root User by adding Users to the Docker Group. If there is no Docker group, you can always create one."
},
{
"code": null,
"e": 2007,
"s": 1948,
"text": "You can create a Docker Group using the following command."
},
{
"code": null,
"e": 2028,
"s": 2007,
"text": "sudo groupadd docker"
},
{
"code": null,
"e": 2129,
"s": 2028,
"text": "If there is already a Docker group in your local machine, the output of the below command would be −"
},
{
"code": null,
"e": 2169,
"s": 2129,
"text": "groupadd: group 'docker' already exists"
},
{
"code": null,
"e": 2270,
"s": 2169,
"text": "After you have created the Docker Group, you can now add Non Root Users using the following command."
},
{
"code": null,
"e": 2310,
"s": 2270,
"text": "sudo usermod −aG docker [non−root user]"
},
{
"code": null,
"e": 2379,
"s": 2310,
"text": "To verify the group membership, you need to re−login to your Docker."
},
{
"code": null,
"e": 2396,
"s": 2379,
"text": "Using Dockerfile"
},
{
"code": null,
"e": 2413,
"s": 2396,
"text": "Using Dockerfile"
},
{
"code": null,
"e": 2749,
"s": 2413,
"text": "Another simpler solution to access a Docker Container using Non Root User, is to specify the instructions in the Dockerfile. Docker allows you to add the User using the −u flag along with the useradd command and then using the USER instruction, you can decide which user you want to be logged in as when you start the Docker Container."
},
{
"code": null,
"e": 2779,
"s": 2749,
"text": "Look at the Dockerfile below."
},
{
"code": null,
"e": 2944,
"s": 2779,
"text": "#Pull the base image as Ubuntu\nFROM ubuntu:latest\n\n#Add a user with userid 8877 and name nonroot\nRUN useradd −u 8877 nonroot\n\n#Run Container as nonroot\nUSER nonroot"
},
{
"code": null,
"e": 3283,
"s": 2944,
"text": "In the above Dockerfile, Ubuntu is the base Docker Image pulled from the Docker registry. The useradd command along with the -u flag adds a user with the specified name and Id using the Docker RUN instruction. The USER instruction is used to specify which user to be logged in while running the Docker Container associated with the image."
},
{
"code": null,
"e": 3385,
"s": 3283,
"text": "To build the Docker Image using the above Dockerfile, you can use the following Docker Build command."
},
{
"code": null,
"e": 3417,
"s": 3385,
"text": "sudo docker build −t my−image ."
},
{
"code": null,
"e": 3476,
"s": 3417,
"text": "Run the Docker Container associated with the Docker Image."
},
{
"code": null,
"e": 3510,
"s": 3476,
"text": "sudo docker run −it my−image bash"
},
{
"code": null,
"e": 3642,
"s": 3510,
"text": "This opens the bash of the ubuntu Container. To verify that you have been logged in as a non−root user, you can use the id command."
},
{
"code": null,
"e": 3646,
"s": 3642,
"text": "id\n"
},
{
"code": null,
"e": 3782,
"s": 3646,
"text": "You will find that the Docker Container’s user and group are now changed to the Non−Root user that you had specified in the Dockerfile."
},
{
"code": null,
"e": 4309,
"s": 3782,
"text": "Majority of the Docker Users either forget or don’t find it necessary to change their user privileges and switch to Non Root user. It is a bad practice and always poses a threat when the application is deployed and made public. Not only it poses a threat to that particular application, but also through the application, hackers can manipulate the entire filesystem of the Docker Container inside which the application is running along with other important applications that might be deployed inside the same Docker Container."
},
{
"code": null,
"e": 4653,
"s": 4309,
"text": "In this article, we saw two different methods through which you can switch the current user as a non root user. The process discussed in Method 2 is better and widely used due to the fact that almost all the Docker applications require a Dockerfile to maintain the Container and using two simple additional statements, you can make the switch."
}
] |
GATE | GATE-CS-2015 (Set 1) | Question 56 - GeeksforGeeks
|
28 Jun, 2021
Consider a main memory with five page frames and the following sequence of page references: 3, 8, 2, 3, 9, 1, 6, 3, 8, 9, 3, 6, 2, 1, 3. Which one of the following is true with respect to page replacement policies First-In-First Out (FIFO) and Least Recently Used (LRU)?
(A) Both incur the same number of page faults(B) FIFO incurs 2 more page faults than LRU(C) LRU incurs 2 more page faults than FIFO(D) FIFO incurs 1 more page faults than LRUAnswer: (A)Explanation:
3, 8, 2, 3, 9, 1, 6, 3, 8, 9, 3, 6, 2, 1, 3
In both FIFO and LRU, we get following after
considering 3, 8, 2, 3, 9, 1, 3 8 2 9 1
FIFO
6 replaces 3
8 2 9 1 6
3 replaces 8
2 9 1 6 3
8 replaces 2
9 1 6 3 8
2 replaces 9
1 6 3 8 2
No more page faults
LRU
6 replaces 8
3 2 9 1 6
8 replaces 2
3 9 1 6 8
2 replaces 1
3 9 6 8 2
1 replaces 8
3 9 6 2 1
Quiz of this Question
GATE-CS-2015 (Set 1)
GATE-GATE-CS-2015 (Set 1)
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
GATE | GATE-CS-2014-(Set-1) | Question 30
GATE | GATE-CS-2015 (Set 1) | Question 65
GATE | GATE CS 2010 | Question 45
GATE | GATE-CS-2004 | Question 3
GATE | GATE-CS-2015 (Set 3) | Question 65
C++ Program to count Vowels in a string using Pointer
GATE | GATE CS 2012 | Question 40
GATE | GATE-CS-2006 | Question 49
GATE | GATE-CS-2015 (Set 1) | Question 42
GATE | GATE-CS-2014-(Set-3) | Question 65
|
[
{
"code": null,
"e": 24101,
"s": 24073,
"text": "\n28 Jun, 2021"
},
{
"code": null,
"e": 24372,
"s": 24101,
"text": "Consider a main memory with five page frames and the following sequence of page references: 3, 8, 2, 3, 9, 1, 6, 3, 8, 9, 3, 6, 2, 1, 3. Which one of the following is true with respect to page replacement policies First-In-First Out (FIFO) and Least Recently Used (LRU)?"
},
{
"code": null,
"e": 24570,
"s": 24372,
"text": "(A) Both incur the same number of page faults(B) FIFO incurs 2 more page faults than LRU(C) LRU incurs 2 more page faults than FIFO(D) FIFO incurs 1 more page faults than LRUAnswer: (A)Explanation:"
},
{
"code": null,
"e": 24925,
"s": 24570,
"text": "3, 8, 2, 3, 9, 1, 6, 3, 8, 9, 3, 6, 2, 1, 3\n\nIn both FIFO and LRU, we get following after \nconsidering 3, 8, 2, 3, 9, 1, 3 8 2 9 1\n\nFIFO\n6 replaces 3\n8 2 9 1 6\n\n3 replaces 8\n2 9 1 6 3\n\n8 replaces 2\n9 1 6 3 8\n\n2 replaces 9\n1 6 3 8 2\n\nNo more page faults\n\nLRU\n6 replaces 8\n3 2 9 1 6\n \n8 replaces 2\n3 9 1 6 8\n\n2 replaces 1\n3 9 6 8 2\n\n1 replaces 8\n3 9 6 2 1 "
},
{
"code": null,
"e": 24947,
"s": 24925,
"text": "Quiz of this Question"
},
{
"code": null,
"e": 24968,
"s": 24947,
"text": "GATE-CS-2015 (Set 1)"
},
{
"code": null,
"e": 24994,
"s": 24968,
"text": "GATE-GATE-CS-2015 (Set 1)"
},
{
"code": null,
"e": 24999,
"s": 24994,
"text": "GATE"
},
{
"code": null,
"e": 25097,
"s": 24999,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25106,
"s": 25097,
"text": "Comments"
},
{
"code": null,
"e": 25119,
"s": 25106,
"text": "Old Comments"
},
{
"code": null,
"e": 25161,
"s": 25119,
"text": "GATE | GATE-CS-2014-(Set-1) | Question 30"
},
{
"code": null,
"e": 25203,
"s": 25161,
"text": "GATE | GATE-CS-2015 (Set 1) | Question 65"
},
{
"code": null,
"e": 25237,
"s": 25203,
"text": "GATE | GATE CS 2010 | Question 45"
},
{
"code": null,
"e": 25270,
"s": 25237,
"text": "GATE | GATE-CS-2004 | Question 3"
},
{
"code": null,
"e": 25312,
"s": 25270,
"text": "GATE | GATE-CS-2015 (Set 3) | Question 65"
},
{
"code": null,
"e": 25366,
"s": 25312,
"text": "C++ Program to count Vowels in a string using Pointer"
},
{
"code": null,
"e": 25400,
"s": 25366,
"text": "GATE | GATE CS 2012 | Question 40"
},
{
"code": null,
"e": 25434,
"s": 25400,
"text": "GATE | GATE-CS-2006 | Question 49"
},
{
"code": null,
"e": 25476,
"s": 25434,
"text": "GATE | GATE-CS-2015 (Set 1) | Question 42"
}
] |
Java & MySQL - Commit & Rollback
|
Once you are done with your changes and you want to commit the changes then call commit() method on connection object as follows −
conn.commit( );
Otherwise, to roll back updates to the database made using the Connection named conn, use the following code −
conn.rollback( );
The following example illustrates the use of a commit and rollback object −
try{
//Assume a valid connection object conn
conn.setAutoCommit(false);
Statement stmt = conn.createStatement();
String SQL = "INSERT INTO Employees " +
"VALUES (106, 20, 'Rita', 'Tez')";
stmt.executeUpdate(SQL);
//Submit a malformed SQL statement that breaks
String SQL = "INSERTED IN Employees " +
"VALUES (107, 22, 'Sita', 'Singh')";
stmt.executeUpdate(SQL);
// If there is no error.
conn.commit();
}catch(SQLException se){
// If there is any error.
conn.rollback();
}
In this case, none of the above INSERT statement would success and everything would be rolled back.
Following is the example, which makes use of commit and rollback described.
This sample code has been written based on the environment and database setup done in the previous chapters.
Copy and paste the following example in TestApplication.java, compile and run as follows −
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class TestApplication {
static final String DB_URL = "jdbc:mysql://localhost/TUTORIALSPOINT";
static final String USER = "guest";
static final String PASS = "guest123";
static final String QUERY = "SELECT id, first, last, age FROM Employees";
static final String INSERT_QUERY = "INSERT INTO Employees (first, last, age) values('Rita', 'Tez', 20)";
static final String INSERT_QUERY_2 = "INSERT INTO Employees (first, last, age) values('Sita', 'Singh', 20)";
public static void printResultSet(ResultSet rs) throws SQLException{
// Ensure we start with first row
rs.beforeFirst();
while(rs.next()){
// Display values
System.out.print("ID: " + rs.getInt("id"));
System.out.print(", Age: " + rs.getInt("age"));
System.out.print(", First: " + rs.getString("first"));
System.out.println(", Last: " + rs.getString("last"));
}
System.out.println();
}
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
try{
// Open a connection
System.out.println("Connecting to database...");
conn = DriverManager.getConnection(DB_URL,USER,PASS);
// Set auto commit as false.
conn.setAutoCommit(false);
// Execute a query to create statment with
// required arguments for RS example.
System.out.println("Creating statement...");
stmt = conn.createStatement(
ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_UPDATABLE);
// INSERT a row into Employees table
System.out.println("Inserting one row....");
stmt.executeUpdate(INSERT_QUERY);
// INSERT one more row into Employees table
stmt.executeUpdate(INSERT_QUERY_2);
// Commit data here.
System.out.println("Commiting data here....");
conn.commit();
// Now list all the available records.
String sql = "SELECT id, first, last, age FROM Employees";
ResultSet rs = stmt.executeQuery(sql);
System.out.println("List result set for reference....");
printResultSet(rs);
// Clean-up environment
rs.close();
stmt.close();
conn.close();
}catch(SQLException se){
se.printStackTrace();
// If there is an error then rollback the changes.
System.out.println("Rolling back data here....");
try{
if(conn!=null)
conn.rollback();
}catch(SQLException se2){
se2.printStackTrace();
}
}catch(Exception e){
e.printStackTrace();
}finally{
// finally block used to close resources
try{
if(stmt!=null)
stmt.close();
}catch(SQLException se2){
se2.printStackTrace();
}
try{
if(conn!=null)
conn.close();
}catch(SQLException se){
se.printStackTrace();
}
}
}
}
Now let us compile the above example as follows −
C:\>javac TestApplication.java
C:\>
When you run TestApplication, it produces the following result −
C:\>java TestApplication
Connecting to database...
Creating statement...
Inserting one row....
Commiting data here....
List result set for reference....
ID: 1, Age: 23, First: Zara, Last: Ali
ID: 2, Age: 30, First: Mahnaz, Last: Fatma
ID: 3, Age: 35, First: Zaid, Last: Khan
ID: 4, Age: 33, First: Sumit, Last: Mittal
ID: 5, Age: 40, First: John, Last: Paul
ID: 6, Age: 20, First: Rita, Last: Tez
ID: 7, Age: 20, First: Sita, Last: Singh
C:\>
16 Lectures
2 hours
Malhar Lathkar
19 Lectures
5 hours
Malhar Lathkar
25 Lectures
2.5 hours
Anadi Sharma
126 Lectures
7 hours
Tushar Kale
119 Lectures
17.5 hours
Monica Mittal
76 Lectures
7 hours
Arnab Chakraborty
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2817,
"s": 2686,
"text": "Once you are done with your changes and you want to commit the changes then call commit() method on connection object as follows −"
},
{
"code": null,
"e": 2834,
"s": 2817,
"text": "conn.commit( );\n"
},
{
"code": null,
"e": 2945,
"s": 2834,
"text": "Otherwise, to roll back updates to the database made using the Connection named conn, use the following code −"
},
{
"code": null,
"e": 2964,
"s": 2945,
"text": "conn.rollback( );\n"
},
{
"code": null,
"e": 3040,
"s": 2964,
"text": "The following example illustrates the use of a commit and rollback object −"
},
{
"code": null,
"e": 3588,
"s": 3040,
"text": "try{\n //Assume a valid connection object conn\n conn.setAutoCommit(false);\n Statement stmt = conn.createStatement();\n \n String SQL = \"INSERT INTO Employees \" +\n \"VALUES (106, 20, 'Rita', 'Tez')\";\n stmt.executeUpdate(SQL); \n //Submit a malformed SQL statement that breaks\n String SQL = \"INSERTED IN Employees \" +\n \"VALUES (107, 22, 'Sita', 'Singh')\";\n stmt.executeUpdate(SQL);\n // If there is no error.\n conn.commit();\n}catch(SQLException se){\n // If there is any error.\n conn.rollback();\n}"
},
{
"code": null,
"e": 3688,
"s": 3588,
"text": "In this case, none of the above INSERT statement would success and everything would be rolled back."
},
{
"code": null,
"e": 3764,
"s": 3688,
"text": "Following is the example, which makes use of commit and rollback described."
},
{
"code": null,
"e": 3873,
"s": 3764,
"text": "This sample code has been written based on the environment and database setup done in the previous chapters."
},
{
"code": null,
"e": 3964,
"s": 3873,
"text": "Copy and paste the following example in TestApplication.java, compile and run as follows −"
},
{
"code": null,
"e": 7211,
"s": 3964,
"text": "import java.sql.Connection;\nimport java.sql.DriverManager;\nimport java.sql.ResultSet;\nimport java.sql.SQLException;\nimport java.sql.Statement;\n\npublic class TestApplication {\n static final String DB_URL = \"jdbc:mysql://localhost/TUTORIALSPOINT\";\n static final String USER = \"guest\";\n static final String PASS = \"guest123\";\n static final String QUERY = \"SELECT id, first, last, age FROM Employees\";\n static final String INSERT_QUERY = \"INSERT INTO Employees (first, last, age) values('Rita', 'Tez', 20)\";\n static final String INSERT_QUERY_2 = \"INSERT INTO Employees (first, last, age) values('Sita', 'Singh', 20)\";\n\n public static void printResultSet(ResultSet rs) throws SQLException{\n // Ensure we start with first row\n rs.beforeFirst();\n while(rs.next()){\n // Display values\n System.out.print(\"ID: \" + rs.getInt(\"id\"));\n System.out.print(\", Age: \" + rs.getInt(\"age\"));\n System.out.print(\", First: \" + rs.getString(\"first\"));\n System.out.println(\", Last: \" + rs.getString(\"last\"));\n }\n System.out.println();\n }\n\n public static void main(String[] args) {\n\n Connection conn = null;\n Statement stmt = null;\n try{\n // Open a connection\n System.out.println(\"Connecting to database...\");\n conn = DriverManager.getConnection(DB_URL,USER,PASS);\n\n // Set auto commit as false.\n conn.setAutoCommit(false);\n\n // Execute a query to create statment with\n // required arguments for RS example.\n System.out.println(\"Creating statement...\");\n stmt = conn.createStatement(\n ResultSet.TYPE_SCROLL_INSENSITIVE,\n ResultSet.CONCUR_UPDATABLE);\n\n // INSERT a row into Employees table\n System.out.println(\"Inserting one row....\");\n stmt.executeUpdate(INSERT_QUERY); \n\n // INSERT one more row into Employees table\n stmt.executeUpdate(INSERT_QUERY_2);\n\n // Commit data here.\n System.out.println(\"Commiting data here....\");\n conn.commit();\n\n // Now list all the available records.\n String sql = \"SELECT id, first, last, age FROM Employees\";\n ResultSet rs = stmt.executeQuery(sql);\n System.out.println(\"List result set for reference....\");\n printResultSet(rs);\n\n // Clean-up environment\n rs.close();\n stmt.close();\n conn.close();\n }catch(SQLException se){\n se.printStackTrace();\n // If there is an error then rollback the changes.\n System.out.println(\"Rolling back data here....\");\n try{\n if(conn!=null)\n conn.rollback();\n }catch(SQLException se2){\n se2.printStackTrace();\n }\n }catch(Exception e){\n e.printStackTrace();\n }finally{\n // finally block used to close resources\n try{\n if(stmt!=null)\n stmt.close();\n }catch(SQLException se2){\n se2.printStackTrace();\n } \n try{\n if(conn!=null)\n conn.close();\n }catch(SQLException se){\n se.printStackTrace();\n }\n }\t\t \n }\n}"
},
{
"code": null,
"e": 7261,
"s": 7211,
"text": "Now let us compile the above example as follows −"
},
{
"code": null,
"e": 7298,
"s": 7261,
"text": "C:\\>javac TestApplication.java\nC:\\>\n"
},
{
"code": null,
"e": 7363,
"s": 7298,
"text": "When you run TestApplication, it produces the following result −"
},
{
"code": null,
"e": 7807,
"s": 7363,
"text": "C:\\>java TestApplication\nConnecting to database...\nCreating statement...\nInserting one row....\nCommiting data here....\nList result set for reference....\nID: 1, Age: 23, First: Zara, Last: Ali\nID: 2, Age: 30, First: Mahnaz, Last: Fatma\nID: 3, Age: 35, First: Zaid, Last: Khan\nID: 4, Age: 33, First: Sumit, Last: Mittal\nID: 5, Age: 40, First: John, Last: Paul\nID: 6, Age: 20, First: Rita, Last: Tez\nID: 7, Age: 20, First: Sita, Last: Singh\nC:\\>\n"
},
{
"code": null,
"e": 7840,
"s": 7807,
"text": "\n 16 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 7856,
"s": 7840,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 7889,
"s": 7856,
"text": "\n 19 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 7905,
"s": 7889,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 7940,
"s": 7905,
"text": "\n 25 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 7954,
"s": 7940,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 7988,
"s": 7954,
"text": "\n 126 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 8002,
"s": 7988,
"text": " Tushar Kale"
},
{
"code": null,
"e": 8039,
"s": 8002,
"text": "\n 119 Lectures \n 17.5 hours \n"
},
{
"code": null,
"e": 8054,
"s": 8039,
"text": " Monica Mittal"
},
{
"code": null,
"e": 8087,
"s": 8054,
"text": "\n 76 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 8106,
"s": 8087,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 8113,
"s": 8106,
"text": " Print"
},
{
"code": null,
"e": 8124,
"s": 8113,
"text": " Add Notes"
}
] |
HBase - Read Data
|
The get command and the get() method of HTable class are used to read data from a table in HBase. Using get command, you can get a single row of data at a time. Its syntax is as follows:
get ’<table name>’,’row1’
The following example shows how to use the get command. Let us scan the first row of the emp table.
hbase(main):012:0> get 'emp', '1'
COLUMN CELL
personal : city timestamp = 1417521848375, value = hyderabad
personal : name timestamp = 1417521785385, value = ramu
professional: designation timestamp = 1417521885277, value = manager
professional: salary timestamp = 1417521903862, value = 50000
4 row(s) in 0.0270 seconds
Given below is the syntax to read a specific column using the get method.
hbase> get 'table name', ‘rowid’, {COLUMN ⇒ ‘column family:column name ’}
Given below is the example to read a specific column in HBase table.
hbase(main):015:0> get 'emp', 'row1', {COLUMN ⇒ 'personal:name'}
COLUMN CELL
personal:name timestamp = 1418035791555, value = raju
1 row(s) in 0.0080 seconds
To read data from an HBase table, use the get() method of the HTable class. This method requires an instance of the Get class. Follow the steps given below to retrieve data from the HBase table.
Configuration class adds HBase configuration files to its object. You can create a configuration object using the create() method of the HbaseConfiguration class as shown below.
Configuration conf = HbaseConfiguration.create();
You have a class called HTable, an implementation of Table in HBase. This class is used to communicate with a single HBase table. While instantiating this class, it accepts the configuration object and the table name as parameters. You can instantiate the HTable class as shown below.
HTable hTable = new HTable(conf, tableName);
You can retrieve data from the HBase table using the get() method of the HTable class. This method extracts a cell from a given row. It requires a Get class object as parameter. Create it as shown below.
Get get = new Get(toBytes("row1"));
While retrieving data, you can get a single row by id, or get a set of rows by a set of row ids, or scan an entire table or a subset of rows.
You can retrieve an HBase table data using the add method variants in Get class.
To get a specific column from a specific column family, use the following method.
get.addFamily(personal)
To get all the columns from a specific column family, use the following method.
get.addColumn(personal, name)
Get the result by passing your Get class instance to the get method of the HTable class. This method returns the Result class object, which holds the requested result. Given below is the usage of get() method.
Result result = table.get(g);
The Result class provides the getValue() method to read the values from its instance. Use it as shown below to read the values from the Result instance.
byte [] value = result.getValue(Bytes.toBytes("personal"),Bytes.toBytes("name"));
byte [] value1 = result.getValue(Bytes.toBytes("personal"),Bytes.toBytes("city"));
Given below is the complete program to read values from an HBase table.
import java.io.IOException;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.HBaseConfiguration;
import org.apache.hadoop.hbase.client.Get;
import org.apache.hadoop.hbase.client.HTable;
import org.apache.hadoop.hbase.client.Result;
import org.apache.hadoop.hbase.util.Bytes;
public class RetriveData{
public static void main(String[] args) throws IOException, Exception{
// Instantiating Configuration class
Configuration config = HBaseConfiguration.create();
// Instantiating HTable class
HTable table = new HTable(config, "emp");
// Instantiating Get class
Get g = new Get(Bytes.toBytes("row1"));
// Reading the data
Result result = table.get(g);
// Reading values from Result class object
byte [] value = result.getValue(Bytes.toBytes("personal"),Bytes.toBytes("name"));
byte [] value1 = result.getValue(Bytes.toBytes("personal"),Bytes.toBytes("city"));
// Printing the values
String name = Bytes.toString(value);
String city = Bytes.toString(value1);
System.out.println("name: " + name + " city: " + city);
}
}
Compile and execute the above program as shown below.
$javac RetriveData.java
$java RetriveData
The following should be the output:
name: Raju city: Delhi
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2224,
"s": 2037,
"text": "The get command and the get() method of HTable class are used to read data from a table in HBase. Using get command, you can get a single row of data at a time. Its syntax is as follows:"
},
{
"code": null,
"e": 2251,
"s": 2224,
"text": "get ’<table name>’,’row1’\n"
},
{
"code": null,
"e": 2351,
"s": 2251,
"text": "The following example shows how to use the get command. Let us scan the first row of the emp table."
},
{
"code": null,
"e": 2705,
"s": 2351,
"text": "hbase(main):012:0> get 'emp', '1'\n\n COLUMN CELL\n \npersonal : city timestamp = 1417521848375, value = hyderabad\n\npersonal : name timestamp = 1417521785385, value = ramu\n\nprofessional: designation timestamp = 1417521885277, value = manager\n\nprofessional: salary timestamp = 1417521903862, value = 50000\n\n4 row(s) in 0.0270 seconds\n"
},
{
"code": null,
"e": 2779,
"s": 2705,
"text": "Given below is the syntax to read a specific column using the get method."
},
{
"code": null,
"e": 2854,
"s": 2779,
"text": "hbase> get 'table name', ‘rowid’, {COLUMN ⇒ ‘column family:column name ’}\n"
},
{
"code": null,
"e": 2923,
"s": 2854,
"text": "Given below is the example to read a specific column in HBase table."
},
{
"code": null,
"e": 3101,
"s": 2923,
"text": "hbase(main):015:0> get 'emp', 'row1', {COLUMN ⇒ 'personal:name'}\n COLUMN CELL \npersonal:name timestamp = 1418035791555, value = raju\n1 row(s) in 0.0080 seconds\n"
},
{
"code": null,
"e": 3296,
"s": 3101,
"text": "To read data from an HBase table, use the get() method of the HTable class. This method requires an instance of the Get class. Follow the steps given below to retrieve data from the HBase table."
},
{
"code": null,
"e": 3474,
"s": 3296,
"text": "Configuration class adds HBase configuration files to its object. You can create a configuration object using the create() method of the HbaseConfiguration class as shown below."
},
{
"code": null,
"e": 3525,
"s": 3474,
"text": "Configuration conf = HbaseConfiguration.create();\n"
},
{
"code": null,
"e": 3810,
"s": 3525,
"text": "You have a class called HTable, an implementation of Table in HBase. This class is used to communicate with a single HBase table. While instantiating this class, it accepts the configuration object and the table name as parameters. You can instantiate the HTable class as shown below."
},
{
"code": null,
"e": 3856,
"s": 3810,
"text": "HTable hTable = new HTable(conf, tableName);\n"
},
{
"code": null,
"e": 4060,
"s": 3856,
"text": "You can retrieve data from the HBase table using the get() method of the HTable class. This method extracts a cell from a given row. It requires a Get class object as parameter. Create it as shown below."
},
{
"code": null,
"e": 4097,
"s": 4060,
"text": "Get get = new Get(toBytes(\"row1\"));\n"
},
{
"code": null,
"e": 4239,
"s": 4097,
"text": "While retrieving data, you can get a single row by id, or get a set of rows by a set of row ids, or scan an entire table or a subset of rows."
},
{
"code": null,
"e": 4320,
"s": 4239,
"text": "You can retrieve an HBase table data using the add method variants in Get class."
},
{
"code": null,
"e": 4402,
"s": 4320,
"text": "To get a specific column from a specific column family, use the following method."
},
{
"code": null,
"e": 4428,
"s": 4402,
"text": "get.addFamily(personal) \n"
},
{
"code": null,
"e": 4508,
"s": 4428,
"text": "To get all the columns from a specific column family, use the following method."
},
{
"code": null,
"e": 4540,
"s": 4508,
"text": "get.addColumn(personal, name) \n"
},
{
"code": null,
"e": 4750,
"s": 4540,
"text": "Get the result by passing your Get class instance to the get method of the HTable class. This method returns the Result class object, which holds the requested result. Given below is the usage of get() method."
},
{
"code": null,
"e": 4783,
"s": 4750,
"text": "Result result = table.get(g); \n"
},
{
"code": null,
"e": 4936,
"s": 4783,
"text": "The Result class provides the getValue() method to read the values from its instance. Use it as shown below to read the values from the Result instance."
},
{
"code": null,
"e": 5102,
"s": 4936,
"text": "byte [] value = result.getValue(Bytes.toBytes(\"personal\"),Bytes.toBytes(\"name\"));\nbyte [] value1 = result.getValue(Bytes.toBytes(\"personal\"),Bytes.toBytes(\"city\"));\n"
},
{
"code": null,
"e": 5174,
"s": 5102,
"text": "Given below is the complete program to read values from an HBase table."
},
{
"code": null,
"e": 6333,
"s": 5174,
"text": "import java.io.IOException;\n\nimport org.apache.hadoop.conf.Configuration;\n\nimport org.apache.hadoop.hbase.HBaseConfiguration;\nimport org.apache.hadoop.hbase.client.Get;\nimport org.apache.hadoop.hbase.client.HTable;\nimport org.apache.hadoop.hbase.client.Result;\nimport org.apache.hadoop.hbase.util.Bytes;\n\npublic class RetriveData{\n\n public static void main(String[] args) throws IOException, Exception{\n \n // Instantiating Configuration class\n Configuration config = HBaseConfiguration.create();\n\n // Instantiating HTable class\n HTable table = new HTable(config, \"emp\");\n\n // Instantiating Get class\n Get g = new Get(Bytes.toBytes(\"row1\"));\n\n // Reading the data\n Result result = table.get(g);\n\n // Reading values from Result class object\n byte [] value = result.getValue(Bytes.toBytes(\"personal\"),Bytes.toBytes(\"name\"));\n\n byte [] value1 = result.getValue(Bytes.toBytes(\"personal\"),Bytes.toBytes(\"city\"));\n\n // Printing the values\n String name = Bytes.toString(value);\n String city = Bytes.toString(value1);\n \n System.out.println(\"name: \" + name + \" city: \" + city);\n }\n}"
},
{
"code": null,
"e": 6387,
"s": 6333,
"text": "Compile and execute the above program as shown below."
},
{
"code": null,
"e": 6430,
"s": 6387,
"text": "$javac RetriveData.java\n$java RetriveData\n"
},
{
"code": null,
"e": 6466,
"s": 6430,
"text": "The following should be the output:"
},
{
"code": null,
"e": 6490,
"s": 6466,
"text": "name: Raju city: Delhi\n"
},
{
"code": null,
"e": 6497,
"s": 6490,
"text": " Print"
},
{
"code": null,
"e": 6508,
"s": 6497,
"text": " Add Notes"
}
] |
gRPC - Hello World App with Java
|
Let us now create a basic "Hello World" like app that will use gRPC along with Java.
First let us define the "greeting.proto" file in common_proto_files −
syntax = "proto3";
option java_package = "com.tp.greeting";
service Greeter {
rpc greet (ClientInput) returns (ServerOutput) {}
}
message ClientInput {
string greeting = 1;
string name = 2;
}
message ServerOutput {
string message = 1;
}
Let us now take a closer look at this code block and see the role of each line −
syntax = "proto3";
The "syntax" here represents the version of Protobuf that we are using. So, we are using the latest version 3 and the schema thus can use all the syntax which is valid for version 3.
package tutorial;
The package here is used for conflict resolution if, say, we have multiple classes/members with the same name.
option java_package = "com.tp.greeting";
This argument is specific to Java, i.e., the package where to auto-generate the code from the ".proto" file.
service Greeter {
rpc greet(ClientInput) returns (ServerOutput) {}
}
This block represents the name of the service "Greeter" and the function name "greet" which can be called. The "greet" function takes in the input of type "ClientInput" and returns the output of type "ServerOutput". Now let us look at these types.
message ClientInput {
string greeting = 1;
string name = 2;
}
In the above block, we have defined the ClientInput which contains two attributes, "greeting" and the "name", both of them being strings. The client is supposed to send the object of type "ClientInput" to the server.
message ServerOutput {
string message = 1;
}
In the above block, we have defined that, given a "ClientInput", the server would return the "ServerOutput" which will contain a single attribute "message". The server is supposed to send the object of type "ServerOutput" to the client.
Note that we already had the Maven setup done to auto-generating our class files as well as our RPC code. So, now we can simply compile our project −
mvn clean install
This should auto-generate the source code required for us to use gRPC. The source code would be placed under −
Protobuf class code: target/generated-sources/protobuf/java/com.tp.greeting
Protobuf gRPC code: target/generated-sources/protobuf/grpc-java/com.tp.greeting
Now that we have defined the proto file which contains the function definition, let us setup a server which can serve to call these functions.
Let us write our server code to serve the above function and save it in com.tp.grpc.GreetServer.java −
package com.tp.grpc;
import io.grpc.Server;
import io.grpc.ServerBuilder;
import io.grpc.stub.StreamObserver;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import java.util.logging.Logger;
import com.tp.greeting.GreeterGrpc;
import com.tp.greeting.Greeting.ClientInput;
import com.tp.greeting.Greeting.ServerOutput;
public class GreetServer {
private static final Logger logger = Logger.getLogger(GreetServer.class.getName());
private Server server;
private void start() throws IOException {
int port = 50051;
server = ServerBuilder.forPort(port).addService(new GreeterImpl()).build().start();
logger.info("Server started, listening on " + port);
Runtime.getRuntime().addShutdownHook(new Thread() {
@Override
public void run() {
System.err.println("Shutting down gRPC server");
try {
server.shutdown().awaitTermination(30, TimeUnit.SECONDS);
} catch (InterruptedException e) {
e.printStackTrace(System.err);
}
}
});
}
static class GreeterImpl extends GreeterGrpc.GreeterImplBase {
@Override
public void greet(ClientInput req, StreamObserver<ServerOutput> responseObserver) {
logger.info("Got request from client: " + req);
ServerOutput reply = ServerOutput.newBuilder().setMessage(
"Server says " + "\"" + req.getGreeting() + " " + req.getName() + "\""
).build();
responseObserver.onNext(reply);
responseObserver.onCompleted();
}
}
public static void main(String[] args) throws IOException, InterruptedException {
final GreetServer greetServer = new GreetServer();
greetServer.start();
greetServer.server.awaitTermination();
}
}
The above code starts a gRPC server at a specified port and serves the functions and services which we had written in our proto file. Let us walk through the above code −
Starting from the main method, we create a gRPC server at a specified port.
Starting from the main method, we create a gRPC server at a specified port.
But before starting the server, we assign the server the service which we want to run, i.e., in our case, the Greeter service.
But before starting the server, we assign the server the service which we want to run, i.e., in our case, the Greeter service.
For this purpose, we need to pass the service instance to the server, so we go ahead and create a service instance, i.e., in our case, the GreeterImpl.
For this purpose, we need to pass the service instance to the server, so we go ahead and create a service instance, i.e., in our case, the GreeterImpl.
The service instance needs to provide an implementation of the method/function which is present in the ".proto" file, i.e., in our case,the greet method.
The service instance needs to provide an implementation of the method/function which is present in the ".proto" file, i.e., in our case,the greet method.
The method expects an object of type as defined in the ".proto" file, i.e., in our case, the ClientInput.
The method expects an object of type as defined in the ".proto" file, i.e., in our case, the ClientInput.
The method works on the above input, does the computation, and then is supposed to return the mentioned output in the ".proto" file, i.e., in our case, the ServerOutput.
The method works on the above input, does the computation, and then is supposed to return the mentioned output in the ".proto" file, i.e., in our case, the ServerOutput.
Finally, we also have a shutdown hook to ensure clean shutting down of the server when we are done executing our code.
Finally, we also have a shutdown hook to ensure clean shutting down of the server when we are done executing our code.
Now that we have written the code for the server, let us setup a client which can call these functions.
Let us write our client code to call the above function and save it in com.tp.grpc.GreetClient.java −
package com.tp.grpc;
import io.grpc.Channel;
import io.grpc.ManagedChannel;
import io.grpc.ManagedChannelBuilder;
import io.grpc.StatusRuntimeException;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
import java.util.logging.Logger;
import com.tp.greeting.GreeterGrpc;
import com.tp.greeting.Greeting.ServerOutput;
import com.tp.greeting.Greeting.ClientInput;
public class GreetClient {
private static final Logger logger = Logger.getLogger(GreetClient.class.getName());
private final GreeterGrpc.GreeterBlockingStub blockingStub;
public GreetClient(Channel channel) {
blockingStub = GreeterGrpc.newBlockingStub(channel);
}
public void makeGreeting(String greeting, String username) {
logger.info("Sending greeting to server: " + greeting + " for name: " + username);
ClientInput request = ClientInput.newBuilder().setName(username).setGreeting(greeting).build();
logger.info("Sending to server: " + request);
ServerOutput response;
try {
response = blockingStub.greet(request);
} catch (StatusRuntimeException e) {
logger.log(Level.WARNING, "RPC failed: {0}", e.getStatus());
return;
}
logger.info("Got following from the server: " + response.getMessage());
}
public static void main(String[] args) throws Exception {
String greeting = args[0];
String username = args[1];
String serverAddress = "localhost:50051";
ManagedChannel channel = ManagedChannelBuilder.forTarget(serverAddress)
.usePlaintext()
.build();
try {
GreetClient client = new GreetClient(channel);
client.makeGreeting(greeting, username);
} finally {
channel.shutdownNow().awaitTermination(5, TimeUnit.SECONDS);
}
}
}
The above code starts a gRPC server at a specified port and serves the functions and services which we had written in our proto file. Let us walk through the above code −
Starting from main method, we accept two arguments, i.e., name and the greeting.
Starting from main method, we accept two arguments, i.e., name and the greeting.
We setup a Channel for gRPC communication to our server.
We setup a Channel for gRPC communication to our server.
Next, we create a blocking stub using the channel we created. This is where we have the service "Greeter" whose functions we plan to call.A stub is nothing but a wrapper that hides the remote call complexity from the caller.
Next, we create a blocking stub using the channel we created. This is where we have the service "Greeter" whose functions we plan to call.A stub is nothing but a wrapper that hides the remote call complexity from the caller.
Then, we simply create the expected input defined in the ".proto" file,i.e., in our case, the ClientInput.
Then, we simply create the expected input defined in the ".proto" file,i.e., in our case, the ClientInput.
We ultimately make the call and await result from the server.
We ultimately make the call and await result from the server.
Finally, we close the channel to avoid any resource leak.
Finally, we close the channel to avoid any resource leak.
So, that is our client code.
Now, that we have defined our proto file, written our server, and the client code, let us proceed and execute this code and see things in actions.
For running the code, fire up two shells. Start the server on the first shell by executing the following command −
java -cp .\target\grpc-point-1.0.jar com.tp.grpc.GreetServer
We would see the following output −
Jul 03, 2021 1:04:23 PM com.tp.grpc.GreetServer start
INFO: Server started, listening on 50051
The above output implies that the server has started.
Now, let us start the client.
java -cp .\target\grpc-point-1.0.jar com.tp.grpc.GreetClient
Hello Jane
We would see the following output −
Jul 03, 2021 1:05:59 PM com.tp.grpc.GreetClient greet
INFO: Sending greeting to server: Hello for name: Jane
Jul 03, 2021 1:05:59 PM com.tp.grpc.GreetClient greet
INFO: Sending to server: greeting: "Hello"
name: "Jane"
Jul 03, 2021 1:06:00 PM com.tp.grpc.GreetClient greet
INFO: Got following from the server: Server says "Hello Jane"
And now, if we open the server logs, we will get to see the following −
Jul 03, 2021 1:04:23 PM com.tp.grpc.GreetServer start
INFO: Server started, listening on 50051
Jul 03, 2021 1:06:00 PM com.tp.grpc.GreetServer$GreeterImpl
greet
INFO: Got request from client: greeting: "Hello"
name: "Jane"
So, the client was able to call the server as expected and the server responded with greeting the client back.
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 1922,
"s": 1837,
"text": "Let us now create a basic \"Hello World\" like app that will use gRPC along with Java."
},
{
"code": null,
"e": 1992,
"s": 1922,
"text": "First let us define the \"greeting.proto\" file in common_proto_files −"
},
{
"code": null,
"e": 2242,
"s": 1992,
"text": "syntax = \"proto3\";\noption java_package = \"com.tp.greeting\";\nservice Greeter {\n rpc greet (ClientInput) returns (ServerOutput) {}\n}\nmessage ClientInput {\n string greeting = 1;\n string name = 2;\n}\nmessage ServerOutput {\n string message = 1;\n}\n"
},
{
"code": null,
"e": 2323,
"s": 2242,
"text": "Let us now take a closer look at this code block and see the role of each line −"
},
{
"code": null,
"e": 2343,
"s": 2323,
"text": "syntax = \"proto3\";\n"
},
{
"code": null,
"e": 2526,
"s": 2343,
"text": "The \"syntax\" here represents the version of Protobuf that we are using. So, we are using the latest version 3 and the schema thus can use all the syntax which is valid for version 3."
},
{
"code": null,
"e": 2545,
"s": 2526,
"text": "package tutorial;\n"
},
{
"code": null,
"e": 2656,
"s": 2545,
"text": "The package here is used for conflict resolution if, say, we have multiple classes/members with the same name."
},
{
"code": null,
"e": 2698,
"s": 2656,
"text": "option java_package = \"com.tp.greeting\";\n"
},
{
"code": null,
"e": 2807,
"s": 2698,
"text": "This argument is specific to Java, i.e., the package where to auto-generate the code from the \".proto\" file."
},
{
"code": null,
"e": 2880,
"s": 2807,
"text": "service Greeter {\n rpc greet(ClientInput) returns (ServerOutput) {}\n}\n"
},
{
"code": null,
"e": 3128,
"s": 2880,
"text": "This block represents the name of the service \"Greeter\" and the function name \"greet\" which can be called. The \"greet\" function takes in the input of type \"ClientInput\" and returns the output of type \"ServerOutput\". Now let us look at these types."
},
{
"code": null,
"e": 3197,
"s": 3128,
"text": "message ClientInput {\n string greeting = 1;\n string name = 2;\n}\n"
},
{
"code": null,
"e": 3414,
"s": 3197,
"text": "In the above block, we have defined the ClientInput which contains two attributes, \"greeting\" and the \"name\", both of them being strings. The client is supposed to send the object of type \"ClientInput\" to the server."
},
{
"code": null,
"e": 3463,
"s": 3414,
"text": "message ServerOutput {\n string message = 1;\n}\n"
},
{
"code": null,
"e": 3700,
"s": 3463,
"text": "In the above block, we have defined that, given a \"ClientInput\", the server would return the \"ServerOutput\" which will contain a single attribute \"message\". The server is supposed to send the object of type \"ServerOutput\" to the client."
},
{
"code": null,
"e": 3850,
"s": 3700,
"text": "Note that we already had the Maven setup done to auto-generating our class files as well as our RPC code. So, now we can simply compile our project −"
},
{
"code": null,
"e": 3869,
"s": 3850,
"text": "mvn clean install\n"
},
{
"code": null,
"e": 3980,
"s": 3869,
"text": "This should auto-generate the source code required for us to use gRPC. The source code would be placed under −"
},
{
"code": null,
"e": 4137,
"s": 3980,
"text": "Protobuf class code: target/generated-sources/protobuf/java/com.tp.greeting\nProtobuf gRPC code: target/generated-sources/protobuf/grpc-java/com.tp.greeting\n"
},
{
"code": null,
"e": 4280,
"s": 4137,
"text": "Now that we have defined the proto file which contains the function definition, let us setup a server which can serve to call these functions."
},
{
"code": null,
"e": 4383,
"s": 4280,
"text": "Let us write our server code to serve the above function and save it in com.tp.grpc.GreetServer.java −"
},
{
"code": null,
"e": 6197,
"s": 4383,
"text": "package com.tp.grpc;\n\nimport io.grpc.Server;\nimport io.grpc.ServerBuilder;\nimport io.grpc.stub.StreamObserver;\nimport java.io.IOException;\nimport java.util.concurrent.TimeUnit;\nimport java.util.logging.Logger;\nimport com.tp.greeting.GreeterGrpc;\nimport com.tp.greeting.Greeting.ClientInput;\nimport com.tp.greeting.Greeting.ServerOutput;\n\npublic class GreetServer {\n private static final Logger logger = Logger.getLogger(GreetServer.class.getName());\n private Server server;\n private void start() throws IOException {\n int port = 50051;\n server = ServerBuilder.forPort(port).addService(new GreeterImpl()).build().start();\n \n logger.info(\"Server started, listening on \" + port);\n \n Runtime.getRuntime().addShutdownHook(new Thread() {\n @Override\n public void run() {\n System.err.println(\"Shutting down gRPC server\");\n try {\n server.shutdown().awaitTermination(30, TimeUnit.SECONDS);\n } catch (InterruptedException e) {\n e.printStackTrace(System.err);\n }\n }\n });\n }\n static class GreeterImpl extends GreeterGrpc.GreeterImplBase {\n @Override\n public void greet(ClientInput req, StreamObserver<ServerOutput> responseObserver) {\n logger.info(\"Got request from client: \" + req);\n ServerOutput reply = ServerOutput.newBuilder().setMessage(\n \"Server says \" + \"\\\"\" + req.getGreeting() + \" \" + req.getName() + \"\\\"\"\n ).build();\n responseObserver.onNext(reply);\n responseObserver.onCompleted();\n }\n }\n public static void main(String[] args) throws IOException, InterruptedException {\n final GreetServer greetServer = new GreetServer();\n greetServer.start();\n greetServer.server.awaitTermination();\n }\n} "
},
{
"code": null,
"e": 6368,
"s": 6197,
"text": "The above code starts a gRPC server at a specified port and serves the functions and services which we had written in our proto file. Let us walk through the above code −"
},
{
"code": null,
"e": 6444,
"s": 6368,
"text": "Starting from the main method, we create a gRPC server at a specified port."
},
{
"code": null,
"e": 6520,
"s": 6444,
"text": "Starting from the main method, we create a gRPC server at a specified port."
},
{
"code": null,
"e": 6647,
"s": 6520,
"text": "But before starting the server, we assign the server the service which we want to run, i.e., in our case, the Greeter service."
},
{
"code": null,
"e": 6774,
"s": 6647,
"text": "But before starting the server, we assign the server the service which we want to run, i.e., in our case, the Greeter service."
},
{
"code": null,
"e": 6926,
"s": 6774,
"text": "For this purpose, we need to pass the service instance to the server, so we go ahead and create a service instance, i.e., in our case, the GreeterImpl."
},
{
"code": null,
"e": 7078,
"s": 6926,
"text": "For this purpose, we need to pass the service instance to the server, so we go ahead and create a service instance, i.e., in our case, the GreeterImpl."
},
{
"code": null,
"e": 7232,
"s": 7078,
"text": "The service instance needs to provide an implementation of the method/function which is present in the \".proto\" file, i.e., in our case,the greet method."
},
{
"code": null,
"e": 7386,
"s": 7232,
"text": "The service instance needs to provide an implementation of the method/function which is present in the \".proto\" file, i.e., in our case,the greet method."
},
{
"code": null,
"e": 7492,
"s": 7386,
"text": "The method expects an object of type as defined in the \".proto\" file, i.e., in our case, the ClientInput."
},
{
"code": null,
"e": 7598,
"s": 7492,
"text": "The method expects an object of type as defined in the \".proto\" file, i.e., in our case, the ClientInput."
},
{
"code": null,
"e": 7768,
"s": 7598,
"text": "The method works on the above input, does the computation, and then is supposed to return the mentioned output in the \".proto\" file, i.e., in our case, the ServerOutput."
},
{
"code": null,
"e": 7938,
"s": 7768,
"text": "The method works on the above input, does the computation, and then is supposed to return the mentioned output in the \".proto\" file, i.e., in our case, the ServerOutput."
},
{
"code": null,
"e": 8057,
"s": 7938,
"text": "Finally, we also have a shutdown hook to ensure clean shutting down of the server when we are done executing our code."
},
{
"code": null,
"e": 8176,
"s": 8057,
"text": "Finally, we also have a shutdown hook to ensure clean shutting down of the server when we are done executing our code."
},
{
"code": null,
"e": 8280,
"s": 8176,
"text": "Now that we have written the code for the server, let us setup a client which can call these functions."
},
{
"code": null,
"e": 8382,
"s": 8280,
"text": "Let us write our client code to call the above function and save it in com.tp.grpc.GreetClient.java −"
},
{
"code": null,
"e": 10192,
"s": 8382,
"text": "package com.tp.grpc;\n\nimport io.grpc.Channel;\nimport io.grpc.ManagedChannel;\nimport io.grpc.ManagedChannelBuilder;\nimport io.grpc.StatusRuntimeException;\nimport java.util.concurrent.TimeUnit;\nimport java.util.logging.Level;\nimport java.util.logging.Logger;\n\nimport com.tp.greeting.GreeterGrpc;\nimport com.tp.greeting.Greeting.ServerOutput;\nimport com.tp.greeting.Greeting.ClientInput;\n\npublic class GreetClient {\n private static final Logger logger = Logger.getLogger(GreetClient.class.getName());\n private final GreeterGrpc.GreeterBlockingStub blockingStub;\n \n public GreetClient(Channel channel) {\n blockingStub = GreeterGrpc.newBlockingStub(channel);\n }\n public void makeGreeting(String greeting, String username) {\n logger.info(\"Sending greeting to server: \" + greeting + \" for name: \" + username);\n ClientInput request = ClientInput.newBuilder().setName(username).setGreeting(greeting).build();\n logger.info(\"Sending to server: \" + request);\n ServerOutput response;\n try {\n response = blockingStub.greet(request);\n } catch (StatusRuntimeException e) {\n logger.log(Level.WARNING, \"RPC failed: {0}\", e.getStatus());\n return;\n }\n logger.info(\"Got following from the server: \" + response.getMessage());\n }\n \n public static void main(String[] args) throws Exception {\n String greeting = args[0];\n String username = args[1];\n String serverAddress = \"localhost:50051\";\n\t ManagedChannel channel = ManagedChannelBuilder.forTarget(serverAddress)\n .usePlaintext()\n .build();\n try {\n GreetClient client = new GreetClient(channel);\n client.makeGreeting(greeting, username);\n } finally {\n channel.shutdownNow().awaitTermination(5, TimeUnit.SECONDS);\n }\n }\n}"
},
{
"code": null,
"e": 10363,
"s": 10192,
"text": "The above code starts a gRPC server at a specified port and serves the functions and services which we had written in our proto file. Let us walk through the above code −"
},
{
"code": null,
"e": 10444,
"s": 10363,
"text": "Starting from main method, we accept two arguments, i.e., name and the greeting."
},
{
"code": null,
"e": 10525,
"s": 10444,
"text": "Starting from main method, we accept two arguments, i.e., name and the greeting."
},
{
"code": null,
"e": 10582,
"s": 10525,
"text": "We setup a Channel for gRPC communication to our server."
},
{
"code": null,
"e": 10639,
"s": 10582,
"text": "We setup a Channel for gRPC communication to our server."
},
{
"code": null,
"e": 10864,
"s": 10639,
"text": "Next, we create a blocking stub using the channel we created. This is where we have the service \"Greeter\" whose functions we plan to call.A stub is nothing but a wrapper that hides the remote call complexity from the caller."
},
{
"code": null,
"e": 11089,
"s": 10864,
"text": "Next, we create a blocking stub using the channel we created. This is where we have the service \"Greeter\" whose functions we plan to call.A stub is nothing but a wrapper that hides the remote call complexity from the caller."
},
{
"code": null,
"e": 11196,
"s": 11089,
"text": "Then, we simply create the expected input defined in the \".proto\" file,i.e., in our case, the ClientInput."
},
{
"code": null,
"e": 11303,
"s": 11196,
"text": "Then, we simply create the expected input defined in the \".proto\" file,i.e., in our case, the ClientInput."
},
{
"code": null,
"e": 11365,
"s": 11303,
"text": "We ultimately make the call and await result from the server."
},
{
"code": null,
"e": 11427,
"s": 11365,
"text": "We ultimately make the call and await result from the server."
},
{
"code": null,
"e": 11485,
"s": 11427,
"text": "Finally, we close the channel to avoid any resource leak."
},
{
"code": null,
"e": 11543,
"s": 11485,
"text": "Finally, we close the channel to avoid any resource leak."
},
{
"code": null,
"e": 11572,
"s": 11543,
"text": "So, that is our client code."
},
{
"code": null,
"e": 11719,
"s": 11572,
"text": "Now, that we have defined our proto file, written our server, and the client code, let us proceed and execute this code and see things in actions."
},
{
"code": null,
"e": 11834,
"s": 11719,
"text": "For running the code, fire up two shells. Start the server on the first shell by executing the following command −"
},
{
"code": null,
"e": 11896,
"s": 11834,
"text": "java -cp .\\target\\grpc-point-1.0.jar com.tp.grpc.GreetServer\n"
},
{
"code": null,
"e": 11932,
"s": 11896,
"text": "We would see the following output −"
},
{
"code": null,
"e": 12028,
"s": 11932,
"text": "Jul 03, 2021 1:04:23 PM com.tp.grpc.GreetServer start\nINFO: Server started, listening on 50051\n"
},
{
"code": null,
"e": 12082,
"s": 12028,
"text": "The above output implies that the server has started."
},
{
"code": null,
"e": 12112,
"s": 12082,
"text": "Now, let us start the client."
},
{
"code": null,
"e": 12186,
"s": 12112,
"text": "java -cp .\\target\\grpc-point-1.0.jar com.tp.grpc.GreetClient \nHello Jane\n"
},
{
"code": null,
"e": 12222,
"s": 12186,
"text": "We would see the following output −"
},
{
"code": null,
"e": 12559,
"s": 12222,
"text": "Jul 03, 2021 1:05:59 PM com.tp.grpc.GreetClient greet\nINFO: Sending greeting to server: Hello for name: Jane\nJul 03, 2021 1:05:59 PM com.tp.grpc.GreetClient greet\nINFO: Sending to server: greeting: \"Hello\"\nname: \"Jane\"\n\nJul 03, 2021 1:06:00 PM com.tp.grpc.GreetClient greet\nINFO: Got following from the server: Server says \"Hello Jane\"\n"
},
{
"code": null,
"e": 12631,
"s": 12559,
"text": "And now, if we open the server logs, we will get to see the following −"
},
{
"code": null,
"e": 12856,
"s": 12631,
"text": "Jul 03, 2021 1:04:23 PM com.tp.grpc.GreetServer start\nINFO: Server started, listening on 50051\nJul 03, 2021 1:06:00 PM com.tp.grpc.GreetServer$GreeterImpl \ngreet\nINFO: Got request from client: greeting: \"Hello\"\nname: \"Jane\"\n"
},
{
"code": null,
"e": 12967,
"s": 12856,
"text": "So, the client was able to call the server as expected and the server responded with greeting the client back."
},
{
"code": null,
"e": 12974,
"s": 12967,
"text": " Print"
},
{
"code": null,
"e": 12985,
"s": 12974,
"text": " Add Notes"
}
] |
Angular Material - Subheaders
|
The md-subheader, an Angular directive, is used to show a subheader for a section.
The following example shows the use of md-subheader and also the uses of subheader component.
am_subheaders.htm
<html lang = "en">
<head>
<link rel = "stylesheet"
href = "https://ajax.googleapis.com/ajax/libs/angular_material/1.0.0/angular-material.min.css">
<script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular-animate.min.js"></script>
<script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular-aria.min.js"></script>
<script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular-messages.min.js"></script>
<script src = "https://ajax.googleapis.com/ajax/libs/angular_material/1.0.0/angular-material.min.js"></script>
<link rel = "stylesheet" href = "https://fonts.googleapis.com/icon?family=Material+Icons">
<script language = "javascript">
angular
.module('firstApplication', ['ngMaterial'])
.controller('subheaderController', subheaderController);
function subheaderController ($scope) {
$scope.fruitNames = ['Apple', 'Banana', 'Orange'];
$scope.vegNames = ['Carrot', 'Potato', 'Cabbage'];
$scope.eateries = ['Milk', 'Bread'];
}
</script>
</head>
<body ng-app = "firstApplication">
<div id = "subheaderContainer" ng-controller = "subheaderController as ctrl"
layout = "column" flex layout-fill ng-cloak>
<md-toolbar md-scroll-shrink>
<div class = "md-toolbar-tools">Items</div>
</md-toolbar>
<md-content style = "height: 600px;">
<section>
<md-subheader class = "md-primary">Fruits</md-subheader>
<md-list layout-padding>
<md-list-item ng-repeat = "fruits in fruitNames">
<div>
<p>{{fruits}}</p>
</div>
</md-list-item>
</md-list>
</section>
<section>
<md-subheader class = "md-warn">Vegetables</md-subheader>
<md-list layout-padding>
<md-list-item ng-repeat = "veg in vegNames">
<div>
<p>{{veg}}</p>
</div>
</md-list-item>
</md-list>
</section>
<section>
<md-subheader>Eateries</md-subheader>
<md-list layout-padding>
<md-list-item ng-repeat = "eatery in eateries">
<div>
<p>{{eatery}}</p>
</div>
</md-list-item>
</md-list>
</section>
</md-content>
</div>
</body>
</html>
Verify the result.
{{fruits}}
{{veg}}
{{eatery}}
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": 2273,
"s": 2190,
"text": "The md-subheader, an Angular directive, is used to show a subheader for a section."
},
{
"code": null,
"e": 2367,
"s": 2273,
"text": "The following example shows the use of md-subheader and also the uses of subheader component."
},
{
"code": null,
"e": 2385,
"s": 2367,
"text": "am_subheaders.htm"
},
{
"code": null,
"e": 5220,
"s": 2385,
"text": "<html lang = \"en\">\n <head>\n <link rel = \"stylesheet\"\n href = \"https://ajax.googleapis.com/ajax/libs/angular_material/1.0.0/angular-material.min.css\">\n <script src = \"https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js\"></script>\n <script src = \"https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular-animate.min.js\"></script>\n <script src = \"https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular-aria.min.js\"></script>\n <script src = \"https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular-messages.min.js\"></script>\n <script src = \"https://ajax.googleapis.com/ajax/libs/angular_material/1.0.0/angular-material.min.js\"></script>\n <link rel = \"stylesheet\" href = \"https://fonts.googleapis.com/icon?family=Material+Icons\">\n \n <script language = \"javascript\">\n angular\n .module('firstApplication', ['ngMaterial'])\n .controller('subheaderController', subheaderController);\n\n function subheaderController ($scope) {\n $scope.fruitNames = ['Apple', 'Banana', 'Orange'];\n $scope.vegNames = ['Carrot', 'Potato', 'Cabbage'];\n $scope.eateries = ['Milk', 'Bread'];\n }\t \n </script> \n </head>\n \n <body ng-app = \"firstApplication\"> \n <div id = \"subheaderContainer\" ng-controller = \"subheaderController as ctrl\"\n layout = \"column\" flex layout-fill ng-cloak>\n <md-toolbar md-scroll-shrink>\n <div class = \"md-toolbar-tools\">Items</div>\n </md-toolbar>\n \n <md-content style = \"height: 600px;\">\n <section>\n <md-subheader class = \"md-primary\">Fruits</md-subheader>\n <md-list layout-padding>\n <md-list-item ng-repeat = \"fruits in fruitNames\">\n <div>\n <p>{{fruits}}</p>\n </div>\n </md-list-item>\n </md-list>\n </section>\n \n <section>\n <md-subheader class = \"md-warn\">Vegetables</md-subheader>\n <md-list layout-padding>\n <md-list-item ng-repeat = \"veg in vegNames\">\n <div>\n <p>{{veg}}</p>\n </div>\n </md-list-item>\n </md-list>\n </section>\n \n <section>\n <md-subheader>Eateries</md-subheader>\n <md-list layout-padding>\n <md-list-item ng-repeat = \"eatery in eateries\">\n <div>\n <p>{{eatery}}</p>\n </div>\n </md-list-item>\n </md-list>\n </section>\n </md-content>\n \n </div>\n </body>\n</html>"
},
{
"code": null,
"e": 5239,
"s": 5220,
"text": "Verify the result."
},
{
"code": null,
"e": 5250,
"s": 5239,
"text": "{{fruits}}"
},
{
"code": null,
"e": 5258,
"s": 5250,
"text": "{{veg}}"
},
{
"code": null,
"e": 5269,
"s": 5258,
"text": "{{eatery}}"
},
{
"code": null,
"e": 5304,
"s": 5269,
"text": "\n 16 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 5318,
"s": 5304,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 5353,
"s": 5318,
"text": "\n 28 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 5367,
"s": 5353,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 5402,
"s": 5367,
"text": "\n 11 Lectures \n 7.5 hours \n"
},
{
"code": null,
"e": 5422,
"s": 5402,
"text": " SHIVPRASAD KOIRALA"
},
{
"code": null,
"e": 5457,
"s": 5422,
"text": "\n 16 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 5474,
"s": 5457,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 5507,
"s": 5474,
"text": "\n 69 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 5519,
"s": 5507,
"text": " Senol Atac"
},
{
"code": null,
"e": 5554,
"s": 5519,
"text": "\n 53 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 5566,
"s": 5554,
"text": " Senol Atac"
},
{
"code": null,
"e": 5573,
"s": 5566,
"text": " Print"
},
{
"code": null,
"e": 5584,
"s": 5573,
"text": " Add Notes"
}
] |
Creating interactive maps and Geo Visualizations in Java - GeeksforGeeks
|
24 Jan, 2022
Unfolding is a library to create interactive maps and geo visualizations in Processing and Java. In this article, we will discuss what are the features of unfolding and how it is used to create interactive maps in Java and Processing. The main purpose of using unfolding is to create not only static maps but also interactive maps in both java and processing. It can easily be installed on eclipse by downloading the unfolding template from the official website. It is widely used due to the features provided by unfolding like:
Interaction Events: In unfolding, we can easily create interactive maps. The basic interactions like zoom and pan are included in this library. Apart from these, more advanced features like overview, details or multitouch gestures can also be easily added to the maps.Data Visualization: This library is very robust that it even lets users create geo-positioned markers to display the data on a map. This visual style can be freely adapted. This library also supports users to load and display user-defined shapes like points, lines or polygons.Styled Maps: This library is a title-based map library. This library allows map titles to have various geographic features and styles. It also comes with map providers like OpenStreetMap or TileMill.Clean & Extendable Code: This library allows the beginners to easily create simple maps. Advanced users can also sketch their prototypes or create their own sophisticated visualizations.
Interaction Events: In unfolding, we can easily create interactive maps. The basic interactions like zoom and pan are included in this library. Apart from these, more advanced features like overview, details or multitouch gestures can also be easily added to the maps.
Data Visualization: This library is very robust that it even lets users create geo-positioned markers to display the data on a map. This visual style can be freely adapted. This library also supports users to load and display user-defined shapes like points, lines or polygons.
Styled Maps: This library is a title-based map library. This library allows map titles to have various geographic features and styles. It also comes with map providers like OpenStreetMap or TileMill.
Clean & Extendable Code: This library allows the beginners to easily create simple maps. Advanced users can also sketch their prototypes or create their own sophisticated visualizations.
Approach: In this implementation, let’s consider to draw two maps, one is Delhi and the other is Mumbai using this library. The map created is interactive as we can zoom in and zoom out. We need to set up our maps using the latitude and the longitude of the place. The draw function in the program runs repeatedly and draws the map repeatedly on the canvas. Below is the implementation of the above approach:
Java
// Java implementation of using// unfolding maps // Importing the libraries in eclipseimport processing.core.PApplet;import de.fhpotsdam.unfolding.UnfoldingMap;import de.fhpotsdam.unfolding.geo.Location;import de.fhpotsdam.unfolding .providers.AbstractMapProvider;import de.fhpotsdam.unfolding .providers.Google;import de.fhpotsdam.unfolding .providers.MBTilesMapProvider;import de.fhpotsdam.unfolding .utils.MapUtils; // Class to make the mappublic class MakeYourMap extends PApplet { // To keep eclipse from reporting // a warning private static final long serialVersionUID = 1L; // Initializing the height and // width of the map private static int mapWidth = 350; private static int mapHeight = 500; // This map is used to display Mumbai UnfoldingMap map1; // This map is used to display Delhi UnfoldingMap map2; // Function which implements the unfolds // library public void setup() { // Set the Applet window to be // 900x600 width and height. // The OPENGL argument indicates // to use the Processing // library's 2D drawing size(900, 600, P2D); // This sets the background colour // for the Applet. Here, colour // blue is chosen this.background(0, 0, 128); // Select a map provider. // Here we are using google provider AbstractMapProvider provider = new Google.GoogleTerrainProvider(); // Set a zoom level to focus on // our specified location int zoomLevel = 10; // Creating the first map map1 = new UnfoldingMap( this, 40, 50, mapWidth, mapHeight, provider); // This line zooms in and centers // the map at 28.7041 (latitude) // and 77.1025° (longitude) for Mumbai. map1.zoomAndPanTo( zoomLevel, new Location(28.7041f, 77.1025f)); // This line makes the map interactive // as we can zoom in and out. And, here // we have zoomed our focus to the // Mumbai location by setting the // zoom level to 10. MapUtils .createDefaultEventDispatcher( this, map1); // Creating the same map for // Delhi AbstractMapProvider provider2 = new Google.GoogleMapProvider(); map2 = new UnfoldingMap( this, 40 + mapWidth + 10, 50, mapWidth, mapHeight, provider2); // 19.0760 (latitude) and // 72.8777 (longitude) are for Delhi map2.zoomAndPanTo( zoomLevel, new Location(19.0760f, 72.8777f)); // This line makes the map interactive MapUtils .createDefaultEventDispatcher( this, map2); } // Function to draw the applet window public void draw() { // The draw method is implemented // repeatedly by drawing our maps // again and again on the canvas map1.draw(); map2.draw(); }}
Output: On running the above code, the following output is obtained:
surinderdawra388
java-advanced
Advanced Computer Subject
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
ML | Linear Regression
Decision Tree
System Design Tutorial
Copying Files to and from Docker Containers
Python | Decision tree implementation
Arrays in Java
Split() String method in Java with examples
For-each loop in Java
Initialize an ArrayList in Java
Arrays.sort() in Java with examples
|
[
{
"code": null,
"e": 23839,
"s": 23811,
"text": "\n24 Jan, 2022"
},
{
"code": null,
"e": 24370,
"s": 23839,
"text": "Unfolding is a library to create interactive maps and geo visualizations in Processing and Java. In this article, we will discuss what are the features of unfolding and how it is used to create interactive maps in Java and Processing. The main purpose of using unfolding is to create not only static maps but also interactive maps in both java and processing. It can easily be installed on eclipse by downloading the unfolding template from the official website. It is widely used due to the features provided by unfolding like: "
},
{
"code": null,
"e": 25301,
"s": 24370,
"text": "Interaction Events: In unfolding, we can easily create interactive maps. The basic interactions like zoom and pan are included in this library. Apart from these, more advanced features like overview, details or multitouch gestures can also be easily added to the maps.Data Visualization: This library is very robust that it even lets users create geo-positioned markers to display the data on a map. This visual style can be freely adapted. This library also supports users to load and display user-defined shapes like points, lines or polygons.Styled Maps: This library is a title-based map library. This library allows map titles to have various geographic features and styles. It also comes with map providers like OpenStreetMap or TileMill.Clean & Extendable Code: This library allows the beginners to easily create simple maps. Advanced users can also sketch their prototypes or create their own sophisticated visualizations."
},
{
"code": null,
"e": 25570,
"s": 25301,
"text": "Interaction Events: In unfolding, we can easily create interactive maps. The basic interactions like zoom and pan are included in this library. Apart from these, more advanced features like overview, details or multitouch gestures can also be easily added to the maps."
},
{
"code": null,
"e": 25848,
"s": 25570,
"text": "Data Visualization: This library is very robust that it even lets users create geo-positioned markers to display the data on a map. This visual style can be freely adapted. This library also supports users to load and display user-defined shapes like points, lines or polygons."
},
{
"code": null,
"e": 26048,
"s": 25848,
"text": "Styled Maps: This library is a title-based map library. This library allows map titles to have various geographic features and styles. It also comes with map providers like OpenStreetMap or TileMill."
},
{
"code": null,
"e": 26235,
"s": 26048,
"text": "Clean & Extendable Code: This library allows the beginners to easily create simple maps. Advanced users can also sketch their prototypes or create their own sophisticated visualizations."
},
{
"code": null,
"e": 26645,
"s": 26235,
"text": "Approach: In this implementation, let’s consider to draw two maps, one is Delhi and the other is Mumbai using this library. The map created is interactive as we can zoom in and zoom out. We need to set up our maps using the latitude and the longitude of the place. The draw function in the program runs repeatedly and draws the map repeatedly on the canvas. Below is the implementation of the above approach: "
},
{
"code": null,
"e": 26650,
"s": 26645,
"text": "Java"
},
{
"code": "// Java implementation of using// unfolding maps // Importing the libraries in eclipseimport processing.core.PApplet;import de.fhpotsdam.unfolding.UnfoldingMap;import de.fhpotsdam.unfolding.geo.Location;import de.fhpotsdam.unfolding .providers.AbstractMapProvider;import de.fhpotsdam.unfolding .providers.Google;import de.fhpotsdam.unfolding .providers.MBTilesMapProvider;import de.fhpotsdam.unfolding .utils.MapUtils; // Class to make the mappublic class MakeYourMap extends PApplet { // To keep eclipse from reporting // a warning private static final long serialVersionUID = 1L; // Initializing the height and // width of the map private static int mapWidth = 350; private static int mapHeight = 500; // This map is used to display Mumbai UnfoldingMap map1; // This map is used to display Delhi UnfoldingMap map2; // Function which implements the unfolds // library public void setup() { // Set the Applet window to be // 900x600 width and height. // The OPENGL argument indicates // to use the Processing // library's 2D drawing size(900, 600, P2D); // This sets the background colour // for the Applet. Here, colour // blue is chosen this.background(0, 0, 128); // Select a map provider. // Here we are using google provider AbstractMapProvider provider = new Google.GoogleTerrainProvider(); // Set a zoom level to focus on // our specified location int zoomLevel = 10; // Creating the first map map1 = new UnfoldingMap( this, 40, 50, mapWidth, mapHeight, provider); // This line zooms in and centers // the map at 28.7041 (latitude) // and 77.1025° (longitude) for Mumbai. map1.zoomAndPanTo( zoomLevel, new Location(28.7041f, 77.1025f)); // This line makes the map interactive // as we can zoom in and out. And, here // we have zoomed our focus to the // Mumbai location by setting the // zoom level to 10. MapUtils .createDefaultEventDispatcher( this, map1); // Creating the same map for // Delhi AbstractMapProvider provider2 = new Google.GoogleMapProvider(); map2 = new UnfoldingMap( this, 40 + mapWidth + 10, 50, mapWidth, mapHeight, provider2); // 19.0760 (latitude) and // 72.8777 (longitude) are for Delhi map2.zoomAndPanTo( zoomLevel, new Location(19.0760f, 72.8777f)); // This line makes the map interactive MapUtils .createDefaultEventDispatcher( this, map2); } // Function to draw the applet window public void draw() { // The draw method is implemented // repeatedly by drawing our maps // again and again on the canvas map1.draw(); map2.draw(); }}",
"e": 29676,
"s": 26650,
"text": null
},
{
"code": null,
"e": 29747,
"s": 29676,
"text": "Output: On running the above code, the following output is obtained: "
},
{
"code": null,
"e": 29766,
"s": 29749,
"text": "surinderdawra388"
},
{
"code": null,
"e": 29780,
"s": 29766,
"text": "java-advanced"
},
{
"code": null,
"e": 29806,
"s": 29780,
"text": "Advanced Computer Subject"
},
{
"code": null,
"e": 29811,
"s": 29806,
"text": "Java"
},
{
"code": null,
"e": 29816,
"s": 29811,
"text": "Java"
},
{
"code": null,
"e": 29914,
"s": 29816,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29923,
"s": 29914,
"text": "Comments"
},
{
"code": null,
"e": 29936,
"s": 29923,
"text": "Old Comments"
},
{
"code": null,
"e": 29959,
"s": 29936,
"text": "ML | Linear Regression"
},
{
"code": null,
"e": 29973,
"s": 29959,
"text": "Decision Tree"
},
{
"code": null,
"e": 29996,
"s": 29973,
"text": "System Design Tutorial"
},
{
"code": null,
"e": 30040,
"s": 29996,
"text": "Copying Files to and from Docker Containers"
},
{
"code": null,
"e": 30078,
"s": 30040,
"text": "Python | Decision tree implementation"
},
{
"code": null,
"e": 30093,
"s": 30078,
"text": "Arrays in Java"
},
{
"code": null,
"e": 30137,
"s": 30093,
"text": "Split() String method in Java with examples"
},
{
"code": null,
"e": 30159,
"s": 30137,
"text": "For-each loop in Java"
},
{
"code": null,
"e": 30191,
"s": 30159,
"text": "Initialize an ArrayList in Java"
}
] |
The Struggles I Had When Switching to Python | Towards Data Science
|
When I started learning data science, I started learning with R. I was a statistics major, and in the world of academia, there is a heavy preference of R over Python. There isn’t anything inherently wrong with learning one or the other, but I had invested several years mastering R before I joined the workforce and Python became a requirement.
I went into my first job with expectations of being able to build models and automate everything using the tools I had in R. My dreams of predicting and eliminating all the work were quickly dashed when I found out that nobody at my job knew much of anything about R. This meant that anything I created would have no support from the IT department or any of my coworkers if I ever moved on. I could automate my own work but if I started moving my way up the corporate ladder, nobody would be able to do my job the way I was.
As time went on, I started working more with the data science team and their IT support team. They introduced me to this wonderful language called Python. As with any new language or tool, there was a bit of a learning curve that came with it. I struggled a lot. Here are some of the things about Python that are different that really tripped me up.
Yup, first on the list is my inability to save data frames after modifying them. In R, that might look something like this (when using dplyr):
dataframe <- dataframe %>% select(-col1)
In case you don’t know dplyr well, this code simply drops the column named col1. Since the data frame, dataframe, and function, select, are physically separate from each other, I wouldn’t really expect the output to be saved, so without thinking I assign it to dataframe to overwrite it without the col1 column.
To do the same thing in Python, I used to do something like this:
# The wrong way!>>> dataframe.drop('col1')
The first couple times I did this I would spend the following hour or two muttering curse words under my breath, wondering why col1 was still part of my data frame. You might ask, why wouldn’t I just assign the output to the original variable? Well in python we get these nifty things called methods, like .drop(). They are physically attached to the object they are acting upon. To the Python newbie, we want to believe that they will just change the object and we don’t have to save anything. Alas, the wonderful world of Python doesn’t work like that.
# This actually SAVES the modification>>> dataframe = dataframe.drop('col1')
So there you have it, my first struggle switching from R to Python:
I never remember to save my Python data frames after modifying them
This in and of itself isn’t the most confusing thing in the world, just different from the way R handles things. But those familiar with Python data frame methods might know a little trick that will not require you to save your data frame after dropping a column...
Before all you python experts get all up in arms about how you can in fact modify data frames in place, yes, I know about that now. If I really didn’t want to reassign the variable I could just add the inplace=True argument to the .drop() method. Nice and flexible, problem solved, right?
# We don't need to save changes here>>> dataframe.drop('col1', inplace=True)
Sure that works, but what happens when a method doesn’t have an inplace argument or I’m using a function instead of a method? Being new to the language, having options doesn’t exactly make things easier to remember or use.
In terms of having the ability to complete operations in place, I am all for it. Heck, it is even well implemented in the sense that it isn’t the default behavior to modify data frames in place. But that is for data frames.
What about lists? If I create a list of strings, many string methods, like .append, .insert, .pop, and .remove modify the list in place, with no need to save the result. Take this example where we remove 9 from the list (because 7 ate 9, obviously 😏).
>>> x = [7, 8, 9]>>> x.remove(9)>>> print(x)[1] [7, 8]
What makes it worse is that in a typical way Python is taught, you will learn about lists and how they work before you learn anything about a data frame. The confusion comes because in Python, lists are not analogous to data frame columns the same way R vectors are analogous to data frame columns.
So that was my second big struggle when learning Python:
Some objects (lists) are modified in place by their methods, while others (DataFrames) you need to save in order to modify them through their object methods
It is one of those things that needs to be learned, to some extent is just memorizing how each different object works. I guess some things just look different when coming from R to Python. Which brings me to my next struggle...
In R, we often, somewhat carelessly, load all of our packages into our workspace. R will try to find a function in a loaded library by name, and execute if it exists.
Sometimes you load a package and it will “mask” a function from another package. If you aren’t familiar, this just means that it will use the version of the function from the latest package loaded that has the function. If you want to specify a different library’s version of the function, you can do that. Just put the package name before the function, separated by a double colon (::). Here are some examples:
# Uses the "base" library version of filterfilter(x)# Uses the "dplyr" library version of filterlibrary(dplyr)filter(x)# Uses the "base" version, even if it's maskedbase::filer(x)
That’s really all there is to functions in R. It uses the latest loaded version unless you tell it otherwise.
In Python, things are a little different. There are 3 main ways functions can be called. I use the term function a bit loosely here because to an R user, methods look a lot like functions.
A function name, like with len()
A function from a module, like with pd.DataFrame()
A method from a object class, like df.drop()
You might see them in code as follows.
# A functionlen(df)# A function from a modulepd.DataFrame(myDict)# An object class methoddf.drop('col1')
How is this confusing? Well, in Python you need to know how to call what would just be a function in R. In R, if you want to know how many columns a data frame has, you would just use the ncol() function. In Python, there isn’t a built in function to do this. Instead, you can use the len() function on the .columns attribute of a DataFrame.
# Rncol(df)# Pythonlen(df.columns)
Another example how Python functions can be confusing to R users is finding the number of rows in a DataFrame. In R, we once again use a single function, nrow(). In Python, we call len() on the entire data frame instead of its columns attribute.
# Rnrow(df)# Pythonlen(df)
So here we used the exact same len() function to get different pieces of information about our data frame in Python. The drawback is having to remember what to pass as the argument to len(). R keeps it simple. If we want the number of columns, use ncol(). Number of rows? That’s right, nrow().
Let’s do one more example to show the difficulties of knowing where a function lives in Python. Say we want to know both number of rows and number of columns. In R, the dim() function will serve us well. It will return a vector with the number of rows and number of columns. In order to do this in one call in Python, we need to use the .shape attribute. .shape will return a tuple with the number of rows and columns.
# Rdim(df)# Pythondf.shape
So if you’re still with me at this point, we’re not even using a method or function in Python, we’re just looking up an attribute of the data frame. So there you have it:
R has functions to complete tasks, where in Python you may have to use a function, an object method, an object attribute, or some combination to do the same thing
It isn’t wrong, but makes it so much harder to remember how to get information for someone who is used to just using a function.
Let’s try something else. Say we want to create a dataframe, a very common task in both languages. In R, we just use the dataframe function. In python, we have to specify where python should look for the dataframe function, specifically in the pandas library.
# Rx <- data.frame(X = c(1, 2, 3, 4, 5))# Pythonx = pd.DataFrame({X: [1, 2, 3, 4, 5]})
This is different because we HAVE to specify which package the function is from in Python. R would just use the latest loaded package that contains the function. The benefit of python’s implementation is that you always know the package the function is coming from. This is different, and causes some confusion if you aren’t used to needing to specify which package your function is coming from.
Sometimes in Python you need to specify what module your function is coming from, where R will just guess which package to use
Now the final thing that always got me about Python functions was object methods. They aren’t inherently bad, but they can be confusing for us R users. As we mentioned earlier, they sometimes act on the object in place, and other times they need to be saved over the original object to modify it. This section is about how functions are used, and that is difficult to remember in python.
In R, we call functions by their name, adding objects and options as arguments. Using the pipe operator %>%, you can define an object as the first argument of a function. Each action is telling R to “do this” and each pipe operator is saying “then.” When we string them together, we can complete multiple actions at the same time in a highly readable format.
df %>% select(-col1) %>% summarize(avg_col1 = mean(col1))
Using pipes is the closest analogy I can come up with in R to how object methods work in Python. They can both be strung together, and each step acts as a “do this then” set of instructions. The way they get written is just a little different.
df.drop('col2', 1).mean()
This statement above takes df then drops col2 then gets the average of the remaining values. Similar behavior, but different implementation.
Python methods can be strung together like how we would use the pipe operator in R, just a little less easy to read
No really, it may sound weird, but going to Python I never wanted to look at what errors were saying or put effort into figuring them out. I already mastered R and when things don’t run, I usually already knew what to look for without reading the errors.
After gaining some experience with this, it became much easier to help other R to Python converts. The errors would tell me which of the struggles they were dealing with.
Read your errors carefully and understand what code it is referring to and what it is saying is wrong
In Python, I got a lot more errors than I would in R and it was frustrating. But errors are extremely helpful in learning a language and mastering it. Let’s take this one for example:
>>> '2' + 2Traceback (most recent call last): File "<stdin>", line 1, in <module>TypeError: Can't convert 'int' object to str implicitly
Errors in python are helpfully labelled for you. The very first part of the error will say Traceback, usually with some text with a file and line number. Not always the most helpful for the beginner for more complex errors, but remember it is there.
The next part of the error text is TypeError. This is a category of error. There are many types of errors in Python (see a whole bunch of them in the official Python documentation). This one is saying something about the types of objects used in the code is causing the error.
The next part of the error gives you more details about the error that was encountered. Here we can see that python doesn’t know how to add an int object to a str object. From here we can easily fix our code. If the goal was to concatenate two strings together, we can add single quotes to the second 2.
>>> '2' + '2'[1] '22'
If the goal was to add two numbers together, we need to eliminate the single quotes on the first one so that it has the correct type.
>>> 2 + 2[1] 4
Either way, reading the error helps us know that the objects need to be of the same type for our code to work.
Not sure what an error means? Search it up online. Some errors are more complex than others and some may be due to some other part of your code. Break it down as simple as you can and work through it piece by piece.
You’ll master python just as quickly as you mastered R in no time. There are many who have come before you who have experience going from one language to another.
Let’s recap the lessons I learned while learning Python as an R user:
In Python, some methods modify objects in place (like lists methods) while others need to save the output over the original variable to modify it (like data frame methods)
R uses functions for almost everything while Python uses a mix of functions, object methods, and object attributes to do the same things
R generally guesses which library your function is from. Python generally needs to be told where to look
R can use the pipe operator %>% to string operations together. Python object methods can sometimes be strung together to achieve the same result
R and Python both provide errors when your code fails. These contain valuable information and learning to read and correct them is the only way to truly master the language
If all else fails, ask someone more experienced on your team or in your class what you are doing wrong. If that doesn’t work, ask the internet. There are tons of free and paid resources out there. Check out some of the ones below:
w3schools.com — a comprehensive knowledge base of Python, R, SQL, and other programming and scripting languages. It is free to everyone and has interactive examples for more languages and concepts.
Datacamp.com (PAID link) — Interactive programming tutorials, mainly focusing on R and Python for data analysis. They offer the first chapter of every course for free, so go ahead and try out their Python for R Users course!
Python for R Users (PAID link) — Written specifically get you up to speed on Python, this book focuses on actionable code and performing the analysis you already know in Python!
|
[
{
"code": null,
"e": 516,
"s": 171,
"text": "When I started learning data science, I started learning with R. I was a statistics major, and in the world of academia, there is a heavy preference of R over Python. There isn’t anything inherently wrong with learning one or the other, but I had invested several years mastering R before I joined the workforce and Python became a requirement."
},
{
"code": null,
"e": 1041,
"s": 516,
"text": "I went into my first job with expectations of being able to build models and automate everything using the tools I had in R. My dreams of predicting and eliminating all the work were quickly dashed when I found out that nobody at my job knew much of anything about R. This meant that anything I created would have no support from the IT department or any of my coworkers if I ever moved on. I could automate my own work but if I started moving my way up the corporate ladder, nobody would be able to do my job the way I was."
},
{
"code": null,
"e": 1391,
"s": 1041,
"text": "As time went on, I started working more with the data science team and their IT support team. They introduced me to this wonderful language called Python. As with any new language or tool, there was a bit of a learning curve that came with it. I struggled a lot. Here are some of the things about Python that are different that really tripped me up."
},
{
"code": null,
"e": 1534,
"s": 1391,
"text": "Yup, first on the list is my inability to save data frames after modifying them. In R, that might look something like this (when using dplyr):"
},
{
"code": null,
"e": 1578,
"s": 1534,
"text": "dataframe <- dataframe %>% select(-col1)"
},
{
"code": null,
"e": 1890,
"s": 1578,
"text": "In case you don’t know dplyr well, this code simply drops the column named col1. Since the data frame, dataframe, and function, select, are physically separate from each other, I wouldn’t really expect the output to be saved, so without thinking I assign it to dataframe to overwrite it without the col1 column."
},
{
"code": null,
"e": 1956,
"s": 1890,
"text": "To do the same thing in Python, I used to do something like this:"
},
{
"code": null,
"e": 1999,
"s": 1956,
"text": "# The wrong way!>>> dataframe.drop('col1')"
},
{
"code": null,
"e": 2554,
"s": 1999,
"text": "The first couple times I did this I would spend the following hour or two muttering curse words under my breath, wondering why col1 was still part of my data frame. You might ask, why wouldn’t I just assign the output to the original variable? Well in python we get these nifty things called methods, like .drop(). They are physically attached to the object they are acting upon. To the Python newbie, we want to believe that they will just change the object and we don’t have to save anything. Alas, the wonderful world of Python doesn’t work like that."
},
{
"code": null,
"e": 2631,
"s": 2554,
"text": "# This actually SAVES the modification>>> dataframe = dataframe.drop('col1')"
},
{
"code": null,
"e": 2699,
"s": 2631,
"text": "So there you have it, my first struggle switching from R to Python:"
},
{
"code": null,
"e": 2767,
"s": 2699,
"text": "I never remember to save my Python data frames after modifying them"
},
{
"code": null,
"e": 3033,
"s": 2767,
"text": "This in and of itself isn’t the most confusing thing in the world, just different from the way R handles things. But those familiar with Python data frame methods might know a little trick that will not require you to save your data frame after dropping a column..."
},
{
"code": null,
"e": 3322,
"s": 3033,
"text": "Before all you python experts get all up in arms about how you can in fact modify data frames in place, yes, I know about that now. If I really didn’t want to reassign the variable I could just add the inplace=True argument to the .drop() method. Nice and flexible, problem solved, right?"
},
{
"code": null,
"e": 3399,
"s": 3322,
"text": "# We don't need to save changes here>>> dataframe.drop('col1', inplace=True)"
},
{
"code": null,
"e": 3622,
"s": 3399,
"text": "Sure that works, but what happens when a method doesn’t have an inplace argument or I’m using a function instead of a method? Being new to the language, having options doesn’t exactly make things easier to remember or use."
},
{
"code": null,
"e": 3846,
"s": 3622,
"text": "In terms of having the ability to complete operations in place, I am all for it. Heck, it is even well implemented in the sense that it isn’t the default behavior to modify data frames in place. But that is for data frames."
},
{
"code": null,
"e": 4098,
"s": 3846,
"text": "What about lists? If I create a list of strings, many string methods, like .append, .insert, .pop, and .remove modify the list in place, with no need to save the result. Take this example where we remove 9 from the list (because 7 ate 9, obviously 😏)."
},
{
"code": null,
"e": 4153,
"s": 4098,
"text": ">>> x = [7, 8, 9]>>> x.remove(9)>>> print(x)[1] [7, 8]"
},
{
"code": null,
"e": 4452,
"s": 4153,
"text": "What makes it worse is that in a typical way Python is taught, you will learn about lists and how they work before you learn anything about a data frame. The confusion comes because in Python, lists are not analogous to data frame columns the same way R vectors are analogous to data frame columns."
},
{
"code": null,
"e": 4509,
"s": 4452,
"text": "So that was my second big struggle when learning Python:"
},
{
"code": null,
"e": 4666,
"s": 4509,
"text": "Some objects (lists) are modified in place by their methods, while others (DataFrames) you need to save in order to modify them through their object methods"
},
{
"code": null,
"e": 4894,
"s": 4666,
"text": "It is one of those things that needs to be learned, to some extent is just memorizing how each different object works. I guess some things just look different when coming from R to Python. Which brings me to my next struggle..."
},
{
"code": null,
"e": 5061,
"s": 4894,
"text": "In R, we often, somewhat carelessly, load all of our packages into our workspace. R will try to find a function in a loaded library by name, and execute if it exists."
},
{
"code": null,
"e": 5473,
"s": 5061,
"text": "Sometimes you load a package and it will “mask” a function from another package. If you aren’t familiar, this just means that it will use the version of the function from the latest package loaded that has the function. If you want to specify a different library’s version of the function, you can do that. Just put the package name before the function, separated by a double colon (::). Here are some examples:"
},
{
"code": null,
"e": 5653,
"s": 5473,
"text": "# Uses the \"base\" library version of filterfilter(x)# Uses the \"dplyr\" library version of filterlibrary(dplyr)filter(x)# Uses the \"base\" version, even if it's maskedbase::filer(x)"
},
{
"code": null,
"e": 5763,
"s": 5653,
"text": "That’s really all there is to functions in R. It uses the latest loaded version unless you tell it otherwise."
},
{
"code": null,
"e": 5952,
"s": 5763,
"text": "In Python, things are a little different. There are 3 main ways functions can be called. I use the term function a bit loosely here because to an R user, methods look a lot like functions."
},
{
"code": null,
"e": 5985,
"s": 5952,
"text": "A function name, like with len()"
},
{
"code": null,
"e": 6036,
"s": 5985,
"text": "A function from a module, like with pd.DataFrame()"
},
{
"code": null,
"e": 6081,
"s": 6036,
"text": "A method from a object class, like df.drop()"
},
{
"code": null,
"e": 6120,
"s": 6081,
"text": "You might see them in code as follows."
},
{
"code": null,
"e": 6225,
"s": 6120,
"text": "# A functionlen(df)# A function from a modulepd.DataFrame(myDict)# An object class methoddf.drop('col1')"
},
{
"code": null,
"e": 6567,
"s": 6225,
"text": "How is this confusing? Well, in Python you need to know how to call what would just be a function in R. In R, if you want to know how many columns a data frame has, you would just use the ncol() function. In Python, there isn’t a built in function to do this. Instead, you can use the len() function on the .columns attribute of a DataFrame."
},
{
"code": null,
"e": 6602,
"s": 6567,
"text": "# Rncol(df)# Pythonlen(df.columns)"
},
{
"code": null,
"e": 6848,
"s": 6602,
"text": "Another example how Python functions can be confusing to R users is finding the number of rows in a DataFrame. In R, we once again use a single function, nrow(). In Python, we call len() on the entire data frame instead of its columns attribute."
},
{
"code": null,
"e": 6875,
"s": 6848,
"text": "# Rnrow(df)# Pythonlen(df)"
},
{
"code": null,
"e": 7169,
"s": 6875,
"text": "So here we used the exact same len() function to get different pieces of information about our data frame in Python. The drawback is having to remember what to pass as the argument to len(). R keeps it simple. If we want the number of columns, use ncol(). Number of rows? That’s right, nrow()."
},
{
"code": null,
"e": 7588,
"s": 7169,
"text": "Let’s do one more example to show the difficulties of knowing where a function lives in Python. Say we want to know both number of rows and number of columns. In R, the dim() function will serve us well. It will return a vector with the number of rows and number of columns. In order to do this in one call in Python, we need to use the .shape attribute. .shape will return a tuple with the number of rows and columns."
},
{
"code": null,
"e": 7615,
"s": 7588,
"text": "# Rdim(df)# Pythondf.shape"
},
{
"code": null,
"e": 7786,
"s": 7615,
"text": "So if you’re still with me at this point, we’re not even using a method or function in Python, we’re just looking up an attribute of the data frame. So there you have it:"
},
{
"code": null,
"e": 7949,
"s": 7786,
"text": "R has functions to complete tasks, where in Python you may have to use a function, an object method, an object attribute, or some combination to do the same thing"
},
{
"code": null,
"e": 8078,
"s": 7949,
"text": "It isn’t wrong, but makes it so much harder to remember how to get information for someone who is used to just using a function."
},
{
"code": null,
"e": 8338,
"s": 8078,
"text": "Let’s try something else. Say we want to create a dataframe, a very common task in both languages. In R, we just use the dataframe function. In python, we have to specify where python should look for the dataframe function, specifically in the pandas library."
},
{
"code": null,
"e": 8425,
"s": 8338,
"text": "# Rx <- data.frame(X = c(1, 2, 3, 4, 5))# Pythonx = pd.DataFrame({X: [1, 2, 3, 4, 5]})"
},
{
"code": null,
"e": 8821,
"s": 8425,
"text": "This is different because we HAVE to specify which package the function is from in Python. R would just use the latest loaded package that contains the function. The benefit of python’s implementation is that you always know the package the function is coming from. This is different, and causes some confusion if you aren’t used to needing to specify which package your function is coming from."
},
{
"code": null,
"e": 8948,
"s": 8821,
"text": "Sometimes in Python you need to specify what module your function is coming from, where R will just guess which package to use"
},
{
"code": null,
"e": 9336,
"s": 8948,
"text": "Now the final thing that always got me about Python functions was object methods. They aren’t inherently bad, but they can be confusing for us R users. As we mentioned earlier, they sometimes act on the object in place, and other times they need to be saved over the original object to modify it. This section is about how functions are used, and that is difficult to remember in python."
},
{
"code": null,
"e": 9695,
"s": 9336,
"text": "In R, we call functions by their name, adding objects and options as arguments. Using the pipe operator %>%, you can define an object as the first argument of a function. Each action is telling R to “do this” and each pipe operator is saying “then.” When we string them together, we can complete multiple actions at the same time in a highly readable format."
},
{
"code": null,
"e": 9753,
"s": 9695,
"text": "df %>% select(-col1) %>% summarize(avg_col1 = mean(col1))"
},
{
"code": null,
"e": 9997,
"s": 9753,
"text": "Using pipes is the closest analogy I can come up with in R to how object methods work in Python. They can both be strung together, and each step acts as a “do this then” set of instructions. The way they get written is just a little different."
},
{
"code": null,
"e": 10023,
"s": 9997,
"text": "df.drop('col2', 1).mean()"
},
{
"code": null,
"e": 10164,
"s": 10023,
"text": "This statement above takes df then drops col2 then gets the average of the remaining values. Similar behavior, but different implementation."
},
{
"code": null,
"e": 10280,
"s": 10164,
"text": "Python methods can be strung together like how we would use the pipe operator in R, just a little less easy to read"
},
{
"code": null,
"e": 10535,
"s": 10280,
"text": "No really, it may sound weird, but going to Python I never wanted to look at what errors were saying or put effort into figuring them out. I already mastered R and when things don’t run, I usually already knew what to look for without reading the errors."
},
{
"code": null,
"e": 10706,
"s": 10535,
"text": "After gaining some experience with this, it became much easier to help other R to Python converts. The errors would tell me which of the struggles they were dealing with."
},
{
"code": null,
"e": 10808,
"s": 10706,
"text": "Read your errors carefully and understand what code it is referring to and what it is saying is wrong"
},
{
"code": null,
"e": 10992,
"s": 10808,
"text": "In Python, I got a lot more errors than I would in R and it was frustrating. But errors are extremely helpful in learning a language and mastering it. Let’s take this one for example:"
},
{
"code": null,
"e": 11130,
"s": 10992,
"text": ">>> '2' + 2Traceback (most recent call last): File \"<stdin>\", line 1, in <module>TypeError: Can't convert 'int' object to str implicitly"
},
{
"code": null,
"e": 11380,
"s": 11130,
"text": "Errors in python are helpfully labelled for you. The very first part of the error will say Traceback, usually with some text with a file and line number. Not always the most helpful for the beginner for more complex errors, but remember it is there."
},
{
"code": null,
"e": 11657,
"s": 11380,
"text": "The next part of the error text is TypeError. This is a category of error. There are many types of errors in Python (see a whole bunch of them in the official Python documentation). This one is saying something about the types of objects used in the code is causing the error."
},
{
"code": null,
"e": 11961,
"s": 11657,
"text": "The next part of the error gives you more details about the error that was encountered. Here we can see that python doesn’t know how to add an int object to a str object. From here we can easily fix our code. If the goal was to concatenate two strings together, we can add single quotes to the second 2."
},
{
"code": null,
"e": 11983,
"s": 11961,
"text": ">>> '2' + '2'[1] '22'"
},
{
"code": null,
"e": 12117,
"s": 11983,
"text": "If the goal was to add two numbers together, we need to eliminate the single quotes on the first one so that it has the correct type."
},
{
"code": null,
"e": 12132,
"s": 12117,
"text": ">>> 2 + 2[1] 4"
},
{
"code": null,
"e": 12243,
"s": 12132,
"text": "Either way, reading the error helps us know that the objects need to be of the same type for our code to work."
},
{
"code": null,
"e": 12459,
"s": 12243,
"text": "Not sure what an error means? Search it up online. Some errors are more complex than others and some may be due to some other part of your code. Break it down as simple as you can and work through it piece by piece."
},
{
"code": null,
"e": 12622,
"s": 12459,
"text": "You’ll master python just as quickly as you mastered R in no time. There are many who have come before you who have experience going from one language to another."
},
{
"code": null,
"e": 12692,
"s": 12622,
"text": "Let’s recap the lessons I learned while learning Python as an R user:"
},
{
"code": null,
"e": 12864,
"s": 12692,
"text": "In Python, some methods modify objects in place (like lists methods) while others need to save the output over the original variable to modify it (like data frame methods)"
},
{
"code": null,
"e": 13001,
"s": 12864,
"text": "R uses functions for almost everything while Python uses a mix of functions, object methods, and object attributes to do the same things"
},
{
"code": null,
"e": 13106,
"s": 13001,
"text": "R generally guesses which library your function is from. Python generally needs to be told where to look"
},
{
"code": null,
"e": 13251,
"s": 13106,
"text": "R can use the pipe operator %>% to string operations together. Python object methods can sometimes be strung together to achieve the same result"
},
{
"code": null,
"e": 13424,
"s": 13251,
"text": "R and Python both provide errors when your code fails. These contain valuable information and learning to read and correct them is the only way to truly master the language"
},
{
"code": null,
"e": 13655,
"s": 13424,
"text": "If all else fails, ask someone more experienced on your team or in your class what you are doing wrong. If that doesn’t work, ask the internet. There are tons of free and paid resources out there. Check out some of the ones below:"
},
{
"code": null,
"e": 13853,
"s": 13655,
"text": "w3schools.com — a comprehensive knowledge base of Python, R, SQL, and other programming and scripting languages. It is free to everyone and has interactive examples for more languages and concepts."
},
{
"code": null,
"e": 14078,
"s": 13853,
"text": "Datacamp.com (PAID link) — Interactive programming tutorials, mainly focusing on R and Python for data analysis. They offer the first chapter of every course for free, so go ahead and try out their Python for R Users course!"
}
] |
How to add a variable to Python plt.title?
|
To add a varaible to Python plt.title(), we can take the following steps −
Create data points for x and y using numpy and num (is a variable) to calculate y and set this in title.
Create data points for x and y using numpy and num (is a variable) to calculate y and set this in title.
Plot x and y data points using plot() method with red color.
Plot x and y data points using plot() method with red color.
Set the title of the curve with variable num.
Set the title of the curve with variable num.
To display the figure, use show() method.
To display the figure, use show() method.
import numpy as np
from matplotlib import pyplot as plt
plt.rcParams["figure.figsize"] = [7.00, 3.50]
plt.rcParams["figure.autolayout"] = True
x = np.linspace(-1, 1, 10)
num = 2
y = num ** x
plt.plot(x, y, c='red')
plt.title(f"y=%d$^x$" % num)
plt.show()
|
[
{
"code": null,
"e": 1137,
"s": 1062,
"text": "To add a varaible to Python plt.title(), we can take the following steps −"
},
{
"code": null,
"e": 1242,
"s": 1137,
"text": "Create data points for x and y using numpy and num (is a variable) to calculate y and set this in title."
},
{
"code": null,
"e": 1347,
"s": 1242,
"text": "Create data points for x and y using numpy and num (is a variable) to calculate y and set this in title."
},
{
"code": null,
"e": 1408,
"s": 1347,
"text": "Plot x and y data points using plot() method with red color."
},
{
"code": null,
"e": 1469,
"s": 1408,
"text": "Plot x and y data points using plot() method with red color."
},
{
"code": null,
"e": 1515,
"s": 1469,
"text": "Set the title of the curve with variable num."
},
{
"code": null,
"e": 1561,
"s": 1515,
"text": "Set the title of the curve with variable num."
},
{
"code": null,
"e": 1603,
"s": 1561,
"text": "To display the figure, use show() method."
},
{
"code": null,
"e": 1645,
"s": 1603,
"text": "To display the figure, use show() method."
},
{
"code": null,
"e": 1900,
"s": 1645,
"text": "import numpy as np\nfrom matplotlib import pyplot as plt\nplt.rcParams[\"figure.figsize\"] = [7.00, 3.50]\nplt.rcParams[\"figure.autolayout\"] = True\nx = np.linspace(-1, 1, 10)\nnum = 2\ny = num ** x\nplt.plot(x, y, c='red')\nplt.title(f\"y=%d$^x$\" % num)\nplt.show()"
}
] |
Python – Non-overlapping Random Ranges
|
22 Apr, 2020
Sometimes, while working with Python, we can have problem in which we need to extract N random ranges which are non-overlapping in nature and with given range size. This can have applications in which we work with data. Lets discuss certain way in which this task can be performed.
Method : Using any() + randint() + loopThis is brute force way in which this task can be performed. In this we extract random ranges using randint(), and check for non-repetition of number ranges using any() and loop.
# Python3 code to demonstrate working of # Non-overlapping Random Ranges# Using loop + any() + randint()import random # initializing N N = 7 # initializing K K = 5 # Non-overlapping Random Ranges# Using loop + any() + randint()tot = 10000res = set()for _ in range(N): temp = random.randint(0, tot - K) while any(temp >= idx and temp <= idx + K for idx in res): temp = random.randint(0, tot - K) res.add(temp)res = [(idx, idx + K) for idx in res] # printing result print("The N Non-overlapping Random ranges are : " + str(res))
The N Non-overlapping Random ranges are : [(5347, 5352), (7108, 7113), (5479, 5484), (1906, 1911), (2228, 2233), (5206, 5211), (3260, 3265)]
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": "\n22 Apr, 2020"
},
{
"code": null,
"e": 310,
"s": 28,
"text": "Sometimes, while working with Python, we can have problem in which we need to extract N random ranges which are non-overlapping in nature and with given range size. This can have applications in which we work with data. Lets discuss certain way in which this task can be performed."
},
{
"code": null,
"e": 528,
"s": 310,
"text": "Method : Using any() + randint() + loopThis is brute force way in which this task can be performed. In this we extract random ranges using randint(), and check for non-repetition of number ranges using any() and loop."
},
{
"code": "# Python3 code to demonstrate working of # Non-overlapping Random Ranges# Using loop + any() + randint()import random # initializing N N = 7 # initializing K K = 5 # Non-overlapping Random Ranges# Using loop + any() + randint()tot = 10000res = set()for _ in range(N): temp = random.randint(0, tot - K) while any(temp >= idx and temp <= idx + K for idx in res): temp = random.randint(0, tot - K) res.add(temp)res = [(idx, idx + K) for idx in res] # printing result print(\"The N Non-overlapping Random ranges are : \" + str(res)) ",
"e": 1069,
"s": 528,
"text": null
},
{
"code": null,
"e": 1211,
"s": 1069,
"text": "The N Non-overlapping Random ranges are : [(5347, 5352), (7108, 7113), (5479, 5484), (1906, 1911), (2228, 2233), (5206, 5211), (3260, 3265)]\n"
},
{
"code": null,
"e": 1232,
"s": 1211,
"text": "Python list-programs"
},
{
"code": null,
"e": 1239,
"s": 1232,
"text": "Python"
},
{
"code": null,
"e": 1255,
"s": 1239,
"text": "Python Programs"
}
] |
Python | Adding value to sublists
|
08 Apr, 2019
Sometimes, we just have to manipulate a list of lists by appending a similar value to all the sublists. Using a loop for achieving this particular task can be an option but sometimes leads to sacrifice the readability of code. It is always wanted to have a oneliner to perform this particular task. Let’s discuss certain ways in which this can be done.
Method #1 : Using list comprehensionList comprehension can be used to perform this particular task using a similar looping construct but in just a single line. This increases code readability.
# Python3 code to demonstrate # appending single value # using list comprehension # initializing list of liststest_list = [[1, 3], [3, 4], [6, 5], [4, 5]] # printing original list print("The original list : " + str(test_list)) # declaring element to be insertedK = "GFG" # using list comprehension # appending single valueres = [[i, j, K ] for i, j in test_list] # printing result print("The list after adding element : " + str(res))
The original list : [[1, 3], [3, 4], [6, 5], [4, 5]]The list after adding element : [[1, 3, ‘GFG’], [3, 4, ‘GFG’], [6, 5, ‘GFG’], [4, 5, ‘GFG’]]
Method #2 : Using list comprehension + "+" operatorThis method is quite similar to the above method, but the difference is that plus operator is used to add the new element to each sublist.
# Python3 code to demonstrate # appending single value # using list comprehension + "+" operator # initializing list of liststest_list = [[1, 3], [3, 4], [6, 5], [4, 5]] # printing original list print("The original list : " + str(test_list)) # declaring element to be insertedK = "GFG" # using list comprehension + "+" operator# appending single valueres = [sub + [K] for sub in test_list] # printing result print("The list after adding element : " + str(res))
The original list : [[1, 3], [3, 4], [6, 5], [4, 5]]The list after adding element : [[1, 3, ‘GFG’], [3, 4, ‘GFG’], [6, 5, ‘GFG’], [4, 5, ‘GFG’]]
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": "\n08 Apr, 2019"
},
{
"code": null,
"e": 381,
"s": 28,
"text": "Sometimes, we just have to manipulate a list of lists by appending a similar value to all the sublists. Using a loop for achieving this particular task can be an option but sometimes leads to sacrifice the readability of code. It is always wanted to have a oneliner to perform this particular task. Let’s discuss certain ways in which this can be done."
},
{
"code": null,
"e": 574,
"s": 381,
"text": "Method #1 : Using list comprehensionList comprehension can be used to perform this particular task using a similar looping construct but in just a single line. This increases code readability."
},
{
"code": "# Python3 code to demonstrate # appending single value # using list comprehension # initializing list of liststest_list = [[1, 3], [3, 4], [6, 5], [4, 5]] # printing original list print(\"The original list : \" + str(test_list)) # declaring element to be insertedK = \"GFG\" # using list comprehension # appending single valueres = [[i, j, K ] for i, j in test_list] # printing result print(\"The list after adding element : \" + str(res))",
"e": 1016,
"s": 574,
"text": null
},
{
"code": null,
"e": 1161,
"s": 1016,
"text": "The original list : [[1, 3], [3, 4], [6, 5], [4, 5]]The list after adding element : [[1, 3, ‘GFG’], [3, 4, ‘GFG’], [6, 5, ‘GFG’], [4, 5, ‘GFG’]]"
},
{
"code": null,
"e": 1353,
"s": 1163,
"text": "Method #2 : Using list comprehension + \"+\" operatorThis method is quite similar to the above method, but the difference is that plus operator is used to add the new element to each sublist."
},
{
"code": "# Python3 code to demonstrate # appending single value # using list comprehension + \"+\" operator # initializing list of liststest_list = [[1, 3], [3, 4], [6, 5], [4, 5]] # printing original list print(\"The original list : \" + str(test_list)) # declaring element to be insertedK = \"GFG\" # using list comprehension + \"+\" operator# appending single valueres = [sub + [K] for sub in test_list] # printing result print(\"The list after adding element : \" + str(res))",
"e": 1821,
"s": 1353,
"text": null
},
{
"code": null,
"e": 1966,
"s": 1821,
"text": "The original list : [[1, 3], [3, 4], [6, 5], [4, 5]]The list after adding element : [[1, 3, ‘GFG’], [3, 4, ‘GFG’], [6, 5, ‘GFG’], [4, 5, ‘GFG’]]"
},
{
"code": null,
"e": 1987,
"s": 1966,
"text": "Python list-programs"
},
{
"code": null,
"e": 1994,
"s": 1987,
"text": "Python"
},
{
"code": null,
"e": 2010,
"s": 1994,
"text": "Python Programs"
}
] |
How to Permute the Rows and Columns in a Matrix on MATLAB?
|
27 Jan, 2022
In this article, we will discuss how to find the permutation of the rows and columns in a Matrix with the help of multiple approaches
In this approach, we are simply permuting the rows and columns of the matrix in the specified format of rows and columns respectively. For column permutation, we take an example of a 3*3 matrix being permuted in such a way that its first column becomes the second one, the second becomes the third one and lastly, the third becomes the first column.
Example 1:
Matlab
% MATLAB code for column permutation% and specifying a 3*3 matrixA = [1 2 3 4 5 6 7 8 9] % Initializing a list of columns (Index)% in which above matrix need to be% permutedindex = [3 1 2] % Getting the column permuted matrix BB = A(:, index)
Output:
A =
1 2 3
4 5 6
7 8 9
index =
3 1 2
B =
3 1 2
6 4 5
9 7 8
Example 2:
Matlab
% MATLAB code for rows permutation.% Specifying a 3*3 matrixA = [1 2 3 4 5 6 7 8 9] % Initializing a list of rows (Index)% in which above matrix need to be% permutedindex = [3 1 2] % Getting the rows permuted matrix BB = A(index,
Output:
A =
1 2 3
4 5 6
7 8 9
index =
3 1 2
B =
7 8 9
1 2 3
4 5 6
The perms() function returns a matrix that contains all the possible permutations of the elements of the specified vector “v” in reverse lexicographic order. Here each row of the returned matrix contains a different permutation of the “n” elements of the specified vector “v”. The returned matrix has the same data type as the given vector “v” and has n! rows and n columns.
Syntax:
perms(v)
Parameters: This function accepts a parameter which is illustrated below:
v: This is the specified vector containing the “n” number of elements.
Return Value: It returns a matrix that contains all the possible permutations of the elements of the specified vector “v” in reverse lexicographic order.
Example 1:
Matlab
% MATLAB code for perms()% Initializing a vector of some elementsvector = [1 2 3]; % Calling the perms() function over the% above vector as its parameter whose% elements are going to be permutedP = perms(vector)
Output:
P =
3 2 1
3 1 2
2 3 1
2 1 3
1 3 2
1 2 3
Example 2:
Matlab
% MATLAB code for perms()% Initializing a vector of some complex numbersvector = [1+2i 3+4i 5+6i]; % Calling the perms() function over the% above vector as its parameter whose% elements are going to be permutedP = perms(vector)
Output:
P =
5 + 6i 3 + 4i 1 + 2i
5 + 6i 1 + 2i 3 + 4i
3 + 4i 5 + 6i 1 + 2i
3 + 4i 1 + 2i 5 + 6i
1 + 2i 5 + 6i 3 + 4i
1 + 2i 3 + 4i 5 + 6i
The permute() function rearranges the dimensions of the specified array in the order specified by the vector dimorder.
Syntax:
permute(A, dimorder)
Parameters: This function accepts two parameters, which are illustrated below:
A: This is the specified array matrix.
dimorder: This is the specified vector order in which permutation is being done.
Return Value: It returns the permuted matrix.
Example 1:
Matlab
% MATLAB code for permute()% Creating a random 2*3 matrixA = rand(2, 3) % Calling the permute() function% over the above matrix in the% dimension order of [2 1]B = permute(A, [2 1])
Output:
A =
0.32773 0.12633 0.67752
0.26285 0.91283 0.42994
B =
0.32773 0.26285
0.12633 0.91283
0.67752 0.42994
Example 2:
Matlab
% MATLAB code for permute ()% Creating 2-by-3-by-2 random array matrixA = rand(3, 3, 2) % Calling the permute() function% over the above matrix in the% dimension order of [2 3 1]B = permute(A, [2 3 1])
Output:
A =
ans(:,:,1) =
0.53364 0.65671 0.32496
0.82471 0.36042 0.31604
0.82714 0.84231 0.70248
ans(:,:,2) =
0.424538 0.498572 0.972245
0.069400 0.799598 0.754885
0.722046 0.807107 0.392804
B =
ans(:,:,1) =
0.53364 0.42454
0.65671 0.49857
0.32496 0.97224
ans(:,:,2) =
0.824706 0.069400
0.360418 0.799598
0.316038 0.754885
ans(:,:,3) =
0.82714 0.72205
0.84231 0.80711
0.70248 0.39280
arorakashish0911
simranarora5sos
MATLAB-matrix
MATLAB-programs
Picked
MATLAB
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n27 Jan, 2022"
},
{
"code": null,
"e": 162,
"s": 28,
"text": "In this article, we will discuss how to find the permutation of the rows and columns in a Matrix with the help of multiple approaches"
},
{
"code": null,
"e": 513,
"s": 162,
"text": "In this approach, we are simply permuting the rows and columns of the matrix in the specified format of rows and columns respectively. For column permutation, we take an example of a 3*3 matrix being permuted in such a way that its first column becomes the second one, the second becomes the third one and lastly, the third becomes the first column."
},
{
"code": null,
"e": 525,
"s": 513,
"text": "Example 1: "
},
{
"code": null,
"e": 532,
"s": 525,
"text": "Matlab"
},
{
"code": "% MATLAB code for column permutation% and specifying a 3*3 matrixA = [1 2 3 4 5 6 7 8 9] % Initializing a list of columns (Index)% in which above matrix need to be% permutedindex = [3 1 2] % Getting the column permuted matrix BB = A(:, index)",
"e": 788,
"s": 532,
"text": null
},
{
"code": null,
"e": 797,
"s": 788,
"text": "Output: "
},
{
"code": null,
"e": 897,
"s": 797,
"text": "A =\n 1 2 3\n 4 5 6\n 7 8 9\nindex =\n 3 1 2\nB =\n 3 1 2\n 6 4 5\n 9 7 8"
},
{
"code": null,
"e": 909,
"s": 897,
"text": "Example 2: "
},
{
"code": null,
"e": 916,
"s": 909,
"text": "Matlab"
},
{
"code": "% MATLAB code for rows permutation.% Specifying a 3*3 matrixA = [1 2 3 4 5 6 7 8 9] % Initializing a list of rows (Index)% in which above matrix need to be% permutedindex = [3 1 2] % Getting the rows permuted matrix BB = A(index, ",
"e": 1160,
"s": 916,
"text": null
},
{
"code": null,
"e": 1169,
"s": 1160,
"text": "Output: "
},
{
"code": null,
"e": 1269,
"s": 1169,
"text": "A =\n 1 2 3\n 4 5 6\n 7 8 9\nindex =\n 3 1 2\nB =\n 7 8 9\n 1 2 3\n 4 5 6"
},
{
"code": null,
"e": 1644,
"s": 1269,
"text": "The perms() function returns a matrix that contains all the possible permutations of the elements of the specified vector “v” in reverse lexicographic order. Here each row of the returned matrix contains a different permutation of the “n” elements of the specified vector “v”. The returned matrix has the same data type as the given vector “v” and has n! rows and n columns."
},
{
"code": null,
"e": 1653,
"s": 1644,
"text": "Syntax: "
},
{
"code": null,
"e": 1662,
"s": 1653,
"text": "perms(v)"
},
{
"code": null,
"e": 1736,
"s": 1662,
"text": "Parameters: This function accepts a parameter which is illustrated below:"
},
{
"code": null,
"e": 1807,
"s": 1736,
"text": "v: This is the specified vector containing the “n” number of elements."
},
{
"code": null,
"e": 1962,
"s": 1807,
"text": "Return Value: It returns a matrix that contains all the possible permutations of the elements of the specified vector “v” in reverse lexicographic order. "
},
{
"code": null,
"e": 1974,
"s": 1962,
"text": "Example 1: "
},
{
"code": null,
"e": 1981,
"s": 1974,
"text": "Matlab"
},
{
"code": "% MATLAB code for perms()% Initializing a vector of some elementsvector = [1 2 3]; % Calling the perms() function over the% above vector as its parameter whose% elements are going to be permutedP = perms(vector)",
"e": 2193,
"s": 1981,
"text": null
},
{
"code": null,
"e": 2202,
"s": 2193,
"text": "Output: "
},
{
"code": null,
"e": 2278,
"s": 2202,
"text": "P =\n 3 2 1\n 3 1 2\n 2 3 1\n 2 1 3\n 1 3 2\n 1 2 3"
},
{
"code": null,
"e": 2290,
"s": 2278,
"text": "Example 2: "
},
{
"code": null,
"e": 2297,
"s": 2290,
"text": "Matlab"
},
{
"code": "% MATLAB code for perms()% Initializing a vector of some complex numbersvector = [1+2i 3+4i 5+6i]; % Calling the perms() function over the% above vector as its parameter whose% elements are going to be permutedP = perms(vector)",
"e": 2525,
"s": 2297,
"text": null
},
{
"code": null,
"e": 2534,
"s": 2525,
"text": "Output: "
},
{
"code": null,
"e": 2700,
"s": 2534,
"text": "P =\n 5 + 6i 3 + 4i 1 + 2i\n 5 + 6i 1 + 2i 3 + 4i\n 3 + 4i 5 + 6i 1 + 2i\n 3 + 4i 1 + 2i 5 + 6i\n 1 + 2i 5 + 6i 3 + 4i\n 1 + 2i 3 + 4i 5 + 6i"
},
{
"code": null,
"e": 2819,
"s": 2700,
"text": "The permute() function rearranges the dimensions of the specified array in the order specified by the vector dimorder."
},
{
"code": null,
"e": 2828,
"s": 2819,
"text": "Syntax: "
},
{
"code": null,
"e": 2849,
"s": 2828,
"text": "permute(A, dimorder)"
},
{
"code": null,
"e": 2929,
"s": 2849,
"text": "Parameters: This function accepts two parameters, which are illustrated below: "
},
{
"code": null,
"e": 2968,
"s": 2929,
"text": "A: This is the specified array matrix."
},
{
"code": null,
"e": 3049,
"s": 2968,
"text": "dimorder: This is the specified vector order in which permutation is being done."
},
{
"code": null,
"e": 3095,
"s": 3049,
"text": "Return Value: It returns the permuted matrix."
},
{
"code": null,
"e": 3107,
"s": 3095,
"text": "Example 1: "
},
{
"code": null,
"e": 3114,
"s": 3107,
"text": "Matlab"
},
{
"code": "% MATLAB code for permute()% Creating a random 2*3 matrixA = rand(2, 3) % Calling the permute() function% over the above matrix in the% dimension order of [2 1]B = permute(A, [2 1])",
"e": 3296,
"s": 3114,
"text": null
},
{
"code": null,
"e": 3305,
"s": 3296,
"text": "Output: "
},
{
"code": null,
"e": 3433,
"s": 3305,
"text": "A =\n 0.32773 0.12633 0.67752\n 0.26285 0.91283 0.42994\nB =\n 0.32773 0.26285\n 0.12633 0.91283\n 0.67752 0.42994"
},
{
"code": null,
"e": 3445,
"s": 3433,
"text": "Example 2: "
},
{
"code": null,
"e": 3452,
"s": 3445,
"text": "Matlab"
},
{
"code": "% MATLAB code for permute ()% Creating 2-by-3-by-2 random array matrixA = rand(3, 3, 2) % Calling the permute() function% over the above matrix in the% dimension order of [2 3 1]B = permute(A, [2 3 1])",
"e": 3654,
"s": 3452,
"text": null
},
{
"code": null,
"e": 3663,
"s": 3654,
"text": "Output: "
},
{
"code": null,
"e": 4111,
"s": 3663,
"text": "A =\nans(:,:,1) =\n 0.53364 0.65671 0.32496\n 0.82471 0.36042 0.31604\n 0.82714 0.84231 0.70248\nans(:,:,2) =\n 0.424538 0.498572 0.972245\n 0.069400 0.799598 0.754885\n 0.722046 0.807107 0.392804\nB =\nans(:,:,1) =\n 0.53364 0.42454\n 0.65671 0.49857\n 0.32496 0.97224\nans(:,:,2) =\n 0.824706 0.069400\n 0.360418 0.799598\n 0.316038 0.754885\nans(:,:,3) =\n 0.82714 0.72205\n 0.84231 0.80711\n 0.70248 0.39280"
},
{
"code": null,
"e": 4130,
"s": 4113,
"text": "arorakashish0911"
},
{
"code": null,
"e": 4146,
"s": 4130,
"text": "simranarora5sos"
},
{
"code": null,
"e": 4160,
"s": 4146,
"text": "MATLAB-matrix"
},
{
"code": null,
"e": 4176,
"s": 4160,
"text": "MATLAB-programs"
},
{
"code": null,
"e": 4183,
"s": 4176,
"text": "Picked"
},
{
"code": null,
"e": 4190,
"s": 4183,
"text": "MATLAB"
}
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.