title
stringlengths
3
221
text
stringlengths
17
477k
parsed
listlengths
0
3.17k
SciPy – Constants
13 Jan, 2022 Scipy stands for Scientific Python and in any Scientific/Mathematical calculation, we often need universal constants to carry out tasks, one famous example is calculating the Area of a circle = ‘pi*r*r’ where PI = 3.14... or a more complicated one like finding forcegravity = G*M*m ⁄ (distance)2 where G = gravitational constant. In all such scenarios, it would be very handy if we have reference material to look up these constants and incorporate them into our calculation with ease. Scipy-Constants is a sub-module inside the Scipy library that does this for us. It contains an exhaustive list of universal mathematical constants, Physical constants, and units. which can be looked up with just 1 line of code. Just type the name of the constant in place of XXXX in ‘scipy.constants.XXXX‘ format to access its value. Below listed are a few most important constants using scipy.constant module down below. The list is not exhaustive, but it gives a good idea of how to access constants. Python3 # import moduleimport scipy # Just type the name of the constant in# scipy.constant.XXXX format to access its value.print("sciPy - pi:", scipy.constants.pi)print("Golden ratio:", scipy.constants.golden_ratio)print("Speed of light in vacuum:", scipy.constants.c)print("Gravitational Constant:", scipy.constants.G)print("Molar Gas Constant:", scipy.constants.R)print("Boltzman Constant:", scipy.constants.k)print("Proton mass Constant:", scipy.constants.proton_mass) Output: We can use an inbuilt method to find the constants relevant to our use case. Constants are stored using a dictionary data structure, and we can use the scipy. constants.find() API to find all relevant constants from the dict and use them accordingly. The code below demonstrates using scipy. constants.find() API. The below code prints all constants which contain the ‘electron’ word in it, and we can filter out the one which is required. Python3 import scipy # find method looks up in the dictorary and# finds out all the constants containing# 'electron' word in it and returns a list# of constants.res = scipy.constants.find("electron")print(res, end='\n') Output: Not just the magnitude of a constant we can also access the unit and degree of uncertainty associated with the magnitude of any physical_constants stored in scipy.constants module, using the format physical_constants[name] = (value, unit, uncertainty). Python3 import scipy # This returns a tuple (value, unit, uncertainty)# associated with the physical constantprint(scipy.constants.physical_constants['alpha particle mass']) Output: (6.6446573357e-27, 'kg', 2e-36) Example: Python3 import scipy # Area of a circle using# scipy.constants.pidef Area_of_Circle(r): return scipy.constants.pi * r * r # Calculates the gravational fordef force_gravity(M, m, dist): return (scipy.constants.G*M*m) / (dist**2) print(f'Area of Circle: {Area_of_Circle(5)}')print(f'Gravitational force: {force_gravity(10,5,1)}') Output: Apart from the above variables, scipy.constants also contain more physical constants, and below is a list of all methods available in scipy.constants module with an explanation. Below are the most commonly used constants available in SciPy module: Below are the unit constants available in the SciPy module: Mass: Time: Length: Pressure: Area: Speed: singghakshay simmytarika5 adnanirshad158 Picked 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 ? 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": "\n13 Jan, 2022" }, { "code": null, "e": 514, "s": 28, "text": "Scipy stands for Scientific Python and in any Scientific/Mathematical calculation, we often need universal constants to carry out tasks, one famous example is calculating the Area of a circle = ‘pi*r*r’ where PI = 3.14... or a more complicated one like finding forcegravity = G*M*m ⁄ (distance)2 where G = gravitational constant. In all such scenarios, it would be very handy if we have reference material to look up these constants and incorporate them into our calculation with ease." }, { "code": null, "e": 742, "s": 514, "text": "Scipy-Constants is a sub-module inside the Scipy library that does this for us. It contains an exhaustive list of universal mathematical constants, Physical constants, and units. which can be looked up with just 1 line of code." }, { "code": null, "e": 1019, "s": 742, "text": "Just type the name of the constant in place of XXXX in ‘scipy.constants.XXXX‘ format to access its value. Below listed are a few most important constants using scipy.constant module down below. The list is not exhaustive, but it gives a good idea of how to access constants. " }, { "code": null, "e": 1027, "s": 1019, "text": "Python3" }, { "code": "# import moduleimport scipy # Just type the name of the constant in# scipy.constant.XXXX format to access its value.print(\"sciPy - pi:\", scipy.constants.pi)print(\"Golden ratio:\", scipy.constants.golden_ratio)print(\"Speed of light in vacuum:\", scipy.constants.c)print(\"Gravitational Constant:\", scipy.constants.G)print(\"Molar Gas Constant:\", scipy.constants.R)print(\"Boltzman Constant:\", scipy.constants.k)print(\"Proton mass Constant:\", scipy.constants.proton_mass)", "e": 1492, "s": 1027, "text": null }, { "code": null, "e": 1500, "s": 1492, "text": "Output:" }, { "code": null, "e": 1752, "s": 1500, "text": "We can use an inbuilt method to find the constants relevant to our use case. Constants are stored using a dictionary data structure, and we can use the scipy. constants.find() API to find all relevant constants from the dict and use them accordingly. " }, { "code": null, "e": 1942, "s": 1752, "text": "The code below demonstrates using scipy. constants.find() API. The below code prints all constants which contain the ‘electron’ word in it, and we can filter out the one which is required. " }, { "code": null, "e": 1950, "s": 1942, "text": "Python3" }, { "code": "import scipy # find method looks up in the dictorary and# finds out all the constants containing# 'electron' word in it and returns a list# of constants.res = scipy.constants.find(\"electron\")print(res, end='\\n')", "e": 2163, "s": 1950, "text": null }, { "code": null, "e": 2171, "s": 2163, "text": "Output:" }, { "code": null, "e": 2370, "s": 2171, "text": "Not just the magnitude of a constant we can also access the unit and degree of uncertainty associated with the magnitude of any physical_constants stored in scipy.constants module, using the format " }, { "code": null, "e": 2425, "s": 2370, "text": "physical_constants[name] = (value, unit, uncertainty)." }, { "code": null, "e": 2433, "s": 2425, "text": "Python3" }, { "code": "import scipy # This returns a tuple (value, unit, uncertainty)# associated with the physical constantprint(scipy.constants.physical_constants['alpha particle mass'])", "e": 2600, "s": 2433, "text": null }, { "code": null, "e": 2609, "s": 2600, "text": "Output: " }, { "code": null, "e": 2641, "s": 2609, "text": "(6.6446573357e-27, 'kg', 2e-36)" }, { "code": null, "e": 2650, "s": 2641, "text": "Example:" }, { "code": null, "e": 2658, "s": 2650, "text": "Python3" }, { "code": "import scipy # Area of a circle using# scipy.constants.pidef Area_of_Circle(r): return scipy.constants.pi * r * r # Calculates the gravational fordef force_gravity(M, m, dist): return (scipy.constants.G*M*m) / (dist**2) print(f'Area of Circle: {Area_of_Circle(5)}')print(f'Gravitational force: {force_gravity(10,5,1)}')", "e": 2985, "s": 2658, "text": null }, { "code": null, "e": 2993, "s": 2985, "text": "Output:" }, { "code": null, "e": 3171, "s": 2993, "text": "Apart from the above variables, scipy.constants also contain more physical constants, and below is a list of all methods available in scipy.constants module with an explanation." }, { "code": null, "e": 3241, "s": 3171, "text": "Below are the most commonly used constants available in SciPy module:" }, { "code": null, "e": 3301, "s": 3241, "text": "Below are the unit constants available in the SciPy module:" }, { "code": null, "e": 3307, "s": 3301, "text": "Mass:" }, { "code": null, "e": 3313, "s": 3307, "text": "Time:" }, { "code": null, "e": 3321, "s": 3313, "text": "Length:" }, { "code": null, "e": 3331, "s": 3321, "text": "Pressure:" }, { "code": null, "e": 3337, "s": 3331, "text": "Area:" }, { "code": null, "e": 3344, "s": 3337, "text": "Speed:" }, { "code": null, "e": 3357, "s": 3344, "text": "singghakshay" }, { "code": null, "e": 3370, "s": 3357, "text": "simmytarika5" }, { "code": null, "e": 3385, "s": 3370, "text": "adnanirshad158" }, { "code": null, "e": 3392, "s": 3385, "text": "Picked" }, { "code": null, "e": 3405, "s": 3392, "text": "Python-scipy" }, { "code": null, "e": 3412, "s": 3405, "text": "Python" }, { "code": null, "e": 3510, "s": 3412, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3542, "s": 3510, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 3569, "s": 3542, "text": "Python Classes and Objects" }, { "code": null, "e": 3590, "s": 3569, "text": "Python OOPs Concepts" }, { "code": null, "e": 3613, "s": 3590, "text": "Introduction To PYTHON" }, { "code": null, "e": 3669, "s": 3613, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 3700, "s": 3669, "text": "Python | os.path.join() method" }, { "code": null, "e": 3742, "s": 3700, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 3784, "s": 3742, "text": "Check if element exists in list in Python" }, { "code": null, "e": 3823, "s": 3784, "text": "Python | datetime.timedelta() function" } ]
Difference between Shallow and Deep copy of a class
16 Nov, 2020 Shallow Copy: Shallow repetition is quicker. However, it’s “lazy” it handles pointers and references. Rather than creating a contemporary copy of the particular knowledge the pointer points to, it simply copies over the pointer price. So, each the first and therefore the copy can have pointers that reference constant underlying knowledge. Deep Copy: Deep repetition truly clones the underlying data. It is not shared between the first and therefore the copy. Below is the tabular Difference between the Shallow Copy and Deep Copy: Below is the program to explain the shallow and deep copy of the class. Python3 # Python3 implementation of the Deep# copy and Shallow Copyfrom copy import copy, deepcopy # Class of Carclass Car: def __init__(self, name, colors): self.name = name self.colors = colors honda = Car("Honda", ["Red", "Blue"]) # Deepcopy of Hondadeepcopy_honda = deepcopy(honda)deepcopy_honda.colors.append("Green")print(deepcopy_honda.colors, \ honda.colors) # Shallow Copy of Hondacopy_honda = copy(honda) copy_honda.colors.append("Green")print(copy_honda.colors, \ honda.colors) ['Red', 'Blue', 'Green'] ['Red', 'Blue'] ['Red', 'Blue', 'Green'] ['Red', 'Blue', 'Green'] pulkitagarwal03pulkit python Difference Between Programming Language Python python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Difference between var, let and const keywords in JavaScript Difference Between Method Overloading and Method Overriding in Java Similarities and Difference between Java and C++ Difference between Internal and External fragmentation Difference between Compile-time and Run-time Polymorphism in Java Arrow operator -> in C/C++ with Examples Modulo Operator (%) in C/C++ with Examples Structures in C++ Decorators with parameters in Python C# | Data Types
[ { "code": null, "e": 54, "s": 26, "text": "\n16 Nov, 2020" }, { "code": null, "e": 395, "s": 54, "text": "Shallow Copy: Shallow repetition is quicker. However, it’s “lazy” it handles pointers and references. Rather than creating a contemporary copy of the particular knowledge the pointer points to, it simply copies over the pointer price. So, each the first and therefore the copy can have pointers that reference constant underlying knowledge." }, { "code": null, "e": 515, "s": 395, "text": "Deep Copy: Deep repetition truly clones the underlying data. It is not shared between the first and therefore the copy." }, { "code": null, "e": 588, "s": 515, "text": "Below is the tabular Difference between the Shallow Copy and Deep Copy: " }, { "code": null, "e": 662, "s": 590, "text": "Below is the program to explain the shallow and deep copy of the class." }, { "code": null, "e": 672, "s": 664, "text": "Python3" }, { "code": "# Python3 implementation of the Deep# copy and Shallow Copyfrom copy import copy, deepcopy # Class of Carclass Car: def __init__(self, name, colors): self.name = name self.colors = colors honda = Car(\"Honda\", [\"Red\", \"Blue\"]) # Deepcopy of Hondadeepcopy_honda = deepcopy(honda)deepcopy_honda.colors.append(\"Green\")print(deepcopy_honda.colors, \\ honda.colors) # Shallow Copy of Hondacopy_honda = copy(honda) copy_honda.colors.append(\"Green\")print(copy_honda.colors, \\ honda.colors)", "e": 1181, "s": 672, "text": null }, { "code": null, "e": 1275, "s": 1181, "text": "['Red', 'Blue', 'Green'] ['Red', 'Blue']\n['Red', 'Blue', 'Green'] ['Red', 'Blue', 'Green']\n\n\n" }, { "code": null, "e": 1299, "s": 1277, "text": "pulkitagarwal03pulkit" }, { "code": null, "e": 1306, "s": 1299, "text": "python" }, { "code": null, "e": 1325, "s": 1306, "text": "Difference Between" }, { "code": null, "e": 1346, "s": 1325, "text": "Programming Language" }, { "code": null, "e": 1353, "s": 1346, "text": "Python" }, { "code": null, "e": 1360, "s": 1353, "text": "python" }, { "code": null, "e": 1458, "s": 1360, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1519, "s": 1458, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 1587, "s": 1519, "text": "Difference Between Method Overloading and Method Overriding in Java" }, { "code": null, "e": 1636, "s": 1587, "text": "Similarities and Difference between Java and C++" }, { "code": null, "e": 1691, "s": 1636, "text": "Difference between Internal and External fragmentation" }, { "code": null, "e": 1757, "s": 1691, "text": "Difference between Compile-time and Run-time Polymorphism in Java" }, { "code": null, "e": 1798, "s": 1757, "text": "Arrow operator -> in C/C++ with Examples" }, { "code": null, "e": 1841, "s": 1798, "text": "Modulo Operator (%) in C/C++ with Examples" }, { "code": null, "e": 1859, "s": 1841, "text": "Structures in C++" }, { "code": null, "e": 1896, "s": 1859, "text": "Decorators with parameters in Python" } ]
Java.util.Collections.rotate() Method in Java with Examples
07 Dec, 2018 java.util.Collections.rotate() method is present in java.util.Collections class. It is used to rotate the elements present in the specified list of Collection by a given distance. Syntax: public static void rotate(List< type > list, int distance) Parameters : list - the list to be rotated. distance - the distance to rotate the list. type - Type of list to be rotated. Examples of types are Integer, String, etc. Returns : NA Throws: UnsupportedOperationException - if the specified list or its list-iterator does not support the set operation. There are no constraints on distance value. It may be zero, negative, or greater than list.size(). After calling this method, the element at index i will be the element previously at index (i – distance) mod list.size(), for all values of i between 0 and list.size()-1, inclusive. // Java program to demonstrate working of // java.utils.Collections.rotate() import java.util.*; public class RotateDemo{ public static void main(String[] args) { // Let us create a list of strings List<String> mylist = new ArrayList<String>(); mylist.add("practice"); mylist.add("code"); mylist.add("quiz"); mylist.add("geeksforgeeks"); System.out.println("Original List : " + mylist); // Here we are using rotate() method // to rotate the element by distance 2 Collections.rotate(mylist, 2); System.out.println("Rotated List: " + mylist); }} Output: Original List : [practice, code, quiz, geeksforgeeks] Rotated List: [quiz, geeksforgeeks, practice, code] How to quickly rotate an array in Java using rotate()? Arrays class in Java doesn’t have rotate method. We can use Collections.rotate() to quickly rotate an array also. // Java program to demonstrate rotation of array// with Collections.rotate()import java.util.*; public class RotateDemo{ public static void main(String[] args) { // Let us create an array of integers Integer arr[] = {10, 20, 30, 40, 50}; System.out.println("Original Array : " + Arrays.toString(arr)); // Please refer below post for details of asList() // https://www.geeksforgeeks.org/array-class-in-java/ // rotating an array by distance 2 Collections.rotate(Arrays.asList(arr), 2); System.out.println("Modified Array : " + Arrays.toString(arr)); }} Output: Original Array : [10, 20, 30, 40, 50] Modified Array : [40, 50, 10, 20, 30] This article is contributed by Gaurav Miglani. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. Java - util package Java-Collections Java-Collections-Class Java-Functions Java Java Java-Collections Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n07 Dec, 2018" }, { "code": null, "e": 232, "s": 52, "text": "java.util.Collections.rotate() method is present in java.util.Collections class. It is used to rotate the elements present in the specified list of Collection by a given distance." }, { "code": null, "e": 610, "s": 232, "text": "Syntax:\npublic static void rotate(List< type > list, int distance)\nParameters : \nlist - the list to be rotated.\ndistance - the distance to rotate the list. \ntype - Type of list to be rotated. Examples of \n types are Integer, String, etc.\nReturns :\nNA\nThrows:\nUnsupportedOperationException - if the specified list or \nits list-iterator does not support the set operation.\n" }, { "code": null, "e": 891, "s": 610, "text": "There are no constraints on distance value. It may be zero, negative, or greater than list.size(). After calling this method, the element at index i will be the element previously at index (i – distance) mod list.size(), for all values of i between 0 and list.size()-1, inclusive." }, { "code": "// Java program to demonstrate working of // java.utils.Collections.rotate() import java.util.*; public class RotateDemo{ public static void main(String[] args) { // Let us create a list of strings List<String> mylist = new ArrayList<String>(); mylist.add(\"practice\"); mylist.add(\"code\"); mylist.add(\"quiz\"); mylist.add(\"geeksforgeeks\"); System.out.println(\"Original List : \" + mylist); // Here we are using rotate() method // to rotate the element by distance 2 Collections.rotate(mylist, 2); System.out.println(\"Rotated List: \" + mylist); }}", "e": 1534, "s": 891, "text": null }, { "code": null, "e": 1542, "s": 1534, "text": "Output:" }, { "code": null, "e": 1649, "s": 1542, "text": "Original List : [practice, code, quiz, geeksforgeeks]\nRotated List: [quiz, geeksforgeeks, practice, code]\n" }, { "code": null, "e": 1704, "s": 1649, "text": "How to quickly rotate an array in Java using rotate()?" }, { "code": null, "e": 1818, "s": 1704, "text": "Arrays class in Java doesn’t have rotate method. We can use Collections.rotate() to quickly rotate an array also." }, { "code": "// Java program to demonstrate rotation of array// with Collections.rotate()import java.util.*; public class RotateDemo{ public static void main(String[] args) { // Let us create an array of integers Integer arr[] = {10, 20, 30, 40, 50}; System.out.println(\"Original Array : \" + Arrays.toString(arr)); // Please refer below post for details of asList() // https://www.geeksforgeeks.org/array-class-in-java/ // rotating an array by distance 2 Collections.rotate(Arrays.asList(arr), 2); System.out.println(\"Modified Array : \" + Arrays.toString(arr)); }}", "e": 2524, "s": 1818, "text": null }, { "code": null, "e": 2532, "s": 2524, "text": "Output:" }, { "code": null, "e": 2609, "s": 2532, "text": "Original Array : [10, 20, 30, 40, 50]\nModified Array : [40, 50, 10, 20, 30]\n" }, { "code": null, "e": 2911, "s": 2609, "text": "This article is contributed by Gaurav Miglani. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks." }, { "code": null, "e": 3036, "s": 2911, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 3056, "s": 3036, "text": "Java - util package" }, { "code": null, "e": 3073, "s": 3056, "text": "Java-Collections" }, { "code": null, "e": 3096, "s": 3073, "text": "Java-Collections-Class" }, { "code": null, "e": 3111, "s": 3096, "text": "Java-Functions" }, { "code": null, "e": 3116, "s": 3111, "text": "Java" }, { "code": null, "e": 3121, "s": 3116, "text": "Java" }, { "code": null, "e": 3138, "s": 3121, "text": "Java-Collections" } ]
Capped Collections in MongoDB
17 Feb, 2021 Capped collections are fixed-size collections means when we create the collection, we must fix the maximum size of the collection(in bytes) and the maximum number of documents that it can store. After creation, if we try to add more than documents to their capacity, it overwrites the existing documents. It supports high-throughput operations, that are useful when we insert and retrieve documents based on insertion order. The working of the capped collection is similar to circular buffers, which means once the fixed space is allocated for the capped collection, it creates/makes spaces for the new documents by overwriting the oldest documents in the given collection. Capped collection can also have _id field and by default, each _id field has an index. We create the capped collections using the createCollection() method in MongoDB. When we create a new capped collection, we must specify the maximum size of the collection in bytes, which will MongoDB pre-allocate for the collection. The size of the capped collection contains a small amount of space for the internal overhead and if the value of the size field is less than or equal to 4096, then the capacity of the collection is 4096 bytes. Otherwise, MongoDB will automatically increase the size to make it an integer multiple of 256 and specify a maximum document count using the max field. If the given collection reaches the maximum size limit before it reaches the maximum document count, then MongoDB removes older documents to create space for the new document. Syntax: db.createCollection(<name>, {capped: <boolean>, autoIndexId: <boolean>, size: <number>, max: <number>, storageEngine: <document>, validator: <document>, validationLevel: <string>, validationAction: <string>, indexOptionDefaults: <document>, viewOn: <string>, pipeline: <pipeline>, collation: <document>, writeConcern: <document>}) Parameters: name: It represents the name of the collection and it is of string type. options: It is an optional parameter. Optional parameters: capped: It is used to create a capped collection. If the value of this field is true then you must specify the maximum size in the size field. It is of boolean type. autoIndexId: If the value of this field is false then it disables the automatic creation of an index on the _id field. It is of boolean type. size: It specifies the maximum size of the collection in bytes. It is of number type. max: It specifies the maximum number of documents allowed in the capped collection. It is of number type. storageEngine: It is available only for the WiredTiger storage engine only. It is of the document type. validator: It specifies the validation rules for the collection. It is of the document type. validationLevel: It illustrates how strictly MongoDB applies the validation rule on the existing document during updates. It is of sting type. validationAction: It illustrates whether to error on invalid documents or just warn about the violations but allows invalid documents to be inserted. It is of string type. indexOptionDefaults: It allows the user to specify the default configuration for indexes when creating a collection. It is of document type. viewOn: Name of the source collection or view from which to create the view. It is of string type. pipeline: It is an array that contains the aggregation pipeline stages. Or using this parameter we can apply pipeline to the view or viewOne collection. It is of an array type. collation: It specifies the default collation from the given collection. It is of the document type. writeConcern: It expresses the write concern for the operation. If you want to use default write concern then avoid this parameter. It is of document type. Examples: In the following example, we are working with the “gfg” database in which we are creating a new capped collection of name “student” with maximum document capacity “4” using createCollection() method. db.createCollection("student", {capped:true, size:10000, max:4}) Now we insert the documents in the student collection: After insert documents, we will display all the documents present in the student collection using find() method. Now, if we try to insert one more document, it will override the existing document. In the example, we are inserting a new document with the name Akash that overrides the existing document with the name Mihir: After inserting one or more document: We can check whether the collection is capped or not with the isCapped() method in MongoDB. This method returns true is the specified collections capped collection. Otherwise, return, false. Syntax: db.Collection_name.isCapped() Example: db.student.isCapped() After convert student collection to a capped: If there is an existing collection that we want to change it to capped, we can do it using the convertToCapped command. It changes the current collection to capped collection: Syntax: { convertToCapped: <collection>, size: <capped size>, writeConcern: <document>, comment: <any> } Example: db.runCommand({"convertToCapped":"student",size:5000}) Before convert to capped: After convert to capped: To return documents in insertion order, queries do not need an index, since it provides greater insertion throughput. Capped collections allow changes that match the size of the original document to ensure that the document does not change its position on the disk. Holding log files is useful. The update operation fails if the update of a document exceeds the original size of the collection. Deleting documents from a capped collection is not possible. If you want to delete all records from a capped collection, then use the given command: { emptycapped: Collection_name } Capped collection cant be shard. MongoDB Picked MongoDB Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to connect MongoDB with ReactJS ? MongoDB - limit() Method MongoDB - sort() Method MongoDB - FindOne() Method MongoDB updateOne() Method - db.Collection.updateOne() MongoDB - Compound Indexes MongoDB - Regex MongoDB updateMany() Method - db.Collection.updateMany() MongoDB Cursor Spring Boot - CRUD Operations using MongoDB
[ { "code": null, "e": 28, "s": 0, "text": "\n17 Feb, 2021" }, { "code": null, "e": 789, "s": 28, "text": "Capped collections are fixed-size collections means when we create the collection, we must fix the maximum size of the collection(in bytes) and the maximum number of documents that it can store. After creation, if we try to add more than documents to their capacity, it overwrites the existing documents. It supports high-throughput operations, that are useful when we insert and retrieve documents based on insertion order. The working of the capped collection is similar to circular buffers, which means once the fixed space is allocated for the capped collection, it creates/makes spaces for the new documents by overwriting the oldest documents in the given collection. Capped collection can also have _id field and by default, each _id field has an index." }, { "code": null, "e": 1561, "s": 789, "text": "We create the capped collections using the createCollection() method in MongoDB. When we create a new capped collection, we must specify the maximum size of the collection in bytes, which will MongoDB pre-allocate for the collection. The size of the capped collection contains a small amount of space for the internal overhead and if the value of the size field is less than or equal to 4096, then the capacity of the collection is 4096 bytes. Otherwise, MongoDB will automatically increase the size to make it an integer multiple of 256 and specify a maximum document count using the max field. If the given collection reaches the maximum size limit before it reaches the maximum document count, then MongoDB removes older documents to create space for the new document." }, { "code": null, "e": 1569, "s": 1561, "text": "Syntax:" }, { "code": null, "e": 1900, "s": 1569, "text": "db.createCollection(<name>, {capped: <boolean>, autoIndexId: <boolean>, size: <number>, max: <number>, storageEngine: <document>, validator: <document>, validationLevel: <string>, validationAction: <string>, indexOptionDefaults: <document>, viewOn: <string>, pipeline: <pipeline>, collation: <document>, writeConcern: <document>})" }, { "code": null, "e": 1912, "s": 1900, "text": "Parameters:" }, { "code": null, "e": 1985, "s": 1912, "text": "name: It represents the name of the collection and it is of string type." }, { "code": null, "e": 2023, "s": 1985, "text": "options: It is an optional parameter." }, { "code": null, "e": 2044, "s": 2023, "text": "Optional parameters:" }, { "code": null, "e": 2210, "s": 2044, "text": "capped: It is used to create a capped collection. If the value of this field is true then you must specify the maximum size in the size field. It is of boolean type." }, { "code": null, "e": 2352, "s": 2210, "text": "autoIndexId: If the value of this field is false then it disables the automatic creation of an index on the _id field. It is of boolean type." }, { "code": null, "e": 2438, "s": 2352, "text": "size: It specifies the maximum size of the collection in bytes. It is of number type." }, { "code": null, "e": 2544, "s": 2438, "text": "max: It specifies the maximum number of documents allowed in the capped collection. It is of number type." }, { "code": null, "e": 2648, "s": 2544, "text": "storageEngine: It is available only for the WiredTiger storage engine only. It is of the document type." }, { "code": null, "e": 2741, "s": 2648, "text": "validator: It specifies the validation rules for the collection. It is of the document type." }, { "code": null, "e": 2884, "s": 2741, "text": "validationLevel: It illustrates how strictly MongoDB applies the validation rule on the existing document during updates. It is of sting type." }, { "code": null, "e": 3056, "s": 2884, "text": "validationAction: It illustrates whether to error on invalid documents or just warn about the violations but allows invalid documents to be inserted. It is of string type." }, { "code": null, "e": 3197, "s": 3056, "text": "indexOptionDefaults: It allows the user to specify the default configuration for indexes when creating a collection. It is of document type." }, { "code": null, "e": 3296, "s": 3197, "text": "viewOn: Name of the source collection or view from which to create the view. It is of string type." }, { "code": null, "e": 3473, "s": 3296, "text": "pipeline: It is an array that contains the aggregation pipeline stages. Or using this parameter we can apply pipeline to the view or viewOne collection. It is of an array type." }, { "code": null, "e": 3574, "s": 3473, "text": "collation: It specifies the default collation from the given collection. It is of the document type." }, { "code": null, "e": 3730, "s": 3574, "text": "writeConcern: It expresses the write concern for the operation. If you want to use default write concern then avoid this parameter. It is of document type." }, { "code": null, "e": 3740, "s": 3730, "text": "Examples:" }, { "code": null, "e": 3940, "s": 3740, "text": "In the following example, we are working with the “gfg” database in which we are creating a new capped collection of name “student” with maximum document capacity “4” using createCollection() method." }, { "code": null, "e": 4005, "s": 3940, "text": "db.createCollection(\"student\", {capped:true, size:10000, max:4})" }, { "code": null, "e": 4060, "s": 4005, "text": "Now we insert the documents in the student collection:" }, { "code": null, "e": 4173, "s": 4060, "text": "After insert documents, we will display all the documents present in the student collection using find() method." }, { "code": null, "e": 4383, "s": 4173, "text": "Now, if we try to insert one more document, it will override the existing document. In the example, we are inserting a new document with the name Akash that overrides the existing document with the name Mihir:" }, { "code": null, "e": 4421, "s": 4383, "text": "After inserting one or more document:" }, { "code": null, "e": 4612, "s": 4421, "text": "We can check whether the collection is capped or not with the isCapped() method in MongoDB. This method returns true is the specified collections capped collection. Otherwise, return, false." }, { "code": null, "e": 4620, "s": 4612, "text": "Syntax:" }, { "code": null, "e": 4650, "s": 4620, "text": "db.Collection_name.isCapped()" }, { "code": null, "e": 4659, "s": 4650, "text": "Example:" }, { "code": null, "e": 4681, "s": 4659, "text": "db.student.isCapped()" }, { "code": null, "e": 4727, "s": 4681, "text": "After convert student collection to a capped:" }, { "code": null, "e": 4903, "s": 4727, "text": "If there is an existing collection that we want to change it to capped, we can do it using the convertToCapped command. It changes the current collection to capped collection:" }, { "code": null, "e": 4911, "s": 4903, "text": "Syntax:" }, { "code": null, "e": 4914, "s": 4911, "text": "{ " }, { "code": null, "e": 4949, "s": 4914, "text": " convertToCapped: <collection>," }, { "code": null, "e": 4974, "s": 4949, "text": " size: <capped size>," }, { "code": null, "e": 5004, "s": 4974, "text": " writeConcern: <document>," }, { "code": null, "e": 5023, "s": 5004, "text": " comment: <any>" }, { "code": null, "e": 5025, "s": 5023, "text": "}" }, { "code": null, "e": 5034, "s": 5025, "text": "Example:" }, { "code": null, "e": 5089, "s": 5034, "text": "db.runCommand({\"convertToCapped\":\"student\",size:5000})" }, { "code": null, "e": 5115, "s": 5089, "text": "Before convert to capped:" }, { "code": null, "e": 5140, "s": 5115, "text": "After convert to capped:" }, { "code": null, "e": 5258, "s": 5140, "text": "To return documents in insertion order, queries do not need an index, since it provides greater insertion throughput." }, { "code": null, "e": 5406, "s": 5258, "text": "Capped collections allow changes that match the size of the original document to ensure that the document does not change its position on the disk." }, { "code": null, "e": 5435, "s": 5406, "text": "Holding log files is useful." }, { "code": null, "e": 5535, "s": 5435, "text": "The update operation fails if the update of a document exceeds the original size of the collection." }, { "code": null, "e": 5684, "s": 5535, "text": "Deleting documents from a capped collection is not possible. If you want to delete all records from a capped collection, then use the given command:" }, { "code": null, "e": 5717, "s": 5684, "text": "{ emptycapped: Collection_name }" }, { "code": null, "e": 5750, "s": 5717, "text": "Capped collection cant be shard." }, { "code": null, "e": 5758, "s": 5750, "text": "MongoDB" }, { "code": null, "e": 5765, "s": 5758, "text": "Picked" }, { "code": null, "e": 5773, "s": 5765, "text": "MongoDB" }, { "code": null, "e": 5871, "s": 5773, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 5909, "s": 5871, "text": "How to connect MongoDB with ReactJS ?" }, { "code": null, "e": 5934, "s": 5909, "text": "MongoDB - limit() Method" }, { "code": null, "e": 5958, "s": 5934, "text": "MongoDB - sort() Method" }, { "code": null, "e": 5985, "s": 5958, "text": "MongoDB - FindOne() Method" }, { "code": null, "e": 6040, "s": 5985, "text": "MongoDB updateOne() Method - db.Collection.updateOne()" }, { "code": null, "e": 6067, "s": 6040, "text": "MongoDB - Compound Indexes" }, { "code": null, "e": 6083, "s": 6067, "text": "MongoDB - Regex" }, { "code": null, "e": 6140, "s": 6083, "text": "MongoDB updateMany() Method - db.Collection.updateMany()" }, { "code": null, "e": 6155, "s": 6140, "text": "MongoDB Cursor" } ]
Groupon Archives - GeeksforGeeks
Longest Palindromic Substring | Set 1 Longest Palindromic Substring | Set 2 Search in a row wise and column wise sorted matrix Groupon Interview Experience | Set 4 (SDE2 for Experienced) Groupon Interview | Set 1 (SDE Profile - Fresher) Git - Difference Between Git Fetch and Git Pull Unit Testing in Spring Boot Project using Mockito and Junit ReactJS useNavigate() Hook SDE SHEET - A Complete Guide for SDE Preparation How to Install and Use NVM on Windows?
[ { "code": null, "e": 24168, "s": 24130, "text": "Longest Palindromic Substring | Set 1" }, { "code": null, "e": 24206, "s": 24168, "text": "Longest Palindromic Substring | Set 2" }, { "code": null, "e": 24257, "s": 24206, "text": "Search in a row wise and column wise sorted matrix" }, { "code": null, "e": 24317, "s": 24257, "text": "Groupon Interview Experience | Set 4 (SDE2 for Experienced)" }, { "code": null, "e": 24367, "s": 24317, "text": "Groupon Interview | Set 1 (SDE Profile - Fresher)" }, { "code": null, "e": 24415, "s": 24367, "text": "Git - Difference Between Git Fetch and Git Pull" }, { "code": null, "e": 24475, "s": 24415, "text": "Unit Testing in Spring Boot Project using Mockito and Junit" }, { "code": null, "e": 24502, "s": 24475, "text": "ReactJS useNavigate() Hook" }, { "code": null, "e": 24551, "s": 24502, "text": "SDE SHEET - A Complete Guide for SDE Preparation" } ]
Pizza Shop Billing System using Java Swing
19 Apr, 2021 Java is a fascinating programming language that provides its users with a plethora of features like OOP, platform independence, simplicity, GUI based programming, etc. One such feature is creating robust applications using the Swing toolkit provided by Java Foundation Classes. This can be used to create lightweight visual components for simple applications, such as EMI calculator, tax calculator, billing systems, record management systems, etc. This article aims to guide beginners on how to create a GUI based java application using Java Swing toolkit. Consider a scenario of a local pizza shop that is shifting from its traditional approach of manually calculating bills to an automatic billing system. According to their requirements, the customer needs to choose two things The pizza base typeChoice of toppings The pizza base type Choice of toppings Based on these, the total amount is calculated and printed. A pizza can have more than 1 topping but can have only one type of crust at a time. Below are the pricing details to create the application. Advantage of Java swing over plain application No need to handle large chunks of code, therefore decreasing the complexity of programming.Provides GUI(graphical user interface) based editor for easier understanding No need to handle large chunks of code, therefore decreasing the complexity of programming. Provides GUI(graphical user interface) based editor for easier understanding Netbeans is used to create GUI applications since it’s a well crafted open-source IDE that provides features of a Component inspector, Drag-and-Drop of widgets, Debugger, Object browser, etc. Steps to create the Pizza Shop Billing System: Follow the steps to create the application. Create a new Java application by clicking on New Project -> Java -> Java Application and give a suitable project name. Eg: GeeksForGeeks and click Finish. Click on New Project Now create a new file by going to the File option on the menu bar, then New File-> Swing GUI Forms -> JFrame Form, and give a suitable file name. Eg. PizzaBill.java and click Finish. After successful file creation, you will now be presented with the following screen. The 3 important parts of this window are: Design: This is the area where we will create the design/template of our application.Source: This is where the logic code of the program is written.Palette: This component contains all the widgets which we need to drag and drop on the design area. Design: This is the area where we will create the design/template of our application.Source: This is where the logic code of the program is written.Palette: This component contains all the widgets which we need to drag and drop on the design area. Design: This is the area where we will create the design/template of our application. Source: This is where the logic code of the program is written. Palette: This component contains all the widgets which we need to drag and drop on the design area. Now before coding and dragging out the widgets from the palette, create a rough design of what exactly is needed in the application. This gives the programmer a better understanding of what exactly is expected from the problem statement. Java Swing contains many components or controls but it is necessary to understand what is needed by our application. As per the rough diagram below, The application should display information that cannot be edited. For example Company name, Menu options, etc. This is where we use Jlabel (java Label control). Now as per user choice, information needs to be fed into the system, so we use a JTextField control. According to the problem, a pizza can have more than 1 topping but can have only one type of crust at a time. Hence, we use JCheckBox and JRadioButton controls respectively. Now, to group and hold all similar components like radio buttons and checkboxes, you can use JPanel. Lastly, we need a command/action button which is used to execute the program logic. This is done with the help of JButton. Rough design of the expected application Now from the palette situated at the right-hand side of the window, start dragging the toolkit widgets as per the above diagram. Drag Components from palette to design area After all the components are moved, your design should look like this. Pizza Billing System design Let us now quickly go through the usage of each component in the program tabulated below. Refer to the corresponding object numbers from the previous image. Now to type the code, double-click on jButton1, you will be directed to the source tab. Here type in the following code. Type in the code under JButton1 Action Button Java // Takes input from TextFieldsint orderno = Integer.parseInt( jTextField1.getText());String custname = jTextField2.getText();int qty = Integer.parseInt( jTextField3.getText());double rate = 0; // Pizza Type conditionsif (jRadioButton1.isSelected()) { rate = 200;}else if (jRadioButton2.isSelected()) { rate = 300;}else if (jRadioButton3.isSelected()) { rate = 150;}// Displays rate of selected pizza// type in TextFieldjTextField4.setText( "" + rate); double topamt = 0; // Pizza toppings conditionsif (jCheckBox1.isSelected()) { topamt = 60;}if (jCheckBox2.isSelected()) { topamt = topamt + 30;}if (jCheckBox3.isSelected()) { topamt = topamt + 40;}if (jCheckBox4.isSelected()) { topamt = topamt + 50;}// Displays total amount of// selected pizza toppings in TextFieldjTextField6.setText( "" + topamt); // Total amount is calculateddouble totalpayable = (rate * qty) + topamt;jTextField5.setText("" + totalpayable); // Displays order detailsjTextArea1 .setText( "Hello, your Order Id is: " + orderno + "\nName: " + custname + "\nAMOUNT PAYABLE IS: " + totalpayable); Now to clear all textfields, textareas, radiobuttons, and checkboxes, write the following code under the jButton2 ActionPerformed option which can be achieved by clicking twice on Clear Button in the design area. Java jTextField1.setText("");jTextField2.setText("");jTextField3.setText("");jTextField4.setText("");jTextField5.setText("");jTextField6.setText("");jRadioButton1.setSelected(false);jRadioButton2.setSelected(false);jRadioButton3.setSelected(false);jCheckBox1.setSelected(false);jCheckBox2.setSelected(false);jCheckBox3.setSelected(false);jCheckBox4.setSelected(false);jTextArea1.setText(""); This completes the creation of the application. Input necessary details and select Run File option from the drop-down menu. Final output Output: simranarora5sos java-advanced java-swing Java Programs Project Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n19 Apr, 2021" }, { "code": null, "e": 612, "s": 54, "text": "Java is a fascinating programming language that provides its users with a plethora of features like OOP, platform independence, simplicity, GUI based programming, etc. One such feature is creating robust applications using the Swing toolkit provided by Java Foundation Classes. This can be used to create lightweight visual components for simple applications, such as EMI calculator, tax calculator, billing systems, record management systems, etc. This article aims to guide beginners on how to create a GUI based java application using Java Swing toolkit." }, { "code": null, "e": 837, "s": 612, "text": "Consider a scenario of a local pizza shop that is shifting from its traditional approach of manually calculating bills to an automatic billing system. According to their requirements, the customer needs to choose two things " }, { "code": null, "e": 875, "s": 837, "text": "The pizza base typeChoice of toppings" }, { "code": null, "e": 895, "s": 875, "text": "The pizza base type" }, { "code": null, "e": 914, "s": 895, "text": "Choice of toppings" }, { "code": null, "e": 1115, "s": 914, "text": "Based on these, the total amount is calculated and printed. A pizza can have more than 1 topping but can have only one type of crust at a time. Below are the pricing details to create the application." }, { "code": null, "e": 1163, "s": 1115, "text": "Advantage of Java swing over plain application " }, { "code": null, "e": 1331, "s": 1163, "text": "No need to handle large chunks of code, therefore decreasing the complexity of programming.Provides GUI(graphical user interface) based editor for easier understanding" }, { "code": null, "e": 1423, "s": 1331, "text": "No need to handle large chunks of code, therefore decreasing the complexity of programming." }, { "code": null, "e": 1500, "s": 1423, "text": "Provides GUI(graphical user interface) based editor for easier understanding" }, { "code": null, "e": 1693, "s": 1500, "text": "Netbeans is used to create GUI applications since it’s a well crafted open-source IDE that provides features of a Component inspector, Drag-and-Drop of widgets, Debugger, Object browser, etc. " }, { "code": null, "e": 1740, "s": 1693, "text": "Steps to create the Pizza Shop Billing System:" }, { "code": null, "e": 1784, "s": 1740, "text": "Follow the steps to create the application." }, { "code": null, "e": 1940, "s": 1784, "text": "Create a new Java application by clicking on New Project -> Java -> Java Application and give a suitable project name. Eg: GeeksForGeeks and click Finish. " }, { "code": null, "e": 1963, "s": 1942, "text": "Click on New Project" }, { "code": null, "e": 2148, "s": 1963, "text": "Now create a new file by going to the File option on the menu bar, then New File-> Swing GUI Forms -> JFrame Form, and give a suitable file name. Eg. PizzaBill.java and click Finish. " }, { "code": null, "e": 2523, "s": 2148, "text": "After successful file creation, you will now be presented with the following screen. The 3 important parts of this window are: Design: This is the area where we will create the design/template of our application.Source: This is where the logic code of the program is written.Palette: This component contains all the widgets which we need to drag and drop on the design area." }, { "code": null, "e": 2771, "s": 2523, "text": "Design: This is the area where we will create the design/template of our application.Source: This is where the logic code of the program is written.Palette: This component contains all the widgets which we need to drag and drop on the design area." }, { "code": null, "e": 2857, "s": 2771, "text": "Design: This is the area where we will create the design/template of our application." }, { "code": null, "e": 2921, "s": 2857, "text": "Source: This is where the logic code of the program is written." }, { "code": null, "e": 3021, "s": 2921, "text": "Palette: This component contains all the widgets which we need to drag and drop on the design area." }, { "code": null, "e": 4068, "s": 3021, "text": "Now before coding and dragging out the widgets from the palette, create a rough design of what exactly is needed in the application. This gives the programmer a better understanding of what exactly is expected from the problem statement. Java Swing contains many components or controls but it is necessary to understand what is needed by our application. As per the rough diagram below, The application should display information that cannot be edited. For example Company name, Menu options, etc. This is where we use Jlabel (java Label control). Now as per user choice, information needs to be fed into the system, so we use a JTextField control. According to the problem, a pizza can have more than 1 topping but can have only one type of crust at a time. Hence, we use JCheckBox and JRadioButton controls respectively. Now, to group and hold all similar components like radio buttons and checkboxes, you can use JPanel. Lastly, we need a command/action button which is used to execute the program logic. This is done with the help of JButton." }, { "code": null, "e": 4109, "s": 4068, "text": "Rough design of the expected application" }, { "code": null, "e": 4238, "s": 4109, "text": "Now from the palette situated at the right-hand side of the window, start dragging the toolkit widgets as per the above diagram." }, { "code": null, "e": 4282, "s": 4238, "text": "Drag Components from palette to design area" }, { "code": null, "e": 4353, "s": 4282, "text": "After all the components are moved, your design should look like this." }, { "code": null, "e": 4381, "s": 4353, "text": "Pizza Billing System design" }, { "code": null, "e": 4538, "s": 4381, "text": "Let us now quickly go through the usage of each component in the program tabulated below. Refer to the corresponding object numbers from the previous image." }, { "code": null, "e": 4659, "s": 4538, "text": "Now to type the code, double-click on jButton1, you will be directed to the source tab. Here type in the following code." }, { "code": null, "e": 4705, "s": 4659, "text": "Type in the code under JButton1 Action Button" }, { "code": null, "e": 4710, "s": 4705, "text": "Java" }, { "code": "// Takes input from TextFieldsint orderno = Integer.parseInt( jTextField1.getText());String custname = jTextField2.getText();int qty = Integer.parseInt( jTextField3.getText());double rate = 0; // Pizza Type conditionsif (jRadioButton1.isSelected()) { rate = 200;}else if (jRadioButton2.isSelected()) { rate = 300;}else if (jRadioButton3.isSelected()) { rate = 150;}// Displays rate of selected pizza// type in TextFieldjTextField4.setText( \"\" + rate); double topamt = 0; // Pizza toppings conditionsif (jCheckBox1.isSelected()) { topamt = 60;}if (jCheckBox2.isSelected()) { topamt = topamt + 30;}if (jCheckBox3.isSelected()) { topamt = topamt + 40;}if (jCheckBox4.isSelected()) { topamt = topamt + 50;}// Displays total amount of// selected pizza toppings in TextFieldjTextField6.setText( \"\" + topamt); // Total amount is calculateddouble totalpayable = (rate * qty) + topamt;jTextField5.setText(\"\" + totalpayable); // Displays order detailsjTextArea1 .setText( \"Hello, your Order Id is: \" + orderno + \"\\nName: \" + custname + \"\\nAMOUNT PAYABLE IS: \" + totalpayable);", "e": 5857, "s": 4710, "text": null }, { "code": null, "e": 6073, "s": 5860, "text": "Now to clear all textfields, textareas, radiobuttons, and checkboxes, write the following code under the jButton2 ActionPerformed option which can be achieved by clicking twice on Clear Button in the design area." }, { "code": null, "e": 6080, "s": 6075, "text": "Java" }, { "code": "jTextField1.setText(\"\");jTextField2.setText(\"\");jTextField3.setText(\"\");jTextField4.setText(\"\");jTextField5.setText(\"\");jTextField6.setText(\"\");jRadioButton1.setSelected(false);jRadioButton2.setSelected(false);jRadioButton3.setSelected(false);jCheckBox1.setSelected(false);jCheckBox2.setSelected(false);jCheckBox3.setSelected(false);jCheckBox4.setSelected(false);jTextArea1.setText(\"\");", "e": 6467, "s": 6080, "text": null }, { "code": null, "e": 6594, "s": 6470, "text": "This completes the creation of the application. Input necessary details and select Run File option from the drop-down menu." }, { "code": null, "e": 6607, "s": 6594, "text": "Final output" }, { "code": null, "e": 6619, "s": 6609, "text": "Output: " }, { "code": null, "e": 6639, "s": 6623, "text": "simranarora5sos" }, { "code": null, "e": 6653, "s": 6639, "text": "java-advanced" }, { "code": null, "e": 6664, "s": 6653, "text": "java-swing" }, { "code": null, "e": 6678, "s": 6664, "text": "Java Programs" }, { "code": null, "e": 6686, "s": 6678, "text": "Project" } ]
How to ping a server using JavaScript ?
29 Nov, 2021 Pinging a server is used to determine whether it is online or not. The idea is to send an echo message to the server (called ping) and the server is expected to reply back with a similar message (called pong). Ping messages are sent and received by using ICMP (Internet Control Messaging Protocol). The lower the ping time, the stronger is the connection between the host and the server. Approach: One obvious approach is to use the command prompt for sending ping messages to the server. Please refer to this post for details. In this article, we’ll be using Ajax to send a request to the required server and then examining the status code received to find whether the server is running or not. The idea is that a server is definitely up and running if it returns a status code 200. Other status codes like 400 etc. point toward a possible server outage. Below is the step by step implementation: Step 1: Create a file named ‘index.html‘ file to design the basic web page. The function “pingURL” is invoked when a user clicks on the button on the web page. HTML <!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content= "width=device-width, initial-scale=1.0"> <script src="index.js"></script> <script type="text/javascript" src= "https://code.jquery.com/jquery-1.7.1.min.js"> </script> <title>Ping a server using JavaScript</title></head> <body> <label for="url"> Enter the URL you want to ping: </label><br> <input type="text" id="url" name="url" style="margin: 10px;"><br> <input type="submit" value="Submit" onclick="pingURL()"></body> </html> Step 2: Create the ‘index.js‘ file to make a request to the server. The “pingURL” function defined the required configuration for the Ajax request in the ‘settings’ variable. index.js function pingURL() { // The custom URL entered by user var URL = $("#url").val(); var settings = { // Defines the configurations // for the request cache: false, dataType: "jsonp", async: true, crossDomain: true, url: URL, method: "GET", headers: { accept: "application/json", "Access-Control-Allow-Origin": "*", }, // Defines the response to be made // for certain status codes statusCode: { 200: function (response) { console.log("Status 200: Page is up!"); }, 400: function (response) { console.log("Status 400: Page is down."); }, 0: function (response) { console.log("Status 0: Page is down."); }, }, }; // Sends the request and observes the response $.ajax(settings).done(function (response) { console.log(response); });} Open the web page in your web browser.Press ‘Ctrl+Shift+I‘ to navigate to Browser Developer Tools.Enter the URL you wish to ping in the form input and click the ‘Submit’ button. Open the web page in your web browser. Press ‘Ctrl+Shift+I‘ to navigate to Browser Developer Tools. Enter the URL you wish to ping in the form input and click the ‘Submit’ button. javascript-object JavaScript-Questions Picked JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n29 Nov, 2021" }, { "code": null, "e": 418, "s": 28, "text": "Pinging a server is used to determine whether it is online or not. The idea is to send an echo message to the server (called ping) and the server is expected to reply back with a similar message (called pong). Ping messages are sent and received by using ICMP (Internet Control Messaging Protocol). The lower the ping time, the stronger is the connection between the host and the server. " }, { "code": null, "e": 887, "s": 418, "text": "Approach: One obvious approach is to use the command prompt for sending ping messages to the server. Please refer to this post for details. In this article, we’ll be using Ajax to send a request to the required server and then examining the status code received to find whether the server is running or not. The idea is that a server is definitely up and running if it returns a status code 200. Other status codes like 400 etc. point toward a possible server outage. " }, { "code": null, "e": 929, "s": 887, "text": "Below is the step by step implementation:" }, { "code": null, "e": 1090, "s": 929, "text": "Step 1: Create a file named ‘index.html‘ file to design the basic web page. The function “pingURL” is invoked when a user clicks on the button on the web page. " }, { "code": null, "e": 1095, "s": 1090, "text": "HTML" }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\"> <meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\"> <meta name=\"viewport\" content= \"width=device-width, initial-scale=1.0\"> <script src=\"index.js\"></script> <script type=\"text/javascript\" src= \"https://code.jquery.com/jquery-1.7.1.min.js\"> </script> <title>Ping a server using JavaScript</title></head> <body> <label for=\"url\"> Enter the URL you want to ping: </label><br> <input type=\"text\" id=\"url\" name=\"url\" style=\"margin: 10px;\"><br> <input type=\"submit\" value=\"Submit\" onclick=\"pingURL()\"></body> </html>", "e": 1759, "s": 1095, "text": null }, { "code": null, "e": 1936, "s": 1759, "text": "Step 2: Create the ‘index.js‘ file to make a request to the server. The “pingURL” function defined the required configuration for the Ajax request in the ‘settings’ variable. " }, { "code": null, "e": 1945, "s": 1936, "text": "index.js" }, { "code": "function pingURL() { // The custom URL entered by user var URL = $(\"#url\").val(); var settings = { // Defines the configurations // for the request cache: false, dataType: \"jsonp\", async: true, crossDomain: true, url: URL, method: \"GET\", headers: { accept: \"application/json\", \"Access-Control-Allow-Origin\": \"*\", }, // Defines the response to be made // for certain status codes statusCode: { 200: function (response) { console.log(\"Status 200: Page is up!\"); }, 400: function (response) { console.log(\"Status 400: Page is down.\"); }, 0: function (response) { console.log(\"Status 0: Page is down.\"); }, }, }; // Sends the request and observes the response $.ajax(settings).done(function (response) { console.log(response); });}", "e": 2794, "s": 1945, "text": null }, { "code": null, "e": 2973, "s": 2794, "text": "Open the web page in your web browser.Press ‘Ctrl+Shift+I‘ to navigate to Browser Developer Tools.Enter the URL you wish to ping in the form input and click the ‘Submit’ button." }, { "code": null, "e": 3012, "s": 2973, "text": "Open the web page in your web browser." }, { "code": null, "e": 3073, "s": 3012, "text": "Press ‘Ctrl+Shift+I‘ to navigate to Browser Developer Tools." }, { "code": null, "e": 3154, "s": 3073, "text": "Enter the URL you wish to ping in the form input and click the ‘Submit’ button." }, { "code": null, "e": 3172, "s": 3154, "text": "javascript-object" }, { "code": null, "e": 3193, "s": 3172, "text": "JavaScript-Questions" }, { "code": null, "e": 3200, "s": 3193, "text": "Picked" }, { "code": null, "e": 3211, "s": 3200, "text": "JavaScript" }, { "code": null, "e": 3228, "s": 3211, "text": "Web Technologies" } ]
Create a Date object using the Calendar class in Java
For using Calendar class, import the following package. import java.util.Calendar; Now, let us create an object of Calendar class. Calendar calendar = Calendar.getInstance(); Set the date, month and year. calendar.set(Calendar.YEAR, 2018); calendar.set(Calendar.MONTH, 11); calendar.set(Calendar.DATE, 18); Create a Date object using Calendar class. java.util.Date dt = calendar.getTime(); The following is an example. Live Demo import java.util.Calendar; public class Demo { public static void main(String[] args) { Calendar calendar = Calendar.getInstance(); // Set year, month and date calendar.set(Calendar.YEAR, 2018); calendar.set(Calendar.MONTH, 11); calendar.set(Calendar.DATE, 18); // util date object java.util.Date dt = calendar.getTime(); System.out.println("Date: "+dt); } } Date: Tue Dec 18 08:29:51 UTC 2018
[ { "code": null, "e": 1118, "s": 1062, "text": "For using Calendar class, import the following package." }, { "code": null, "e": 1145, "s": 1118, "text": "import java.util.Calendar;" }, { "code": null, "e": 1193, "s": 1145, "text": "Now, let us create an object of Calendar class." }, { "code": null, "e": 1237, "s": 1193, "text": "Calendar calendar = Calendar.getInstance();" }, { "code": null, "e": 1267, "s": 1237, "text": "Set the date, month and year." }, { "code": null, "e": 1369, "s": 1267, "text": "calendar.set(Calendar.YEAR, 2018);\ncalendar.set(Calendar.MONTH, 11);\ncalendar.set(Calendar.DATE, 18);" }, { "code": null, "e": 1412, "s": 1369, "text": "Create a Date object using Calendar class." }, { "code": null, "e": 1452, "s": 1412, "text": "java.util.Date dt = calendar.getTime();" }, { "code": null, "e": 1481, "s": 1452, "text": "The following is an example." }, { "code": null, "e": 1492, "s": 1481, "text": " Live Demo" }, { "code": null, "e": 1905, "s": 1492, "text": "import java.util.Calendar;\npublic class Demo {\n public static void main(String[] args) {\n Calendar calendar = Calendar.getInstance();\n // Set year, month and date\n calendar.set(Calendar.YEAR, 2018);\n calendar.set(Calendar.MONTH, 11);\n calendar.set(Calendar.DATE, 18);\n // util date object\n java.util.Date dt = calendar.getTime();\n System.out.println(\"Date: \"+dt);\n }\n}" }, { "code": null, "e": 1940, "s": 1905, "text": "Date: Tue Dec 18 08:29:51 UTC 2018" } ]
PHP - Function MySQLi Fetch Array
mysqli_fetch_array(result,resulttype); It is used to fetchs a result row as an associative array It returns an array of strings that corresponds to the fetched row. result It specifies the result set identifier resulttype It specifies what type of array that should be produced Try out the following example <?php $connection_mysql = mysqli_connect("localhost","username","password","db"); if (mysqli_connect_errno($connection_mysql)){ echo "Failed to connect to MySQL: " . mysqli_connect_error(); } $sql = "SELECT name,age FROM emp"; $result = mysqli_query($connection_mysql,$sql); $row = mysqli_fetch_array($result,MYSQLI_NUM); print $row[0]; print "\n"; print $row[1]; $row = mysqli_fetch_array($result,MYSQLI_ASSOC); print $row["name"]; print "\n"; print $row["age"]; mysqli_free_result($result); mysqli_close($connection_mysql); ?> 45 Lectures 9 hours Malhar Lathkar 34 Lectures 4 hours Syed Raza 84 Lectures 5.5 hours Frahaan Hussain 17 Lectures 1 hours Nivedita Jain 100 Lectures 34 hours Azaz Patel 43 Lectures 5.5 hours Vijay Kumar Parvatha Reddy Print Add Notes Bookmark this page
[ { "code": null, "e": 2797, "s": 2757, "text": "mysqli_fetch_array(result,resulttype);\n" }, { "code": null, "e": 2855, "s": 2797, "text": "It is used to fetchs a result row as an associative array" }, { "code": null, "e": 2923, "s": 2855, "text": "It returns an array of strings that corresponds to the fetched row." }, { "code": null, "e": 2930, "s": 2923, "text": "result" }, { "code": null, "e": 2969, "s": 2930, "text": "It specifies the result set identifier" }, { "code": null, "e": 2980, "s": 2969, "text": "resulttype" }, { "code": null, "e": 3036, "s": 2980, "text": "It specifies what type of array that should be produced" }, { "code": null, "e": 3066, "s": 3036, "text": "Try out the following example" }, { "code": null, "e": 3666, "s": 3066, "text": "<?php\n $connection_mysql = mysqli_connect(\"localhost\",\"username\",\"password\",\"db\");\n \n if (mysqli_connect_errno($connection_mysql)){\n echo \"Failed to connect to MySQL: \" . mysqli_connect_error();\n }\n \n $sql = \"SELECT name,age FROM emp\";\n $result = mysqli_query($connection_mysql,$sql);\n $row = mysqli_fetch_array($result,MYSQLI_NUM);\n \n print $row[0];\n print \"\\n\";\n print $row[1];\n \n $row = mysqli_fetch_array($result,MYSQLI_ASSOC);\n print $row[\"name\"];\n print \"\\n\";\n print $row[\"age\"];\n \n mysqli_free_result($result);\n mysqli_close($connection_mysql);\n?>" }, { "code": null, "e": 3699, "s": 3666, "text": "\n 45 Lectures \n 9 hours \n" }, { "code": null, "e": 3715, "s": 3699, "text": " Malhar Lathkar" }, { "code": null, "e": 3748, "s": 3715, "text": "\n 34 Lectures \n 4 hours \n" }, { "code": null, "e": 3759, "s": 3748, "text": " Syed Raza" }, { "code": null, "e": 3794, "s": 3759, "text": "\n 84 Lectures \n 5.5 hours \n" }, { "code": null, "e": 3811, "s": 3794, "text": " Frahaan Hussain" }, { "code": null, "e": 3844, "s": 3811, "text": "\n 17 Lectures \n 1 hours \n" }, { "code": null, "e": 3859, "s": 3844, "text": " Nivedita Jain" }, { "code": null, "e": 3894, "s": 3859, "text": "\n 100 Lectures \n 34 hours \n" }, { "code": null, "e": 3906, "s": 3894, "text": " Azaz Patel" }, { "code": null, "e": 3941, "s": 3906, "text": "\n 43 Lectures \n 5.5 hours \n" }, { "code": null, "e": 3969, "s": 3941, "text": " Vijay Kumar Parvatha Reddy" }, { "code": null, "e": 3976, "s": 3969, "text": " Print" }, { "code": null, "e": 3987, "s": 3976, "text": " Add Notes" } ]
Adding a scatter of points to a boxplot using Matplotlib
To add a scatter of points to a boxplot using matplotlib, we can use boxplot() method and enumerate the Pandas dataframe to get the x and y data points to plot the scatter points. Set the figure size and adjust the padding between and around the subplots. Set the figure size and adjust the padding between and around the subplots. Make a dataframe using DataFrame class with the keys, Box1 and Box2. Make a dataframe using DataFrame class with the keys, Box1 and Box2. Make boxplots from the dataframe. Make boxplots from the dataframe. Find x and y for the scatter plot using data (Step 1). Find x and y for the scatter plot using data (Step 1). To display the figure, use show() method. To display the figure, use show() method. import pandas as pd import numpy as np from matplotlib import pyplot as plt plt.rcParams["figure.figsize"] = [7.50, 3.50] plt.rcParams["figure.autolayout"] = True data = pd.DataFrame({"Box1": np.random.rand(10), "Box2": np.random.rand(10)}) data.boxplot() for i, d in enumerate(data): y = data[d] x = np.random.normal(i + 1, 0.04, len(y)) plt.scatter(x, y) plt.show()
[ { "code": null, "e": 1242, "s": 1062, "text": "To add a scatter of points to a boxplot using matplotlib, we can use boxplot() method and enumerate the Pandas dataframe to get the x and y data points to plot the scatter points." }, { "code": null, "e": 1318, "s": 1242, "text": "Set the figure size and adjust the padding between and around the subplots." }, { "code": null, "e": 1394, "s": 1318, "text": "Set the figure size and adjust the padding between and around the subplots." }, { "code": null, "e": 1463, "s": 1394, "text": "Make a dataframe using DataFrame class with the keys, Box1 and Box2." }, { "code": null, "e": 1532, "s": 1463, "text": "Make a dataframe using DataFrame class with the keys, Box1 and Box2." }, { "code": null, "e": 1566, "s": 1532, "text": "Make boxplots from the dataframe." }, { "code": null, "e": 1600, "s": 1566, "text": "Make boxplots from the dataframe." }, { "code": null, "e": 1655, "s": 1600, "text": "Find x and y for the scatter plot using data (Step 1)." }, { "code": null, "e": 1710, "s": 1655, "text": "Find x and y for the scatter plot using data (Step 1)." }, { "code": null, "e": 1752, "s": 1710, "text": "To display the figure, use show() method." }, { "code": null, "e": 1794, "s": 1752, "text": "To display the figure, use show() method." }, { "code": null, "e": 2171, "s": 1794, "text": "import pandas as pd\nimport numpy as np\nfrom matplotlib import pyplot as plt\nplt.rcParams[\"figure.figsize\"] = [7.50, 3.50]\nplt.rcParams[\"figure.autolayout\"] = True\ndata = pd.DataFrame({\"Box1\": np.random.rand(10), \"Box2\": np.random.rand(10)})\ndata.boxplot()\nfor i, d in enumerate(data):\n y = data[d]\n x = np.random.normal(i + 1, 0.04, len(y))\n plt.scatter(x, y)\nplt.show()" } ]
DAX Information - ISNUMBER function
Checks whether a value is a number, and returns TRUE or FALSE. ISNUMBER (<value>) value The value you want to test. TRUE or FALSE. = ISNUMBER (5.0): The DAX formula returns TRUE. = ISNUMBER("AB"): This DAX formula returns FALSE. 53 Lectures 5.5 hours Abhay Gadiya 24 Lectures 2 hours Randy Minder 26 Lectures 4.5 hours Randy Minder Print Add Notes Bookmark this page
[ { "code": null, "e": 2064, "s": 2001, "text": "Checks whether a value is a number, and returns TRUE or FALSE." }, { "code": null, "e": 2085, "s": 2064, "text": "ISNUMBER (<value>) \n" }, { "code": null, "e": 2091, "s": 2085, "text": "value" }, { "code": null, "e": 2119, "s": 2091, "text": "The value you want to test." }, { "code": null, "e": 2134, "s": 2119, "text": "TRUE or FALSE." }, { "code": null, "e": 2234, "s": 2134, "text": "= ISNUMBER (5.0): The DAX formula returns TRUE. \n= ISNUMBER(\"AB\"): This DAX formula returns FALSE. " }, { "code": null, "e": 2269, "s": 2234, "text": "\n 53 Lectures \n 5.5 hours \n" }, { "code": null, "e": 2283, "s": 2269, "text": " Abhay Gadiya" }, { "code": null, "e": 2316, "s": 2283, "text": "\n 24 Lectures \n 2 hours \n" }, { "code": null, "e": 2330, "s": 2316, "text": " Randy Minder" }, { "code": null, "e": 2365, "s": 2330, "text": "\n 26 Lectures \n 4.5 hours \n" }, { "code": null, "e": 2379, "s": 2365, "text": " Randy Minder" }, { "code": null, "e": 2386, "s": 2379, "text": " Print" }, { "code": null, "e": 2397, "s": 2386, "text": " Add Notes" } ]
How to write :hover condition for a:before and a:after in CSS?
18 May, 2022 The :before and :after selectors in CSS is used to add content before and after an element. The :hover is pseudo-class and :before & :after are pseudo-elements. In CSS, pseudo-elements are written after pseudo-class. Syntax: a:hover::before { // CSS Property } a:hover::after { // CSS Property } In CSS3 double colon(::) is used to denote pseudo-element. For IE8 or older use a single colon (CSS2 syntax) is used. Example 1: This example uses :hover condition for a:before and a:after in an element. html <!DOCTYPE html><html> <head> <title> :hover condition for a:before and a:after </title> <!-- Style to add hover condition --> <style> a:hover::before { content: "Before -"; } a:hover::after { content: "-after"; } </style> </head> <body> <a href="#" > Hover here </a> </body></html> Output: HTML Before Mouse move over: After Mouse move over: Example 2: This example uses :hover condition for a:before and a:after in an element. html <!DOCTYPE html><html> <head> <title> :hover condition for a:before and a:after </title> <style> a:hover::before { content: "Before -"; background-color: green; } a:hover::after{ content: "-after"; background-color: green; } </style> </head> <body> <a href="#" > GeeksForGeeks </a> </body></html> Output: HTML Before Mouse move over: After Mouse move over : CSS is the foundation of webpages, is used for webpage development by styling websites and web apps.You can learn CSS from the ground up by following this CSS Tutorial and CSS Examples. hardikkoriintern CSS-Misc HTML-Misc Picked CSS 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": "\n18 May, 2022" }, { "code": null, "e": 270, "s": 52, "text": "The :before and :after selectors in CSS is used to add content before and after an element. The :hover is pseudo-class and :before & :after are pseudo-elements. In CSS, pseudo-elements are written after pseudo-class. " }, { "code": null, "e": 279, "s": 270, "text": "Syntax: " }, { "code": null, "e": 358, "s": 279, "text": "a:hover::before {\n // CSS Property\n}\na:hover::after {\n // CSS Property\n}" }, { "code": null, "e": 477, "s": 358, "text": "In CSS3 double colon(::) is used to denote pseudo-element. For IE8 or older use a single colon (CSS2 syntax) is used. " }, { "code": null, "e": 564, "s": 477, "text": "Example 1: This example uses :hover condition for a:before and a:after in an element. " }, { "code": null, "e": 569, "s": 564, "text": "html" }, { "code": "<!DOCTYPE html><html> <head> <title> :hover condition for a:before and a:after </title> <!-- Style to add hover condition --> <style> a:hover::before { content: \"Before -\"; } a:hover::after { content: \"-after\"; } </style> </head> <body> <a href=\"#\" > Hover here </a> </body></html>", "e": 969, "s": 569, "text": null }, { "code": null, "e": 977, "s": 969, "text": "Output:" }, { "code": null, "e": 1007, "s": 977, "text": "HTML Before Mouse move over: " }, { "code": null, "e": 1034, "s": 1011, "text": "After Mouse move over:" }, { "code": null, "e": 1124, "s": 1037, "text": "Example 2: This example uses :hover condition for a:before and a:after in an element. " }, { "code": null, "e": 1129, "s": 1124, "text": "html" }, { "code": "<!DOCTYPE html><html> <head> <title> :hover condition for a:before and a:after </title> <style> a:hover::before { content: \"Before -\"; background-color: green; } a:hover::after{ content: \"-after\"; background-color: green; } </style> </head> <body> <a href=\"#\" > GeeksForGeeks </a> </body></html>", "e": 1610, "s": 1129, "text": null }, { "code": null, "e": 1618, "s": 1610, "text": "Output:" }, { "code": null, "e": 1647, "s": 1618, "text": "HTML Before Mouse move over:" }, { "code": null, "e": 1674, "s": 1650, "text": "After Mouse move over :" }, { "code": null, "e": 1860, "s": 1674, "text": "CSS is the foundation of webpages, is used for webpage development by styling websites and web apps.You can learn CSS from the ground up by following this CSS Tutorial and CSS Examples." }, { "code": null, "e": 1877, "s": 1860, "text": "hardikkoriintern" }, { "code": null, "e": 1886, "s": 1877, "text": "CSS-Misc" }, { "code": null, "e": 1896, "s": 1886, "text": "HTML-Misc" }, { "code": null, "e": 1903, "s": 1896, "text": "Picked" }, { "code": null, "e": 1907, "s": 1903, "text": "CSS" }, { "code": null, "e": 1912, "s": 1907, "text": "HTML" }, { "code": null, "e": 1929, "s": 1912, "text": "Web Technologies" }, { "code": null, "e": 1934, "s": 1929, "text": "HTML" } ]
How to count the number of occurrences of a specific value in a column with a single MySQL query?
For this, you can use GROUP BY clause along with IN(). Let us first create a table − mysql> create table DemoTable -> ( -> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY, -> Name varchar(100) -> ); Query OK, 0 rows affected (0.87 sec) Insert some records in the table using insert command − mysql> insert into DemoTable(Name) values('John'); Query OK, 1 row affected (0.23 sec) mysql> insert into DemoTable(Name) values('Chris'); Query OK, 1 row affected (0.12 sec) mysql> insert into DemoTable(Name) values('David'); Query OK, 1 row affected (0.23 sec) mysql> insert into DemoTable(Name) values('Chris'); Query OK, 1 row affected (0.17 sec) mysql> insert into DemoTable(Name) values('Chris'); Query OK, 1 row affected (0.21 sec) mysql> insert into DemoTable(Name) values('John'); Query OK, 1 row affected (0.10 sec) mysql> insert into DemoTable(Name) values('Carol'); Query OK, 1 row affected (0.20 sec) mysql> insert into DemoTable(Name) values('Sam'); Query OK, 1 row affected (0.19 sec) Display all records from the table using select statement − mysql> select *from DemoTable; This will produce the following output − +----+-------+ | Id | Name | +----+-------+ | 1 | John | | 2 | Chris | | 3 | David | | 4 | Chris | | 5 | Chris | | 6 | John | | 7 | Carol | | 8 | Sam | +----+-------+ 8 rows in set (0.00 sec) Now, count the number of occurrences of a specific value in a column with a single query − mysql> select Name,count(*) AS Occurrences from DemoTable -> where Name in('John','Chris') group by Name; This will produce the following output − +-------+-------------+ | Name | Occurrences | +-------+-------------+ | John | 2 | | Chris | 3 | +-------+-------------+ 2 rows in set (0.00 sec)
[ { "code": null, "e": 1272, "s": 1187, "text": "For this, you can use GROUP BY clause along with IN(). Let us first create a table −" }, { "code": null, "e": 1430, "s": 1272, "text": "mysql> create table DemoTable\n -> (\n -> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,\n -> Name varchar(100)\n -> );\nQuery OK, 0 rows affected (0.87 sec)" }, { "code": null, "e": 1486, "s": 1430, "text": "Insert some records in the table using insert command −" }, { "code": null, "e": 2193, "s": 1486, "text": "mysql> insert into DemoTable(Name) values('John');\nQuery OK, 1 row affected (0.23 sec)\n\nmysql> insert into DemoTable(Name) values('Chris');\nQuery OK, 1 row affected (0.12 sec)\n\nmysql> insert into DemoTable(Name) values('David');\nQuery OK, 1 row affected (0.23 sec)\n\nmysql> insert into DemoTable(Name) values('Chris');\nQuery OK, 1 row affected (0.17 sec)\n\nmysql> insert into DemoTable(Name) values('Chris');\nQuery OK, 1 row affected (0.21 sec)\n\nmysql> insert into DemoTable(Name) values('John');\nQuery OK, 1 row affected (0.10 sec)\n\nmysql> insert into DemoTable(Name) values('Carol');\nQuery OK, 1 row affected (0.20 sec)\n\nmysql> insert into DemoTable(Name) values('Sam');\nQuery OK, 1 row affected (0.19 sec)" }, { "code": null, "e": 2253, "s": 2193, "text": "Display all records from the table using select statement −" }, { "code": null, "e": 2284, "s": 2253, "text": "mysql> select *from DemoTable;" }, { "code": null, "e": 2325, "s": 2284, "text": "This will produce the following output −" }, { "code": null, "e": 2530, "s": 2325, "text": "+----+-------+\n| Id | Name |\n+----+-------+\n| 1 | John |\n| 2 | Chris |\n| 3 | David |\n| 4 | Chris |\n| 5 | Chris |\n| 6 | John |\n| 7 | Carol |\n| 8 | Sam |\n+----+-------+\n8 rows in set (0.00 sec)" }, { "code": null, "e": 2621, "s": 2530, "text": "Now, count the number of occurrences of a specific value in a column with a single query −" }, { "code": null, "e": 2730, "s": 2621, "text": "mysql> select Name,count(*) AS Occurrences from DemoTable\n -> where Name in('John','Chris') group by Name;" }, { "code": null, "e": 2771, "s": 2730, "text": "This will produce the following output −" }, { "code": null, "e": 2940, "s": 2771, "text": "+-------+-------------+\n| Name | Occurrences |\n+-------+-------------+\n| John | 2 |\n| Chris | 3 |\n+-------+-------------+\n2 rows in set (0.00 sec)" } ]
Snowfall display using Pygame in Python
11 Sep, 2021 Not everybody must have witnessed Snowfall personally but wait a minute, What if you can see the snowfall right on your screen by just a few lines of creativity and Programming. Before starting the topic, it is highly recommended revising the basics of Pygame. 1. Importing modules First, we need to import the Pygame module by using the command. import pygame Also, along with Pygame, we will also need random module. Python has a built-in module that you can use to make random numbers just by importing random module. import random 2. Initialize the game engine It simply means choose the colors you want to use. In programming World, Whatever you can think you can make. At the end of the article, you will find green snowfall on the white background. Python3 # initializepygame.init() # chosen colours will be used# to display the outputWHITE = [255, 255, 255]GREEN = [0, 255, 0] 3. Specify the size of the screen It can be a new number depending upon the resolution of your system. Python3 # specify the size SIZE = [400, 400]screen = pygame.display.set_mode(SIZE) 4. Assign a name to your snowfall window screen The name given can be seen on the left corner of the output window. Python3 # caption for output window pygame.display.set_caption("Programming World of GFG") 5. Create an empty array for your snowfall Python3 snowFall = [] 6. Looping to get snowfall positions Make a loop and run to 50 times and add a snowfall in a random x,y position using random Module. Python3 for i in range(50): x = random.randrange(0, 400) y = random.randrange(0, 400) snowFall.append([x, y]) 7. Track time Create an object to help track time Python3 # object to track time clock = pygame.time.Clock() 8. Set criteria for snowfall occurrence Snowfall should occur until the user presses the close button and for this inside while loop, use a for loop. Python3 # loop till the close button is presseddone = False while not done: # User did something for event in pygame.event.get(): # If user clicked close if event.type == pygame.QUIT: # Flag that we are done so # we exit this loop done = True 9. Set the screen background : Python3 screen.fill(WHITE) 10. Process the snowfall Now use a for loop to process each Snowfall in the list : Python3 for i in range(len(snowFall)): 11. Draw the snowfall Python3 pygame.draw.circle(screen, GREEN, snowFall[i], 2) 12. Adding movement Python3 # Move the snowFall down one pixel snowFall[i][1] += 1 # If the snowFall has moved off the bottom of the screen if snowFall[i][1] > 400: # Reset it just above the top y = random.randrange(-50, -10) snowFall[i][1] = y # Give it a new x position x = random.randrange(0, 400) snowFall[i][0] = x # Go ahead and update the screen with what we've drawn. pygame.display.flip() clock.tick(20)pygame.quit() And Yes, Green snowfall has started!! Python3 import pygameimport randompygame.init() WHITE = [255, 255, 255]GREEN = [0,255,0]SIZE = [400, 400] screen = pygame.display.set_mode(SIZE)pygame.display.set_caption("Programming World of GFG") snowFall = []for i in range(50): x = random.randrange(0, 400) y = random.randrange(0, 400) snowFall.append([x, y]) clock = pygame.time.Clock()done = Falsewhile not done: for event in pygame.event.get(): if event.type == pygame.QUIT: done = True screen.fill(WHITE) for i in range(len(snowFall)): pygame.draw.circle(screen, GREEN, snowFall[i], 2) snowFall[i][1] += 1 if snowFall[i][1] > 400: y = random.randrange(-50, -10) snowFall[i][1] = y x = random.randrange(0, 400) snowFall[i][0] = x pygame.display.flip() clock.tick(20)pygame.quit() Output gabaa406 Python-PyGame Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n11 Sep, 2021" }, { "code": null, "e": 230, "s": 52, "text": "Not everybody must have witnessed Snowfall personally but wait a minute, What if you can see the snowfall right on your screen by just a few lines of creativity and Programming." }, { "code": null, "e": 315, "s": 230, "text": " Before starting the topic, it is highly recommended revising the basics of Pygame. " }, { "code": null, "e": 336, "s": 315, "text": "1. Importing modules" }, { "code": null, "e": 401, "s": 336, "text": "First, we need to import the Pygame module by using the command." }, { "code": null, "e": 416, "s": 401, "text": "import pygame " }, { "code": null, "e": 576, "s": 416, "text": "Also, along with Pygame, we will also need random module. Python has a built-in module that you can use to make random numbers just by importing random module." }, { "code": null, "e": 591, "s": 576, "text": "import random " }, { "code": null, "e": 622, "s": 591, "text": "2. Initialize the game engine " }, { "code": null, "e": 813, "s": 622, "text": "It simply means choose the colors you want to use. In programming World, Whatever you can think you can make. At the end of the article, you will find green snowfall on the white background." }, { "code": null, "e": 821, "s": 813, "text": "Python3" }, { "code": "# initializepygame.init() # chosen colours will be used# to display the outputWHITE = [255, 255, 255]GREEN = [0, 255, 0]", "e": 942, "s": 821, "text": null }, { "code": null, "e": 978, "s": 942, "text": "3. Specify the size of the screen " }, { "code": null, "e": 1048, "s": 978, "text": " It can be a new number depending upon the resolution of your system." }, { "code": null, "e": 1056, "s": 1048, "text": "Python3" }, { "code": "# specify the size SIZE = [400, 400]screen = pygame.display.set_mode(SIZE)", "e": 1131, "s": 1056, "text": null }, { "code": null, "e": 1179, "s": 1131, "text": "4. Assign a name to your snowfall window screen" }, { "code": null, "e": 1247, "s": 1179, "text": "The name given can be seen on the left corner of the output window." }, { "code": null, "e": 1255, "s": 1247, "text": "Python3" }, { "code": "# caption for output window pygame.display.set_caption(\"Programming World of GFG\")", "e": 1338, "s": 1255, "text": null }, { "code": null, "e": 1382, "s": 1338, "text": "5. Create an empty array for your snowfall " }, { "code": null, "e": 1390, "s": 1382, "text": "Python3" }, { "code": "snowFall = []", "e": 1404, "s": 1390, "text": null }, { "code": null, "e": 1442, "s": 1404, "text": " 6. Looping to get snowfall positions" }, { "code": null, "e": 1540, "s": 1442, "text": "Make a loop and run to 50 times and add a snowfall in a random x,y position using random Module. " }, { "code": null, "e": 1548, "s": 1540, "text": "Python3" }, { "code": "for i in range(50): x = random.randrange(0, 400) y = random.randrange(0, 400) snowFall.append([x, y])", "e": 1659, "s": 1548, "text": null }, { "code": null, "e": 1673, "s": 1659, "text": "7. Track time" }, { "code": null, "e": 1709, "s": 1673, "text": "Create an object to help track time" }, { "code": null, "e": 1717, "s": 1709, "text": "Python3" }, { "code": "# object to track time clock = pygame.time.Clock()", "e": 1768, "s": 1717, "text": null }, { "code": null, "e": 1808, "s": 1768, "text": "8. Set criteria for snowfall occurrence" }, { "code": null, "e": 1919, "s": 1808, "text": " Snowfall should occur until the user presses the close button and for this inside while loop, use a for loop." }, { "code": null, "e": 1927, "s": 1919, "text": "Python3" }, { "code": "# loop till the close button is presseddone = False while not done: # User did something for event in pygame.event.get(): # If user clicked close if event.type == pygame.QUIT: # Flag that we are done so # we exit this loop done = True", "e": 2211, "s": 1927, "text": null }, { "code": null, "e": 2242, "s": 2211, "text": "9. Set the screen background :" }, { "code": null, "e": 2250, "s": 2242, "text": "Python3" }, { "code": "screen.fill(WHITE)", "e": 2269, "s": 2250, "text": null }, { "code": null, "e": 2295, "s": 2269, "text": " 10. Process the snowfall" }, { "code": null, "e": 2354, "s": 2295, "text": "Now use a for loop to process each Snowfall in the list : " }, { "code": null, "e": 2362, "s": 2354, "text": "Python3" }, { "code": "for i in range(len(snowFall)):", "e": 2393, "s": 2362, "text": null }, { "code": null, "e": 2416, "s": 2393, "text": "11. Draw the snowfall " }, { "code": null, "e": 2424, "s": 2416, "text": "Python3" }, { "code": "pygame.draw.circle(screen, GREEN, snowFall[i], 2)", "e": 2474, "s": 2424, "text": null }, { "code": null, "e": 2501, "s": 2481, "text": "12. Adding movement" }, { "code": null, "e": 2509, "s": 2501, "text": "Python3" }, { "code": "# Move the snowFall down one pixel snowFall[i][1] += 1 # If the snowFall has moved off the bottom of the screen if snowFall[i][1] > 400: # Reset it just above the top y = random.randrange(-50, -10) snowFall[i][1] = y # Give it a new x position x = random.randrange(0, 400) snowFall[i][0] = x # Go ahead and update the screen with what we've drawn. pygame.display.flip() clock.tick(20)pygame.quit()", "e": 3027, "s": 2509, "text": null }, { "code": null, "e": 3065, "s": 3027, "text": "And Yes, Green snowfall has started!!" }, { "code": null, "e": 3073, "s": 3065, "text": "Python3" }, { "code": "import pygameimport randompygame.init() WHITE = [255, 255, 255]GREEN = [0,255,0]SIZE = [400, 400] screen = pygame.display.set_mode(SIZE)pygame.display.set_caption(\"Programming World of GFG\") snowFall = []for i in range(50): x = random.randrange(0, 400) y = random.randrange(0, 400) snowFall.append([x, y]) clock = pygame.time.Clock()done = Falsewhile not done: for event in pygame.event.get(): if event.type == pygame.QUIT: done = True screen.fill(WHITE) for i in range(len(snowFall)): pygame.draw.circle(screen, GREEN, snowFall[i], 2) snowFall[i][1] += 1 if snowFall[i][1] > 400: y = random.randrange(-50, -10) snowFall[i][1] = y x = random.randrange(0, 400) snowFall[i][0] = x pygame.display.flip() clock.tick(20)pygame.quit()", "e": 3923, "s": 3073, "text": null }, { "code": null, "e": 3930, "s": 3923, "text": "Output" }, { "code": null, "e": 3939, "s": 3930, "text": "gabaa406" }, { "code": null, "e": 3953, "s": 3939, "text": "Python-PyGame" }, { "code": null, "e": 3960, "s": 3953, "text": "Python" } ]
Fork() – Practice questions
17 Feb, 2020 Prerequisite: basics of fork, fork and binary tree, Example1:What is the output of the following code? #include <stdio.h>#include <unistd.h>int main(){ if (fork() || fork()) fork(); printf("1 "); return 0;} Output: 1 1 1 1 1 Explanation:1. It will create two process one parent P (has process ID of child process)and other is child C1 (process ID = 0).2. In if statement we used OR operator( || ) and in this case second condition is evaluated when first condition is false.3. Parent process P will return positive integer so it directly execute statement and create two more processes (one parent P and other is child C2). Child process C1 will return 0 so it checks for second condition and second condition again create two more processes(one parent C1 and other is child C3).4. C1 return positive integer so it will further create two more processes (one parent C1 and other is child C4). Child C3 return 0 so it will directly print 1. Example 2:What is the output of following code? #include <stdio.h>#include <unistd.h> int main(){ if (fork()) { if (!fork()) { fork(); printf("1 "); } else { printf("2 "); } } else { printf("3 "); } printf("4 "); return 0;} Output: 2 4 1 4 1 4 3 4 Explanation:1. It will create two process one parent P (has process ID of child process) and other is child C1 (process ID = 0).2. When condition is true parent P executes if statement and child C1 executes else statement and print 3. Parent P checks next if statement and create two process (one parent P and child C2). In if statement we are using not operator (i.e, !), it executes for child process C2 and parent P executes else part and print value 2. Child C2further creates two new processes (one parent C2 and other is child C3). Example 3:What is the output of following code? #include <stdio.h>#include <unistd.h> int main(){ if (fork() && (!fork())) { if (fork() || fork()) { fork(); } } printf("2 "); return 0;} Output: 2 2 2 2 2 2 2 Explanation:1. Fork will create two process one parent P (has process id of new child) and other one is child C1 (process id=0).2. In if statement we are using AND operator (i.e, &&) and in this case if first condition is false then it will not evaluate second condition and print 2. Parent process P check for second condition and create two new processes (one parent P and other is child C2). In second condition we are using NOT operator which return true for child process C2 and it executes inner if statement.3. Child C2 again create two new processes (one parent C2 and child C3) and we are using OR operator (i.e, ||) which evaluate second condition when first condition is false. Parent C2 execute if part and create two new processes (one parent C2 and child C4) whereas child C3 check for second condition and create two new processes (one parent C3 and child C5).4. Parent C3 enters in if part and further create two new processes (one parent C3 and child C6). satish_kumar Copia system-programming C Language Linux-Unix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Unordered Sets in C++ Standard Template Library Operators in C / C++ Exception Handling in C++ What is the purpose of a function prototype? TCP Server-Client implementation 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": "\n17 Feb, 2020" }, { "code": null, "e": 106, "s": 54, "text": "Prerequisite: basics of fork, fork and binary tree," }, { "code": null, "e": 157, "s": 106, "text": "Example1:What is the output of the following code?" }, { "code": "#include <stdio.h>#include <unistd.h>int main(){ if (fork() || fork()) fork(); printf(\"1 \"); return 0;}", "e": 277, "s": 157, "text": null }, { "code": null, "e": 285, "s": 277, "text": "Output:" }, { "code": null, "e": 297, "s": 285, "text": " 1 1 1 1 1 " }, { "code": null, "e": 1012, "s": 297, "text": "Explanation:1. It will create two process one parent P (has process ID of child process)and other is child C1 (process ID = 0).2. In if statement we used OR operator( || ) and in this case second condition is evaluated when first condition is false.3. Parent process P will return positive integer so it directly execute statement and create two more processes (one parent P and other is child C2). Child process C1 will return 0 so it checks for second condition and second condition again create two more processes(one parent C1 and other is child C3).4. C1 return positive integer so it will further create two more processes (one parent C1 and other is child C4). Child C3 return 0 so it will directly print 1." }, { "code": null, "e": 1060, "s": 1012, "text": "Example 2:What is the output of following code?" }, { "code": "#include <stdio.h>#include <unistd.h> int main(){ if (fork()) { if (!fork()) { fork(); printf(\"1 \"); } else { printf(\"2 \"); } } else { printf(\"3 \"); } printf(\"4 \"); return 0;}", "e": 1323, "s": 1060, "text": null }, { "code": null, "e": 1331, "s": 1323, "text": "Output:" }, { "code": null, "e": 1349, "s": 1331, "text": " 2 4 1 4 1 4 3 4 " }, { "code": null, "e": 1887, "s": 1349, "text": "Explanation:1. It will create two process one parent P (has process ID of child process) and other is child C1 (process ID = 0).2. When condition is true parent P executes if statement and child C1 executes else statement and print 3. Parent P checks next if statement and create two process (one parent P and child C2). In if statement we are using not operator (i.e, !), it executes for child process C2 and parent P executes else part and print value 2. Child C2further creates two new processes (one parent C2 and other is child C3)." }, { "code": null, "e": 1935, "s": 1887, "text": "Example 3:What is the output of following code?" }, { "code": "#include <stdio.h>#include <unistd.h> int main(){ if (fork() && (!fork())) { if (fork() || fork()) { fork(); } } printf(\"2 \"); return 0;}", "e": 2111, "s": 1935, "text": null }, { "code": null, "e": 2119, "s": 2111, "text": "Output:" }, { "code": null, "e": 2135, "s": 2119, "text": " 2 2 2 2 2 2 2 " }, { "code": null, "e": 3108, "s": 2135, "text": "Explanation:1. Fork will create two process one parent P (has process id of new child) and other one is child C1 (process id=0).2. In if statement we are using AND operator (i.e, &&) and in this case if first condition is false then it will not evaluate second condition and print 2. Parent process P check for second condition and create two new processes (one parent P and other is child C2). In second condition we are using NOT operator which return true for child process C2 and it executes inner if statement.3. Child C2 again create two new processes (one parent C2 and child C3) and we are using OR operator (i.e, ||) which evaluate second condition when first condition is false. Parent C2 execute if part and create two new processes (one parent C2 and child C4) whereas child C3 check for second condition and create two new processes (one parent C3 and child C5).4. Parent C3 enters in if part and further create two new processes (one parent C3 and child C6)." }, { "code": null, "e": 3121, "s": 3108, "text": "satish_kumar" }, { "code": null, "e": 3127, "s": 3121, "text": "Copia" }, { "code": null, "e": 3146, "s": 3127, "text": "system-programming" }, { "code": null, "e": 3157, "s": 3146, "text": "C Language" }, { "code": null, "e": 3168, "s": 3157, "text": "Linux-Unix" }, { "code": null, "e": 3266, "s": 3168, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3314, "s": 3266, "text": "Unordered Sets in C++ Standard Template Library" }, { "code": null, "e": 3335, "s": 3314, "text": "Operators in C / C++" }, { "code": null, "e": 3361, "s": 3335, "text": "Exception Handling in C++" }, { "code": null, "e": 3406, "s": 3361, "text": "What is the purpose of a function prototype?" }, { "code": null, "e": 3444, "s": 3406, "text": "TCP Server-Client implementation in C" }, { "code": null, "e": 3484, "s": 3444, "text": "Sed Command in Linux/Unix with examples" }, { "code": null, "e": 3524, "s": 3484, "text": "AWK command in Unix/Linux with examples" }, { "code": null, "e": 3551, "s": 3524, "text": "grep command in Unix/Linux" }, { "code": null, "e": 3586, "s": 3551, "text": "cut command in Linux with examples" } ]
HTML | DOM onblur Event
28 Jun, 2019 The HTML DOM onblur event occurs when an object loses focus. The onblur event is the opposite of the onfocus event.The onblur event is mostly used with form validation code (e.g. when the user leaves a form field). Syntax: In HTML: <element onblur="myScript"> In JavaScript: object.onblur = function(){myScript}; In JavaScript, using the addEventListener() method: object.addEventListener("blur", myScript); Example: Using HTML <!DOCTYPE html><html> <body> <center> <h1 style="color:green"> GeeksforGeeks </h1> <h2>HTML DOM onblur event</h2> Email: <input type="email" id="email" onblur="myFunction()"> <script> function myFunction() { alert("Focus lost"); } </script> </center></body> </html> Output: Example: In JavaScript: <!DOCTYPE html><html> <body> <center> <h1 style="color:green"> GeeksforGeeks </h1> <h2>HTML DOM onblur event</h2> <input type="email" id="email"> <script> document.getElementById("email").onblur = function() { myFunction() }; function myFunction() { alert("Input field lost focus."); } </script> </center></body> </html> Output: Example: In JavaScript, using the addEventListener() method <!DOCTYPE html><html> <body> <center> <h1 style="color:green"> GeeksforGeeks </h1> <h2>HTML DOM onblur event</h2> <input type="email" id="email"> <script> document.getElementById( "email").addEventListener("blur", myFunction); function myFunction() { alert("Input field lost focus."); } </script> </center></body> </html> Output: Supported Browsers: The browsers supported by HTML DOM onblur Event are listed below: Google Chrome Internet Explorer Firefox Apple Safari Opera HTML-DOM HTML Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. REST API (Introduction) Design a Tribute Page using HTML & CSS Build a Survey Form using HTML and CSS Angular File Upload Design a web page using HTML and CSS Installation of Node.js on Linux Difference between var, let and const keywords in JavaScript How to fetch data from an API in ReactJS ? Differences between Functional Components and Class Components in React Remove elements from a JavaScript Array
[ { "code": null, "e": 28, "s": 0, "text": "\n28 Jun, 2019" }, { "code": null, "e": 243, "s": 28, "text": "The HTML DOM onblur event occurs when an object loses focus. The onblur event is the opposite of the onfocus event.The onblur event is mostly used with form validation code (e.g. when the user leaves a form field)." }, { "code": null, "e": 251, "s": 243, "text": "Syntax:" }, { "code": null, "e": 260, "s": 251, "text": "In HTML:" }, { "code": null, "e": 288, "s": 260, "text": "<element onblur=\"myScript\">" }, { "code": null, "e": 303, "s": 288, "text": "In JavaScript:" }, { "code": null, "e": 341, "s": 303, "text": "object.onblur = function(){myScript};" }, { "code": null, "e": 393, "s": 341, "text": "In JavaScript, using the addEventListener() method:" }, { "code": null, "e": 436, "s": 393, "text": "object.addEventListener(\"blur\", myScript);" }, { "code": null, "e": 456, "s": 436, "text": "Example: Using HTML" }, { "code": "<!DOCTYPE html><html> <body> <center> <h1 style=\"color:green\"> GeeksforGeeks </h1> <h2>HTML DOM onblur event</h2> Email: <input type=\"email\" id=\"email\" onblur=\"myFunction()\"> <script> function myFunction() { alert(\"Focus lost\"); } </script> </center></body> </html>", "e": 818, "s": 456, "text": null }, { "code": null, "e": 826, "s": 818, "text": "Output:" }, { "code": null, "e": 850, "s": 826, "text": "Example: In JavaScript:" }, { "code": "<!DOCTYPE html><html> <body> <center> <h1 style=\"color:green\"> GeeksforGeeks </h1> <h2>HTML DOM onblur event</h2> <input type=\"email\" id=\"email\"> <script> document.getElementById(\"email\").onblur = function() { myFunction() }; function myFunction() { alert(\"Input field lost focus.\"); } </script> </center></body> </html>", "e": 1306, "s": 850, "text": null }, { "code": null, "e": 1314, "s": 1306, "text": "Output:" }, { "code": null, "e": 1374, "s": 1314, "text": "Example: In JavaScript, using the addEventListener() method" }, { "code": "<!DOCTYPE html><html> <body> <center> <h1 style=\"color:green\"> GeeksforGeeks </h1> <h2>HTML DOM onblur event</h2> <input type=\"email\" id=\"email\"> <script> document.getElementById( \"email\").addEventListener(\"blur\", myFunction); function myFunction() { alert(\"Input field lost focus.\"); } </script> </center></body> </html>", "e": 1818, "s": 1374, "text": null }, { "code": null, "e": 1826, "s": 1818, "text": "Output:" }, { "code": null, "e": 1912, "s": 1826, "text": "Supported Browsers: The browsers supported by HTML DOM onblur Event are listed below:" }, { "code": null, "e": 1926, "s": 1912, "text": "Google Chrome" }, { "code": null, "e": 1944, "s": 1926, "text": "Internet Explorer" }, { "code": null, "e": 1952, "s": 1944, "text": "Firefox" }, { "code": null, "e": 1965, "s": 1952, "text": "Apple Safari" }, { "code": null, "e": 1971, "s": 1965, "text": "Opera" }, { "code": null, "e": 1980, "s": 1971, "text": "HTML-DOM" }, { "code": null, "e": 1985, "s": 1980, "text": "HTML" }, { "code": null, "e": 2002, "s": 1985, "text": "Web Technologies" }, { "code": null, "e": 2007, "s": 2002, "text": "HTML" }, { "code": null, "e": 2105, "s": 2007, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2129, "s": 2105, "text": "REST API (Introduction)" }, { "code": null, "e": 2168, "s": 2129, "text": "Design a Tribute Page using HTML & CSS" }, { "code": null, "e": 2207, "s": 2168, "text": "Build a Survey Form using HTML and CSS" }, { "code": null, "e": 2227, "s": 2207, "text": "Angular File Upload" }, { "code": null, "e": 2264, "s": 2227, "text": "Design a web page using HTML and CSS" }, { "code": null, "e": 2297, "s": 2264, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 2358, "s": 2297, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 2401, "s": 2358, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 2473, "s": 2401, "text": "Differences between Functional Components and Class Components in React" } ]
Python | Button Action in Kivy
29 Jun, 2021 Kivy is a platform-independent GUI tool in Python. As it can be run on Android, IOS, Linux and Windows, etc. It is basically used to develop the Android application, but it does not mean that it can not be used on Desktop applications. ???????? Kivy Tutorial – Learn Kivy with Examples. Now in this article, we will learn how to build a button in kivy by using the kv file, just like the button we use in calculators and many more places.Buttons : The Button is a Label with associated actions that are triggered when the button is pressed (or released after a click/touch). To bind the action of button when it pressed we have the function on_press. Basic Approach for the button Actions using .kv file: 1) Import kivy 2) Import kivy app 3) Import Box layout 4) create .kv with label and button 5) Bind button to a method 6) create method Now let’s code the .py file. Python3 # import kivy moduleimport kivy # this restrict the kivy version i.e# below this kivy version you cannot# use the app or softwarekivy.require("1.9.1") # base Class of your App inherits from the App class.# app:always refers to the instance of your applicationfrom kivy.app import App # BoxLayout arranges children# in a vertical or horizontal box.from kivy.uix.boxlayout import BoxLayout # class in which we are defining action on clickclass RootWidget(BoxLayout): def btn_clk(self): self.lbl.text = "You have been pressed" # creating action class and calling# Rootwidget by returning itclass ActionApp(App): def build(self): return RootWidget() # creating the myApp root for ActionApp() class myApp = ActionApp() # run function runs the whole program# i.e run() method which calls the# target function passed to the constructor.myApp.run() .kv file of the above code [action.kv] :Must be saved with the name of the ActionApp class. i.e action.kv. Python3 # Base widget from Rootwidget class in .py file<RootWidget>: # used to change the label text # as in rootwidget class lbl:my_label # child that is an instance of the BoxLayout BoxLayout: orientation: 'vertical' size: [1, .25] Button: text:'Click Me' font_size:"50sp" color: [0, 255, 255, .67] on_press: root.btn_clk() Label: # id is limited in scope to the rule # it is declared in. An id is a weakref # to the widget and not the widget itself. id: my_label text: 'No click Yet' color: [0, 84, 80, 19] Output: Video explaining output: Note: BoxLayout arranges widgets in either in a vertical fashion that is one on top of another or in a horizontal fashion that is one after another. rajeev0719singh Python-gui Python-kivy 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 Python String | replace() How to Install PIP on Windows ? *args and **kwargs in Python Python Classes and Objects Python OOPs Concepts Convert integer to string in Python Introduction To PYTHON
[ { "code": null, "e": 53, "s": 25, "text": "\n29 Jun, 2021" }, { "code": null, "e": 290, "s": 53, "text": "Kivy is a platform-independent GUI tool in Python. As it can be run on Android, IOS, Linux and Windows, etc. It is basically used to develop the Android application, but it does not mean that it can not be used on Desktop applications. " }, { "code": null, "e": 341, "s": 290, "text": "???????? Kivy Tutorial – Learn Kivy with Examples." }, { "code": null, "e": 761, "s": 341, "text": "Now in this article, we will learn how to build a button in kivy by using the kv file, just like the button we use in calculators and many more places.Buttons : The Button is a Label with associated actions that are triggered when the button is pressed (or released after a click/touch). To bind the action of button when it pressed we have the function on_press. Basic Approach for the button Actions using .kv file: " }, { "code": null, "e": 896, "s": 761, "text": "1) Import kivy\n2) Import kivy app\n3) Import Box layout\n4) create .kv with label and button\n5) Bind button to a method\n6) create method" }, { "code": null, "e": 926, "s": 896, "text": "Now let’s code the .py file. " }, { "code": null, "e": 934, "s": 926, "text": "Python3" }, { "code": "# import kivy moduleimport kivy # this restrict the kivy version i.e# below this kivy version you cannot# use the app or softwarekivy.require(\"1.9.1\") # base Class of your App inherits from the App class.# app:always refers to the instance of your applicationfrom kivy.app import App # BoxLayout arranges children# in a vertical or horizontal box.from kivy.uix.boxlayout import BoxLayout # class in which we are defining action on clickclass RootWidget(BoxLayout): def btn_clk(self): self.lbl.text = \"You have been pressed\" # creating action class and calling# Rootwidget by returning itclass ActionApp(App): def build(self): return RootWidget() # creating the myApp root for ActionApp() class myApp = ActionApp() # run function runs the whole program# i.e run() method which calls the# target function passed to the constructor.myApp.run()", "e": 1802, "s": 934, "text": null }, { "code": null, "e": 1913, "s": 1802, "text": " .kv file of the above code [action.kv] :Must be saved with the name of the ActionApp class. i.e action.kv. " }, { "code": null, "e": 1921, "s": 1913, "text": "Python3" }, { "code": "# Base widget from Rootwidget class in .py file<RootWidget>: # used to change the label text # as in rootwidget class lbl:my_label # child that is an instance of the BoxLayout BoxLayout: orientation: 'vertical' size: [1, .25] Button: text:'Click Me' font_size:\"50sp\" color: [0, 255, 255, .67] on_press: root.btn_clk() Label: # id is limited in scope to the rule # it is declared in. An id is a weakref # to the widget and not the widget itself. id: my_label text: 'No click Yet' color: [0, 84, 80, 19]", "e": 2532, "s": 1921, "text": null }, { "code": null, "e": 2541, "s": 2532, "text": "Output: " }, { "code": null, "e": 2570, "s": 2543, "text": "Video explaining output: " }, { "code": null, "e": 2720, "s": 2570, "text": "Note: BoxLayout arranges widgets in either in a vertical fashion that is one on top of another or in a horizontal fashion that is one after another. " }, { "code": null, "e": 2736, "s": 2720, "text": "rajeev0719singh" }, { "code": null, "e": 2747, "s": 2736, "text": "Python-gui" }, { "code": null, "e": 2759, "s": 2747, "text": "Python-kivy" }, { "code": null, "e": 2766, "s": 2759, "text": "Python" }, { "code": null, "e": 2864, "s": 2766, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2882, "s": 2864, "text": "Python Dictionary" }, { "code": null, "e": 2924, "s": 2882, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 2946, "s": 2924, "text": "Enumerate() in Python" }, { "code": null, "e": 2972, "s": 2946, "text": "Python String | replace()" }, { "code": null, "e": 3004, "s": 2972, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 3033, "s": 3004, "text": "*args and **kwargs in Python" }, { "code": null, "e": 3060, "s": 3033, "text": "Python Classes and Objects" }, { "code": null, "e": 3081, "s": 3060, "text": "Python OOPs Concepts" }, { "code": null, "e": 3117, "s": 3081, "text": "Convert integer to string in Python" } ]
ML | Label Encoding of datasets in Python
18 May, 2022 In machine learning, we usually deal with datasets that contain multiple labels in one or more than one columns. These labels can be in the form of words or numbers. To make the data understandable or in human-readable form, the training data is often labelled in words. Label Encoding refers to converting the labels into a numeric form so as to convert them into the machine-readable form. Machine learning algorithms can then decide in a better way how those labels must be operated. It is an important pre-processing step for the structured dataset in supervised learning. Example : Suppose we have a column Height in some dataset. After applying label encoding, the Height column is converted into: where 0 is the label for tall, 1 is the label for medium, and 2 is a label for short height. We apply Label Encoding on iris dataset on the target column which is Species. It contains three species Iris-setosa, Iris-versicolor, Iris-virginica. Python3 # Import libraries import numpy as npimport pandas as pd # Import datasetdf = pd.read_csv('../../data/Iris.csv') df['species'].unique() Output: array(['Iris-setosa', 'Iris-versicolor', 'Iris-virginica'], dtype=object) After applying Label Encoding – Python3 # Import label encoderfrom sklearn import preprocessing # label_encoder object knows how to understand word labels.label_encoder = preprocessing.LabelEncoder() # Encode labels in column 'species'.df['species']= label_encoder.fit_transform(df['species']) df['species'].unique() Output: array([0, 1, 2], dtype=int64) Limitation of label Encoding Label encoding converts the data in machine-readable form, but it assigns a unique number(starting from 0) to each class of data. This may lead to the generation of priority issues in the training of data sets. A label with a high value may be considered to have high priority than a label having a lower value. ExampleAn attribute having output classes Mexico, Paris, Dubai. On Label Encoding, this column lets Mexico is replaced with 0, Paris is replaced with 1, and Dubai is replaced with 2. With this, it can be interpreted that Dubai has high priority than Mexico and Paris while training the model, But actually, there is no such priority relation between these cities here. deepak_jain tanwarsinghvaibhav akshaysingh98088 Advanced Computer Subject Machine Learning Python Machine Learning Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n18 May, 2022" }, { "code": null, "e": 324, "s": 52, "text": "In machine learning, we usually deal with datasets that contain multiple labels in one or more than one columns. These labels can be in the form of words or numbers. To make the data understandable or in human-readable form, the training data is often labelled in words. " }, { "code": null, "e": 630, "s": 324, "text": "Label Encoding refers to converting the labels into a numeric form so as to convert them into the machine-readable form. Machine learning algorithms can then decide in a better way how those labels must be operated. It is an important pre-processing step for the structured dataset in supervised learning." }, { "code": null, "e": 690, "s": 630, "text": "Example : Suppose we have a column Height in some dataset. " }, { "code": null, "e": 759, "s": 690, "text": "After applying label encoding, the Height column is converted into: " }, { "code": null, "e": 852, "s": 759, "text": "where 0 is the label for tall, 1 is the label for medium, and 2 is a label for short height." }, { "code": null, "e": 1004, "s": 852, "text": "We apply Label Encoding on iris dataset on the target column which is Species. It contains three species Iris-setosa, Iris-versicolor, Iris-virginica. " }, { "code": null, "e": 1012, "s": 1004, "text": "Python3" }, { "code": "# Import libraries import numpy as npimport pandas as pd # Import datasetdf = pd.read_csv('../../data/Iris.csv') df['species'].unique()", "e": 1150, "s": 1012, "text": null }, { "code": null, "e": 1159, "s": 1150, "text": "Output: " }, { "code": null, "e": 1233, "s": 1159, "text": "array(['Iris-setosa', 'Iris-versicolor', 'Iris-virginica'], dtype=object)" }, { "code": null, "e": 1266, "s": 1233, "text": "After applying Label Encoding – " }, { "code": null, "e": 1274, "s": 1266, "text": "Python3" }, { "code": "# Import label encoderfrom sklearn import preprocessing # label_encoder object knows how to understand word labels.label_encoder = preprocessing.LabelEncoder() # Encode labels in column 'species'.df['species']= label_encoder.fit_transform(df['species']) df['species'].unique()", "e": 1554, "s": 1274, "text": null }, { "code": null, "e": 1563, "s": 1554, "text": "Output: " }, { "code": null, "e": 1593, "s": 1563, "text": "array([0, 1, 2], dtype=int64)" }, { "code": null, "e": 1934, "s": 1593, "text": "Limitation of label Encoding Label encoding converts the data in machine-readable form, but it assigns a unique number(starting from 0) to each class of data. This may lead to the generation of priority issues in the training of data sets. A label with a high value may be considered to have high priority than a label having a lower value." }, { "code": null, "e": 2304, "s": 1934, "text": "ExampleAn attribute having output classes Mexico, Paris, Dubai. On Label Encoding, this column lets Mexico is replaced with 0, Paris is replaced with 1, and Dubai is replaced with 2. With this, it can be interpreted that Dubai has high priority than Mexico and Paris while training the model, But actually, there is no such priority relation between these cities here. " }, { "code": null, "e": 2316, "s": 2304, "text": "deepak_jain" }, { "code": null, "e": 2335, "s": 2316, "text": "tanwarsinghvaibhav" }, { "code": null, "e": 2352, "s": 2335, "text": "akshaysingh98088" }, { "code": null, "e": 2378, "s": 2352, "text": "Advanced Computer Subject" }, { "code": null, "e": 2395, "s": 2378, "text": "Machine Learning" }, { "code": null, "e": 2402, "s": 2395, "text": "Python" }, { "code": null, "e": 2419, "s": 2402, "text": "Machine Learning" } ]
Find the nearest smaller numbers on left side in an array
31 May, 2022 Given an array of integers, find the nearest smaller number for every element such that the smaller element is on the left side. Examples: Input: arr[] = {1, 6, 4, 10, 2, 5} Output: {_, 1, 1, 4, 1, 2} First element ('1') has no element on left side. For 6, there is only one smaller element on left side '1'. For 10, there are three smaller elements on left side (1, 6 and 4), nearest among the three elements is 4. Input: arr[] = {1, 3, 0, 2, 5} Output: {_, 1, _, 0, 2} Expected time complexity is O(n). A Simple Solution is to use two nested loops. The outer loop starts from the second element, the inner loop goes to all elements on the left side of the element picked by the outer loop and stops as soon as it finds a smaller element. C++ C Java Python3 C# PHP Javascript // C++ implementation of simple algorithm to find// smaller element on left side#include <iostream>using namespace std; // Prints smaller elements on left side of every elementvoid printPrevSmaller(int arr[], int n){ // Always print empty or '_' for first element cout << "_, "; // Start from second element for (int i = 1; i < n; i++) { // look for smaller element on left of 'i' int j; for (j = i - 1; j >= 0; j--) { if (arr[j] < arr[i]) { cout << arr[j] << ", "; break; } } // If there is no smaller element on left of 'i' if (j == -1) cout << "_, "; }} int main(){ int arr[] = { 1, 3, 0, 2, 5 }; int n = sizeof(arr) / sizeof(arr[0]); printPrevSmaller(arr, n); return 0;} // This code is contributed by Aditya Kumar (adityakumar129) // C implementation of simple algorithm to find// smaller element on left side#include <stdio.h> // Prints smaller elements on left side of every elementvoid printPrevSmaller(int arr[], int n){ // Always print empty or '_' for first element printf("_, "); // Start from second element for (int i = 1; i < n; i++) { // look for smaller element on left of 'i' int j; for (j = i - 1; j >= 0; j--) { if (arr[j] < arr[i]) { printf("%d, ",arr[j]); break; } } // If there is no smaller element on left of 'i' if (j == -1) printf("_, "); }} /* Driver program to test insertion sort */int main(){ int arr[] = { 1, 3, 0, 2, 5 }; int n = sizeof(arr) / sizeof(arr[0]); printPrevSmaller(arr, n); return 0;} // This code is contributed by Aditya Kumar (adityakumar129) // Java implementation of simple algorithm to find smaller// element on left sideimport java.io.*;class GFG { // Prints smaller elements on left side of every element static void printPrevSmaller(int[] arr, int n) { // Always print empty or '_' for first element System.out.print("_, "); // Start from second element for (int i = 1; i < n; i++) { // look for smaller element on left of 'i' int j; for (j = i - 1; j >= 0; j--) { if (arr[j] < arr[i]) { System.out.print(arr[j] + ", "); break; } } // If there is no smaller element on left of 'i' if (j == -1) System.out.print("_, "); } } // Driver Code public static void main(String[] args) { int[] arr = { 1, 3, 0, 2, 5 }; int n = arr.length; printPrevSmaller(arr, n); }} // This code is contributed by Aditya Kumar (adityakumar129) # Python 3 implementation of simple# algorithm to find smaller element# on left side # Prints smaller elements on left# side of every elementdef printPrevSmaller(arr, n): # Always print empty or '_' for # first element print("_, ", end="") # Start from second element for i in range(1, n ): # look for smaller element # on left of 'i' for j in range(i-1 ,-2 ,-1): if (arr[j] < arr[i]): print(arr[j] ,", ", end="") break # If there is no smaller # element on left of 'i' if (j == -1): print("_, ", end="") # Driver program to test insertion# sortarr = [1, 3, 0, 2, 5]n = len(arr)printPrevSmaller(arr, n) # This code is contributed by# Smitha // C# implementation of simple// algorithm to find smaller// element on left sideusing System; class GFG { // Prints smaller elements on // left side of every element static void printPrevSmaller(int []arr, int n) { // Always print empty or '_' // for first element Console.Write( "_, "); // Start from second element for (int i = 1; i < n; i++) { // look for smaller // element on left of 'i' int j; for(j = i - 1; j >= 0; j--) { if (arr[j] < arr[i]) { Console.Write(arr[j] + ", "); break; } } // If there is no smaller // element on left of 'i' if (j == -1) Console.Write( "_, ") ; } } // Driver Code public static void Main () { int []arr = {1, 3, 0, 2, 5}; int n = arr.Length; printPrevSmaller(arr, n); }} // This code is contributed by anuj_67. <?php// PHP implementation of simple// algorithm to find smaller// element on left side // Prints smaller elements on// left side of every elementfunction printPrevSmaller( $arr, $n){ // Always print empty or // '_' for first element echo "_, "; // Start from second element for($i = 1; $i < $n; $i++) { // look for smaller // element on left of 'i' $j; for($j = $i - 1; $j >= 0; $j--) { if ($arr[$j] < $arr[$i]) { echo $arr[$j] , ", "; break; } } // If there is no smaller // element on left of 'i' if ($j == -1) echo "_, " ; }} // Driver Code $arr = array(1, 3, 0, 2, 5); $n = count($arr); printPrevSmaller($arr, $n); // This code is contributed by anuj_67.?> <script> // Javascript implementation// of simple algorithm to find// smaller element on left side // Prints smaller elements on// left side of every elementfunction printPrevSmaller( arr, n){ // Always print empty or '_' for first element document.write("_, "); // Start from second element for (let i=1; i<n; i++) { // look for smaller element on left of 'i' let j; for (j=i-1; j>=0; j--) { if (arr[j] < arr[i]) { document.write(arr[j] + ", "); break; } } // If there is no smaller element on left of 'i' if (j == -1) document.write("_, "); }} // Driver program let arr = [ 1, 3, 0, 2, 5 ]; let n = arr.length; printPrevSmaller(arr, n); </script> Output: _, 1, _, 0, 2, , The time complexity of the above solution is O(n2). There can be an Efficient Solution that works in O(n) time. The idea is to use a stack. Stack is used to maintain a subsequence of the values that have been processed so far and are smaller than any later value that has already been processed. Algorithm: Stack-based Let input sequence be 'arr[]' and size of array be 'n' 1) Create a new empty stack S 2) For every element 'arr[i]' in the input sequence 'arr[]', where 'i' goes from 0 to n-1. a) while S is nonempty and the top element of S is greater than or equal to 'arr[i]': pop S b) if S is empty: 'arr[i]' has no preceding smaller value c) else: the nearest smaller value to 'arr[i]' is the top element of S d) push 'arr[i]' onto S Below is the implementation of the above algorithm. C++ Java Python3 C# Javascript // C++ implementation of efficient algorithm to find// smaller element on left side#include <iostream>#include <stack>using namespace std; // Prints smaller elements on left side of every elementvoid printPrevSmaller(int arr[], int n){ // Create an empty stack stack<int> S; // Traverse all array elements for (int i=0; i<n; i++) { // Keep removing top element from S while the top // element is greater than or equal to arr[i] while (!S.empty() && S.top() >= arr[i]) S.pop(); // If all elements in S were greater than arr[i] if (S.empty()) cout << "_, "; else //Else print the nearest smaller element cout << S.top() << ", "; // Push this element S.push(arr[i]); }} int main(){ int arr[] = {1, 3, 0, 2, 5}; int n = sizeof(arr)/sizeof(arr[0]); printPrevSmaller(arr, n); return 0;} import java.util.Stack; //Java implementation of efficient algorithm to find// smaller element on left sideclass GFG { // Prints smaller elements on left side of every element static void printPrevSmaller(int arr[], int n) { // Create an empty stack Stack<Integer> S = new Stack<>(); // Traverse all array elements for (int i = 0; i < n; i++) { // Keep removing top element from S while the top // element is greater than or equal to arr[i] while (!S.empty() && S.peek() >= arr[i]) { S.pop(); } // If all elements in S were greater than arr[i] if (S.empty()) { System.out.print("_, "); } else //Else print the nearest smaller element { System.out.print(S.peek() + ", "); } // Push this element S.push(arr[i]); } } /* Driver program to test insertion sort */ public static void main(String[] args) { int arr[] = {1, 3, 0, 2, 5}; int n = arr.length; printPrevSmaller(arr, n); }} # Python3 implementation of efficient# algorithm to find smaller element# on left sideimport math as mt # Prints smaller elements on left# side of every elementdef printPrevSmaller(arr, n): # Create an empty stack S = list() # Traverse all array elements for i in range(n): # Keep removing top element from S # while the top element is greater # than or equal to arr[i] while (len(S) > 0 and S[-1] >= arr[i]): S.pop() # If all elements in S were greater # than arr[i] if (len(S) == 0): print("_, ", end = "") else: # Else print the nearest # smaller element print(S[-1], end = ", ") # Push this element S.append(arr[i]) # Driver Codearr = [ 1, 3, 0, 2, 5]n = len(arr)printPrevSmaller(arr, n) # This code is contributed by# Mohit kumar 29 // C# implementation of efficient algorithm to find// smaller element on left sideusing System;using System.Collections.Generic; public class GFG{ // Prints smaller elements on left side of every element static void printPrevSmaller(int []arr, int n) { // Create an empty stack Stack<int> S = new Stack<int>(); // Traverse all array elements for (int i = 0; i < n; i++) { // Keep removing top element from S while the top // element is greater than or equal to arr[i] while (S.Count != 0 && S.Peek() >= arr[i]) { S.Pop(); } // If all elements in S were greater than arr[i] if (S.Count == 0) { Console.Write("_, "); } else //Else print the nearest smaller element { Console.Write(S.Peek() + ", "); } // Push this element S.Push(arr[i]); } } /* Driver code */ public static void Main(String[] args) { int []arr = {1, 3, 0, 2, 5}; int n = arr.Length; printPrevSmaller(arr, n); }} // This code is contributed by Princi Singh <script> // Javascript implementation of efficient// algorithm to find smaller element on left side // Prints smaller elements on left// side of every elementfunction printPrevSmaller(arr, n){ // Create an empty stack let S = []; // Traverse all array elements for(let i = 0; i < n; i++) { // Keep removing top element from S // while the top element is greater // than or equal to arr[i] while ((S.length != 0) && (S[S.length - 1] >= arr[i])) { S.pop(); } // If all elements in S were // greater than arr[i] if (S.length == 0) { document.write("_, "); } // Else print the nearest smaller element else { document.write(S[S.length - 1] + ", "); } // Push this element S.push(arr[i]); }} // Driver codelet arr = [ 1, 3, 0, 2, 5 ];let n = arr.length; printPrevSmaller(arr, n); // This code is contributed by divyeshrabadiya07 </script> Output: _, 1, _, 0, 2, Time complexity of the above program is O(n) as every element is pushed and popped at most once to the stack. So overall constant number of operations are performed per element. This article is contributed by Ashish Kumar Singh. Please write comments if you find the above codes/algorithms incorrect, or find other ways to solve the same problem. vt_m Smitha Dinesh Semwal princiraj1992 mohit kumar 29 princi singh jana_sayantan divyeshrabadiya07 adityakumar129 rishuabhishek06 Amazon Arrays Searching Stack Amazon Arrays Searching Stack Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n31 May, 2022" }, { "code": null, "e": 183, "s": 54, "text": "Given an array of integers, find the nearest smaller number for every element such that the smaller element is on the left side." }, { "code": null, "e": 194, "s": 183, "text": "Examples: " }, { "code": null, "e": 483, "s": 194, "text": "Input: arr[] = {1, 6, 4, 10, 2, 5}\nOutput: {_, 1, 1, 4, 1, 2}\nFirst element ('1') has no element on left side. For 6, \nthere is only one smaller element on left side '1'. \nFor 10, there are three smaller elements on left side (1,\n6 and 4), nearest among the three elements is 4." }, { "code": null, "e": 545, "s": 483, "text": "Input: arr[] = {1, 3, 0, 2, 5}\nOutput: {_, 1, _, 0, 2}" }, { "code": null, "e": 580, "s": 545, "text": "Expected time complexity is O(n). " }, { "code": null, "e": 817, "s": 580, "text": "A Simple Solution is to use two nested loops. The outer loop starts from the second element, the inner loop goes to all elements on the left side of the element picked by the outer loop and stops as soon as it finds a smaller element. " }, { "code": null, "e": 821, "s": 817, "text": "C++" }, { "code": null, "e": 823, "s": 821, "text": "C" }, { "code": null, "e": 828, "s": 823, "text": "Java" }, { "code": null, "e": 836, "s": 828, "text": "Python3" }, { "code": null, "e": 839, "s": 836, "text": "C#" }, { "code": null, "e": 843, "s": 839, "text": "PHP" }, { "code": null, "e": 854, "s": 843, "text": "Javascript" }, { "code": "// C++ implementation of simple algorithm to find// smaller element on left side#include <iostream>using namespace std; // Prints smaller elements on left side of every elementvoid printPrevSmaller(int arr[], int n){ // Always print empty or '_' for first element cout << \"_, \"; // Start from second element for (int i = 1; i < n; i++) { // look for smaller element on left of 'i' int j; for (j = i - 1; j >= 0; j--) { if (arr[j] < arr[i]) { cout << arr[j] << \", \"; break; } } // If there is no smaller element on left of 'i' if (j == -1) cout << \"_, \"; }} int main(){ int arr[] = { 1, 3, 0, 2, 5 }; int n = sizeof(arr) / sizeof(arr[0]); printPrevSmaller(arr, n); return 0;} // This code is contributed by Aditya Kumar (adityakumar129)", "e": 1724, "s": 854, "text": null }, { "code": "// C implementation of simple algorithm to find// smaller element on left side#include <stdio.h> // Prints smaller elements on left side of every elementvoid printPrevSmaller(int arr[], int n){ // Always print empty or '_' for first element printf(\"_, \"); // Start from second element for (int i = 1; i < n; i++) { // look for smaller element on left of 'i' int j; for (j = i - 1; j >= 0; j--) { if (arr[j] < arr[i]) { printf(\"%d, \",arr[j]); break; } } // If there is no smaller element on left of 'i' if (j == -1) printf(\"_, \"); }} /* Driver program to test insertion sort */int main(){ int arr[] = { 1, 3, 0, 2, 5 }; int n = sizeof(arr) / sizeof(arr[0]); printPrevSmaller(arr, n); return 0;} // This code is contributed by Aditya Kumar (adityakumar129)", "e": 2613, "s": 1724, "text": null }, { "code": "// Java implementation of simple algorithm to find smaller// element on left sideimport java.io.*;class GFG { // Prints smaller elements on left side of every element static void printPrevSmaller(int[] arr, int n) { // Always print empty or '_' for first element System.out.print(\"_, \"); // Start from second element for (int i = 1; i < n; i++) { // look for smaller element on left of 'i' int j; for (j = i - 1; j >= 0; j--) { if (arr[j] < arr[i]) { System.out.print(arr[j] + \", \"); break; } } // If there is no smaller element on left of 'i' if (j == -1) System.out.print(\"_, \"); } } // Driver Code public static void main(String[] args) { int[] arr = { 1, 3, 0, 2, 5 }; int n = arr.length; printPrevSmaller(arr, n); }} // This code is contributed by Aditya Kumar (adityakumar129)", "e": 3627, "s": 2613, "text": null }, { "code": "# Python 3 implementation of simple# algorithm to find smaller element# on left side # Prints smaller elements on left# side of every elementdef printPrevSmaller(arr, n): # Always print empty or '_' for # first element print(\"_, \", end=\"\") # Start from second element for i in range(1, n ): # look for smaller element # on left of 'i' for j in range(i-1 ,-2 ,-1): if (arr[j] < arr[i]): print(arr[j] ,\", \", end=\"\") break # If there is no smaller # element on left of 'i' if (j == -1): print(\"_, \", end=\"\") # Driver program to test insertion# sortarr = [1, 3, 0, 2, 5]n = len(arr)printPrevSmaller(arr, n) # This code is contributed by# Smitha", "e": 4434, "s": 3627, "text": null }, { "code": "// C# implementation of simple// algorithm to find smaller// element on left sideusing System; class GFG { // Prints smaller elements on // left side of every element static void printPrevSmaller(int []arr, int n) { // Always print empty or '_' // for first element Console.Write( \"_, \"); // Start from second element for (int i = 1; i < n; i++) { // look for smaller // element on left of 'i' int j; for(j = i - 1; j >= 0; j--) { if (arr[j] < arr[i]) { Console.Write(arr[j] + \", \"); break; } } // If there is no smaller // element on left of 'i' if (j == -1) Console.Write( \"_, \") ; } } // Driver Code public static void Main () { int []arr = {1, 3, 0, 2, 5}; int n = arr.Length; printPrevSmaller(arr, n); }} // This code is contributed by anuj_67.", "e": 5561, "s": 4434, "text": null }, { "code": "<?php// PHP implementation of simple// algorithm to find smaller// element on left side // Prints smaller elements on// left side of every elementfunction printPrevSmaller( $arr, $n){ // Always print empty or // '_' for first element echo \"_, \"; // Start from second element for($i = 1; $i < $n; $i++) { // look for smaller // element on left of 'i' $j; for($j = $i - 1; $j >= 0; $j--) { if ($arr[$j] < $arr[$i]) { echo $arr[$j] , \", \"; break; } } // If there is no smaller // element on left of 'i' if ($j == -1) echo \"_, \" ; }} // Driver Code $arr = array(1, 3, 0, 2, 5); $n = count($arr); printPrevSmaller($arr, $n); // This code is contributed by anuj_67.?>", "e": 6406, "s": 5561, "text": null }, { "code": "<script> // Javascript implementation// of simple algorithm to find// smaller element on left side // Prints smaller elements on// left side of every elementfunction printPrevSmaller( arr, n){ // Always print empty or '_' for first element document.write(\"_, \"); // Start from second element for (let i=1; i<n; i++) { // look for smaller element on left of 'i' let j; for (j=i-1; j>=0; j--) { if (arr[j] < arr[i]) { document.write(arr[j] + \", \"); break; } } // If there is no smaller element on left of 'i' if (j == -1) document.write(\"_, \"); }} // Driver program let arr = [ 1, 3, 0, 2, 5 ]; let n = arr.length; printPrevSmaller(arr, n); </script>", "e": 7222, "s": 6406, "text": null }, { "code": null, "e": 7231, "s": 7222, "text": "Output: " }, { "code": null, "e": 7248, "s": 7231, "text": "_, 1, _, 0, 2, ," }, { "code": null, "e": 7300, "s": 7248, "text": "The time complexity of the above solution is O(n2)." }, { "code": null, "e": 7544, "s": 7300, "text": "There can be an Efficient Solution that works in O(n) time. The idea is to use a stack. Stack is used to maintain a subsequence of the values that have been processed so far and are smaller than any later value that has already been processed." }, { "code": null, "e": 7570, "s": 7544, "text": "Algorithm: Stack-based " }, { "code": null, "e": 8071, "s": 7570, "text": "Let input sequence be 'arr[]' and size of array be 'n'\n\n1) Create a new empty stack S\n\n2) For every element 'arr[i]' in the input sequence 'arr[]',\n where 'i' goes from 0 to n-1.\n a) while S is nonempty and the top element of \n S is greater than or equal to 'arr[i]':\n pop S\n \n b) if S is empty:\n 'arr[i]' has no preceding smaller value\n c) else:\n the nearest smaller value to 'arr[i]' is \n the top element of S\n\n d) push 'arr[i]' onto S" }, { "code": null, "e": 8124, "s": 8071, "text": "Below is the implementation of the above algorithm. " }, { "code": null, "e": 8128, "s": 8124, "text": "C++" }, { "code": null, "e": 8133, "s": 8128, "text": "Java" }, { "code": null, "e": 8141, "s": 8133, "text": "Python3" }, { "code": null, "e": 8144, "s": 8141, "text": "C#" }, { "code": null, "e": 8155, "s": 8144, "text": "Javascript" }, { "code": "// C++ implementation of efficient algorithm to find// smaller element on left side#include <iostream>#include <stack>using namespace std; // Prints smaller elements on left side of every elementvoid printPrevSmaller(int arr[], int n){ // Create an empty stack stack<int> S; // Traverse all array elements for (int i=0; i<n; i++) { // Keep removing top element from S while the top // element is greater than or equal to arr[i] while (!S.empty() && S.top() >= arr[i]) S.pop(); // If all elements in S were greater than arr[i] if (S.empty()) cout << \"_, \"; else //Else print the nearest smaller element cout << S.top() << \", \"; // Push this element S.push(arr[i]); }} int main(){ int arr[] = {1, 3, 0, 2, 5}; int n = sizeof(arr)/sizeof(arr[0]); printPrevSmaller(arr, n); return 0;}", "e": 9059, "s": 8155, "text": null }, { "code": "import java.util.Stack; //Java implementation of efficient algorithm to find// smaller element on left sideclass GFG { // Prints smaller elements on left side of every element static void printPrevSmaller(int arr[], int n) { // Create an empty stack Stack<Integer> S = new Stack<>(); // Traverse all array elements for (int i = 0; i < n; i++) { // Keep removing top element from S while the top // element is greater than or equal to arr[i] while (!S.empty() && S.peek() >= arr[i]) { S.pop(); } // If all elements in S were greater than arr[i] if (S.empty()) { System.out.print(\"_, \"); } else //Else print the nearest smaller element { System.out.print(S.peek() + \", \"); } // Push this element S.push(arr[i]); } } /* Driver program to test insertion sort */ public static void main(String[] args) { int arr[] = {1, 3, 0, 2, 5}; int n = arr.length; printPrevSmaller(arr, n); }}", "e": 10177, "s": 9059, "text": null }, { "code": "# Python3 implementation of efficient# algorithm to find smaller element# on left sideimport math as mt # Prints smaller elements on left# side of every elementdef printPrevSmaller(arr, n): # Create an empty stack S = list() # Traverse all array elements for i in range(n): # Keep removing top element from S # while the top element is greater # than or equal to arr[i] while (len(S) > 0 and S[-1] >= arr[i]): S.pop() # If all elements in S were greater # than arr[i] if (len(S) == 0): print(\"_, \", end = \"\") else: # Else print the nearest # smaller element print(S[-1], end = \", \") # Push this element S.append(arr[i]) # Driver Codearr = [ 1, 3, 0, 2, 5]n = len(arr)printPrevSmaller(arr, n) # This code is contributed by# Mohit kumar 29", "e": 11056, "s": 10177, "text": null }, { "code": "// C# implementation of efficient algorithm to find// smaller element on left sideusing System;using System.Collections.Generic; public class GFG{ // Prints smaller elements on left side of every element static void printPrevSmaller(int []arr, int n) { // Create an empty stack Stack<int> S = new Stack<int>(); // Traverse all array elements for (int i = 0; i < n; i++) { // Keep removing top element from S while the top // element is greater than or equal to arr[i] while (S.Count != 0 && S.Peek() >= arr[i]) { S.Pop(); } // If all elements in S were greater than arr[i] if (S.Count == 0) { Console.Write(\"_, \"); } else //Else print the nearest smaller element { Console.Write(S.Peek() + \", \"); } // Push this element S.Push(arr[i]); } } /* Driver code */ public static void Main(String[] args) { int []arr = {1, 3, 0, 2, 5}; int n = arr.Length; printPrevSmaller(arr, n); }} // This code is contributed by Princi Singh", "e": 12272, "s": 11056, "text": null }, { "code": "<script> // Javascript implementation of efficient// algorithm to find smaller element on left side // Prints smaller elements on left// side of every elementfunction printPrevSmaller(arr, n){ // Create an empty stack let S = []; // Traverse all array elements for(let i = 0; i < n; i++) { // Keep removing top element from S // while the top element is greater // than or equal to arr[i] while ((S.length != 0) && (S[S.length - 1] >= arr[i])) { S.pop(); } // If all elements in S were // greater than arr[i] if (S.length == 0) { document.write(\"_, \"); } // Else print the nearest smaller element else { document.write(S[S.length - 1] + \", \"); } // Push this element S.push(arr[i]); }} // Driver codelet arr = [ 1, 3, 0, 2, 5 ];let n = arr.length; printPrevSmaller(arr, n); // This code is contributed by divyeshrabadiya07 </script>", "e": 13313, "s": 12272, "text": null }, { "code": null, "e": 13322, "s": 13313, "text": "Output: " }, { "code": null, "e": 13337, "s": 13322, "text": "_, 1, _, 0, 2," }, { "code": null, "e": 13515, "s": 13337, "text": "Time complexity of the above program is O(n) as every element is pushed and popped at most once to the stack. So overall constant number of operations are performed per element." }, { "code": null, "e": 13685, "s": 13515, "text": "This article is contributed by Ashish Kumar Singh. Please write comments if you find the above codes/algorithms incorrect, or find other ways to solve the same problem. " }, { "code": null, "e": 13690, "s": 13685, "text": "vt_m" }, { "code": null, "e": 13711, "s": 13690, "text": "Smitha Dinesh Semwal" }, { "code": null, "e": 13725, "s": 13711, "text": "princiraj1992" }, { "code": null, "e": 13740, "s": 13725, "text": "mohit kumar 29" }, { "code": null, "e": 13753, "s": 13740, "text": "princi singh" }, { "code": null, "e": 13767, "s": 13753, "text": "jana_sayantan" }, { "code": null, "e": 13785, "s": 13767, "text": "divyeshrabadiya07" }, { "code": null, "e": 13800, "s": 13785, "text": "adityakumar129" }, { "code": null, "e": 13816, "s": 13800, "text": "rishuabhishek06" }, { "code": null, "e": 13823, "s": 13816, "text": "Amazon" }, { "code": null, "e": 13830, "s": 13823, "text": "Arrays" }, { "code": null, "e": 13840, "s": 13830, "text": "Searching" }, { "code": null, "e": 13846, "s": 13840, "text": "Stack" }, { "code": null, "e": 13853, "s": 13846, "text": "Amazon" }, { "code": null, "e": 13860, "s": 13853, "text": "Arrays" }, { "code": null, "e": 13870, "s": 13860, "text": "Searching" }, { "code": null, "e": 13876, "s": 13870, "text": "Stack" } ]
Scatter plot in Plotly using graph_objects class
30 Aug, 2021 Plotly is a Python library which is used to design graphs, especially interactive graphs. It can plot various graphs and charts like histogram, barplot, boxplot, spreadplot and many more. It is mainly used in data analysis as well as financial analysis. plotly is an interactive visualization library. Scatter plot are those charts in which data points are represented horizontally and on vertical axis to show that how one variable affect on another variable. The scatter() method of graph_objects class produces a scatter trace. The mode of the property decides the appearance of data points. Syntax: plotly.graph_objects.Scatter(arg=None, cliponaxis=None, connectgaps=None, customdata=None, customdatasrc=None, dx=None, dy=None, error_x=None, error_y=None, fill=None, fillcolor=None, groupnorm=None, hoverinfo=None, hoverinfosrc=None, hoverlabel=None, hoveron=None, hovertemplate=None, hovertemplatesrc=None, hovertext=None, hovertextsrc=None, ids=None, idssrc=None, legendgroup=None, line=None, marker=None, meta=None, metasrc=None, mode=None, name=None, opacity=None, orientation=None, r=None, rsrc=None, selected=None, selectedpoints=None, showlegend=None, stackgaps=None, stackgroup=None, stream=None, t=None, text=None, textfont=None, textposition=None, textpositionsrc=None, textsrc=None, texttemplate=None, texttemplatesrc=None, tsrc=None, uid=None, uirevision=None, unselected=None, visible=None, x=None, x0=None, xaxis=None, xcalendar=None, xsrc=None, y=None, y0=None, yaxis=None, ycalendar=None, ysrc=None, **kwargs) Parameters: Example: Python3 import plotly.graph_objects as pximport numpy as np # creating random data through randomint# function of numpy.randomnp.random.seed(42) random_x= np.random.randint(1,101,100)random_y= np.random.randint(1,101,100) plot = px.Figure(data=[px.Scatter( x = random_x, y = random_y, mode = 'markers',)]) plot.show() Output: Color scale can be shown using the showscale parameter. This parameter takes a boolean value. If the value is true then the scale is shown otherwise not. Example: Python3 import plotly.graph_objects as goimport numpy as np n = 10000plot = go.Figure(data=[go.Scatter( x = np.random.randn(n), mode = 'markers', marker=dict( color=np.random.randn(n), colorscale='Viridis', showscale=True ))]) plot.show() Output: In scatter plot can be styled using keywords arguments, let’s see the examples given below: Example 1: Changing the color of the graph Python3 import plotly.graph_objects as pximport numpy as np # creating random data through randomint# function of numpy.randomnp.random.seed(42) random_x= np.random.randint(1,101,100)random_y= np.random.randint(1,101,100) plot = px.Figure(data=[px.Scatter( x = random_x, y = random_y, mode = 'markers', marker_color='rgba(199, 10, 165, .9)')]) plot.show() Output: Example 2: Using tips dataset Python3 import plotly.graph_objects as pximport plotly.express as goimport numpy as np df = go.data.tips() x = df['total_bill']y = df['day'] plot = px.Figure(data=[px.Scatter( x = x, y = y, mode = 'markers', marker_color='rgba(199, 10, 165, .9)')]) plot.update_traces(mode='markers', marker_size=10) plot.show() Output: The bubble scatter plot can be created using the marker size. Marker size and color are used to control the overall size of the marker. Marker size helps to maintain the color inside the bubble in the graph. Example: Python3 import plotly.graph_objects as pximport numpy as np # creating random data through randomint# function of numpy.randomnp.random.seed(42) random_x= np.random.randint(1,101,100)random_y= np.random.randint(1,101,100) plot = px.Figure(data=[px.Scatter( x = random_x, y = random_y, mode = 'markers', marker_size = [115, 20, 30])]) plot.show() Output: adnanirshad158 Python-Plotly 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 Convert integer to string in Python
[ { "code": null, "e": 28, "s": 0, "text": "\n30 Aug, 2021" }, { "code": null, "e": 330, "s": 28, "text": "Plotly is a Python library which is used to design graphs, especially interactive graphs. It can plot various graphs and charts like histogram, barplot, boxplot, spreadplot and many more. It is mainly used in data analysis as well as financial analysis. plotly is an interactive visualization library." }, { "code": null, "e": 623, "s": 330, "text": "Scatter plot are those charts in which data points are represented horizontally and on vertical axis to show that how one variable affect on another variable. The scatter() method of graph_objects class produces a scatter trace. The mode of the property decides the appearance of data points." }, { "code": null, "e": 1558, "s": 623, "text": "Syntax: plotly.graph_objects.Scatter(arg=None, cliponaxis=None, connectgaps=None, customdata=None, customdatasrc=None, dx=None, dy=None, error_x=None, error_y=None, fill=None, fillcolor=None, groupnorm=None, hoverinfo=None, hoverinfosrc=None, hoverlabel=None, hoveron=None, hovertemplate=None, hovertemplatesrc=None, hovertext=None, hovertextsrc=None, ids=None, idssrc=None, legendgroup=None, line=None, marker=None, meta=None, metasrc=None, mode=None, name=None, opacity=None, orientation=None, r=None, rsrc=None, selected=None, selectedpoints=None, showlegend=None, stackgaps=None, stackgroup=None, stream=None, t=None, text=None, textfont=None, textposition=None, textpositionsrc=None, textsrc=None, texttemplate=None, texttemplatesrc=None, tsrc=None, uid=None, uirevision=None, unselected=None, visible=None, x=None, x0=None, xaxis=None, xcalendar=None, xsrc=None, y=None, y0=None, yaxis=None, ycalendar=None, ysrc=None, **kwargs)" }, { "code": null, "e": 1570, "s": 1558, "text": "Parameters:" }, { "code": null, "e": 1579, "s": 1570, "text": "Example:" }, { "code": null, "e": 1587, "s": 1579, "text": "Python3" }, { "code": "import plotly.graph_objects as pximport numpy as np # creating random data through randomint# function of numpy.randomnp.random.seed(42) random_x= np.random.randint(1,101,100)random_y= np.random.randint(1,101,100) plot = px.Figure(data=[px.Scatter( x = random_x, y = random_y, mode = 'markers',)]) plot.show()", "e": 1924, "s": 1587, "text": null }, { "code": null, "e": 1936, "s": 1928, "text": "Output:" }, { "code": null, "e": 2094, "s": 1940, "text": "Color scale can be shown using the showscale parameter. This parameter takes a boolean value. If the value is true then the scale is shown otherwise not." }, { "code": null, "e": 2105, "s": 2096, "text": "Example:" }, { "code": null, "e": 2115, "s": 2107, "text": "Python3" }, { "code": "import plotly.graph_objects as goimport numpy as np n = 10000plot = go.Figure(data=[go.Scatter( x = np.random.randn(n), mode = 'markers', marker=dict( color=np.random.randn(n), colorscale='Viridis', showscale=True ))]) plot.show()", "e": 2397, "s": 2115, "text": null }, { "code": null, "e": 2409, "s": 2401, "text": "Output:" }, { "code": null, "e": 2505, "s": 2413, "text": "In scatter plot can be styled using keywords arguments, let’s see the examples given below:" }, { "code": null, "e": 2550, "s": 2507, "text": "Example 1: Changing the color of the graph" }, { "code": null, "e": 2560, "s": 2552, "text": "Python3" }, { "code": "import plotly.graph_objects as pximport numpy as np # creating random data through randomint# function of numpy.randomnp.random.seed(42) random_x= np.random.randint(1,101,100)random_y= np.random.randint(1,101,100) plot = px.Figure(data=[px.Scatter( x = random_x, y = random_y, mode = 'markers', marker_color='rgba(199, 10, 165, .9)')]) plot.show()", "e": 2938, "s": 2560, "text": null }, { "code": null, "e": 2950, "s": 2942, "text": "Output:" }, { "code": null, "e": 2984, "s": 2954, "text": "Example 2: Using tips dataset" }, { "code": null, "e": 2994, "s": 2986, "text": "Python3" }, { "code": "import plotly.graph_objects as pximport plotly.express as goimport numpy as np df = go.data.tips() x = df['total_bill']y = df['day'] plot = px.Figure(data=[px.Scatter( x = x, y = y, mode = 'markers', marker_color='rgba(199, 10, 165, .9)')]) plot.update_traces(mode='markers', marker_size=10) plot.show()", "e": 3327, "s": 2994, "text": null }, { "code": null, "e": 3339, "s": 3331, "text": "Output:" }, { "code": null, "e": 3551, "s": 3343, "text": "The bubble scatter plot can be created using the marker size. Marker size and color are used to control the overall size of the marker. Marker size helps to maintain the color inside the bubble in the graph." }, { "code": null, "e": 3562, "s": 3553, "text": "Example:" }, { "code": null, "e": 3572, "s": 3564, "text": "Python3" }, { "code": "import plotly.graph_objects as pximport numpy as np # creating random data through randomint# function of numpy.randomnp.random.seed(42) random_x= np.random.randint(1,101,100)random_y= np.random.randint(1,101,100) plot = px.Figure(data=[px.Scatter( x = random_x, y = random_y, mode = 'markers', marker_size = [115, 20, 30])]) plot.show()", "e": 3944, "s": 3572, "text": null }, { "code": null, "e": 3956, "s": 3948, "text": "Output:" }, { "code": null, "e": 3975, "s": 3960, "text": "adnanirshad158" }, { "code": null, "e": 3989, "s": 3975, "text": "Python-Plotly" }, { "code": null, "e": 3996, "s": 3989, "text": "Python" }, { "code": null, "e": 4094, "s": 3996, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4112, "s": 4094, "text": "Python Dictionary" }, { "code": null, "e": 4154, "s": 4112, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 4176, "s": 4154, "text": "Enumerate() in Python" }, { "code": null, "e": 4211, "s": 4176, "text": "Read a file line by line in Python" }, { "code": null, "e": 4237, "s": 4211, "text": "Python String | replace()" }, { "code": null, "e": 4269, "s": 4237, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 4298, "s": 4269, "text": "*args and **kwargs in Python" }, { "code": null, "e": 4325, "s": 4298, "text": "Python Classes and Objects" }, { "code": null, "e": 4355, "s": 4325, "text": "Iterate over a list in Python" } ]
Memory Management in Operating System
22 Nov, 2021 The term Memory can be defined as a collection of data in a specific format. It is used to store instructions and processed data. The memory comprises a large array or group of words or bytes, each with its own location. The primary motive of a computer system is to execute programs. These programs, along with the information they access, should be in the main memory during execution. The CPU fetches instructions from memory according to the value of the program counter. To achieve a degree of multiprogramming and proper utilization of memory, memory management is important. Many memory management methods exist, reflecting various approaches, and the effectiveness of each algorithm depends on the situation. Here, we will cover the following memory management topics: What is Main Memory What is Memory Management Why memory Management is required Logical address space and Physical address space Static and dynamic loading Static and dynamic linking Swapping Contiguous Memory allocationMemory AllocationFirst FitBest FitWorst FitFragmentationInternal FragmentationExternal FragmentationPaging Memory AllocationFirst FitBest FitWorst Fit First Fit Best Fit Worst Fit FragmentationInternal FragmentationExternal Fragmentation Internal Fragmentation External Fragmentation Paging Now before, We start memory management let us known about what is main memory. The main memory is central to the operation of a modern computer. Main Memory is a large array of words or bytes, ranging in size from hundreds of thousands to billions. Main memory is a repository of rapidly available information shared by the CPU and I/O devices. Main memory is the place where programs and information are kept when the processor is effectively utilizing them. Main memory is associated with the processor, so moving instructions and information into and out of the processor is extremely fast. Main memory is also known as RAM(Random Access Memory). This memory is a volatile memory.RAM lost its data when a power interruption occurs. Figure 1: Memory hierarchy In a multiprogramming computer, the operating system resides in a part of memory and the rest is used by multiple processes. The task of subdividing the memory among different processes is called memory management. Memory management is a method in the operating system to manage operations between main memory and disk during process execution. The main aim of memory management is to achieve efficient utilization of memory. Allocate and de-allocate memory before and after process execution. To keep track of used memory space by processes. To minimize fragmentation issues. To proper utilization of main memory. To maintain data integrity while executing of process. Now we are discussing the concept of logical address space and Physical address space: Logical Address space: An address generated by the CPU is known as “Logical Address”. It is also known as a Virtual address. Logical address space can be defined as the size of the process. A logical address can be changed. Physical Address space: An address seen by the memory unit (i.e the one loaded into the memory address register of the memory) is commonly known as a “Physical Address”. A Physical address is also known as a Real address. The set of all physical addresses corresponding to these logical addresses is known as Physical address space. A physical address is computed by MMU. The run-time mapping from virtual to physical addresses is done by a hardware device Memory Management Unit(MMU). The physical address always remains constant. To load a process into the main memory is done by a loader. There are two different types of loading : Static loading:- loading the entire program into a fixed address. It requires more memory space. Dynamic loading:- The entire program and all data of a process must be in physical memory for the process to execute. So, the size of a process is limited to the size of physical memory. To gain proper memory utilization, dynamic loading is used. In dynamic loading, a routine is not loaded until it is called. All routines are residing on disk in a relocatable load format. One of the advantages of dynamic loading is that unused routine is never loaded. This loading is useful when a large amount of code is needed to handle it efficiently. To perform a linking task a linker is used. A linker is a program that takes one or more object files generated by a compiler and combines them into a single executable file. Static linking: In static linking, the linker combines all necessary program modules into a single executable program. So there is no runtime dependency. Some operating systems support only static linking, in which system language libraries are treated like any other object module. Dynamic linking: The basic concept of dynamic linking is similar to dynamic loading. In dynamic linking, “Stub” is included for each appropriate library routine reference. A stub is a small piece of code. When the stub is executed, it checks whether the needed routine is already in memory or not. If not available then the program loads the routine into memory. When a process is executed it must have resided in memory. Swapping is a process of swap a process temporarily into a secondary memory from the main memory, which is fast as compared to secondary memory. A swapping allows more processes to be run and can be fit into memory at one time. The main part of swapping is transferred time and the total time directly proportional to the amount of memory swapped. Swapping is also known as roll-out, roll in, because if a higher priority process arrives and wants service, the memory manager can swap out the lower priority process and then load and execute the higher priority process. After finishing higher priority work, the lower priority process swapped back in memory and continued to the execution process. The main memory should oblige both the operating system and the different client processes. Therefore, the allocation of memory becomes an important task in the operating system. The memory is usually divided into two partitions: one for the resident operating system and one for the user processes. We normally need several user processes to reside in memory simultaneously. Therefore, we need to consider how to allocate available memory to the processes that are in the input queue waiting to be brought into memory. In adjacent memory allotment, each process is contained in a single contiguous segment of memory. To gain proper memory utilization, memory allocation must be allocated efficient manner. One of the simplest methods for allocating memory is to divide memory into several fixed-sized partitions and each partition contains exactly one process. Thus, the degree of multiprogramming is obtained by the number of partitions. Multiple partition allocation: In this method, a process is selected from the input queue and loaded into the free partition. When the process terminates, the partition becomes available for other processes. Fixed partition allocation: In this method, the operating system maintains a table that indicates which parts of memory are available and which are occupied by processes. Initially, all memory is available for user processes and is considered one large block of available memory. This available memory is known as “Hole”. When the process arrives and needs memory, we search for a hole that is large enough to store this process. If the requirement fulfills then we allocate memory to process, otherwise keeping the rest available to satisfy future requests. While allocating a memory sometimes dynamic storage allocation problems occur, which concerns how to satisfy a request of size n from a list of free holes. There are some solutions to this problem: First fit:- In the first fit, the first available free hole fulfills the requirement of the process allocated. Here, in this diagram 40 KB memory block is the first available free hole that can store process A (size of 25 KB), because the first two blocks did not have sufficient memory space. Best fit:- In the best fit, allocate the smallest hole that is big enough to process requirements. For this, we search the entire list, unless the list is ordered by size. Here in this example, first, we traverse the complete list and find the last hole 25KB is the best suitable hole for Process A(size 25KB). In this method memory utilization is maximum as compared to other memory allocation techniques. Worst fit:-In the worst fit, allocate the largest available hole to process. This method produces the largest leftover hole. Here in this example, Process A (Size 25 KB) is allocated to the largest available memory block which is 60KB. Inefficient memory utilization is a major issue in the worst fit. A Fragmentation is defined as when the process is loaded and removed after execution from memory, it creates a small free hole. These holes can not be assigned to new processes because holes are not combined or do not fulfill the memory requirement of the process. To achieve a degree of multiprogramming, we must reduce the waste of memory or fragmentation problem. In operating system two types of fragmentation: Internal fragmentation: Internal fragmentation occurs when memory blocks are allocated to the process more than their requested size. Due to this some unused space is leftover and creates an internal fragmentation problem. Example: Suppose there is a fixed partitioning is used for memory allocation and the different size of block 3MB, 6MB, and 7MB space in memory. Now a new process p4 of size 2MB comes and demand for the block of memory. It gets a memory block of 3MB but 1MB block memory is a waste, and it can not be allocated to other processes too. This is called internal fragmentation. External fragmentation: In external fragmentation, we have a free memory block, but we can not assign it to process because blocks are not contiguous. Example: Suppose (consider above example) three process p1, p2, p3 comes with size 2MB, 4MB, and 7MB respectively. Now they get memory blocks of size 3MB, 6MB, and 7MB allocated respectively. After allocating process p1 process and p2 process left 1MB and 2MB. Suppose a new process p4 comes and demands a 3MB block of memory, which is available, but we can not assign it because free memory space is not contiguous. This is called external fragmentation. Both the first fit and best-fit systems for memory allocation affected by external fragmentation. To overcome the external fragmentation problem Compaction is used. In the compaction technique, all free memory space combines and makes one large block. So, this space can be used by other processes effectively. Another possible solution to the external fragmentation is to allow the logical address space of the processes to be noncontiguous, thus permit a process to be allocated physical memory where ever the latter is available. Paging is a memory management scheme that eliminates the need for contiguous allocation of physical memory. This scheme permits the physical address space of a process to be non-contiguous. Logical Address or Virtual Address (represented in bits): An address generated by the CPU Logical Address Space or Virtual Address Space (represented in words or bytes): The set of all logical addresses generated by a program Physical Address (represented in bits): An address actually available on a memory unit Physical Address Space (represented in words or bytes): The set of all physical addresses corresponding to the logical addresses Example: If Logical Address = 31 bits, then Logical Address Space = 231 words = 2 G words (1 G = 230) If Logical Address Space = 128 M words = 27 * 220 words, then Logical Address = log2 227 = 27 bits If Physical Address = 22 bits, then Physical Address Space = 222 words = 4 M words (1 M = 220) If Physical Address Space = 16 M words = 24 * 220 words, then Physical Address = log2 224 = 24 bits The mapping from virtual to physical address is done by the memory management unit (MMU) which is a hardware device and this mapping is known as the paging technique. The Physical Address Space is conceptually divided into several fixed-size blocks, called frames. The Logical Address Space is also split into fixed-size blocks, called pages. Page Size = Frame Size Let us consider an example: Physical Address = 12 bits, then Physical Address Space = 4 K words Logical Address = 13 bits, then Logical Address Space = 8 K words Page size = frame size = 1 K words (assumption) The address generated by the CPU is divided into Page number(p): Number of bits required to represent the pages in Logical Address Space or Page number Page offset(d): Number of bits required to represent a particular word in a page or page size of Logical Address Space or word number of a page or page offset. Physical Address is divided into Frame number(f): Number of bits required to represent the frame of Physical Address Space or Frame number frame Frame offset(d): Number of bits required to represent a particular word in a frame or frame size of Physical Address Space or word number of a frame or frame offset. The hardware implementation of the page table can be done by using dedicated registers. But the usage of register for the page table is satisfactory only if the page table is small. If the page table contains a large number of entries then we can use TLB(translation Look-aside buffer), a special, small, fast look-up hardware cache. The TLB is an associative, high-speed memory. Each entry in TLB consists of two parts: a tag and a value. When this memory is used, then an item is compared with all tags simultaneously. If the item is found, then the corresponding value is returned. Main memory access time = m If page table are kept in main memory, Effective access time = m(for page table) + m(for particular page in page table) For more details, must-read Paging in Operating System raghulgs33 Operating Systems-Memory Management Operating Systems Operating Systems Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Disk Scheduling Algorithms Introduction of Operating System - Set 1 Introduction of Deadlock in Operating System Inter Process Communication (IPC) File Allocation Methods CPU Scheduling in Operating Systems Semaphores in Process Synchronization Difference between Process and Thread Deadlock Prevention And Avoidance Introduction of Process Synchronization
[ { "code": null, "e": 54, "s": 26, "text": "\n22 Nov, 2021" }, { "code": null, "e": 531, "s": 54, "text": "The term Memory can be defined as a collection of data in a specific format. It is used to store instructions and processed data. The memory comprises a large array or group of words or bytes, each with its own location. The primary motive of a computer system is to execute programs. These programs, along with the information they access, should be in the main memory during execution. The CPU fetches instructions from memory according to the value of the program counter. " }, { "code": null, "e": 773, "s": 531, "text": "To achieve a degree of multiprogramming and proper utilization of memory, memory management is important. Many memory management methods exist, reflecting various approaches, and the effectiveness of each algorithm depends on the situation. " }, { "code": null, "e": 875, "s": 773, "text": "Here, we will cover the following memory management topics: " }, { "code": null, "e": 895, "s": 875, "text": "What is Main Memory" }, { "code": null, "e": 921, "s": 895, "text": "What is Memory Management" }, { "code": null, "e": 955, "s": 921, "text": "Why memory Management is required" }, { "code": null, "e": 1004, "s": 955, "text": "Logical address space and Physical address space" }, { "code": null, "e": 1031, "s": 1004, "text": "Static and dynamic loading" }, { "code": null, "e": 1058, "s": 1031, "text": "Static and dynamic linking" }, { "code": null, "e": 1067, "s": 1058, "text": "Swapping" }, { "code": null, "e": 1202, "s": 1067, "text": "Contiguous Memory allocationMemory AllocationFirst FitBest FitWorst FitFragmentationInternal FragmentationExternal FragmentationPaging" }, { "code": null, "e": 1246, "s": 1202, "text": "Memory AllocationFirst FitBest FitWorst Fit" }, { "code": null, "e": 1256, "s": 1246, "text": "First Fit" }, { "code": null, "e": 1265, "s": 1256, "text": "Best Fit" }, { "code": null, "e": 1275, "s": 1265, "text": "Worst Fit" }, { "code": null, "e": 1333, "s": 1275, "text": "FragmentationInternal FragmentationExternal Fragmentation" }, { "code": null, "e": 1356, "s": 1333, "text": "Internal Fragmentation" }, { "code": null, "e": 1379, "s": 1356, "text": "External Fragmentation" }, { "code": null, "e": 1386, "s": 1379, "text": "Paging" }, { "code": null, "e": 1465, "s": 1386, "text": "Now before, We start memory management let us known about what is main memory." }, { "code": null, "e": 2123, "s": 1465, "text": "The main memory is central to the operation of a modern computer. Main Memory is a large array of words or bytes, ranging in size from hundreds of thousands to billions. Main memory is a repository of rapidly available information shared by the CPU and I/O devices. Main memory is the place where programs and information are kept when the processor is effectively utilizing them. Main memory is associated with the processor, so moving instructions and information into and out of the processor is extremely fast. Main memory is also known as RAM(Random Access Memory). This memory is a volatile memory.RAM lost its data when a power interruption occurs." }, { "code": null, "e": 2150, "s": 2123, "text": "Figure 1: Memory hierarchy" }, { "code": null, "e": 2578, "s": 2150, "text": "In a multiprogramming computer, the operating system resides in a part of memory and the rest is used by multiple processes. The task of subdividing the memory among different processes is called memory management. Memory management is a method in the operating system to manage operations between main memory and disk during process execution. The main aim of memory management is to achieve efficient utilization of memory. " }, { "code": null, "e": 2646, "s": 2578, "text": "Allocate and de-allocate memory before and after process execution." }, { "code": null, "e": 2695, "s": 2646, "text": "To keep track of used memory space by processes." }, { "code": null, "e": 2729, "s": 2695, "text": "To minimize fragmentation issues." }, { "code": null, "e": 2767, "s": 2729, "text": "To proper utilization of main memory." }, { "code": null, "e": 2822, "s": 2767, "text": "To maintain data integrity while executing of process." }, { "code": null, "e": 2910, "s": 2822, "text": "Now we are discussing the concept of logical address space and Physical address space: " }, { "code": null, "e": 3134, "s": 2910, "text": "Logical Address space: An address generated by the CPU is known as “Logical Address”. It is also known as a Virtual address. Logical address space can be defined as the size of the process. A logical address can be changed." }, { "code": null, "e": 3666, "s": 3134, "text": "Physical Address space: An address seen by the memory unit (i.e the one loaded into the memory address register of the memory) is commonly known as a “Physical Address”. A Physical address is also known as a Real address. The set of all physical addresses corresponding to these logical addresses is known as Physical address space. A physical address is computed by MMU. The run-time mapping from virtual to physical addresses is done by a hardware device Memory Management Unit(MMU). The physical address always remains constant." }, { "code": null, "e": 3769, "s": 3666, "text": "To load a process into the main memory is done by a loader. There are two different types of loading :" }, { "code": null, "e": 3866, "s": 3769, "text": "Static loading:- loading the entire program into a fixed address. It requires more memory space." }, { "code": null, "e": 4409, "s": 3866, "text": "Dynamic loading:- The entire program and all data of a process must be in physical memory for the process to execute. So, the size of a process is limited to the size of physical memory. To gain proper memory utilization, dynamic loading is used. In dynamic loading, a routine is not loaded until it is called. All routines are residing on disk in a relocatable load format. One of the advantages of dynamic loading is that unused routine is never loaded. This loading is useful when a large amount of code is needed to handle it efficiently." }, { "code": null, "e": 4584, "s": 4409, "text": "To perform a linking task a linker is used. A linker is a program that takes one or more object files generated by a compiler and combines them into a single executable file." }, { "code": null, "e": 4867, "s": 4584, "text": "Static linking: In static linking, the linker combines all necessary program modules into a single executable program. So there is no runtime dependency. Some operating systems support only static linking, in which system language libraries are treated like any other object module." }, { "code": null, "e": 5230, "s": 4867, "text": "Dynamic linking: The basic concept of dynamic linking is similar to dynamic loading. In dynamic linking, “Stub” is included for each appropriate library routine reference. A stub is a small piece of code. When the stub is executed, it checks whether the needed routine is already in memory or not. If not available then the program loads the routine into memory." }, { "code": null, "e": 5992, "s": 5232, "text": "When a process is executed it must have resided in memory. Swapping is a process of swap a process temporarily into a secondary memory from the main memory, which is fast as compared to secondary memory. A swapping allows more processes to be run and can be fit into memory at one time. The main part of swapping is transferred time and the total time directly proportional to the amount of memory swapped. Swapping is also known as roll-out, roll in, because if a higher priority process arrives and wants service, the memory manager can swap out the lower priority process and then load and execute the higher priority process. After finishing higher priority work, the lower priority process swapped back in memory and continued to the execution process. " }, { "code": null, "e": 6614, "s": 5992, "text": "The main memory should oblige both the operating system and the different client processes. Therefore, the allocation of memory becomes an important task in the operating system. The memory is usually divided into two partitions: one for the resident operating system and one for the user processes. We normally need several user processes to reside in memory simultaneously. Therefore, we need to consider how to allocate available memory to the processes that are in the input queue waiting to be brought into memory. In adjacent memory allotment, each process is contained in a single contiguous segment of memory. " }, { "code": null, "e": 6937, "s": 6614, "text": "To gain proper memory utilization, memory allocation must be allocated efficient manner. One of the simplest methods for allocating memory is to divide memory into several fixed-sized partitions and each partition contains exactly one process. Thus, the degree of multiprogramming is obtained by the number of partitions. " }, { "code": null, "e": 7146, "s": 6937, "text": "Multiple partition allocation: In this method, a process is selected from the input queue and loaded into the free partition. When the process terminates, the partition becomes available for other processes. " }, { "code": null, "e": 7903, "s": 7146, "text": "Fixed partition allocation: In this method, the operating system maintains a table that indicates which parts of memory are available and which are occupied by processes. Initially, all memory is available for user processes and is considered one large block of available memory. This available memory is known as “Hole”. When the process arrives and needs memory, we search for a hole that is large enough to store this process. If the requirement fulfills then we allocate memory to process, otherwise keeping the rest available to satisfy future requests. While allocating a memory sometimes dynamic storage allocation problems occur, which concerns how to satisfy a request of size n from a list of free holes. There are some solutions to this problem:" }, { "code": null, "e": 7916, "s": 7903, "text": "First fit:- " }, { "code": null, "e": 8016, "s": 7916, "text": "In the first fit, the first available free hole fulfills the requirement of the process allocated. " }, { "code": null, "e": 8199, "s": 8016, "text": "Here, in this diagram 40 KB memory block is the first available free hole that can store process A (size of 25 KB), because the first two blocks did not have sufficient memory space." }, { "code": null, "e": 8211, "s": 8199, "text": " Best fit:-" }, { "code": null, "e": 8373, "s": 8211, "text": "In the best fit, allocate the smallest hole that is big enough to process requirements. For this, we search the entire list, unless the list is ordered by size. " }, { "code": null, "e": 8512, "s": 8373, "text": "Here in this example, first, we traverse the complete list and find the last hole 25KB is the best suitable hole for Process A(size 25KB)." }, { "code": null, "e": 8608, "s": 8512, "text": "In this method memory utilization is maximum as compared to other memory allocation techniques." }, { "code": null, "e": 8734, "s": 8608, "text": "Worst fit:-In the worst fit, allocate the largest available hole to process. This method produces the largest leftover hole. " }, { "code": null, "e": 8911, "s": 8734, "text": "Here in this example, Process A (Size 25 KB) is allocated to the largest available memory block which is 60KB. Inefficient memory utilization is a major issue in the worst fit." }, { "code": null, "e": 9327, "s": 8911, "text": "A Fragmentation is defined as when the process is loaded and removed after execution from memory, it creates a small free hole. These holes can not be assigned to new processes because holes are not combined or do not fulfill the memory requirement of the process. To achieve a degree of multiprogramming, we must reduce the waste of memory or fragmentation problem. In operating system two types of fragmentation:" }, { "code": null, "e": 9352, "s": 9327, "text": "Internal fragmentation: " }, { "code": null, "e": 9551, "s": 9352, "text": "Internal fragmentation occurs when memory blocks are allocated to the process more than their requested size. Due to this some unused space is leftover and creates an internal fragmentation problem." }, { "code": null, "e": 9925, "s": 9551, "text": " Example: Suppose there is a fixed partitioning is used for memory allocation and the different size of block 3MB, 6MB, and 7MB space in memory. Now a new process p4 of size 2MB comes and demand for the block of memory. It gets a memory block of 3MB but 1MB block memory is a waste, and it can not be allocated to other processes too. This is called internal fragmentation." }, { "code": null, "e": 9949, "s": 9925, "text": "External fragmentation:" }, { "code": null, "e": 10076, "s": 9949, "text": "In external fragmentation, we have a free memory block, but we can not assign it to process because blocks are not contiguous." }, { "code": null, "e": 10533, "s": 10076, "text": "Example: Suppose (consider above example) three process p1, p2, p3 comes with size 2MB, 4MB, and 7MB respectively. Now they get memory blocks of size 3MB, 6MB, and 7MB allocated respectively. After allocating process p1 process and p2 process left 1MB and 2MB. Suppose a new process p4 comes and demands a 3MB block of memory, which is available, but we can not assign it because free memory space is not contiguous. This is called external fragmentation." }, { "code": null, "e": 10844, "s": 10533, "text": "Both the first fit and best-fit systems for memory allocation affected by external fragmentation. To overcome the external fragmentation problem Compaction is used. In the compaction technique, all free memory space combines and makes one large block. So, this space can be used by other processes effectively." }, { "code": null, "e": 11066, "s": 10844, "text": "Another possible solution to the external fragmentation is to allow the logical address space of the processes to be noncontiguous, thus permit a process to be allocated physical memory where ever the latter is available." }, { "code": null, "e": 11256, "s": 11066, "text": "Paging is a memory management scheme that eliminates the need for contiguous allocation of physical memory. This scheme permits the physical address space of a process to be non-contiguous." }, { "code": null, "e": 11346, "s": 11256, "text": "Logical Address or Virtual Address (represented in bits): An address generated by the CPU" }, { "code": null, "e": 11482, "s": 11346, "text": "Logical Address Space or Virtual Address Space (represented in words or bytes): The set of all logical addresses generated by a program" }, { "code": null, "e": 11569, "s": 11482, "text": "Physical Address (represented in bits): An address actually available on a memory unit" }, { "code": null, "e": 11698, "s": 11569, "text": "Physical Address Space (represented in words or bytes): The set of all physical addresses corresponding to the logical addresses" }, { "code": null, "e": 11707, "s": 11698, "text": "Example:" }, { "code": null, "e": 11800, "s": 11707, "text": "If Logical Address = 31 bits, then Logical Address Space = 231 words = 2 G words (1 G = 230)" }, { "code": null, "e": 11899, "s": 11800, "text": "If Logical Address Space = 128 M words = 27 * 220 words, then Logical Address = log2 227 = 27 bits" }, { "code": null, "e": 11994, "s": 11899, "text": "If Physical Address = 22 bits, then Physical Address Space = 222 words = 4 M words (1 M = 220)" }, { "code": null, "e": 12094, "s": 11994, "text": "If Physical Address Space = 16 M words = 24 * 220 words, then Physical Address = log2 224 = 24 bits" }, { "code": null, "e": 12261, "s": 12094, "text": "The mapping from virtual to physical address is done by the memory management unit (MMU) which is a hardware device and this mapping is known as the paging technique." }, { "code": null, "e": 12359, "s": 12261, "text": "The Physical Address Space is conceptually divided into several fixed-size blocks, called frames." }, { "code": null, "e": 12437, "s": 12359, "text": "The Logical Address Space is also split into fixed-size blocks, called pages." }, { "code": null, "e": 12460, "s": 12437, "text": "Page Size = Frame Size" }, { "code": null, "e": 12488, "s": 12460, "text": "Let us consider an example:" }, { "code": null, "e": 12556, "s": 12488, "text": "Physical Address = 12 bits, then Physical Address Space = 4 K words" }, { "code": null, "e": 12622, "s": 12556, "text": "Logical Address = 13 bits, then Logical Address Space = 8 K words" }, { "code": null, "e": 12670, "s": 12622, "text": "Page size = frame size = 1 K words (assumption)" }, { "code": null, "e": 12719, "s": 12670, "text": "The address generated by the CPU is divided into" }, { "code": null, "e": 12822, "s": 12719, "text": "Page number(p): Number of bits required to represent the pages in Logical Address Space or Page number" }, { "code": null, "e": 12982, "s": 12822, "text": "Page offset(d): Number of bits required to represent a particular word in a page or page size of Logical Address Space or word number of a page or page offset." }, { "code": null, "e": 13015, "s": 12982, "text": "Physical Address is divided into" }, { "code": null, "e": 13127, "s": 13015, "text": "Frame number(f): Number of bits required to represent the frame of Physical Address Space or Frame number frame" }, { "code": null, "e": 13293, "s": 13127, "text": "Frame offset(d): Number of bits required to represent a particular word in a frame or frame size of Physical Address Space or word number of a frame or frame offset." }, { "code": null, "e": 13627, "s": 13293, "text": "The hardware implementation of the page table can be done by using dedicated registers. But the usage of register for the page table is satisfactory only if the page table is small. If the page table contains a large number of entries then we can use TLB(translation Look-aside buffer), a special, small, fast look-up hardware cache." }, { "code": null, "e": 13673, "s": 13627, "text": "The TLB is an associative, high-speed memory." }, { "code": null, "e": 13733, "s": 13673, "text": "Each entry in TLB consists of two parts: a tag and a value." }, { "code": null, "e": 13878, "s": 13733, "text": "When this memory is used, then an item is compared with all tags simultaneously. If the item is found, then the corresponding value is returned." }, { "code": null, "e": 14028, "s": 13880, "text": "Main memory access time = m\nIf page table are kept in main memory,\nEffective access time = m(for page table) + m(for particular page in page table)" }, { "code": null, "e": 14083, "s": 14028, "text": "For more details, must-read Paging in Operating System" }, { "code": null, "e": 14094, "s": 14083, "text": "raghulgs33" }, { "code": null, "e": 14130, "s": 14094, "text": "Operating Systems-Memory Management" }, { "code": null, "e": 14148, "s": 14130, "text": "Operating Systems" }, { "code": null, "e": 14166, "s": 14148, "text": "Operating Systems" }, { "code": null, "e": 14264, "s": 14166, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 14291, "s": 14264, "text": "Disk Scheduling Algorithms" }, { "code": null, "e": 14332, "s": 14291, "text": "Introduction of Operating System - Set 1" }, { "code": null, "e": 14377, "s": 14332, "text": "Introduction of Deadlock in Operating System" }, { "code": null, "e": 14411, "s": 14377, "text": "Inter Process Communication (IPC)" }, { "code": null, "e": 14435, "s": 14411, "text": "File Allocation Methods" }, { "code": null, "e": 14471, "s": 14435, "text": "CPU Scheduling in Operating Systems" }, { "code": null, "e": 14509, "s": 14471, "text": "Semaphores in Process Synchronization" }, { "code": null, "e": 14547, "s": 14509, "text": "Difference between Process and Thread" }, { "code": null, "e": 14581, "s": 14547, "text": "Deadlock Prevention And Avoidance" } ]
Why does empty Structure has size 1 byte in C++ but 0 byte in C
04 Aug, 2021 A structure is a user-defined data type in C/C++. A structure creates a data type that can be used to group items of possibly different types into a single type. The ‘struct’ keyword is used to create a structure. The general syntax for creating a structure is as shown below: Syntax- struct structureName{ member1; member2; member3; . . . memberN; }; Structures in C++ can contain two types of members: Data Member– These members are normal C++ variables. A structure can be created with variables of different data types in C++.Member Functions– These members are normal C++ functions. Along with variables, the functions can also be included inside a structure declaration. Data Member– These members are normal C++ variables. A structure can be created with variables of different data types in C++. Member Functions– These members are normal C++ functions. Along with variables, the functions can also be included inside a structure declaration. Problem Statement: Why the size of an empty structure is not zero in C++ but zero in C. Solution:Below is the C program with an empty structure: C // C program with an empty// structure#include <stdio.h> // Driver codeint main(){ // Empty Structure struct empty { }; // Initializing the Variable // of Struct type struct empty empty_struct; // Printing the Size of Struct printf("Size of Empty Struct in C programming = %ld", sizeof(empty_struct));} Size of Empty Struct in C programming = 0 Below is the C++ program with an empty structure: C++ // C++ program to implement// an empty structure#include <iostream>using namespace std; // Driver codeint main(){ // Empty Struct struct empty { }; // Initializing the Variable // of Struct type struct empty empty_struct; // Printing the Size of Struct cout << "Size of Empty Struct in C++ Programming = " << sizeof(empty_struct);} Size of Empty Struct in C++ Programming = 1 If observed carefully, the same code is executed in C and C++, but the output is different in both cases. Let’s discuss the reason behind this- The C++ standard does not permit objects (or classes) of size 0. This is because that would make it possible for two distinct objects to have the same memory location. This is the reason behind the concept that even an empty class and structure must have a size of at least 1. It is known that the size of an empty class is not zero. Generally, it is 1 byte. The C++ Structures also follow the same principle as the C++ Classes follow, i.e. that structures in c++ will also not be of zero bytes. The minimum size must be one byte.Creating an empty structure in C/C++ is a syntactic constraint violation. However, GCC permits an empty structure in C as an extension. Furthermore, the behavior is undefined if the structure does not have any named members because: The C++ standard does not permit objects (or classes) of size 0. This is because that would make it possible for two distinct objects to have the same memory location. This is the reason behind the concept that even an empty class and structure must have a size of at least 1. It is known that the size of an empty class is not zero. Generally, it is 1 byte. The C++ Structures also follow the same principle as the C++ Classes follow, i.e. that structures in c++ will also not be of zero bytes. The minimum size must be one byte. Creating an empty structure in C/C++ is a syntactic constraint violation. However, GCC permits an empty structure in C as an extension. Furthermore, the behavior is undefined if the structure does not have any named members because: C99 says- If the struct-declaration-list contains no named members, the behavior is undefined. This implies- // Constraint Violation struct EmptyGeeksforGeeks {}; // Behavior undefined, // since there is no named member struct EmptyGeeksforGeeks {int :0 ;}; surindertarika1234 C-Structure & Union cpp-structure memory-management C Language C++ CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Unordered Sets in C++ Standard Template Library What is the purpose of a function prototype? Operators in C / C++ Exception Handling in C++ Smart Pointers in C++ and How to Use Them Vector in C++ STL Map in C++ Standard Template Library (STL) Initialize a vector in C++ (7 different ways) Set in C++ Standard Template Library (STL) vector erase() and clear() in C++
[ { "code": null, "e": 28, "s": 0, "text": "\n04 Aug, 2021" }, { "code": null, "e": 305, "s": 28, "text": "A structure is a user-defined data type in C/C++. A structure creates a data type that can be used to group items of possibly different types into a single type. The ‘struct’ keyword is used to create a structure. The general syntax for creating a structure is as shown below:" }, { "code": null, "e": 313, "s": 305, "text": "Syntax-" }, { "code": null, "e": 408, "s": 313, "text": "struct structureName{\n member1;\n member2;\n member3;\n .\n .\n .\n memberN;\n};" }, { "code": null, "e": 461, "s": 408, "text": "Structures in C++ can contain two types of members: " }, { "code": null, "e": 734, "s": 461, "text": "Data Member– These members are normal C++ variables. A structure can be created with variables of different data types in C++.Member Functions– These members are normal C++ functions. Along with variables, the functions can also be included inside a structure declaration." }, { "code": null, "e": 861, "s": 734, "text": "Data Member– These members are normal C++ variables. A structure can be created with variables of different data types in C++." }, { "code": null, "e": 1008, "s": 861, "text": "Member Functions– These members are normal C++ functions. Along with variables, the functions can also be included inside a structure declaration." }, { "code": null, "e": 1096, "s": 1008, "text": "Problem Statement: Why the size of an empty structure is not zero in C++ but zero in C." }, { "code": null, "e": 1153, "s": 1096, "text": "Solution:Below is the C program with an empty structure:" }, { "code": null, "e": 1155, "s": 1153, "text": "C" }, { "code": "// C program with an empty// structure#include <stdio.h> // Driver codeint main(){ // Empty Structure struct empty { }; // Initializing the Variable // of Struct type struct empty empty_struct; // Printing the Size of Struct printf(\"Size of Empty Struct in C programming = %ld\", sizeof(empty_struct));}", "e": 1494, "s": 1155, "text": null }, { "code": null, "e": 1536, "s": 1494, "text": "Size of Empty Struct in C programming = 0" }, { "code": null, "e": 1586, "s": 1536, "text": "Below is the C++ program with an empty structure:" }, { "code": null, "e": 1590, "s": 1586, "text": "C++" }, { "code": "// C++ program to implement// an empty structure#include <iostream>using namespace std; // Driver codeint main(){ // Empty Struct struct empty { }; // Initializing the Variable // of Struct type struct empty empty_struct; // Printing the Size of Struct cout << \"Size of Empty Struct in C++ Programming = \" << sizeof(empty_struct);}", "e": 1948, "s": 1590, "text": null }, { "code": null, "e": 1992, "s": 1948, "text": "Size of Empty Struct in C++ Programming = 1" }, { "code": null, "e": 2136, "s": 1992, "text": "If observed carefully, the same code is executed in C and C++, but the output is different in both cases. Let’s discuss the reason behind this-" }, { "code": null, "e": 2899, "s": 2136, "text": "The C++ standard does not permit objects (or classes) of size 0. This is because that would make it possible for two distinct objects to have the same memory location. This is the reason behind the concept that even an empty class and structure must have a size of at least 1. It is known that the size of an empty class is not zero. Generally, it is 1 byte. The C++ Structures also follow the same principle as the C++ Classes follow, i.e. that structures in c++ will also not be of zero bytes. The minimum size must be one byte.Creating an empty structure in C/C++ is a syntactic constraint violation. However, GCC permits an empty structure in C as an extension. Furthermore, the behavior is undefined if the structure does not have any named members because:" }, { "code": null, "e": 3430, "s": 2899, "text": "The C++ standard does not permit objects (or classes) of size 0. This is because that would make it possible for two distinct objects to have the same memory location. This is the reason behind the concept that even an empty class and structure must have a size of at least 1. It is known that the size of an empty class is not zero. Generally, it is 1 byte. The C++ Structures also follow the same principle as the C++ Classes follow, i.e. that structures in c++ will also not be of zero bytes. The minimum size must be one byte." }, { "code": null, "e": 3663, "s": 3430, "text": "Creating an empty structure in C/C++ is a syntactic constraint violation. However, GCC permits an empty structure in C as an extension. Furthermore, the behavior is undefined if the structure does not have any named members because:" }, { "code": null, "e": 3758, "s": 3663, "text": "C99 says- If the struct-declaration-list contains no named members, the behavior is undefined." }, { "code": null, "e": 3773, "s": 3758, "text": "This implies- " }, { "code": null, "e": 3925, "s": 3773, "text": "// Constraint Violation\nstruct EmptyGeeksforGeeks {};\n\n// Behavior undefined, \n// since there is no named member\nstruct EmptyGeeksforGeeks {int :0 ;}; " }, { "code": null, "e": 3946, "s": 3927, "text": "surindertarika1234" }, { "code": null, "e": 3966, "s": 3946, "text": "C-Structure & Union" }, { "code": null, "e": 3980, "s": 3966, "text": "cpp-structure" }, { "code": null, "e": 3998, "s": 3980, "text": "memory-management" }, { "code": null, "e": 4009, "s": 3998, "text": "C Language" }, { "code": null, "e": 4013, "s": 4009, "text": "C++" }, { "code": null, "e": 4017, "s": 4013, "text": "CPP" }, { "code": null, "e": 4115, "s": 4017, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4163, "s": 4115, "text": "Unordered Sets in C++ Standard Template Library" }, { "code": null, "e": 4208, "s": 4163, "text": "What is the purpose of a function prototype?" }, { "code": null, "e": 4229, "s": 4208, "text": "Operators in C / C++" }, { "code": null, "e": 4255, "s": 4229, "text": "Exception Handling in C++" }, { "code": null, "e": 4297, "s": 4255, "text": "Smart Pointers in C++ and How to Use Them" }, { "code": null, "e": 4315, "s": 4297, "text": "Vector in C++ STL" }, { "code": null, "e": 4358, "s": 4315, "text": "Map in C++ Standard Template Library (STL)" }, { "code": null, "e": 4404, "s": 4358, "text": "Initialize a vector in C++ (7 different ways)" }, { "code": null, "e": 4447, "s": 4404, "text": "Set in C++ Standard Template Library (STL)" } ]
Given a binary tree, print all root-to-leaf paths
16 Jun, 2022 For the below example tree, all root-to-leaf paths are: 10 –> 8 –> 3 10 –> 8 –> 5 10 –> 2 –> 2 Algorithm: Use a path array path[] to store current root to leaf path. Traverse from root to all leaves in top-down fashion. While traversing, store data of all nodes in current path in array path[]. When we reach a leaf node, print the path array. C++ C Java Python3 C# Javascript #include <bits/stdc++.h>using namespace std; /* A binary tree node has data, pointer to left childand a pointer to right child */class node{ public: int data; node* left; node* right;}; /* Prototypes for functions needed in printPaths() */void printPathsRecur(node* node, int path[], int pathLen);void printArray(int ints[], int len); /*Given a binary tree, print out all of its root-to-leafpaths, one per line. Uses a recursive helper to do the work.*/void printPaths(node* node){ int path[1000]; printPathsRecur(node, path, 0);} /* Recursive helper function -- given a node,and an array containing the path from the rootnode up to but not including this node,print out all the root-leaf paths.*/void printPathsRecur(node* node, int path[], int pathLen){ if (node == NULL) return; /* append this node to the path array */ path[pathLen] = node->data; pathLen++; /* it's a leaf, so print the path that lead to here */ if (node->left == NULL && node->right == NULL) { printArray(path, pathLen); } else { /* otherwise try both subtrees */ printPathsRecur(node->left, path, pathLen); printPathsRecur(node->right, path, pathLen); }} /* UTILITY FUNCTIONS *//* Utility that prints out an array on a line. */void printArray(int ints[], int len){ int i; for (i = 0; i < len; i++) { cout << ints[i] << " "; } cout<<endl;} /* utility that allocates a new node with thegiven data and NULL left and right pointers. */node* newnode(int data){ node* Node = new node(); Node->data = data; Node->left = NULL; Node->right = NULL; return(Node);} /* Driver code*/int main(){ /* Constructed binary tree is 10 / \ 8 2 / \ / 3 5 2 */ node *root = newnode(10); root->left = newnode(8); root->right = newnode(2); root->left->left = newnode(3); root->left->right = newnode(5); root->right->left = newnode(2); printPaths(root); return 0;} // This code is contributed by rathbhupendra #include<stdio.h>#include<stdlib.h> /* A binary tree node has data, pointer to left child and a pointer to right child */struct node{ int data; struct node* left; struct node* right;}; /* Prototypes for functions needed in printPaths() */void printPathsRecur(struct node* node, int path[], int pathLen);void printArray(int ints[], int len); /*Given a binary tree, print out all of its root-to-leaf paths, one per line. Uses a recursive helper to do the work.*/void printPaths(struct node* node){ int path[1000]; printPathsRecur(node, path, 0);} /* Recursive helper function -- given a node, and an array containing the path from the root node up to but not including this node, print out all the root-leaf paths.*/void printPathsRecur(struct node* node, int path[], int pathLen){ if (node==NULL) return; /* append this node to the path array */ path[pathLen] = node->data; pathLen++; /* it's a leaf, so print the path that lead to here */ if (node->left==NULL && node->right==NULL) { printArray(path, pathLen); } else { /* otherwise try both subtrees */ printPathsRecur(node->left, path, pathLen); printPathsRecur(node->right, path, pathLen); }} /* UTILITY FUNCTIONS *//* Utility that prints out an array on a line. */void printArray(int ints[], int len){ int i; for (i=0; i<len; i++) { printf("%d ", ints[i]); } printf("\n");} /* utility that allocates a new node with the given data and NULL left and right pointers. */ struct node* newnode(int data){ struct node* node = (struct node*) malloc(sizeof(struct node)); node->data = data; node->left = NULL; node->right = NULL; return(node);} /* Driver program to test above functions*/int main(){ /* Constructed binary tree is 10 / \ 8 2 / \ / 3 5 2 */ struct node *root = newnode(10); root->left = newnode(8); root->right = newnode(2); root->left->left = newnode(3); root->left->right = newnode(5); root->right->left = newnode(2); printPaths(root); getchar(); return 0;} // Java program to print all the node to leaf path /* A binary tree node has data, pointer to left child and a pointer to right child */class Node{ int data; Node left, right; Node(int item) { data = item; left = right = null; }} class BinaryTree{ Node root; /*Given a binary tree, print out all of its root-to-leaf paths, one per line. Uses a recursive helper to do the work.*/ void printPaths(Node node) { int path[] = new int[1000]; printPathsRecur(node, path, 0); } /* Recursive helper function -- given a node, and an array containing the path from the root node up to but not including this node, print out all the root-leaf paths.*/ void printPathsRecur(Node node, int path[], int pathLen) { if (node == null) return; /* append this node to the path array */ path[pathLen] = node.data; pathLen++; /* it's a leaf, so print the path that lead to here */ if (node.left == null && node.right == null) printArray(path, pathLen); else { /* otherwise try both subtrees */ printPathsRecur(node.left, path, pathLen); printPathsRecur(node.right, path, pathLen); } } /* Utility function that prints out an array on a line. */ void printArray(int ints[], int len) { int i; for (i = 0; i < len; i++) { System.out.print(ints[i] + " "); } System.out.println(""); } // driver program to test above functions public static void main(String args[]) { BinaryTree tree = new BinaryTree(); tree.root = new Node(10); tree.root.left = new Node(8); tree.root.right = new Node(2); tree.root.left.left = new Node(3); tree.root.left.right = new Node(5); tree.root.right.left = new Node(2); /* Let us test the built tree by printing Inorder traversal */ tree.printPaths(tree.root); }} // This code has been contributed by Mayank Jaiswal """Python program to print all path from root toleaf in a binary tree""" # binary tree node contains data field ,# left and right pointerclass Node: # constructor to create tree node def __init__(self, data): self.data = data self.left = None self.right = None # function to print all path from root# to leaf in binary treedef printPaths(root): # list to store path path = [] printPathsRec(root, path, 0) # Helper function to print path from root# to leaf in binary treedef printPathsRec(root, path, pathLen): # Base condition - if binary tree is # empty return if root is None: return # add current root's data into # path_ar list # if length of list is gre if(len(path) > pathLen): path[pathLen] = root.data else: path.append(root.data) # increment pathLen by 1 pathLen = pathLen + 1 if root.left is None and root.right is None: # leaf node then print the list printArray(path, pathLen) else: # try for left and right subtree printPathsRec(root.left, path, pathLen) printPathsRec(root.right, path, pathLen) # Helper function to print list in which# root-to-leaf path is storeddef printArray(ints, len): for i in ints[0 : len]: print(i," ",end="") print() # Driver program to test above function"""Constructed binary tree is 10 / \ 8 2 / \ / 3 5 2"""root = Node(10)root.left = Node(8)root.right = Node(2)root.left.left = Node(3)root.left.right = Node(5)root.right.left = Node(2)printPaths(root) # This code has been contributed by Shweta Singh. using System; // C# program to print all the node to leaf path /* A binary tree node has data, pointer to left child and a pointer to right child */public class Node{ public int data; public Node left, right; public Node(int item) { data = item; left = right = null; }} public class BinaryTree{ public Node root; /*Given a binary tree, print out all of its root-to-leaf paths, one per line. Uses a recursive helper to do the work.*/ public virtual void printPaths(Node node) { int[] path = new int[1000]; printPathsRecur(node, path, 0); } /* Recursive helper function -- given a node, and an array containing the path from the root node up to but not including this node, print out all the root-leaf paths.*/ public virtual void printPathsRecur(Node node, int[] path, int pathLen) { if (node == null) { return; } /* append this node to the path array */ path[pathLen] = node.data; pathLen++; /* it's a leaf, so print the path that lead to here */ if (node.left == null && node.right == null) { printArray(path, pathLen); } else { /* otherwise try both subtrees */ printPathsRecur(node.left, path, pathLen); printPathsRecur(node.right, path, pathLen); } } /* Utility function that prints out an array on a line. */ public virtual void printArray(int[] ints, int len) { int i; for (i = 0; i < len; i++) { Console.Write(ints[i] + " "); } Console.WriteLine(""); } // driver program to test above functions public static void Main(string[] args) { BinaryTree tree = new BinaryTree(); tree.root = new Node(10); tree.root.left = new Node(8); tree.root.right = new Node(2); tree.root.left.left = new Node(3); tree.root.left.right = new Node(5); tree.root.right.left = new Node(2); /* Let us test the built tree by printing Inorder traversal */ tree.printPaths(tree.root); }} // This code is contributed by Shrikant13 <script>// javascript program to print all the node to leaf path /* A binary tree node has data, pointer to left child and a pointer to right child */class Node { constructor(val) { this.data = val; this.left = null; this.right = null; }} var root; /* * Given a binary tree, print out all of its root-to-leaf paths, one per line. * Uses a recursive helper to do the work. */ function printPaths(node) { var path = Array(1000).fill(0); printPathsRecur(node, path, 0); } /* * Recursive helper function -- given a node, and an array containing the path * from the root node up to but not including this node, print out all the * root-leaf paths. */ function printPathsRecur(node , path , pathLen) { if (node == null) return; /* append this node to the path array */ path[pathLen] = node.data; pathLen++; /* it's a leaf, so print the path that lead to here */ if (node.left == null && node.right == null) printArray(path, pathLen); else { /* otherwise try both subtrees */ printPathsRecur(node.left, path, pathLen); printPathsRecur(node.right, path, pathLen); } } /* Utility function that prints out an array on a line. */ function printArray(ints , len) { var i; for (i = 0; i < len; i++) { document.write(ints[i] + " "); } document.write("<br/>"); } // driver program to test above functions root = new Node(10); root.left = new Node(8); root.right = new Node(2); root.left.left = new Node(3); root.left.right = new Node(5); root.right.left = new Node(2); /* Let us test the built tree by printing Inorder traversal */ printPaths(root); // This code is contributed by gauravrajput1</script> 10 8 3 10 8 5 10 2 2 Time Complexity: O(n) where n is number of nodes. Space complexity: O(h) where h is height Of a Binary Tree. Chapters descriptions off, selected captions settings, opens captions settings dialog captions off, selected English This is a modal window. Beginning of dialog window. Escape will cancel and close the window. End of dialog window. References: http://cslibrary.stanford.edu/110/BinaryTrees.html Another Method C++ Python3 #include<bits/stdc++.h>using namespace std;/*Binary Tree representation using structure where data is in integer and 2 pointerstruct Node* left and struct Node* right represents left and right pointers of a nodein a tree respectively*/struct Node{ int data; struct Node* left; struct Node* right; Node(int x){ data = x; left = right = NULL; }};/*Recursive helper function which will recursively update our ans vector.it takes root of our tree ,arr vector and ans vector as an argument*/ void helper(Node* root,vector<int> arr,vector<vector<int>> &ans){ if(!root) return; arr.push_back(root->data); if(root->left==NULL && root->right==NULL) { /*This will be only true when the node is leaf node and hence we will update our ans vector by inserting vector arr which have one unique path from root to leaf*/ ans.push_back(arr); //after that we will return since we don't want to check after leaf node return; } /*recursively going left and right until we find the leaf and updating the arr and ans vector simultaneously*/ helper(root->left,arr,ans); helper(root->right,arr,ans);}vector<vector<int>> Paths(Node* root){ /*creating 2-d vector in which each element is a 1-d vector having one unique path from root to leaf*/ vector<vector<int>> ans; /*if root is null than there is no further action require so return*/ if(!root) return ans; vector<int> arr; /*arr is a vector which will have one unique path from root to leaf at a time.arr will be updated recursively*/ helper(root,arr,ans); /*after helper function call our ans vector updated with paths so we will return ans vector*/ return ans;}int main(){ /*defining root and our tree*/ Node *root = new Node(10); root->left = new Node(8); root->right = new Node(2); root->left->left = new Node(3); root->left->right = new Node(5); root->right->left = new Node(2); /*The answer returned will be stored in final 2-d vector*/ vector<vector<int>> final=Paths(root); /*printing paths from root to leaf*/ for(int i=0;i<final.size();i++) { for(int j=0;j<final[i].size();j++) cout<<final[i][j]<<" "; cout<<endl; }} """Python program to print all path from root toleaf in a binary tree""" # binary tree node contains data field ,# left and right pointer class Node: # constructor to create tree node def __init__(self, data): self.data = data self.left = None self.right = None # Recursive helper function which will recursively update our ans array.# it takes root of our tree ,arr array and ans array as an argument def helper(root, arr, ans): if not root: return arr.append(root.data) if root.left is None and root.right is None: # This will be only true when the node is leaf node # and hence we will update our ans array by inserting # array arr which have one unique path from root to leaf ans.append(arr.copy()) del arr[-1] # after that we will return since we don't want to check after leaf node return # recursively going left and right until we find the leaf and updating the arr # and ans array simultaneously helper(root.left, arr, ans) helper(root.right, arr, ans) del arr[-1] def Paths(root): # creating answer in which each element is a array # having one unique path from root to leaf ans = [] # if root is null then there is no further action require so return if not root: return [[]] arr = [] # arr is a array which will have one unique path from root to leaf # at a time.arr will be updated recursively helper(root, arr, ans) # after helper function call our ans array updated with paths so we will return ans array return ans # Helper function to print list in which# root-to-leaf path is storeddef printArray(paths): for path in paths: for i in path: print(i, " ", end="") print() # Driver program to test above function"""Constructed binary tree is 10 / \ 8 2 / \ / 3 5 2"""root = Node(10)root.left = Node(8)root.right = Node(2)root.left.left = Node(3)root.left.right = Node(5)root.right.left = Node(2)paths = Paths(root)printArray(paths) # This Code is Contributed by Vivek Maddeshiya 10 8 3 10 8 5 10 2 2 Time complexity: O(n) Auxiliary Space : O(h) where h is the height of the binary tree.Please write comments if you find any bug in above codes/algorithms, or find other ways to solve the same problem. shweta44 shrikanth13 rathbhupendra monitthakkar gabaa406 Shailendra Singh 1 sooda367 simranarora5sos GauravRajput1 surinderdawra388 clintra vivekmaddheshiya205 isha307 Amazon Tree Amazon Tree Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n16 Jun, 2022" }, { "code": null, "e": 150, "s": 52, "text": "For the below example tree, all root-to-leaf paths are: \n10 –> 8 –> 3 \n10 –> 8 –> 5 \n10 –> 2 –> 2" }, { "code": null, "e": 400, "s": 150, "text": "Algorithm: Use a path array path[] to store current root to leaf path. Traverse from root to all leaves in top-down fashion. While traversing, store data of all nodes in current path in array path[]. When we reach a leaf node, print the path array. " }, { "code": null, "e": 404, "s": 400, "text": "C++" }, { "code": null, "e": 406, "s": 404, "text": "C" }, { "code": null, "e": 411, "s": 406, "text": "Java" }, { "code": null, "e": 419, "s": 411, "text": "Python3" }, { "code": null, "e": 422, "s": 419, "text": "C#" }, { "code": null, "e": 433, "s": 422, "text": "Javascript" }, { "code": "#include <bits/stdc++.h>using namespace std; /* A binary tree node has data, pointer to left childand a pointer to right child */class node{ public: int data; node* left; node* right;}; /* Prototypes for functions needed in printPaths() */void printPathsRecur(node* node, int path[], int pathLen);void printArray(int ints[], int len); /*Given a binary tree, print out all of its root-to-leafpaths, one per line. Uses a recursive helper to do the work.*/void printPaths(node* node){ int path[1000]; printPathsRecur(node, path, 0);} /* Recursive helper function -- given a node,and an array containing the path from the rootnode up to but not including this node,print out all the root-leaf paths.*/void printPathsRecur(node* node, int path[], int pathLen){ if (node == NULL) return; /* append this node to the path array */ path[pathLen] = node->data; pathLen++; /* it's a leaf, so print the path that lead to here */ if (node->left == NULL && node->right == NULL) { printArray(path, pathLen); } else { /* otherwise try both subtrees */ printPathsRecur(node->left, path, pathLen); printPathsRecur(node->right, path, pathLen); }} /* UTILITY FUNCTIONS *//* Utility that prints out an array on a line. */void printArray(int ints[], int len){ int i; for (i = 0; i < len; i++) { cout << ints[i] << \" \"; } cout<<endl;} /* utility that allocates a new node with thegiven data and NULL left and right pointers. */node* newnode(int data){ node* Node = new node(); Node->data = data; Node->left = NULL; Node->right = NULL; return(Node);} /* Driver code*/int main(){ /* Constructed binary tree is 10 / \\ 8 2 / \\ / 3 5 2 */ node *root = newnode(10); root->left = newnode(8); root->right = newnode(2); root->left->left = newnode(3); root->left->right = newnode(5); root->right->left = newnode(2); printPaths(root); return 0;} // This code is contributed by rathbhupendra", "e": 2520, "s": 433, "text": null }, { "code": "#include<stdio.h>#include<stdlib.h> /* A binary tree node has data, pointer to left child and a pointer to right child */struct node{ int data; struct node* left; struct node* right;}; /* Prototypes for functions needed in printPaths() */void printPathsRecur(struct node* node, int path[], int pathLen);void printArray(int ints[], int len); /*Given a binary tree, print out all of its root-to-leaf paths, one per line. Uses a recursive helper to do the work.*/void printPaths(struct node* node){ int path[1000]; printPathsRecur(node, path, 0);} /* Recursive helper function -- given a node, and an array containing the path from the root node up to but not including this node, print out all the root-leaf paths.*/void printPathsRecur(struct node* node, int path[], int pathLen){ if (node==NULL) return; /* append this node to the path array */ path[pathLen] = node->data; pathLen++; /* it's a leaf, so print the path that lead to here */ if (node->left==NULL && node->right==NULL) { printArray(path, pathLen); } else { /* otherwise try both subtrees */ printPathsRecur(node->left, path, pathLen); printPathsRecur(node->right, path, pathLen); }} /* UTILITY FUNCTIONS *//* Utility that prints out an array on a line. */void printArray(int ints[], int len){ int i; for (i=0; i<len; i++) { printf(\"%d \", ints[i]); } printf(\"\\n\");} /* utility that allocates a new node with the given data and NULL left and right pointers. */ struct node* newnode(int data){ struct node* node = (struct node*) malloc(sizeof(struct node)); node->data = data; node->left = NULL; node->right = NULL; return(node);} /* Driver program to test above functions*/int main(){ /* Constructed binary tree is 10 / \\ 8 2 / \\ / 3 5 2 */ struct node *root = newnode(10); root->left = newnode(8); root->right = newnode(2); root->left->left = newnode(3); root->left->right = newnode(5); root->right->left = newnode(2); printPaths(root); getchar(); return 0;}", "e": 4608, "s": 2520, "text": null }, { "code": "// Java program to print all the node to leaf path /* A binary tree node has data, pointer to left child and a pointer to right child */class Node{ int data; Node left, right; Node(int item) { data = item; left = right = null; }} class BinaryTree{ Node root; /*Given a binary tree, print out all of its root-to-leaf paths, one per line. Uses a recursive helper to do the work.*/ void printPaths(Node node) { int path[] = new int[1000]; printPathsRecur(node, path, 0); } /* Recursive helper function -- given a node, and an array containing the path from the root node up to but not including this node, print out all the root-leaf paths.*/ void printPathsRecur(Node node, int path[], int pathLen) { if (node == null) return; /* append this node to the path array */ path[pathLen] = node.data; pathLen++; /* it's a leaf, so print the path that lead to here */ if (node.left == null && node.right == null) printArray(path, pathLen); else { /* otherwise try both subtrees */ printPathsRecur(node.left, path, pathLen); printPathsRecur(node.right, path, pathLen); } } /* Utility function that prints out an array on a line. */ void printArray(int ints[], int len) { int i; for (i = 0; i < len; i++) { System.out.print(ints[i] + \" \"); } System.out.println(\"\"); } // driver program to test above functions public static void main(String args[]) { BinaryTree tree = new BinaryTree(); tree.root = new Node(10); tree.root.left = new Node(8); tree.root.right = new Node(2); tree.root.left.left = new Node(3); tree.root.left.right = new Node(5); tree.root.right.left = new Node(2); /* Let us test the built tree by printing Inorder traversal */ tree.printPaths(tree.root); }} // This code has been contributed by Mayank Jaiswal", "e": 6699, "s": 4608, "text": null }, { "code": "\"\"\"Python program to print all path from root toleaf in a binary tree\"\"\" # binary tree node contains data field ,# left and right pointerclass Node: # constructor to create tree node def __init__(self, data): self.data = data self.left = None self.right = None # function to print all path from root# to leaf in binary treedef printPaths(root): # list to store path path = [] printPathsRec(root, path, 0) # Helper function to print path from root# to leaf in binary treedef printPathsRec(root, path, pathLen): # Base condition - if binary tree is # empty return if root is None: return # add current root's data into # path_ar list # if length of list is gre if(len(path) > pathLen): path[pathLen] = root.data else: path.append(root.data) # increment pathLen by 1 pathLen = pathLen + 1 if root.left is None and root.right is None: # leaf node then print the list printArray(path, pathLen) else: # try for left and right subtree printPathsRec(root.left, path, pathLen) printPathsRec(root.right, path, pathLen) # Helper function to print list in which# root-to-leaf path is storeddef printArray(ints, len): for i in ints[0 : len]: print(i,\" \",end=\"\") print() # Driver program to test above function\"\"\"Constructed binary tree is 10 / \\ 8 2 / \\ / 3 5 2\"\"\"root = Node(10)root.left = Node(8)root.right = Node(2)root.left.left = Node(3)root.left.right = Node(5)root.right.left = Node(2)printPaths(root) # This code has been contributed by Shweta Singh.", "e": 8343, "s": 6699, "text": null }, { "code": "using System; // C# program to print all the node to leaf path /* A binary tree node has data, pointer to left child and a pointer to right child */public class Node{ public int data; public Node left, right; public Node(int item) { data = item; left = right = null; }} public class BinaryTree{ public Node root; /*Given a binary tree, print out all of its root-to-leaf paths, one per line. Uses a recursive helper to do the work.*/ public virtual void printPaths(Node node) { int[] path = new int[1000]; printPathsRecur(node, path, 0); } /* Recursive helper function -- given a node, and an array containing the path from the root node up to but not including this node, print out all the root-leaf paths.*/ public virtual void printPathsRecur(Node node, int[] path, int pathLen) { if (node == null) { return; } /* append this node to the path array */ path[pathLen] = node.data; pathLen++; /* it's a leaf, so print the path that lead to here */ if (node.left == null && node.right == null) { printArray(path, pathLen); } else { /* otherwise try both subtrees */ printPathsRecur(node.left, path, pathLen); printPathsRecur(node.right, path, pathLen); } } /* Utility function that prints out an array on a line. */ public virtual void printArray(int[] ints, int len) { int i; for (i = 0; i < len; i++) { Console.Write(ints[i] + \" \"); } Console.WriteLine(\"\"); } // driver program to test above functions public static void Main(string[] args) { BinaryTree tree = new BinaryTree(); tree.root = new Node(10); tree.root.left = new Node(8); tree.root.right = new Node(2); tree.root.left.left = new Node(3); tree.root.left.right = new Node(5); tree.root.right.left = new Node(2); /* Let us test the built tree by printing Inorder traversal */ tree.printPaths(tree.root); }} // This code is contributed by Shrikant13", "e": 10536, "s": 8343, "text": null }, { "code": "<script>// javascript program to print all the node to leaf path /* A binary tree node has data, pointer to left child and a pointer to right child */class Node { constructor(val) { this.data = val; this.left = null; this.right = null; }} var root; /* * Given a binary tree, print out all of its root-to-leaf paths, one per line. * Uses a recursive helper to do the work. */ function printPaths(node) { var path = Array(1000).fill(0); printPathsRecur(node, path, 0); } /* * Recursive helper function -- given a node, and an array containing the path * from the root node up to but not including this node, print out all the * root-leaf paths. */ function printPathsRecur(node , path , pathLen) { if (node == null) return; /* append this node to the path array */ path[pathLen] = node.data; pathLen++; /* it's a leaf, so print the path that lead to here */ if (node.left == null && node.right == null) printArray(path, pathLen); else { /* otherwise try both subtrees */ printPathsRecur(node.left, path, pathLen); printPathsRecur(node.right, path, pathLen); } } /* Utility function that prints out an array on a line. */ function printArray(ints , len) { var i; for (i = 0; i < len; i++) { document.write(ints[i] + \" \"); } document.write(\"<br/>\"); } // driver program to test above functions root = new Node(10); root.left = new Node(8); root.right = new Node(2); root.left.left = new Node(3); root.left.right = new Node(5); root.right.left = new Node(2); /* Let us test the built tree by printing Inorder traversal */ printPaths(root); // This code is contributed by gauravrajput1</script>", "e": 12439, "s": 10536, "text": null }, { "code": null, "e": 12463, "s": 12439, "text": "10 8 3 \n10 8 5 \n10 2 2 " }, { "code": null, "e": 12513, "s": 12463, "text": "Time Complexity: O(n) where n is number of nodes." }, { "code": null, "e": 12572, "s": 12513, "text": "Space complexity: O(h) where h is height Of a Binary Tree." }, { "code": null, "e": 12581, "s": 12572, "text": "Chapters" }, { "code": null, "e": 12608, "s": 12581, "text": "descriptions off, selected" }, { "code": null, "e": 12658, "s": 12608, "text": "captions settings, opens captions settings dialog" }, { "code": null, "e": 12681, "s": 12658, "text": "captions off, selected" }, { "code": null, "e": 12689, "s": 12681, "text": "English" }, { "code": null, "e": 12713, "s": 12689, "text": "This is a modal window." }, { "code": null, "e": 12782, "s": 12713, "text": "Beginning of dialog window. Escape will cancel and close the window." }, { "code": null, "e": 12804, "s": 12782, "text": "End of dialog window." }, { "code": null, "e": 12868, "s": 12804, "text": "References: http://cslibrary.stanford.edu/110/BinaryTrees.html" }, { "code": null, "e": 12884, "s": 12868, "text": "Another Method " }, { "code": null, "e": 12888, "s": 12884, "text": "C++" }, { "code": null, "e": 12896, "s": 12888, "text": "Python3" }, { "code": "#include<bits/stdc++.h>using namespace std;/*Binary Tree representation using structure where data is in integer and 2 pointerstruct Node* left and struct Node* right represents left and right pointers of a nodein a tree respectively*/struct Node{ int data; struct Node* left; struct Node* right; Node(int x){ data = x; left = right = NULL; }};/*Recursive helper function which will recursively update our ans vector.it takes root of our tree ,arr vector and ans vector as an argument*/ void helper(Node* root,vector<int> arr,vector<vector<int>> &ans){ if(!root) return; arr.push_back(root->data); if(root->left==NULL && root->right==NULL) { /*This will be only true when the node is leaf node and hence we will update our ans vector by inserting vector arr which have one unique path from root to leaf*/ ans.push_back(arr); //after that we will return since we don't want to check after leaf node return; } /*recursively going left and right until we find the leaf and updating the arr and ans vector simultaneously*/ helper(root->left,arr,ans); helper(root->right,arr,ans);}vector<vector<int>> Paths(Node* root){ /*creating 2-d vector in which each element is a 1-d vector having one unique path from root to leaf*/ vector<vector<int>> ans; /*if root is null than there is no further action require so return*/ if(!root) return ans; vector<int> arr; /*arr is a vector which will have one unique path from root to leaf at a time.arr will be updated recursively*/ helper(root,arr,ans); /*after helper function call our ans vector updated with paths so we will return ans vector*/ return ans;}int main(){ /*defining root and our tree*/ Node *root = new Node(10); root->left = new Node(8); root->right = new Node(2); root->left->left = new Node(3); root->left->right = new Node(5); root->right->left = new Node(2); /*The answer returned will be stored in final 2-d vector*/ vector<vector<int>> final=Paths(root); /*printing paths from root to leaf*/ for(int i=0;i<final.size();i++) { for(int j=0;j<final[i].size();j++) cout<<final[i][j]<<\" \"; cout<<endl; }}", "e": 15165, "s": 12896, "text": null }, { "code": "\"\"\"Python program to print all path from root toleaf in a binary tree\"\"\" # binary tree node contains data field ,# left and right pointer class Node: # constructor to create tree node def __init__(self, data): self.data = data self.left = None self.right = None # Recursive helper function which will recursively update our ans array.# it takes root of our tree ,arr array and ans array as an argument def helper(root, arr, ans): if not root: return arr.append(root.data) if root.left is None and root.right is None: # This will be only true when the node is leaf node # and hence we will update our ans array by inserting # array arr which have one unique path from root to leaf ans.append(arr.copy()) del arr[-1] # after that we will return since we don't want to check after leaf node return # recursively going left and right until we find the leaf and updating the arr # and ans array simultaneously helper(root.left, arr, ans) helper(root.right, arr, ans) del arr[-1] def Paths(root): # creating answer in which each element is a array # having one unique path from root to leaf ans = [] # if root is null then there is no further action require so return if not root: return [[]] arr = [] # arr is a array which will have one unique path from root to leaf # at a time.arr will be updated recursively helper(root, arr, ans) # after helper function call our ans array updated with paths so we will return ans array return ans # Helper function to print list in which# root-to-leaf path is storeddef printArray(paths): for path in paths: for i in path: print(i, \" \", end=\"\") print() # Driver program to test above function\"\"\"Constructed binary tree is 10 / \\ 8 2 / \\ / 3 5 2\"\"\"root = Node(10)root.left = Node(8)root.right = Node(2)root.left.left = Node(3)root.left.right = Node(5)root.right.left = Node(2)paths = Paths(root)printArray(paths) # This Code is Contributed by Vivek Maddeshiya", "e": 17276, "s": 15165, "text": null }, { "code": null, "e": 17300, "s": 17276, "text": "10 8 3 \n10 8 5 \n10 2 2 " }, { "code": null, "e": 17508, "s": 17300, "text": "Time complexity: O(n) Auxiliary Space : O(h) where h is the height of the binary tree.Please write comments if you find any bug in above codes/algorithms, or find other ways to solve the same problem. " }, { "code": null, "e": 17517, "s": 17508, "text": "shweta44" }, { "code": null, "e": 17529, "s": 17517, "text": "shrikanth13" }, { "code": null, "e": 17543, "s": 17529, "text": "rathbhupendra" }, { "code": null, "e": 17556, "s": 17543, "text": "monitthakkar" }, { "code": null, "e": 17565, "s": 17556, "text": "gabaa406" }, { "code": null, "e": 17584, "s": 17565, "text": "Shailendra Singh 1" }, { "code": null, "e": 17593, "s": 17584, "text": "sooda367" }, { "code": null, "e": 17609, "s": 17593, "text": "simranarora5sos" }, { "code": null, "e": 17623, "s": 17609, "text": "GauravRajput1" }, { "code": null, "e": 17640, "s": 17623, "text": "surinderdawra388" }, { "code": null, "e": 17648, "s": 17640, "text": "clintra" }, { "code": null, "e": 17668, "s": 17648, "text": "vivekmaddheshiya205" }, { "code": null, "e": 17676, "s": 17668, "text": "isha307" }, { "code": null, "e": 17683, "s": 17676, "text": "Amazon" }, { "code": null, "e": 17688, "s": 17683, "text": "Tree" }, { "code": null, "e": 17695, "s": 17688, "text": "Amazon" }, { "code": null, "e": 17700, "s": 17695, "text": "Tree" } ]
Checking if structure is empty or not in Golang - GeeksforGeeks
04 May, 2020 If the structure is empty means that there is no field present inside that particular structure. In Golang, the size of an empty structure is zero. Whenever the user wants to know if the created structure is empty or not, he can access the structure in the main function through a variable. If there doesn’t exist any field inside the structure, he can simply display that the structure is empty. Syntax: type structure_name struct { } There are different ways to find out whether a structure is empty or not as shown below. 1) To check if the structure is empty: package main import ( "fmt") type Book struct {} func main() { var bk Book if (Book{} == bk) { fmt.Println("It is an empty structure.") } else { fmt.Println("It is not an empty structure.") }} Output: It is an empty structure. Explanation: In the above example, we have created a structure named “Book” in which there is no existing field. In the main function, we created a variable to access our structure. Since there are no fields specified in the structure, it will print that it is an empty structure. Now, if there are fields present in the structure, it will return the message that it is not an empty structure as shown below: package main import ( "fmt") type Book struct { qty int} func main() { var bk Book if (Book{500} == bk) { fmt.Println("It is an empty structure.") } else { fmt.Println("It is not an empty structure.") }} Output: It is not an empty structure. Explanation: In the above example, we have created a structure named “Book” in which we have declared a field named “qty” of data type int. In the main function, we created a variable to access our structure. Since there is a field present in the structure, it will print that it is not an empty structure. 2) Using switch case: package main import ( "fmt") type articles struct {} func main() { x := articles{} switch { case x == articles{}: fmt.Println("Structure is empty.") default: fmt.Println("Structure is not empty.") }} Output: Structure is empty. Explanation: In this example, we created a structure named “articles” in which no fields are declared. Inside the main function, we created a variable “x” and used a switch case to access our structure. Since there are no fields present in the structure, the program will display that the structure is empty. Picked Go Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. strings.Replace() Function in Golang With Examples How to Split a String in Golang? Arrays in Go Golang Maps Slices in Golang How to convert a string in lower case in Golang? How to Trim a String in Golang? Inheritance in GoLang How to Parse JSON in Golang? Different Ways to Find the Type of Variable in Golang
[ { "code": null, "e": 24420, "s": 24392, "text": "\n04 May, 2020" }, { "code": null, "e": 24817, "s": 24420, "text": "If the structure is empty means that there is no field present inside that particular structure. In Golang, the size of an empty structure is zero. Whenever the user wants to know if the created structure is empty or not, he can access the structure in the main function through a variable. If there doesn’t exist any field inside the structure, he can simply display that the structure is empty." }, { "code": null, "e": 24825, "s": 24817, "text": "Syntax:" }, { "code": null, "e": 24861, "s": 24825, "text": "type structure_name struct {\n }\n" }, { "code": null, "e": 24950, "s": 24861, "text": "There are different ways to find out whether a structure is empty or not as shown below." }, { "code": null, "e": 24989, "s": 24950, "text": "1) To check if the structure is empty:" }, { "code": "package main import ( \"fmt\") type Book struct {} func main() { var bk Book if (Book{} == bk) { fmt.Println(\"It is an empty structure.\") } else { fmt.Println(\"It is not an empty structure.\") }}", "e": 25214, "s": 24989, "text": null }, { "code": null, "e": 25222, "s": 25214, "text": "Output:" }, { "code": null, "e": 25248, "s": 25222, "text": "It is an empty structure." }, { "code": null, "e": 25657, "s": 25248, "text": "Explanation: In the above example, we have created a structure named “Book” in which there is no existing field. In the main function, we created a variable to access our structure. Since there are no fields specified in the structure, it will print that it is an empty structure. Now, if there are fields present in the structure, it will return the message that it is not an empty structure as shown below:" }, { "code": "package main import ( \"fmt\") type Book struct { qty int} func main() { var bk Book if (Book{500} == bk) { fmt.Println(\"It is an empty structure.\") } else { fmt.Println(\"It is not an empty structure.\") }}", "e": 25896, "s": 25657, "text": null }, { "code": null, "e": 25904, "s": 25896, "text": "Output:" }, { "code": null, "e": 25934, "s": 25904, "text": "It is not an empty structure." }, { "code": null, "e": 26241, "s": 25934, "text": "Explanation: In the above example, we have created a structure named “Book” in which we have declared a field named “qty” of data type int. In the main function, we created a variable to access our structure. Since there is a field present in the structure, it will print that it is not an empty structure." }, { "code": null, "e": 26263, "s": 26241, "text": "2) Using switch case:" }, { "code": "package main import ( \"fmt\") type articles struct {} func main() { x := articles{} switch { case x == articles{}: fmt.Println(\"Structure is empty.\") default: fmt.Println(\"Structure is not empty.\") }}", "e": 26500, "s": 26263, "text": null }, { "code": null, "e": 26508, "s": 26500, "text": "Output:" }, { "code": null, "e": 26528, "s": 26508, "text": "Structure is empty." }, { "code": null, "e": 26837, "s": 26528, "text": "Explanation: In this example, we created a structure named “articles” in which no fields are declared. Inside the main function, we created a variable “x” and used a switch case to access our structure. Since there are no fields present in the structure, the program will display that the structure is empty." }, { "code": null, "e": 26844, "s": 26837, "text": "Picked" }, { "code": null, "e": 26856, "s": 26844, "text": "Go Language" }, { "code": null, "e": 26954, "s": 26856, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27005, "s": 26954, "text": "strings.Replace() Function in Golang With Examples" }, { "code": null, "e": 27038, "s": 27005, "text": "How to Split a String in Golang?" }, { "code": null, "e": 27051, "s": 27038, "text": "Arrays in Go" }, { "code": null, "e": 27063, "s": 27051, "text": "Golang Maps" }, { "code": null, "e": 27080, "s": 27063, "text": "Slices in Golang" }, { "code": null, "e": 27129, "s": 27080, "text": "How to convert a string in lower case in Golang?" }, { "code": null, "e": 27161, "s": 27129, "text": "How to Trim a String in Golang?" }, { "code": null, "e": 27183, "s": 27161, "text": "Inheritance in GoLang" }, { "code": null, "e": 27212, "s": 27183, "text": "How to Parse JSON in Golang?" } ]
How to restrict argument values using choice options in Python?
Assume you are asked to code a program to accept the number of tennis grandslam titles from the user and process them. We already know, Federer and Nadal share the maximum grandslam titles in Tennis which is 20 (As of 2020) while the minimum is 0, lot of players are still fighting to get their first grandslam title. Let us create a program to accept the titles. Note - Execute the program from terminal. import argparse def get_args(): """ Function : get_args parameters used in .add_argument 1. metavar - Provide a hint to the user about the data type. - By default, all arguments are strings. 2. type - The actual Python data type - (note the lack of quotes around str) 3. help - A brief description of the parameter for the usage """ parser = argparse.ArgumentParser( description='Example for one positional arguments', formatter_class=argparse.ArgumentDefaultsHelpFormatter) # Adding our first argument player titles of type int parser.add_argument('titles', metavar='titles', type=int, help='GrandSlam Titles') return parser.parse_args() # define main def main(titles): print(f" *** Player had won {titles} GrandSlam titles.") if __name__ == '__main__': args = get_args() main(args.titles) Our program is now ready to accept the titles. So let us pass any number(not float) as argument. <<< python test.py 20 *** Player had won 20 GrandSlam titles. <<< python test.py 50 *** Player had won 50 GrandSlam titles. <<< python test.py -1 *** Player had won -1 GrandSlam titles. <<< python test.py 30 *** Player had won 30 GrandSlam titles. While there is no technical issue with the code, there is definetly a functional issue as our program is accepting any number of GrandSlam titles including negative titles. In such cases where we want to restrict the choices of GrandSlam titles, we can use the choices option. In the following example, we restrict the titles to a range (0, 20). import argparse def get_args(): """ Function : get_args parameters used in .add_argument 1. metavar - Provide a hint to the user about the data type. - By default, all arguments are strings. 2. type - The actual Python data type - (note the lack of quotes around str) 3. help - A brief description of the parameter for the usage 4. choices - pre defined range of choices a user can enter to this program """ parser = argparse.ArgumentParser( description='Example for one positional arguments', formatter_class=argparse.ArgumentDefaultsHelpFormatter) # Adding our first argument player titles of type int parser.add_argument('titles', metavar='titles', type=int, choices=range(0, 20), help='GrandSlam Titles') return parser.parse_args() # define main def main(titles): print(f" *** Player had won {titles} GrandSlam titles.") if __name__ == '__main__': args = get_args() main(args.titles) >>> python test.py 30 usage: test.py [-h] titles test.py: error: argument titles: invalid choice: 30 (choose from 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19) <<< python test.py 10 *** Player had won 10 GrandSlam titles. <<< python test.py -1 usage: test.py [-h] titles test.py: error: argument titles: invalid choice: -1 (choose from 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19) <<< python test.py 0 *** Player had won 0 GrandSlam titles. <<< python test.py 20 usage: test.py [-h] titles test.py: error: argument titles: invalid choice: 20 (choose from 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19) Conclusion : The choices option takes a list of values. argparse stops the program if the user fails to supply one of these. The choices option takes a list of values. argparse stops the program if the user fails to supply one of these. The user must choose from the numbers 0-19 or argparse will stop with an error. The user must choose from the numbers 0-19 or argparse will stop with an error. Finally, You can also have a program that accepts string choices. import argparse def get_args(): """ Function : get_args parameters used in .add_argument 1. metavar - Provide a hint to the user about the data type. - By default, all arguments are strings. 2. type - The actual Python data type - (note the lack of quotes around str) 3. help - A brief description of the parameter for the usage 4. choices - pre defined range of choices a user can enter to this program """ parser = argparse.ArgumentParser( description='Example for one positional arguments', formatter_class=argparse.ArgumentDefaultsHelpFormatter) # Adding our first argument player names of type str. parser.add_argument('player', metavar='player', type=str, choices=['federer', 'nadal', 'djokovic'], help='Tennis Players') # Adding our second argument player titles of type int parser.add_argument('titles', metavar='titles', type=int, choices=range(0, 20), help='GrandSlam Titles') return parser.parse_args() # define main def main(player,titles): print(f" *** {player} had won {titles} GrandSlam titles.") if __name__ == '__main__': args = get_args() main(args.player,args.titles) <<< python test.py usage: test.py [-h] player titles test.py: error: the following arguments are required: player, titles <<< python test.py "federer" 30 usage: test.py [-h] player titles test.py: error: argument titles: invalid choice: 30 (choose from 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19) <<< python test.py "murray" 5 usage: test.py [-h] player titles test.py: error: argument player: invalid choice: 'murray' (choose from 'federer', 'nadal', 'djokovic') <<< python test.py "djokovic" 17 *** djokovic had won 17 GrandSlam titles.
[ { "code": null, "e": 1380, "s": 1062, "text": "Assume you are asked to code a program to accept the number of tennis grandslam titles from the user and process them. We already know, Federer and Nadal share the maximum grandslam titles in Tennis which is 20 (As of 2020) while the minimum is 0, lot of players are still fighting to get their first grandslam title." }, { "code": null, "e": 1426, "s": 1380, "text": "Let us create a program to accept the titles." }, { "code": null, "e": 1468, "s": 1426, "text": "Note - Execute the program from terminal." }, { "code": null, "e": 2268, "s": 1468, "text": "import argparse\n\ndef get_args():\n\"\"\" Function : get_args\nparameters used in .add_argument\n1. metavar - Provide a hint to the user about the data type.\n- By default, all arguments are strings.\n\n2. type - The actual Python data type\n- (note the lack of quotes around str)\n\n3. help - A brief description of the parameter for the usage\n\n\"\"\"\n\nparser = argparse.ArgumentParser(\ndescription='Example for one positional arguments',\nformatter_class=argparse.ArgumentDefaultsHelpFormatter)\n\n# Adding our first argument player titles of type int\nparser.add_argument('titles',\nmetavar='titles',\ntype=int,\nhelp='GrandSlam Titles')\n\nreturn parser.parse_args()\n\n# define main\ndef main(titles):\nprint(f\" *** Player had won {titles} GrandSlam titles.\")\n\nif __name__ == '__main__':\nargs = get_args()\nmain(args.titles)" }, { "code": null, "e": 2365, "s": 2268, "text": "Our program is now ready to accept the titles. So let us pass any number(not float) as argument." }, { "code": null, "e": 2613, "s": 2365, "text": "<<< python test.py 20\n*** Player had won 20 GrandSlam titles.\n<<< python test.py 50\n*** Player had won 50 GrandSlam titles.\n<<< python test.py -1\n*** Player had won -1 GrandSlam titles.\n<<< python test.py 30\n*** Player had won 30 GrandSlam titles." }, { "code": null, "e": 2786, "s": 2613, "text": "While there is no technical issue with the code, there is definetly a functional issue as our program is accepting any number of GrandSlam titles including negative titles." }, { "code": null, "e": 2890, "s": 2786, "text": "In such cases where we want to restrict the choices of GrandSlam titles, we can use the choices option." }, { "code": null, "e": 2959, "s": 2890, "text": "In the following example, we restrict the titles to a range (0, 20)." }, { "code": null, "e": 3856, "s": 2959, "text": "import argparse\ndef get_args():\n\"\"\" Function : get_args\nparameters used in .add_argument\n1. metavar - Provide a hint to the user about the data type.\n- By default, all arguments are strings.\n\n2. type - The actual Python data type\n- (note the lack of quotes around str)\n\n3. help - A brief description of the parameter for the usage\n\n4. choices - pre defined range of choices a user can enter to this program\n\n\"\"\"\n\nparser = argparse.ArgumentParser(\ndescription='Example for one positional arguments',\nformatter_class=argparse.ArgumentDefaultsHelpFormatter)\n\n# Adding our first argument player titles of type int\nparser.add_argument('titles',\nmetavar='titles',\ntype=int,\nchoices=range(0, 20),\nhelp='GrandSlam Titles')\n\nreturn parser.parse_args()\n\n# define main\ndef main(titles):\nprint(f\" *** Player had won {titles} GrandSlam titles.\")\n\nif __name__ == '__main__':\nargs = get_args()\nmain(args.titles)" }, { "code": null, "e": 4530, "s": 3856, "text": ">>> python test.py 30\nusage: test.py [-h] titles\ntest.py: error: argument titles: invalid choice: 30 (choose from 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19)\n<<< python test.py 10\n*** Player had won 10 GrandSlam titles.\n<<< python test.py -1\nusage: test.py [-h] titles\ntest.py: error: argument titles: invalid choice: -1 (choose from 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19)\n<<< python test.py 0\n*** Player had won 0 GrandSlam titles.\n<<< python test.py 20\nusage: test.py [-h] titles\ntest.py: error: argument titles: invalid choice: 20 (choose from 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19)" }, { "code": null, "e": 4543, "s": 4530, "text": "Conclusion :" }, { "code": null, "e": 4655, "s": 4543, "text": "The choices option takes a list of values. argparse stops the program if the user fails to supply one of these." }, { "code": null, "e": 4767, "s": 4655, "text": "The choices option takes a list of values. argparse stops the program if the user fails to supply one of these." }, { "code": null, "e": 4847, "s": 4767, "text": "The user must choose from the numbers 0-19 or argparse will stop with an error." }, { "code": null, "e": 4927, "s": 4847, "text": "The user must choose from the numbers 0-19 or argparse will stop with an error." }, { "code": null, "e": 4993, "s": 4927, "text": "Finally, You can also have a program that accepts string choices." }, { "code": null, "e": 6091, "s": 4993, "text": "import argparse\n\ndef get_args():\n\"\"\" Function : get_args\nparameters used in .add_argument\n1. metavar - Provide a hint to the user about the data type.\n- By default, all arguments are strings.\n\n2. type - The actual Python data type\n- (note the lack of quotes around str)\n\n3. help - A brief description of the parameter for the usage\n\n4. choices - pre defined range of choices a user can enter to this program\n\n\"\"\"\n\nparser = argparse.ArgumentParser(\ndescription='Example for one positional arguments',\nformatter_class=argparse.ArgumentDefaultsHelpFormatter)\n\n# Adding our first argument player names of type str.\nparser.add_argument('player',\nmetavar='player',\ntype=str,\nchoices=['federer', 'nadal', 'djokovic'],\nhelp='Tennis Players')\n\n# Adding our second argument player titles of type int\nparser.add_argument('titles',\nmetavar='titles',\ntype=int,\nchoices=range(0, 20),\nhelp='GrandSlam Titles')\n\nreturn parser.parse_args()\n\n# define main\ndef main(player,titles):\nprint(f\" *** {player} had won {titles} GrandSlam titles.\")\n\nif __name__ == '__main__':\nargs = get_args()\nmain(args.player,args.titles)" }, { "code": null, "e": 6656, "s": 6091, "text": "<<< python test.py\nusage: test.py [-h] player titles\ntest.py: error: the following arguments are required: player, titles\n<<< python test.py \"federer\" 30\nusage: test.py [-h] player titles\ntest.py: error: argument titles: invalid choice: 30 (choose from 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19)\n<<< python test.py \"murray\" 5\nusage: test.py [-h] player titles\ntest.py: error: argument player: invalid choice: 'murray' (choose from 'federer', 'nadal', 'djokovic')\n<<< python test.py \"djokovic\" 17\n*** djokovic had won 17 GrandSlam titles." } ]
What is ISOMAP? How to use ISOMAP? When to use ISOMAP? What is geodesic distance? Geodesic distance vs Euclidean distance | Towards Data Science
Dimensionality reduction methods visualize the dataset and reduce its size, as well as reveal different features in the dataset. For non-linear datasets, dimensionality reduction can be examined under various sub-titles such as distance preservation (Isomap), topology preservation (Locally Linear Embedding). This article explains the theoretical part of isometric feature mapping, one of the distance preservation non-linear dimensionality reduction methods, and includes the interpretation and usage areas of the dataset obtained after dimensionality reduction. Studies are enriched with python implementation. Table of Contents1. Isometric Feature Mapping (ISOMAP)- Geodesic Distance vs Euclidean Distance- Interpretation of the result of ISOMAP2. ISOMAP Algorithm3. Use Cases4. Python Tutorials5. References Isomap is a non-linear dimensionality reduction method, which is a different version of metric MDS, and reduces the dimensionality while preserving geodesic distance. The most obvious difference between Metric MDS and ISOMAP: Euclidean distance is preserved in Metric MDS, while geodesic distance is preserved in ISOMAP. So why do we need this? Is it more effective to preserve geodesic distance? Let’s look at Figure 1 to compare Geodesic distance and Euclidean distance as dimensionality reduction techniques. While the Euclidean distance calculates only the distance by ignoring the shape of the dataset, the geodesic distance is calculated by passing the shortest path on the dataset. In this case, we can roughly say that the difference between the geodesic distance and the Euclidean distance; while the geodesic distance considers the data adjacent to these data, in the Euclidean distance it is only calculated the shortest linear path. Of course, since our goal is to reduce the dimensionality of the dataset with the least loss, more effective results can be obtained with geodesic distance according to the dataset. The following code block shows the basic implementation of isomap on the Swiss roll dataset: Looking at the ISOMAP and MDS results, it is seen that the Swiss roll can be unrolled by using ISOMAP. The red data points are shown as ISOMAP results in Figure 2(right), taking into account the neighborhood distance between them. When calculating the Euclidean distance between 2 points, the shortest distance is obtained (linear distance). In the geodesic distance, the shortest path passing over the dataset is obtained. To find this out, a certain value of k is determined and k-nearest is connected to each other by neighbors and the chain continues. In ISOMAP provided in the Sklearn library, it can be set with n_neighbors=5. The default value is 5. The other way to find the shortest path is to draw the circle centered on the initial data and connect each data point by an edge to all of the other data points within the circle. To summarize the difference between geodesic distance and Euclidean distance, let’s take a look at their transformed form. Figure 3 illustrates the comparison of tumor tissue which is applied Euclidean distance and geodesic distance. In Figure 4, the same procedures are applied to the damaged brain region and compared. In the above images, it is seen that geodesic distance can make much more effective discrimination than the Euclidean distance in image datasets. In Figure 4, geodesic distance has been applied on the brain region image, but it is seen that geodesic distance transform can be used very conveniently for google earth, street, and city datasets due to the structure of the image. The ISOMAP is applied on the synthetic face dataset and the result is shown in Figure 5. When looking at the graph, it is seen that the images on the right side of the graph look to the right, the ones on the left to the left, the ones on the upper side look up and the ones below look down so faces turn in the light direction. Another approach is when looking at this graph, it can be easily determined where the camera from which the photo was taken is located. For example, on the left side of the graph, the camera is on the right, on the right side the camera is on the left, on the top side the camera is on the bottom, and the bottom side, the camera is on the top. Of course, these approaches are admissible for this dataset, and each dataset is interpreted individually. In a nutshell, is also a very convenient way to interpret the ISOMAP dataset. As mentioned above, firstly the weighted graph is constructed -find the nearest neighbors of each sample- This is done in two ways: As mentioned above, firstly the weighted graph is constructed -find the nearest neighbors of each sample- This is done in two ways: k nearest neighbors Fixed radius, define a radius value, and groups the samples which are in the radius value. After applying one of them above, nearest neighbors are joined via weighted edges. These weights (between the neighbors) will be Euclidean distance. A fully connected weighted graph between the samples is created so far. 2. Using the Floyd Warshall algorithm or Dijkstra’s algorithm, the pairwise distance for all sample pairs in the fully connected weighted graph is calculated using geodesic distance. 3. Multidimensional Scaling (MDS) is applied to get a low dimension version. The following video explains how to find the shortest path using Floyd- Warshall algorithm: As a limitation of the algorithm, if k-nearest neighbors or fixed radius is too small, the weighted graph may be interrupted instead of fully connected. If the k value or fixed radius is too high, this time the weighted graph may be too dense; it causes to choose the wrong distance in the manifold. Isomap can be used in the medical field to make ultrasound & echocardiography images better interpretable with noise removal. The manifold learning algorithm is applied to two-dimensional echocardiography images to discover the relationship between the frames of consecutive cycles of the heart motion.[4] In this approach, each image can be depicted by a point on a reconstructed two-dimensional manifold by the Isomap algorithm and similar points can be related to similar images according to the property of periodic heartbeat cycle stand together.[4] In a study, ISOMAP was used to interpolate the images between the frames of the videos. By applying ISOMAP to each frame in the video, meaningful features are extracted in the low dimension. To insert new images between 2 frames, it is selected images from the original dataset that are mapped in the same area as those 2 frames.[5] The articles cited in the reference can be read to learn more about the above use cases. In the code block below, Isomap is applied to the faces in the fetch_lfw_people dataset and the result is shown in Figure 6. Dataset License: BSD-3-Clause License As in the synthetic dataset example above, the faces are sorted according to light. In the code block below, Isomap has been applied to the number 9 in the MNIST dataset and the result is shown in Figure 7. Dataset License: BSD-3-Clause License It is seen that the tail of the number 9 on the left side of the graph is tilted to the right and the tail of the number 9 shifts from right to left as you go to the right in the graph. Similarly, while the tail is short at the top, it gets longer as you go from top to bottom. ibrahimkovan.medium.com [1] M. Jordan and J. Kleinberg, Nonlinear Dimensionality Reduction. 2007. [2] “kimvwijnen/geodesic_distance_transform: (Geodesic) Distance Transform following Toivanen et al (1996).” https://github.com/kimvwijnen/geodesic_distance_transform (accessed Oct. 25, 2021). [3] “A Global Geometric Framework for Nonlinear Dimensionality Reduction | Request PDF.” https://www.researchgate.net/publication/285599593_A_Global_Geometric_Framework_for_Nonlinear_Dimensionality_Reduction (accessed Oct. 25, 2021). [4] P. Gifani, H. Behnam, A. Shalbaf, and Z. A. Sani, “Noise reduction of echocardiography images using Isomap algorithm,” 2011 1st Middle East Conf. Biomed. Eng. MECBME 2011, pp. 150–153, 2011, doi: 10.1109/MECBME.2011.5752087. [5] S. ROBASZKIEWICZ and S. EL GHAZZAL, “Interpolating images between video frames using non-linear dimensionality reduction,” no. x, p. 5, [Online]. Available: http://cs229.stanford.edu/proj2012/ElGhazzalRobaszkiewicz-InterpolatingImagesBetweenVideoFramesUsingNonLinearDimensionalityReduction.pdf.
[ { "code": null, "e": 786, "s": 172, "text": "Dimensionality reduction methods visualize the dataset and reduce its size, as well as reveal different features in the dataset. For non-linear datasets, dimensionality reduction can be examined under various sub-titles such as distance preservation (Isomap), topology preservation (Locally Linear Embedding). This article explains the theoretical part of isometric feature mapping, one of the distance preservation non-linear dimensionality reduction methods, and includes the interpretation and usage areas of the dataset obtained after dimensionality reduction. Studies are enriched with python implementation." }, { "code": null, "e": 987, "s": 786, "text": "Table of Contents1. Isometric Feature Mapping (ISOMAP)- Geodesic Distance vs Euclidean Distance- Interpretation of the result of ISOMAP2. ISOMAP Algorithm3. Use Cases4. Python Tutorials5. References" }, { "code": null, "e": 1499, "s": 987, "text": "Isomap is a non-linear dimensionality reduction method, which is a different version of metric MDS, and reduces the dimensionality while preserving geodesic distance. The most obvious difference between Metric MDS and ISOMAP: Euclidean distance is preserved in Metric MDS, while geodesic distance is preserved in ISOMAP. So why do we need this? Is it more effective to preserve geodesic distance? Let’s look at Figure 1 to compare Geodesic distance and Euclidean distance as dimensionality reduction techniques." }, { "code": null, "e": 2207, "s": 1499, "text": "While the Euclidean distance calculates only the distance by ignoring the shape of the dataset, the geodesic distance is calculated by passing the shortest path on the dataset. In this case, we can roughly say that the difference between the geodesic distance and the Euclidean distance; while the geodesic distance considers the data adjacent to these data, in the Euclidean distance it is only calculated the shortest linear path. Of course, since our goal is to reduce the dimensionality of the dataset with the least loss, more effective results can be obtained with geodesic distance according to the dataset. The following code block shows the basic implementation of isomap on the Swiss roll dataset:" }, { "code": null, "e": 2310, "s": 2207, "text": "Looking at the ISOMAP and MDS results, it is seen that the Swiss roll can be unrolled by using ISOMAP." }, { "code": null, "e": 3045, "s": 2310, "text": "The red data points are shown as ISOMAP results in Figure 2(right), taking into account the neighborhood distance between them. When calculating the Euclidean distance between 2 points, the shortest distance is obtained (linear distance). In the geodesic distance, the shortest path passing over the dataset is obtained. To find this out, a certain value of k is determined and k-nearest is connected to each other by neighbors and the chain continues. In ISOMAP provided in the Sklearn library, it can be set with n_neighbors=5. The default value is 5. The other way to find the shortest path is to draw the circle centered on the initial data and connect each data point by an edge to all of the other data points within the circle." }, { "code": null, "e": 3279, "s": 3045, "text": "To summarize the difference between geodesic distance and Euclidean distance, let’s take a look at their transformed form. Figure 3 illustrates the comparison of tumor tissue which is applied Euclidean distance and geodesic distance." }, { "code": null, "e": 3366, "s": 3279, "text": "In Figure 4, the same procedures are applied to the damaged brain region and compared." }, { "code": null, "e": 3744, "s": 3366, "text": "In the above images, it is seen that geodesic distance can make much more effective discrimination than the Euclidean distance in image datasets. In Figure 4, geodesic distance has been applied on the brain region image, but it is seen that geodesic distance transform can be used very conveniently for google earth, street, and city datasets due to the structure of the image." }, { "code": null, "e": 3833, "s": 3744, "text": "The ISOMAP is applied on the synthetic face dataset and the result is shown in Figure 5." }, { "code": null, "e": 4603, "s": 3833, "text": "When looking at the graph, it is seen that the images on the right side of the graph look to the right, the ones on the left to the left, the ones on the upper side look up and the ones below look down so faces turn in the light direction. Another approach is when looking at this graph, it can be easily determined where the camera from which the photo was taken is located. For example, on the left side of the graph, the camera is on the right, on the right side the camera is on the left, on the top side the camera is on the bottom, and the bottom side, the camera is on the top. Of course, these approaches are admissible for this dataset, and each dataset is interpreted individually. In a nutshell, is also a very convenient way to interpret the ISOMAP dataset." }, { "code": null, "e": 4735, "s": 4603, "text": "As mentioned above, firstly the weighted graph is constructed -find the nearest neighbors of each sample- This is done in two ways:" }, { "code": null, "e": 4867, "s": 4735, "text": "As mentioned above, firstly the weighted graph is constructed -find the nearest neighbors of each sample- This is done in two ways:" }, { "code": null, "e": 4887, "s": 4867, "text": "k nearest neighbors" }, { "code": null, "e": 4978, "s": 4887, "text": "Fixed radius, define a radius value, and groups the samples which are in the radius value." }, { "code": null, "e": 5199, "s": 4978, "text": "After applying one of them above, nearest neighbors are joined via weighted edges. These weights (between the neighbors) will be Euclidean distance. A fully connected weighted graph between the samples is created so far." }, { "code": null, "e": 5382, "s": 5199, "text": "2. Using the Floyd Warshall algorithm or Dijkstra’s algorithm, the pairwise distance for all sample pairs in the fully connected weighted graph is calculated using geodesic distance." }, { "code": null, "e": 5459, "s": 5382, "text": "3. Multidimensional Scaling (MDS) is applied to get a low dimension version." }, { "code": null, "e": 5551, "s": 5459, "text": "The following video explains how to find the shortest path using Floyd- Warshall algorithm:" }, { "code": null, "e": 5851, "s": 5551, "text": "As a limitation of the algorithm, if k-nearest neighbors or fixed radius is too small, the weighted graph may be interrupted instead of fully connected. If the k value or fixed radius is too high, this time the weighted graph may be too dense; it causes to choose the wrong distance in the manifold." }, { "code": null, "e": 6406, "s": 5851, "text": "Isomap can be used in the medical field to make ultrasound & echocardiography images better interpretable with noise removal. The manifold learning algorithm is applied to two-dimensional echocardiography images to discover the relationship between the frames of consecutive cycles of the heart motion.[4] In this approach, each image can be depicted by a point on a reconstructed two-dimensional manifold by the Isomap algorithm and similar points can be related to similar images according to the property of periodic heartbeat cycle stand together.[4]" }, { "code": null, "e": 6739, "s": 6406, "text": "In a study, ISOMAP was used to interpolate the images between the frames of the videos. By applying ISOMAP to each frame in the video, meaningful features are extracted in the low dimension. To insert new images between 2 frames, it is selected images from the original dataset that are mapped in the same area as those 2 frames.[5]" }, { "code": null, "e": 6828, "s": 6739, "text": "The articles cited in the reference can be read to learn more about the above use cases." }, { "code": null, "e": 6953, "s": 6828, "text": "In the code block below, Isomap is applied to the faces in the fetch_lfw_people dataset and the result is shown in Figure 6." }, { "code": null, "e": 6991, "s": 6953, "text": "Dataset License: BSD-3-Clause License" }, { "code": null, "e": 7075, "s": 6991, "text": "As in the synthetic dataset example above, the faces are sorted according to light." }, { "code": null, "e": 7198, "s": 7075, "text": "In the code block below, Isomap has been applied to the number 9 in the MNIST dataset and the result is shown in Figure 7." }, { "code": null, "e": 7236, "s": 7198, "text": "Dataset License: BSD-3-Clause License" }, { "code": null, "e": 7514, "s": 7236, "text": "It is seen that the tail of the number 9 on the left side of the graph is tilted to the right and the tail of the number 9 shifts from right to left as you go to the right in the graph. Similarly, while the tail is short at the top, it gets longer as you go from top to bottom." }, { "code": null, "e": 7538, "s": 7514, "text": "ibrahimkovan.medium.com" }, { "code": null, "e": 7612, "s": 7538, "text": "[1] M. Jordan and J. Kleinberg, Nonlinear Dimensionality Reduction. 2007." }, { "code": null, "e": 7805, "s": 7612, "text": "[2] “kimvwijnen/geodesic_distance_transform: (Geodesic) Distance Transform following Toivanen et al (1996).” https://github.com/kimvwijnen/geodesic_distance_transform (accessed Oct. 25, 2021)." }, { "code": null, "e": 8039, "s": 7805, "text": "[3] “A Global Geometric Framework for Nonlinear Dimensionality Reduction | Request PDF.” https://www.researchgate.net/publication/285599593_A_Global_Geometric_Framework_for_Nonlinear_Dimensionality_Reduction (accessed Oct. 25, 2021)." }, { "code": null, "e": 8268, "s": 8039, "text": "[4] P. Gifani, H. Behnam, A. Shalbaf, and Z. A. Sani, “Noise reduction of echocardiography images using Isomap algorithm,” 2011 1st Middle East Conf. Biomed. Eng. MECBME 2011, pp. 150–153, 2011, doi: 10.1109/MECBME.2011.5752087." } ]
Augmenting Neural Networks with Constrained Optimization | by Deepanshu Jindal | Towards Data Science
Adding constraints which incorporate domain knowledge is an interesting way to augment neural networks with world knowledge and improve their performance, especially in low data settings. Use of constraint optimization and/or logic modules on top of neural networks has become a fairly common practice for many structured prediction of tasks in NLP and Computer Vision. For example: BiLSTM-CRF for sequence to sequence tasks in NLP, or use of CRF with potential function coming from a neural network for image segmentation tasks. Nowadays, there has been a lot of active research into incorporating these optimization modules directly into the neural networks thus allowing the networks to train in an end to end fashion. This article explores the popular methods to incorporate constraints in a neural architecture and provides a survey of recent advances in trying to learn the constraints from the data. There are four popular methods by which one can try to incorporate domain constraints into the neural architecture: Using constrained optimization layer on top of neural network Adding constraint violation penalty Constraint enforcing architecture design Data augmentation Constrained Optimization layers Some of the popular constrained optimization layers are Conditional Random Field, Viterbi Decoding, Integer Linear Programming (ILP) or Non Linear Programming (NLP) solvers. So what happens in incorporating constraints via constrained optimization layers is that you take the output of neural network and use this output as a potential function for the optimization layer which enforces constraints. Let’s understand it using a popular architecture that uses this technique — BiLSTM CRF. Suppose you are given a sentence and you have to do Part-of-Speech tagging on it. A Bidirectional LSTM (or BiLSTM) architecture is commonly used for such sequence tagging task. BiLSTM takes into account the word to be tagged along with words preceding and following it to generated a local embedding that is used to predict the tag for the current word. Now we can see that there are a lot of natural constraints over the output space. Say for example one does not frequently see a noun followed by an adjective, or an adverb followed by adverb (all these are soft constraints as some exceptions exist). One would think that neural architecture should be aware of these constraints but it is often not the case. This is illustrated by CRFs performing better than BiLSTM. An innovative approach was to combine the strengths of neural models with CRF and this gave rise to BiLSTM-CRF or LSTM-CRF architectures. The rich embedding produced by BiLSTM acts as feature for CRF layer. Read more about it here. Similar techniques have also been employed in computer vision, popularly for segmentation tasks by combining HMM or CRFs with neural network. See an example here. Constraint Violation Penalty Another popular method to incorporate constraints is using a constraint violation penalty as a regularization method. We introduce an auxiliary loss term corresponding to constraint violation penalty. This added term gives a differentiable measure of how close the neural network is to satisfying constraints. An example of such constraint term can be found here. The addition of such terms also opens up an avenue for semi-supervised learning, as this regularization term can be used to align the model to be more constraint-satisfying even without output labels. In fact, it has been shown that for some problems, any non-trivial hypothesis that satisfies a given set of constraints is a good approximation to the optimal hypothesis. The search for this hypothesis can be done in a setting with no data (or extremely low amounts of data). For further references for this see Label-Free Supervision of Neural Networks with Physics and Domain Knowledge. Neural Architecture Design to enforce constraints This has been one of the earliest yet most elusive approaches to enforcing constraints. In this approach, we design the architecture so that constraints are enforced automatically. We can get an intuition for such method using a recent work advancing this approach : Augmenting Neural Networks with First-order Logic. The work is restricted to enforcing constraints to neurons which have semantic grounding (thus, restricting the approach to output neurons or attention neurons for most practical networks). Moreover, the constraints are of the form L -> R . So whenever the activation for L is high the activation for R should also be high, and thus a bias term corresponding to activation of L gets added to neuron responsible for R, thereby pushing R to be higher whenever L is high. Data Augmentation to enforce constraints One can also enforce constraints by augmenting data to incentivize networks to be more mindful of constraints. Again to gain an intuition of this approach let’s consider A Logic-Driven Framework for Consistency of Neural Models. So the group worked with SNLI task. Given two statements P and Q one needs to tell if P entails Q, P contradicts Q or the two statements are neutral. Naturally one can see transitivity for entailment and commutativity for contradictions. However, the paper shows that SOTA models for SNLI often do not enforce these consistencies. Thus, the main contribution of paper is to use data augmentation so that these consistencies are enforced. For example, if (P, Q) is in dataset with label “contradicts”, then (Q,P) should also be added with label “contradicts”, thus enforcing the model to learn commutativity. This is a fairly nascent area of research where we make a neural model learn constraints from the data itself with limited human supervision. We will focus on two works in this domain. Adversarial Constraint Learning for Structured Prediction, Ren et al They provide an innovative semi-supervised learning approach for structured prediction tasks. They work with assumption that lots of output labels following the distribution of real output space are available (perhaps from a simulator). Then they train a generator network that can generate output labels which can mimic the real output label space using adversarial training techniques. They further tune this generator using limited amounts of labelled training data to associate input labels to output labels. SATNet: Bridging deep learning and logical reasoning using a differentiable satisfiability solver, Wang et al This is a line of research which I personally find very amazing. Basically, they try to build an architecture which can learn the constraints from the data itself. Moreover, they design the architecture such that it can be trained using backpropogation, and thus can be plugged on top of any deep learning architecture for constraint optimization task. They demonstrate the model by learning to solve Sudoku, by just using instances of Sudoku, with no human supervision for identifying constraints. They try to learn a MAX2SAT instance which models the problem at hand by formulating it as a semi-definite Programming instance. In the forward pass they solve the current SDP instance to find variable assignment that optimizes the SDP. Then they compute loss on this variable assignment and backpropogate to modify the SDP instance. Forward Pass : Solve current approximated problemBackward Pass: Improve approximated problem Now, the great thing about having the ability to backpropograte is that you can plug this module on top of any deep learning architecture. Consider that you are given image of a Sudoku, then you can have a CNN to recognize digits, and on top of that you can have a layer of SATNet which will solve the decoded sudoku instance. This entire architecture can be trained end-to-end. Adding constraints to neural architectures not only helps in improving performance, but it also provides newer approaches to make use of unlabelled data, prunes output space thus improving learnability of model and increases generalization. Also imposing constraint consistency helps make the network robust and reliable. This survey of architectures and algorithms is in no way exhaustive, but I hope that it gives a flavor of most of the common constraints incorporating architectures and algorithms.
[ { "code": null, "e": 360, "s": 172, "text": "Adding constraints which incorporate domain knowledge is an interesting way to augment neural networks with world knowledge and improve their performance, especially in low data settings." }, { "code": null, "e": 702, "s": 360, "text": "Use of constraint optimization and/or logic modules on top of neural networks has become a fairly common practice for many structured prediction of tasks in NLP and Computer Vision. For example: BiLSTM-CRF for sequence to sequence tasks in NLP, or use of CRF with potential function coming from a neural network for image segmentation tasks." }, { "code": null, "e": 1079, "s": 702, "text": "Nowadays, there has been a lot of active research into incorporating these optimization modules directly into the neural networks thus allowing the networks to train in an end to end fashion. This article explores the popular methods to incorporate constraints in a neural architecture and provides a survey of recent advances in trying to learn the constraints from the data." }, { "code": null, "e": 1195, "s": 1079, "text": "There are four popular methods by which one can try to incorporate domain constraints into the neural architecture:" }, { "code": null, "e": 1257, "s": 1195, "text": "Using constrained optimization layer on top of neural network" }, { "code": null, "e": 1293, "s": 1257, "text": "Adding constraint violation penalty" }, { "code": null, "e": 1334, "s": 1293, "text": "Constraint enforcing architecture design" }, { "code": null, "e": 1352, "s": 1334, "text": "Data augmentation" }, { "code": null, "e": 1384, "s": 1352, "text": "Constrained Optimization layers" }, { "code": null, "e": 1558, "s": 1384, "text": "Some of the popular constrained optimization layers are Conditional Random Field, Viterbi Decoding, Integer Linear Programming (ILP) or Non Linear Programming (NLP) solvers." }, { "code": null, "e": 1784, "s": 1558, "text": "So what happens in incorporating constraints via constrained optimization layers is that you take the output of neural network and use this output as a potential function for the optimization layer which enforces constraints." }, { "code": null, "e": 1872, "s": 1784, "text": "Let’s understand it using a popular architecture that uses this technique — BiLSTM CRF." }, { "code": null, "e": 2226, "s": 1872, "text": "Suppose you are given a sentence and you have to do Part-of-Speech tagging on it. A Bidirectional LSTM (or BiLSTM) architecture is commonly used for such sequence tagging task. BiLSTM takes into account the word to be tagged along with words preceding and following it to generated a local embedding that is used to predict the tag for the current word." }, { "code": null, "e": 2643, "s": 2226, "text": "Now we can see that there are a lot of natural constraints over the output space. Say for example one does not frequently see a noun followed by an adjective, or an adverb followed by adverb (all these are soft constraints as some exceptions exist). One would think that neural architecture should be aware of these constraints but it is often not the case. This is illustrated by CRFs performing better than BiLSTM." }, { "code": null, "e": 2875, "s": 2643, "text": "An innovative approach was to combine the strengths of neural models with CRF and this gave rise to BiLSTM-CRF or LSTM-CRF architectures. The rich embedding produced by BiLSTM acts as feature for CRF layer. Read more about it here." }, { "code": null, "e": 3038, "s": 2875, "text": "Similar techniques have also been employed in computer vision, popularly for segmentation tasks by combining HMM or CRFs with neural network. See an example here." }, { "code": null, "e": 3067, "s": 3038, "text": "Constraint Violation Penalty" }, { "code": null, "e": 3431, "s": 3067, "text": "Another popular method to incorporate constraints is using a constraint violation penalty as a regularization method. We introduce an auxiliary loss term corresponding to constraint violation penalty. This added term gives a differentiable measure of how close the neural network is to satisfying constraints. An example of such constraint term can be found here." }, { "code": null, "e": 4021, "s": 3431, "text": "The addition of such terms also opens up an avenue for semi-supervised learning, as this regularization term can be used to align the model to be more constraint-satisfying even without output labels. In fact, it has been shown that for some problems, any non-trivial hypothesis that satisfies a given set of constraints is a good approximation to the optimal hypothesis. The search for this hypothesis can be done in a setting with no data (or extremely low amounts of data). For further references for this see Label-Free Supervision of Neural Networks with Physics and Domain Knowledge." }, { "code": null, "e": 4071, "s": 4021, "text": "Neural Architecture Design to enforce constraints" }, { "code": null, "e": 4858, "s": 4071, "text": "This has been one of the earliest yet most elusive approaches to enforcing constraints. In this approach, we design the architecture so that constraints are enforced automatically. We can get an intuition for such method using a recent work advancing this approach : Augmenting Neural Networks with First-order Logic. The work is restricted to enforcing constraints to neurons which have semantic grounding (thus, restricting the approach to output neurons or attention neurons for most practical networks). Moreover, the constraints are of the form L -> R . So whenever the activation for L is high the activation for R should also be high, and thus a bias term corresponding to activation of L gets added to neuron responsible for R, thereby pushing R to be higher whenever L is high." }, { "code": null, "e": 4899, "s": 4858, "text": "Data Augmentation to enforce constraints" }, { "code": null, "e": 5736, "s": 4899, "text": "One can also enforce constraints by augmenting data to incentivize networks to be more mindful of constraints. Again to gain an intuition of this approach let’s consider A Logic-Driven Framework for Consistency of Neural Models. So the group worked with SNLI task. Given two statements P and Q one needs to tell if P entails Q, P contradicts Q or the two statements are neutral. Naturally one can see transitivity for entailment and commutativity for contradictions. However, the paper shows that SOTA models for SNLI often do not enforce these consistencies. Thus, the main contribution of paper is to use data augmentation so that these consistencies are enforced. For example, if (P, Q) is in dataset with label “contradicts”, then (Q,P) should also be added with label “contradicts”, thus enforcing the model to learn commutativity." }, { "code": null, "e": 5921, "s": 5736, "text": "This is a fairly nascent area of research where we make a neural model learn constraints from the data itself with limited human supervision. We will focus on two works in this domain." }, { "code": null, "e": 5990, "s": 5921, "text": "Adversarial Constraint Learning for Structured Prediction, Ren et al" }, { "code": null, "e": 6503, "s": 5990, "text": "They provide an innovative semi-supervised learning approach for structured prediction tasks. They work with assumption that lots of output labels following the distribution of real output space are available (perhaps from a simulator). Then they train a generator network that can generate output labels which can mimic the real output label space using adversarial training techniques. They further tune this generator using limited amounts of labelled training data to associate input labels to output labels." }, { "code": null, "e": 6613, "s": 6503, "text": "SATNet: Bridging deep learning and logical reasoning using a differentiable satisfiability solver, Wang et al" }, { "code": null, "e": 7112, "s": 6613, "text": "This is a line of research which I personally find very amazing. Basically, they try to build an architecture which can learn the constraints from the data itself. Moreover, they design the architecture such that it can be trained using backpropogation, and thus can be plugged on top of any deep learning architecture for constraint optimization task. They demonstrate the model by learning to solve Sudoku, by just using instances of Sudoku, with no human supervision for identifying constraints." }, { "code": null, "e": 7446, "s": 7112, "text": "They try to learn a MAX2SAT instance which models the problem at hand by formulating it as a semi-definite Programming instance. In the forward pass they solve the current SDP instance to find variable assignment that optimizes the SDP. Then they compute loss on this variable assignment and backpropogate to modify the SDP instance." }, { "code": null, "e": 7539, "s": 7446, "text": "Forward Pass : Solve current approximated problemBackward Pass: Improve approximated problem" }, { "code": null, "e": 7918, "s": 7539, "text": "Now, the great thing about having the ability to backpropograte is that you can plug this module on top of any deep learning architecture. Consider that you are given image of a Sudoku, then you can have a CNN to recognize digits, and on top of that you can have a layer of SATNet which will solve the decoded sudoku instance. This entire architecture can be trained end-to-end." }, { "code": null, "e": 8240, "s": 7918, "text": "Adding constraints to neural architectures not only helps in improving performance, but it also provides newer approaches to make use of unlabelled data, prunes output space thus improving learnability of model and increases generalization. Also imposing constraint consistency helps make the network robust and reliable." } ]
Next-Generation Sequencing Data Analysis With PySpark | by Aneesh Panoli | Towards Data Science
With DNA, you have to be able to tell which genes are turned on or off. Current DNA sequencing cannot do that. The next generation of DNA sequencing needs to be able to do this. If somebody invents this, then we can start to very precisely identify cures for diseases. — Elon Musk The rapid growth of Next Generation Sequencing technologies such as single-cell RNA sequencing(scRNA-seq) demands efficient parallel processing and analysis of big data. Hadoop and Spark are the goto opensource frameworks for storing and processing massive datasets. The most significant advantage of Spark is its iterative analytics capability combined with in-memory computing architecture. Calling .cache() on a resilient distributed dataset (RDD) effectively saves it in memory and makes it instantly available for computation, thus the subsequent filter, map, and reduce tasks become instantaneous. Spark has its query language known as Spark SQL, and its MLlib library is highly desirable for machine learning tasks. The scRNA-seq can do what Musk pointed out — figuring out which genes are turned on/off at cellular resolution. But it’s not the silver bullet — because the regulation of gene expression doesn’t stop at the transcription level. The mRNA or the messenger RNA — a proxy of protein-coding regions of the gene — also contains sequences that determine the level of ribosomal protein synthesis. The expressed protein can also undergo a series of post-translational modifications that can activate or repress it. Over the years, I have come to love Google Colab for all my quick and dirty project prototyping. With Colab, you can skip all the initial steps required to get your project off the ground. No need to set up a virtual environment, dependencies, etc. Also, Colab comes with free GPU/TPU for all your machine learning needs. First, go to Colab following the link above and fire up a new Python 3 notebook. PySpark requires Java (Java 1.8) and Scala, so next, we will install them. Now install PySpark, here we will install pyspark[sql] because it will allow us to deal with .gtf, .bed, .bam, and .sam files later. !pip install pyspark[sql] Sequence data from published research is available for download from SRA. Before you can use the sra file, you need to extract .fastq from it using the fastq-dump tool of SRA toolkit. If available, instead of SRA files, you may directly download .fastq, .fa.gz, or .fastq.gz formats, these files can be directly read with PySpark. Be mindful of the file size. At the core of PySpark is the resilient distributed dataset (RDD), it represents an immutable partitioned collection of your data that can be operated in parallel. You begin by initializing a spark context. import pyspark as sparkfrom pyspark import SparkConfsc = spark.SparkContext.getOrCreate(conf=set_conf()) It’s also a good practice to pass in a configuration that is optimal for your workflow. Now it’s time to read and transform our data to RDD. data = sc.textFile(path/to/fastq)# in case you have a list of sequencesdata = sc.parallelize(your_list)# lets take a look at the first read# each read in fastq is represented by 4lines data.take(4) Let’s extract just the sequences from the data. sequences = data.filter(lambda x: x.isalpha())sequences.count() # outputs the size of RDD - the number of reads# => 1843156 Take a look at the first four reads. sequences.take(4) How about finding the length of the reads? Takes only a line of code! read_lengths = sequences.map(lambda seq: len(seq))read_lengths.take(10) Next, compute the average length of the reads. len_sum = read_lengths.reduce(lambda a, b: a+b)len_sum//read_lengths.count()# => 564 Finally, let’s do the base count. First, we will split the sequences to individual bases using list(), then we use flatMap to merge the lists to a single one. Then we go through individual bases and create a tuple with the first element as the base and ‘1’ as its value. Then we use reduceByKey to aggregate values by the first element — key — of the tuple. base_count = sequences.flatMap(lambda seq: list(seq))\ .map(lambda c: (c, 1)) \ .reduceByKey(lambda a, b: a+b)base_count We only care about A, T, G, and C here; the rest are artifacts. As you can see, these sequences are GC rich. I have only scratched the surface here, and there are a lot of cool things you can do with PySpark. I will come back with more in another piece. You can find the code examples in this colab notebook I hope I have covered enough basics here to get you started. Talk to you next time.
[ { "code": null, "e": 453, "s": 172, "text": "With DNA, you have to be able to tell which genes are turned on or off. Current DNA sequencing cannot do that. The next generation of DNA sequencing needs to be able to do this. If somebody invents this, then we can start to very precisely identify cures for diseases. — Elon Musk" }, { "code": null, "e": 1176, "s": 453, "text": "The rapid growth of Next Generation Sequencing technologies such as single-cell RNA sequencing(scRNA-seq) demands efficient parallel processing and analysis of big data. Hadoop and Spark are the goto opensource frameworks for storing and processing massive datasets. The most significant advantage of Spark is its iterative analytics capability combined with in-memory computing architecture. Calling .cache() on a resilient distributed dataset (RDD) effectively saves it in memory and makes it instantly available for computation, thus the subsequent filter, map, and reduce tasks become instantaneous. Spark has its query language known as Spark SQL, and its MLlib library is highly desirable for machine learning tasks." }, { "code": null, "e": 1682, "s": 1176, "text": "The scRNA-seq can do what Musk pointed out — figuring out which genes are turned on/off at cellular resolution. But it’s not the silver bullet — because the regulation of gene expression doesn’t stop at the transcription level. The mRNA or the messenger RNA — a proxy of protein-coding regions of the gene — also contains sequences that determine the level of ribosomal protein synthesis. The expressed protein can also undergo a series of post-translational modifications that can activate or repress it." }, { "code": null, "e": 2004, "s": 1682, "text": "Over the years, I have come to love Google Colab for all my quick and dirty project prototyping. With Colab, you can skip all the initial steps required to get your project off the ground. No need to set up a virtual environment, dependencies, etc. Also, Colab comes with free GPU/TPU for all your machine learning needs." }, { "code": null, "e": 2160, "s": 2004, "text": "First, go to Colab following the link above and fire up a new Python 3 notebook. PySpark requires Java (Java 1.8) and Scala, so next, we will install them." }, { "code": null, "e": 2293, "s": 2160, "text": "Now install PySpark, here we will install pyspark[sql] because it will allow us to deal with .gtf, .bed, .bam, and .sam files later." }, { "code": null, "e": 2319, "s": 2293, "text": "!pip install pyspark[sql]" }, { "code": null, "e": 2650, "s": 2319, "text": "Sequence data from published research is available for download from SRA. Before you can use the sra file, you need to extract .fastq from it using the fastq-dump tool of SRA toolkit. If available, instead of SRA files, you may directly download .fastq, .fa.gz, or .fastq.gz formats, these files can be directly read with PySpark." }, { "code": null, "e": 2679, "s": 2650, "text": "Be mindful of the file size." }, { "code": null, "e": 2843, "s": 2679, "text": "At the core of PySpark is the resilient distributed dataset (RDD), it represents an immutable partitioned collection of your data that can be operated in parallel." }, { "code": null, "e": 2886, "s": 2843, "text": "You begin by initializing a spark context." }, { "code": null, "e": 2991, "s": 2886, "text": "import pyspark as sparkfrom pyspark import SparkConfsc = spark.SparkContext.getOrCreate(conf=set_conf())" }, { "code": null, "e": 3079, "s": 2991, "text": "It’s also a good practice to pass in a configuration that is optimal for your workflow." }, { "code": null, "e": 3132, "s": 3079, "text": "Now it’s time to read and transform our data to RDD." }, { "code": null, "e": 3330, "s": 3132, "text": "data = sc.textFile(path/to/fastq)# in case you have a list of sequencesdata = sc.parallelize(your_list)# lets take a look at the first read# each read in fastq is represented by 4lines data.take(4)" }, { "code": null, "e": 3378, "s": 3330, "text": "Let’s extract just the sequences from the data." }, { "code": null, "e": 3502, "s": 3378, "text": "sequences = data.filter(lambda x: x.isalpha())sequences.count() # outputs the size of RDD - the number of reads# => 1843156" }, { "code": null, "e": 3539, "s": 3502, "text": "Take a look at the first four reads." }, { "code": null, "e": 3557, "s": 3539, "text": "sequences.take(4)" }, { "code": null, "e": 3627, "s": 3557, "text": "How about finding the length of the reads? Takes only a line of code!" }, { "code": null, "e": 3699, "s": 3627, "text": "read_lengths = sequences.map(lambda seq: len(seq))read_lengths.take(10)" }, { "code": null, "e": 3746, "s": 3699, "text": "Next, compute the average length of the reads." }, { "code": null, "e": 3831, "s": 3746, "text": "len_sum = read_lengths.reduce(lambda a, b: a+b)len_sum//read_lengths.count()# => 564" }, { "code": null, "e": 4189, "s": 3831, "text": "Finally, let’s do the base count. First, we will split the sequences to individual bases using list(), then we use flatMap to merge the lists to a single one. Then we go through individual bases and create a tuple with the first element as the base and ‘1’ as its value. Then we use reduceByKey to aggregate values by the first element — key — of the tuple." }, { "code": null, "e": 4354, "s": 4189, "text": "base_count = sequences.flatMap(lambda seq: list(seq))\\ .map(lambda c: (c, 1)) \\ .reduceByKey(lambda a, b: a+b)base_count" }, { "code": null, "e": 4463, "s": 4354, "text": "We only care about A, T, G, and C here; the rest are artifacts. As you can see, these sequences are GC rich." }, { "code": null, "e": 4608, "s": 4463, "text": "I have only scratched the surface here, and there are a lot of cool things you can do with PySpark. I will come back with more in another piece." }, { "code": null, "e": 4662, "s": 4608, "text": "You can find the code examples in this colab notebook" } ]
Cumulative product of digits of all numbers in the given range - GeeksforGeeks
20 Apr, 2021 Given two integers L and R, the task is to find the cumulative product of digits (i.e. product of the product of digits) of all Natural numbers in the range L to R. Examples: Input: L = 2, R = 5 Output: 14 Explanation: 2 * 3 * 4 * 5 = 120Input: L = 11, R = 15 Output: 120 Explanation: (1*1) * (1*2) * (1*3) * (1*4) * (1*5) = 1 * 2 * 3 * 4 * 5 = 120 Approach:To solve the problem mentioned above we have to observe that if: If the difference between L and R is greater than 9 then the product is 0 because there appears a digit 0 in every number after intervals of 9. Otherwise, We can find the product in a loop from L to R, the loop will run a maximum of 9 times. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ program to print the product// of all numbers in range L and R #include <bits/stdc++.h>using namespace std; // Function to get product of digitsint getProduct(int n){ int product = 1; while (n != 0) { product = product * (n % 10); n = n / 10; } return product;} // Function to find the product of digits// of all natural numbers in range L to Rint productinRange(int l, int r){ if (r - l > 9) return 0; else { int p = 1; // Iterate between L to R for (int i = l; i <= r; i++) p *= getProduct(i); return p; }} // Driver Codeint main(){ int l = 11, r = 15; cout << productinRange(l, r) << endl; l = 1, r = 15; cout << productinRange(l, r); return 0;} // Java program to print the product// of all numbers in range L and Rclass GFG{ // Function to get product of digitsstatic int getProduct(int n){ int product = 1; while (n != 0) { product = product * (n % 10); n = n / 10; } return product;} // Function to find the product of digits// of all natural numbers in range L to Rstatic int productinRange(int l, int r){ if (r - l > 9) return 0; else { int p = 1; // Iterate between L to R for (int i = l; i <= r; i++) p *= getProduct(i); return p; }} // Driver Codepublic static void main(String[] args){ int l = 11, r = 15; System.out.print(productinRange(l, r) + "\n"); l = 1; r = 15; System.out.print(productinRange(l, r));}} // This code is contributed by Rohit_ranjan # Python3 program to print the product# of all numbers in range L and R # Function to get product of digitsdef getProduct(n): product = 1 while (n != 0): product = product * (n % 10) n = int(n / 10) return product # Function to find the product of digits# of all natural numbers in range L to Rdef productinRange(l, r): if (r - l > 9): return 0 else: p = 1 # Iterate between L to R for i in range(l, r + 1): p = p * getProduct(i) return p # Driver Codel = 11r = 15print (productinRange(l, r), end='\n') l = 1r = 15print (productinRange(l, r)) # This code is contributed by PratikBasu // C# program to print the product// of all numbers in range L and Rusing System; class GFG{ // Function to get product of digitsstatic int getProduct(int n){ int product = 1; while (n != 0) { product = product * (n % 10); n = n / 10; } return product;} // Function to find the product of digits// of all natural numbers in range L to Rstatic int productinRange(int l, int r){ if (r - l > 9) return 0; else { int p = 1; // Iterate between L to R for(int i = l; i <= r; i++) p *= getProduct(i); return p; }} // Driver Codepublic static void Main(String[] args){ int l = 11, r = 15; Console.Write(productinRange(l, r) + "\n"); l = 1; r = 15; Console.Write(productinRange(l, r));}} // This code is contributed by amal kumar choubey <script> // Javascript program to print the product// of all numbers in range L and R // Function to get product of digitsfunction getProduct(n){ var product = 1; while (n != 0) { product = product * (n % 10); n = parseInt(n / 10); } return product;} // Function to find the product of digits// of all natural numbers in range L to Rfunction productinRange(l, r){ if (r - l > 9) return 0; else { var p = 1; // Iterate between L to R for (var i = l; i <= r; i++) p *= getProduct(i); return p; }} // Driver Codevar l = 11, r = 15;document.write( productinRange(l, r)+ "<br>");l = 1, r = 15;document.write( productinRange(l, r)); // This code is contributed by rutvik_56.</script> 120 0 Rohit_ranjan PratikBasu Amal Kumar Choubey rutvik_56 array-range-queries Natural Numbers number-digits Arrays Mathematical Pattern Searching Arrays Mathematical Pattern Searching Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Maximum and minimum of an array using minimum number of comparisons Multidimensional Arrays in Java Introduction to Arrays Python | Using 2D arrays/lists the right way Linked List vs Array 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": 25028, "s": 25000, "text": "\n20 Apr, 2021" }, { "code": null, "e": 25205, "s": 25028, "text": "Given two integers L and R, the task is to find the cumulative product of digits (i.e. product of the product of digits) of all Natural numbers in the range L to R. Examples: " }, { "code": null, "e": 25381, "s": 25205, "text": "Input: L = 2, R = 5 Output: 14 Explanation: 2 * 3 * 4 * 5 = 120Input: L = 11, R = 15 Output: 120 Explanation: (1*1) * (1*2) * (1*3) * (1*4) * (1*5) = 1 * 2 * 3 * 4 * 5 = 120 " }, { "code": null, "e": 25459, "s": 25383, "text": "Approach:To solve the problem mentioned above we have to observe that if: " }, { "code": null, "e": 25603, "s": 25459, "text": "If the difference between L and R is greater than 9 then the product is 0 because there appears a digit 0 in every number after intervals of 9." }, { "code": null, "e": 25701, "s": 25603, "text": "Otherwise, We can find the product in a loop from L to R, the loop will run a maximum of 9 times." }, { "code": null, "e": 25754, "s": 25701, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 25758, "s": 25754, "text": "C++" }, { "code": null, "e": 25763, "s": 25758, "text": "Java" }, { "code": null, "e": 25771, "s": 25763, "text": "Python3" }, { "code": null, "e": 25774, "s": 25771, "text": "C#" }, { "code": null, "e": 25785, "s": 25774, "text": "Javascript" }, { "code": "// C++ program to print the product// of all numbers in range L and R #include <bits/stdc++.h>using namespace std; // Function to get product of digitsint getProduct(int n){ int product = 1; while (n != 0) { product = product * (n % 10); n = n / 10; } return product;} // Function to find the product of digits// of all natural numbers in range L to Rint productinRange(int l, int r){ if (r - l > 9) return 0; else { int p = 1; // Iterate between L to R for (int i = l; i <= r; i++) p *= getProduct(i); return p; }} // Driver Codeint main(){ int l = 11, r = 15; cout << productinRange(l, r) << endl; l = 1, r = 15; cout << productinRange(l, r); return 0;}", "e": 26553, "s": 25785, "text": null }, { "code": "// Java program to print the product// of all numbers in range L and Rclass GFG{ // Function to get product of digitsstatic int getProduct(int n){ int product = 1; while (n != 0) { product = product * (n % 10); n = n / 10; } return product;} // Function to find the product of digits// of all natural numbers in range L to Rstatic int productinRange(int l, int r){ if (r - l > 9) return 0; else { int p = 1; // Iterate between L to R for (int i = l; i <= r; i++) p *= getProduct(i); return p; }} // Driver Codepublic static void main(String[] args){ int l = 11, r = 15; System.out.print(productinRange(l, r) + \"\\n\"); l = 1; r = 15; System.out.print(productinRange(l, r));}} // This code is contributed by Rohit_ranjan", "e": 27376, "s": 26553, "text": null }, { "code": "# Python3 program to print the product# of all numbers in range L and R # Function to get product of digitsdef getProduct(n): product = 1 while (n != 0): product = product * (n % 10) n = int(n / 10) return product # Function to find the product of digits# of all natural numbers in range L to Rdef productinRange(l, r): if (r - l > 9): return 0 else: p = 1 # Iterate between L to R for i in range(l, r + 1): p = p * getProduct(i) return p # Driver Codel = 11r = 15print (productinRange(l, r), end='\\n') l = 1r = 15print (productinRange(l, r)) # This code is contributed by PratikBasu", "e": 28043, "s": 27376, "text": null }, { "code": "// C# program to print the product// of all numbers in range L and Rusing System; class GFG{ // Function to get product of digitsstatic int getProduct(int n){ int product = 1; while (n != 0) { product = product * (n % 10); n = n / 10; } return product;} // Function to find the product of digits// of all natural numbers in range L to Rstatic int productinRange(int l, int r){ if (r - l > 9) return 0; else { int p = 1; // Iterate between L to R for(int i = l; i <= r; i++) p *= getProduct(i); return p; }} // Driver Codepublic static void Main(String[] args){ int l = 11, r = 15; Console.Write(productinRange(l, r) + \"\\n\"); l = 1; r = 15; Console.Write(productinRange(l, r));}} // This code is contributed by amal kumar choubey", "e": 28883, "s": 28043, "text": null }, { "code": "<script> // Javascript program to print the product// of all numbers in range L and R // Function to get product of digitsfunction getProduct(n){ var product = 1; while (n != 0) { product = product * (n % 10); n = parseInt(n / 10); } return product;} // Function to find the product of digits// of all natural numbers in range L to Rfunction productinRange(l, r){ if (r - l > 9) return 0; else { var p = 1; // Iterate between L to R for (var i = l; i <= r; i++) p *= getProduct(i); return p; }} // Driver Codevar l = 11, r = 15;document.write( productinRange(l, r)+ \"<br>\");l = 1, r = 15;document.write( productinRange(l, r)); // This code is contributed by rutvik_56.</script>", "e": 29646, "s": 28883, "text": null }, { "code": null, "e": 29652, "s": 29646, "text": "120\n0" }, { "code": null, "e": 29667, "s": 29654, "text": "Rohit_ranjan" }, { "code": null, "e": 29678, "s": 29667, "text": "PratikBasu" }, { "code": null, "e": 29697, "s": 29678, "text": "Amal Kumar Choubey" }, { "code": null, "e": 29707, "s": 29697, "text": "rutvik_56" }, { "code": null, "e": 29727, "s": 29707, "text": "array-range-queries" }, { "code": null, "e": 29743, "s": 29727, "text": "Natural Numbers" }, { "code": null, "e": 29757, "s": 29743, "text": "number-digits" }, { "code": null, "e": 29764, "s": 29757, "text": "Arrays" }, { "code": null, "e": 29777, "s": 29764, "text": "Mathematical" }, { "code": null, "e": 29795, "s": 29777, "text": "Pattern Searching" }, { "code": null, "e": 29802, "s": 29795, "text": "Arrays" }, { "code": null, "e": 29815, "s": 29802, "text": "Mathematical" }, { "code": null, "e": 29833, "s": 29815, "text": "Pattern Searching" }, { "code": null, "e": 29931, "s": 29833, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29999, "s": 29931, "text": "Maximum and minimum of an array using minimum number of comparisons" }, { "code": null, "e": 30031, "s": 29999, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 30054, "s": 30031, "text": "Introduction to Arrays" }, { "code": null, "e": 30099, "s": 30054, "text": "Python | Using 2D arrays/lists the right way" }, { "code": null, "e": 30120, "s": 30099, "text": "Linked List vs Array" }, { "code": null, "e": 30150, "s": 30120, "text": "Program for Fibonacci numbers" }, { "code": null, "e": 30210, "s": 30150, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 30225, "s": 30210, "text": "C++ Data Types" }, { "code": null, "e": 30268, "s": 30225, "text": "Set in C++ Standard Template Library (STL)" } ]
Count Set-bits of number using Recursion - GeeksforGeeks
17 Nov, 2021 Given a number N. The task is to find the number of set bits in its binary representation using recursion. Examples: Input : 21 Output : 3 21 represented as 10101 in binary representation Input : 16 Output : 1 16 represented as 10000 in binary representation Approach: First, check the LSB of the number.If the LSB is 1, then we add 1 to our answer and divide the number by 2.If the LSB is 0, we add 0 to our answer and divide the number by 2.Then we recursively follow step (1) until the number is greater than 0. First, check the LSB of the number. If the LSB is 1, then we add 1 to our answer and divide the number by 2. If the LSB is 0, we add 0 to our answer and divide the number by 2. Then we recursively follow step (1) until the number is greater than 0. Below is the implementation of the above approach : C++ Java Python3 C# Javascript // CPP program to find number// of set bist in a number#include <bits/stdc++.h>using namespace std; // Recursive function to find// number of set bist in a numberint CountSetBits(int n){ // Base condition if (n == 0) return 0; // If Least significant bit is set if((n & 1) == 1) return 1 + CountSetBits(n >> 1); // If Least significant bit is not set else return CountSetBits(n >> 1);} // Driver codeint main(){ int n = 21; // Function call cout << CountSetBits(n) << endl; return 0;} // Java program to find number// of set bist in a numberclass GFG{ // Recursive function to find // number of set bist in a number static int CountSetBits(int n) { // Base condition if (n == 0) return 0; // If Least significant bit is set if((n & 1) == 1) return 1 + CountSetBits(n >> 1); // If Least significant bit is not set else return CountSetBits(n >> 1); } // Driver code public static void main (String [] args) { int n = 21; // Function call System.out.println(CountSetBits(n)); }} // This code is contributed by ihritik # Python3 program to find number# of set bist in a number # Recursive function to find# number of set bist in a numberdef CountSetBits(n): # Base condition if (n == 0): return 0; # If Least significant bit is set if((n & 1) == 1): return 1 + CountSetBits(n >> 1); # If Least significant bit is not set else: return CountSetBits(n >> 1); # Driver codeif __name__ == '__main__': n = 21; # Function call print(CountSetBits(n)); # This code is contributed by 29AjayKumar // C# program to find number// of set bist in a numberusing System; class GFG{ // Recursive function to find // number of set bist in a number static int CountSetBits(int n) { // Base condition if (n == 0) return 0; // If Least significant bit is set if((n & 1) == 1) return 1 + CountSetBits(n >> 1); // If Least significant bit is not set else return CountSetBits(n >> 1); } // Driver code public static void Main () { int n = 21; // Function call Console.WriteLine(CountSetBits(n)); }} // This code is contributed by ihritik <script> // Javascript program to find number// of set bist in a number // Recursive function to find// number of set bist in a numberfunction CountSetBits(n){ // Base condition if (n == 0) return 0; // If Least significant bit is set if ((n & 1) == 1) return 1 + CountSetBits(n >> 1); // If Least significant bit is not set else return CountSetBits(n >> 1);} // Driver codevar n = 21; // Function calldocument.write(CountSetBits(n)); // This code is contributed by Amit Katiyar </script> 3 Time Complexity: O(log n) Auxiliary Space: O(log n) ihritik 29AjayKumar Akanksha_Rai amit143katiyar as5853535 kalrap615 simmytarika5 subhammahato348 setBitCount Bit Magic Recursion Recursion Bit Magic Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Set, Clear and Toggle a given bit of a number in C Check whether K-th bit is set or not Program to find parity Hamming code Implementation in C/C++ Write an Efficient Method to Check if a Number is Multiple of 3 Write a program to print all permutations of a given string Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum) Recursion Program for Tower of Hanoi Program for Sum of the digits of a given number
[ { "code": null, "e": 24988, "s": 24960, "text": "\n17 Nov, 2021" }, { "code": null, "e": 25095, "s": 24988, "text": "Given a number N. The task is to find the number of set bits in its binary representation using recursion." }, { "code": null, "e": 25106, "s": 25095, "text": "Examples: " }, { "code": null, "e": 25177, "s": 25106, "text": "Input : 21 Output : 3 21 represented as 10101 in binary representation" }, { "code": null, "e": 25249, "s": 25177, "text": "Input : 16 Output : 1 16 represented as 10000 in binary representation " }, { "code": null, "e": 25261, "s": 25249, "text": "Approach: " }, { "code": null, "e": 25507, "s": 25261, "text": "First, check the LSB of the number.If the LSB is 1, then we add 1 to our answer and divide the number by 2.If the LSB is 0, we add 0 to our answer and divide the number by 2.Then we recursively follow step (1) until the number is greater than 0." }, { "code": null, "e": 25543, "s": 25507, "text": "First, check the LSB of the number." }, { "code": null, "e": 25616, "s": 25543, "text": "If the LSB is 1, then we add 1 to our answer and divide the number by 2." }, { "code": null, "e": 25684, "s": 25616, "text": "If the LSB is 0, we add 0 to our answer and divide the number by 2." }, { "code": null, "e": 25756, "s": 25684, "text": "Then we recursively follow step (1) until the number is greater than 0." }, { "code": null, "e": 25810, "s": 25756, "text": "Below is the implementation of the above approach : " }, { "code": null, "e": 25814, "s": 25810, "text": "C++" }, { "code": null, "e": 25819, "s": 25814, "text": "Java" }, { "code": null, "e": 25827, "s": 25819, "text": "Python3" }, { "code": null, "e": 25830, "s": 25827, "text": "C#" }, { "code": null, "e": 25841, "s": 25830, "text": "Javascript" }, { "code": "// CPP program to find number// of set bist in a number#include <bits/stdc++.h>using namespace std; // Recursive function to find// number of set bist in a numberint CountSetBits(int n){ // Base condition if (n == 0) return 0; // If Least significant bit is set if((n & 1) == 1) return 1 + CountSetBits(n >> 1); // If Least significant bit is not set else return CountSetBits(n >> 1);} // Driver codeint main(){ int n = 21; // Function call cout << CountSetBits(n) << endl; return 0;}", "e": 26397, "s": 25841, "text": null }, { "code": "// Java program to find number// of set bist in a numberclass GFG{ // Recursive function to find // number of set bist in a number static int CountSetBits(int n) { // Base condition if (n == 0) return 0; // If Least significant bit is set if((n & 1) == 1) return 1 + CountSetBits(n >> 1); // If Least significant bit is not set else return CountSetBits(n >> 1); } // Driver code public static void main (String [] args) { int n = 21; // Function call System.out.println(CountSetBits(n)); }} // This code is contributed by ihritik", "e": 27086, "s": 26397, "text": null }, { "code": "# Python3 program to find number# of set bist in a number # Recursive function to find# number of set bist in a numberdef CountSetBits(n): # Base condition if (n == 0): return 0; # If Least significant bit is set if((n & 1) == 1): return 1 + CountSetBits(n >> 1); # If Least significant bit is not set else: return CountSetBits(n >> 1); # Driver codeif __name__ == '__main__': n = 21; # Function call print(CountSetBits(n)); # This code is contributed by 29AjayKumar", "e": 27625, "s": 27086, "text": null }, { "code": "// C# program to find number// of set bist in a numberusing System; class GFG{ // Recursive function to find // number of set bist in a number static int CountSetBits(int n) { // Base condition if (n == 0) return 0; // If Least significant bit is set if((n & 1) == 1) return 1 + CountSetBits(n >> 1); // If Least significant bit is not set else return CountSetBits(n >> 1); } // Driver code public static void Main () { int n = 21; // Function call Console.WriteLine(CountSetBits(n)); }} // This code is contributed by ihritik", "e": 28311, "s": 27625, "text": null }, { "code": "<script> // Javascript program to find number// of set bist in a number // Recursive function to find// number of set bist in a numberfunction CountSetBits(n){ // Base condition if (n == 0) return 0; // If Least significant bit is set if ((n & 1) == 1) return 1 + CountSetBits(n >> 1); // If Least significant bit is not set else return CountSetBits(n >> 1);} // Driver codevar n = 21; // Function calldocument.write(CountSetBits(n)); // This code is contributed by Amit Katiyar </script>", "e": 28858, "s": 28311, "text": null }, { "code": null, "e": 28860, "s": 28858, "text": "3" }, { "code": null, "e": 28888, "s": 28862, "text": "Time Complexity: O(log n)" }, { "code": null, "e": 28914, "s": 28888, "text": "Auxiliary Space: O(log n)" }, { "code": null, "e": 28922, "s": 28914, "text": "ihritik" }, { "code": null, "e": 28934, "s": 28922, "text": "29AjayKumar" }, { "code": null, "e": 28947, "s": 28934, "text": "Akanksha_Rai" }, { "code": null, "e": 28962, "s": 28947, "text": "amit143katiyar" }, { "code": null, "e": 28972, "s": 28962, "text": "as5853535" }, { "code": null, "e": 28982, "s": 28972, "text": "kalrap615" }, { "code": null, "e": 28995, "s": 28982, "text": "simmytarika5" }, { "code": null, "e": 29011, "s": 28995, "text": "subhammahato348" }, { "code": null, "e": 29023, "s": 29011, "text": "setBitCount" }, { "code": null, "e": 29033, "s": 29023, "text": "Bit Magic" }, { "code": null, "e": 29043, "s": 29033, "text": "Recursion" }, { "code": null, "e": 29053, "s": 29043, "text": "Recursion" }, { "code": null, "e": 29063, "s": 29053, "text": "Bit Magic" }, { "code": null, "e": 29161, "s": 29063, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29212, "s": 29161, "text": "Set, Clear and Toggle a given bit of a number in C" }, { "code": null, "e": 29249, "s": 29212, "text": "Check whether K-th bit is set or not" }, { "code": null, "e": 29272, "s": 29249, "text": "Program to find parity" }, { "code": null, "e": 29309, "s": 29272, "text": "Hamming code Implementation in C/C++" }, { "code": null, "e": 29373, "s": 29309, "text": "Write an Efficient Method to Check if a Number is Multiple of 3" }, { "code": null, "e": 29433, "s": 29373, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 29518, "s": 29433, "text": "Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)" }, { "code": null, "e": 29528, "s": 29518, "text": "Recursion" }, { "code": null, "e": 29555, "s": 29528, "text": "Program for Tower of Hanoi" } ]
Java Program to Implement the Schonhage-Strassen Algorithm for Multiplication of Two Numbers - GeeksforGeeks
09 Jun, 2021 Schonhage-Strassen algorithm is one of the fastest ways of multiplying very large integer values (30000 to 150000 decimal digits). This algorithm was developed by Arnold Schönhage and Volker Strassen. Though the Furer’s algorithm is faster than that of Schonhage-Strassen’s algorithm, there are no practical applications for it, except Galactic algorithms (probably not used for any data present on the earth). So, Schonhage-Strassen’s algorithm is considered the best for multiplying large integer values. In this approach of multiplication, the two integers are first multiplied without performing carry. The result set then obtained is called Acyclic Convolution or Linear Convolution. Then we perform carry on the individual columns of the Linear Convolution. Examples: Java // Java program to implement Schonhage-Strassen's// Multiplication Algorithmimport java.io.*; class GFG { // two class level variables to // store the given values static long a, b; // class level array to store the LinearConvolution static int[] linearConvolution; // an integer variable to determine // the length of the LinearConvolution static int length; // to count the no.of digits in each of // the given values a and b static int countDigits(long num) { // an integer variable initialized to // 0 to store the no.of digits int count = 0; // as long as the number is // greater than 0, divide it by 10 // and increment the count while (num > 0) { num /= 10; count++; } // return the count when number becomes 0 return count; } // to perform schonhage-Strassen's Multiplication static void schonhageStrassenMultiplication() { // first find the LinearConvolution findLinearConvolution(); // Then perform carry on it performCarry(); } // to find LinearConvolution static void findLinearConvolution() { // no.of digits in first number (a) int aDigits = countDigits(a); // no.of digits in second number (b) int bDigits = countDigits(b); // a temporary variable to store the value of a long temp = a; // length of the LinearConvolution is // 1 less than the no.of Digits in a + // no.of digits in b length = aDigits + bDigits - 1; linearConvolution = new int[length]; for (int i = 0; i < aDigits; i++, b /= 10) { a = temp; for (int j = 0; j < bDigits; j++, a /= 10) { // multiply the current digit of a with // current digit of b and store in // LinearConvolution linearConvolution[i + j] += (b % 10) * (a % 10); } } System.out.print("The Linear Convolution is: [ "); for (int i = length - 1; i >= 0; i--) { // print the LinearConvolution array System.out.print(linearConvolution[i] + " "); } System.out.println("]"); } // to perform carry on the obtained LinearConvolution static void performCarry() { // initialize product to 0 long product = 0; int carry = 0, base = 1; // for every value in the LinearConvolution for (int i = 0; i < length; i++) { linearConvolution[i] += carry; // add the product of base and units digit of // LinearConvolution[i] to the product product = product + (base * (linearConvolution[i] % 10)); // now LinearConvolution[i]/10 // will become the carry carry = linearConvolution[i] / 10; base *= 10; } System.out.println("\nThe Product is : " + product); } // Driver method public static void main(String[] args) { // initialize the two declared class variables with // the desired values a = 2604; b = 1812; // call schonhageStrassenMultiplication() method schonhageStrassenMultiplication(); }} The Linear Convolution is: [ 2 22 50 14 44 4 8 ] The Product is : 4718448 Time Complexity: O(n. log n . log log n ) sumitgumber28 Picked Technical Scripter 2020 Java Java Programs Technical Scripter Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Stream In Java Different ways of Reading a text file in Java Constructors in Java Exceptions in Java Functional Interfaces in Java Convert a String to Character array in Java Java Programming Examples Convert Double to Integer in Java Implementing a Linked List in Java using Class How to Iterate HashMap in Java?
[ { "code": null, "e": 23948, "s": 23920, "text": "\n09 Jun, 2021" }, { "code": null, "e": 24456, "s": 23948, "text": "Schonhage-Strassen algorithm is one of the fastest ways of multiplying very large integer values (30000 to 150000 decimal digits). This algorithm was developed by Arnold Schönhage and Volker Strassen. Though the Furer’s algorithm is faster than that of Schonhage-Strassen’s algorithm, there are no practical applications for it, except Galactic algorithms (probably not used for any data present on the earth). So, Schonhage-Strassen’s algorithm is considered the best for multiplying large integer values." }, { "code": null, "e": 24713, "s": 24456, "text": "In this approach of multiplication, the two integers are first multiplied without performing carry. The result set then obtained is called Acyclic Convolution or Linear Convolution. Then we perform carry on the individual columns of the Linear Convolution." }, { "code": null, "e": 24724, "s": 24713, "text": "Examples: " }, { "code": null, "e": 24729, "s": 24724, "text": "Java" }, { "code": "// Java program to implement Schonhage-Strassen's// Multiplication Algorithmimport java.io.*; class GFG { // two class level variables to // store the given values static long a, b; // class level array to store the LinearConvolution static int[] linearConvolution; // an integer variable to determine // the length of the LinearConvolution static int length; // to count the no.of digits in each of // the given values a and b static int countDigits(long num) { // an integer variable initialized to // 0 to store the no.of digits int count = 0; // as long as the number is // greater than 0, divide it by 10 // and increment the count while (num > 0) { num /= 10; count++; } // return the count when number becomes 0 return count; } // to perform schonhage-Strassen's Multiplication static void schonhageStrassenMultiplication() { // first find the LinearConvolution findLinearConvolution(); // Then perform carry on it performCarry(); } // to find LinearConvolution static void findLinearConvolution() { // no.of digits in first number (a) int aDigits = countDigits(a); // no.of digits in second number (b) int bDigits = countDigits(b); // a temporary variable to store the value of a long temp = a; // length of the LinearConvolution is // 1 less than the no.of Digits in a + // no.of digits in b length = aDigits + bDigits - 1; linearConvolution = new int[length]; for (int i = 0; i < aDigits; i++, b /= 10) { a = temp; for (int j = 0; j < bDigits; j++, a /= 10) { // multiply the current digit of a with // current digit of b and store in // LinearConvolution linearConvolution[i + j] += (b % 10) * (a % 10); } } System.out.print(\"The Linear Convolution is: [ \"); for (int i = length - 1; i >= 0; i--) { // print the LinearConvolution array System.out.print(linearConvolution[i] + \" \"); } System.out.println(\"]\"); } // to perform carry on the obtained LinearConvolution static void performCarry() { // initialize product to 0 long product = 0; int carry = 0, base = 1; // for every value in the LinearConvolution for (int i = 0; i < length; i++) { linearConvolution[i] += carry; // add the product of base and units digit of // LinearConvolution[i] to the product product = product + (base * (linearConvolution[i] % 10)); // now LinearConvolution[i]/10 // will become the carry carry = linearConvolution[i] / 10; base *= 10; } System.out.println(\"\\nThe Product is : \" + product); } // Driver method public static void main(String[] args) { // initialize the two declared class variables with // the desired values a = 2604; b = 1812; // call schonhageStrassenMultiplication() method schonhageStrassenMultiplication(); }}", "e": 28033, "s": 24729, "text": null }, { "code": null, "e": 28118, "s": 28036, "text": "The Linear Convolution is: [ 2 22 50 14 44 4 8 ]\n\nThe Product is : 4718448" }, { "code": null, "e": 28162, "s": 28120, "text": "Time Complexity: O(n. log n . log log n )" }, { "code": null, "e": 28178, "s": 28164, "text": "sumitgumber28" }, { "code": null, "e": 28185, "s": 28178, "text": "Picked" }, { "code": null, "e": 28209, "s": 28185, "text": "Technical Scripter 2020" }, { "code": null, "e": 28214, "s": 28209, "text": "Java" }, { "code": null, "e": 28228, "s": 28214, "text": "Java Programs" }, { "code": null, "e": 28247, "s": 28228, "text": "Technical Scripter" }, { "code": null, "e": 28252, "s": 28247, "text": "Java" }, { "code": null, "e": 28350, "s": 28252, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28365, "s": 28350, "text": "Stream In Java" }, { "code": null, "e": 28411, "s": 28365, "text": "Different ways of Reading a text file in Java" }, { "code": null, "e": 28432, "s": 28411, "text": "Constructors in Java" }, { "code": null, "e": 28451, "s": 28432, "text": "Exceptions in Java" }, { "code": null, "e": 28481, "s": 28451, "text": "Functional Interfaces in Java" }, { "code": null, "e": 28525, "s": 28481, "text": "Convert a String to Character array in Java" }, { "code": null, "e": 28551, "s": 28525, "text": "Java Programming Examples" }, { "code": null, "e": 28585, "s": 28551, "text": "Convert Double to Integer in Java" }, { "code": null, "e": 28632, "s": 28585, "text": "Implementing a Linked List in Java using Class" } ]
Apache Flume - Fetching Twitter Data
Using Flume, we can fetch data from various services and transport it to centralized stores (HDFS and HBase). This chapter explains how to fetch data from Twitter service and store it in HDFS using Apache Flume. As discussed in Flume Architecture, a webserver generates log data and this data is collected by an agent in Flume. The channel buffers this data to a sink, which finally pushes it to centralized stores. In the example provided in this chapter, we will create an application and get the tweets from it using the experimental twitter source provided by Apache Flume. We will use the memory channel to buffer these tweets and HDFS sink to push these tweets into the HDFS. To fetch Twitter data, we will have to follow the steps given below − Create a twitter Application Install / Start HDFS Configure Flume In order to get the tweets from Twitter, it is needed to create a Twitter application. Follow the steps given below to create a Twitter application. To create a Twitter application, click on the following link https://apps.twitter.com/. Sign in to your Twitter account. You will have a Twitter Application Management window where you can create, delete, and manage Twitter Apps. Click on the Create New App button. You will be redirected to a window where you will get an application form in which you have to fill in your details in order to create the App. While filling the website address, give the complete URL pattern, for example, http://example.com. Fill in the details, accept the Developer Agreement when finished, click on the Create your Twitter application button which is at the bottom of the page. If everything goes fine, an App will be created with the given details as shown below. Under keys and Access Tokens tab at the bottom of the page, you can observe a button named Create my access token. Click on it to generate the access token. Finally, click on the Test OAuth button which is on the right side top of the page. This will lead to a page which displays your Consumer key, Consumer secret, Access token, and Access token secret. Copy these details. These are useful to configure the agent in Flume. Since we are storing the data in HDFS, we need to install / verify Hadoop. Start Hadoop and create a folder in it to store Flume data. Follow the steps given below before configuring Flume. Install Hadoop. If Hadoop is already installed in your system, verify the installation using Hadoop version command, as shown below. $ hadoop version If your system contains Hadoop, and if you have set the path variable, then you will get the following output − Hadoop 2.6.0 Subversion https://git-wip-us.apache.org/repos/asf/hadoop.git -r e3496499ecb8d220fba99dc5ed4c99c8f9e33bb1 Compiled by jenkins on 2014-11-13T21:10Z Compiled with protoc 2.5.0 From source with checksum 18e43357c8f927c0695f1e9522859d6a This command was run using /home/Hadoop/hadoop/share/hadoop/common/hadoop-common-2.6.0.jar Browse through the sbin directory of Hadoop and start yarn and Hadoop dfs (distributed file system) as shown below. cd /$Hadoop_Home/sbin/ $ start-dfs.sh localhost: starting namenode, logging to /home/Hadoop/hadoop/logs/hadoop-Hadoop-namenode-localhost.localdomain.out localhost: starting datanode, logging to /home/Hadoop/hadoop/logs/hadoop-Hadoop-datanode-localhost.localdomain.out Starting secondary namenodes [0.0.0.0] starting secondarynamenode, logging to /home/Hadoop/hadoop/logs/hadoop-Hadoop-secondarynamenode-localhost.localdomain.out $ start-yarn.sh starting yarn daemons starting resourcemanager, logging to /home/Hadoop/hadoop/logs/yarn-Hadoop-resourcemanager-localhost.localdomain.out localhost: starting nodemanager, logging to /home/Hadoop/hadoop/logs/yarn-Hadoop-nodemanager-localhost.localdomain.out In Hadoop DFS, you can create directories using the command mkdir. Browse through it and create a directory with the name twitter_data in the required path as shown below. $cd /$Hadoop_Home/bin/ $ hdfs dfs -mkdir hdfs://localhost:9000/user/Hadoop/twitter_data We have to configure the source, the channel, and the sink using the configuration file in the conf folder. The example given in this chapter uses an experimental source provided by Apache Flume named Twitter 1% Firehose Memory channel and HDFS sink. This source is highly experimental. It connects to the 1% sample Twitter Firehose using streaming API and continuously downloads tweets, converts them to Avro format, and sends Avro events to a downstream Flume sink. We will get this source by default along with the installation of Flume. The jar files corresponding to this source can be located in the lib folder as shown below. Set the classpath variable to the lib folder of Flume in Flume-env.sh file as shown below. export CLASSPATH=$CLASSPATH:/FLUME_HOME/lib/* This source needs the details such as Consumer key, Consumer secret, Access token, and Access token secret of a Twitter application. While configuring this source, you have to provide values to the following properties − Channels Channels Source type : org.apache.flume.source.twitter.TwitterSource Source type : org.apache.flume.source.twitter.TwitterSource consumerKey − The OAuth consumer key consumerKey − The OAuth consumer key consumerSecret − OAuth consumer secret consumerSecret − OAuth consumer secret accessToken − OAuth access token accessToken − OAuth access token accessTokenSecret − OAuth token secret accessTokenSecret − OAuth token secret maxBatchSize − Maximum number of twitter messages that should be in a twitter batch. The default value is 1000 (optional). maxBatchSize − Maximum number of twitter messages that should be in a twitter batch. The default value is 1000 (optional). maxBatchDurationMillis − Maximum number of milliseconds to wait before closing a batch. The default value is 1000 (optional). maxBatchDurationMillis − Maximum number of milliseconds to wait before closing a batch. The default value is 1000 (optional). We are using the memory channel. To configure the memory channel, you must provide value to the type of the channel. type − It holds the type of the channel. In our example, the type is MemChannel. type − It holds the type of the channel. In our example, the type is MemChannel. Capacity − It is the maximum number of events stored in the channel. Its default value is 100 (optional). Capacity − It is the maximum number of events stored in the channel. Its default value is 100 (optional). TransactionCapacity − It is the maximum number of events the channel accepts or sends. Its default value is 100 (optional). TransactionCapacity − It is the maximum number of events the channel accepts or sends. Its default value is 100 (optional). This sink writes data into the HDFS. To configure this sink, you must provide the following details. Channel Channel type − hdfs type − hdfs hdfs.path − the path of the directory in HDFS where data is to be stored. hdfs.path − the path of the directory in HDFS where data is to be stored. And we can provide some optional values based on the scenario. Given below are the optional properties of the HDFS sink that we are configuring in our application. fileType − This is the required file format of our HDFS file. SequenceFile, DataStream and CompressedStream are the three types available with this stream. In our example, we are using the DataStream. fileType − This is the required file format of our HDFS file. SequenceFile, DataStream and CompressedStream are the three types available with this stream. In our example, we are using the DataStream. writeFormat − Could be either text or writable. writeFormat − Could be either text or writable. batchSize − It is the number of events written to a file before it is flushed into the HDFS. Its default value is 100. batchSize − It is the number of events written to a file before it is flushed into the HDFS. Its default value is 100. rollsize − It is the file size to trigger a roll. It default value is 100. rollsize − It is the file size to trigger a roll. It default value is 100. rollCount − It is the number of events written into the file before it is rolled. Its default value is 10. rollCount − It is the number of events written into the file before it is rolled. Its default value is 10. Given below is an example of the configuration file. Copy this content and save as twitter.conf in the conf folder of Flume. # Naming the components on the current agent. TwitterAgent.sources = Twitter TwitterAgent.channels = MemChannel TwitterAgent.sinks = HDFS # Describing/Configuring the source TwitterAgent.sources.Twitter.type = org.apache.flume.source.twitter.TwitterSource TwitterAgent.sources.Twitter.consumerKey = Your OAuth consumer key TwitterAgent.sources.Twitter.consumerSecret = Your OAuth consumer secret TwitterAgent.sources.Twitter.accessToken = Your OAuth consumer key access token TwitterAgent.sources.Twitter.accessTokenSecret = Your OAuth consumer key access token secret TwitterAgent.sources.Twitter.keywords = tutorials point,java, bigdata, mapreduce, mahout, hbase, nosql # Describing/Configuring the sink TwitterAgent.sinks.HDFS.type = hdfs TwitterAgent.sinks.HDFS.hdfs.path = hdfs://localhost:9000/user/Hadoop/twitter_data/ TwitterAgent.sinks.HDFS.hdfs.fileType = DataStream TwitterAgent.sinks.HDFS.hdfs.writeFormat = Text TwitterAgent.sinks.HDFS.hdfs.batchSize = 1000 TwitterAgent.sinks.HDFS.hdfs.rollSize = 0 TwitterAgent.sinks.HDFS.hdfs.rollCount = 10000 # Describing/Configuring the channel TwitterAgent.channels.MemChannel.type = memory TwitterAgent.channels.MemChannel.capacity = 10000 TwitterAgent.channels.MemChannel.transactionCapacity = 100 # Binding the source and sink to the channel TwitterAgent.sources.Twitter.channels = MemChannel TwitterAgent.sinks.HDFS.channel = MemChannel Browse through the Flume home directory and execute the application as shown below. $ cd $FLUME_HOME $ bin/flume-ng agent --conf ./conf/ -f conf/twitter.conf Dflume.root.logger=DEBUG,console -n TwitterAgent If everything goes fine, the streaming of tweets into HDFS will start. Given below is the snapshot of the command prompt window while fetching tweets. You can access the Hadoop Administration Web UI using the URL given below. http://localhost:50070/ Click on the dropdown named Utilities on the right-hand side of the page. You can see two options as shown in the snapshot given below. Click on Browse the file system and enter the path of the HDFS directory where you have stored the tweets. In our example, the path will be /user/Hadoop/twitter_data/. Then, you can see the list of twitter log files stored in HDFS as given below. 46 Lectures 3.5 hours Arnab Chakraborty 23 Lectures 1.5 hours Mukund Kumar Mishra 16 Lectures 1 hours Nilay Mehta 52 Lectures 1.5 hours Bigdata Engineer 14 Lectures 1 hours Bigdata Engineer 23 Lectures 1 hours Bigdata Engineer Print Add Notes Bookmark this page
[ { "code": null, "e": 2069, "s": 1857, "text": "Using Flume, we can fetch data from various services and transport it to centralized stores (HDFS and HBase). This chapter explains how to fetch data from Twitter service and store it in HDFS using Apache Flume." }, { "code": null, "e": 2273, "s": 2069, "text": "As discussed in Flume Architecture, a webserver generates log data and this data is collected by an agent in Flume. The channel buffers this data to a sink, which finally pushes it to centralized stores." }, { "code": null, "e": 2539, "s": 2273, "text": "In the example provided in this chapter, we will create an application and get the tweets from it using the experimental twitter source provided by Apache Flume. We will use the memory channel to buffer these tweets and HDFS sink to push these tweets into the HDFS." }, { "code": null, "e": 2609, "s": 2539, "text": "To fetch Twitter data, we will have to follow the steps given below −" }, { "code": null, "e": 2638, "s": 2609, "text": "Create a twitter Application" }, { "code": null, "e": 2659, "s": 2638, "text": "Install / Start HDFS" }, { "code": null, "e": 2675, "s": 2659, "text": "Configure Flume" }, { "code": null, "e": 2824, "s": 2675, "text": "In order to get the tweets from Twitter, it is needed to create a Twitter application. Follow the steps given below to create a Twitter application." }, { "code": null, "e": 3054, "s": 2824, "text": "To create a Twitter application, click on the following link https://apps.twitter.com/. Sign in to your Twitter account. You will have a Twitter Application Management window where you can create, delete, and manage Twitter Apps." }, { "code": null, "e": 3333, "s": 3054, "text": "Click on the Create New App button. You will be redirected to a window where you will get an application form in which you have to fill in your details in order to create the App. While filling the website address, give the complete URL pattern, for example, http://example.com." }, { "code": null, "e": 3575, "s": 3333, "text": "Fill in the details, accept the Developer Agreement when finished, click on the Create your Twitter application button which is at the bottom of the page. If everything goes fine, an App will be created with the given details as shown below." }, { "code": null, "e": 3732, "s": 3575, "text": "Under keys and Access Tokens tab at the bottom of the page, you can observe a button named Create my access token. Click on it to generate the access token." }, { "code": null, "e": 4001, "s": 3732, "text": "Finally, click on the Test OAuth button which is on the right side top of the page. This will lead to a page which displays your Consumer key, Consumer secret, Access token, and Access token secret. Copy these details. These are useful to configure the agent in Flume." }, { "code": null, "e": 4191, "s": 4001, "text": "Since we are storing the data in HDFS, we need to install / verify Hadoop. Start Hadoop and create a folder in it to store Flume data. Follow the steps given below before configuring Flume." }, { "code": null, "e": 4324, "s": 4191, "text": "Install Hadoop. If Hadoop is already installed in your system, verify the installation using Hadoop version command, as shown below." }, { "code": null, "e": 4343, "s": 4324, "text": "$ hadoop version \n" }, { "code": null, "e": 4455, "s": 4343, "text": "If your system contains Hadoop, and if you have set the path variable, then you will get the following output −" }, { "code": null, "e": 4799, "s": 4455, "text": "Hadoop 2.6.0 \nSubversion https://git-wip-us.apache.org/repos/asf/hadoop.git -r \ne3496499ecb8d220fba99dc5ed4c99c8f9e33bb1 \nCompiled by jenkins on 2014-11-13T21:10Z \nCompiled with protoc 2.5.0 \nFrom source with checksum 18e43357c8f927c0695f1e9522859d6a \nThis command was run using /home/Hadoop/hadoop/share/hadoop/common/hadoop-common-2.6.0.jar\n" }, { "code": null, "e": 4915, "s": 4799, "text": "Browse through the sbin directory of Hadoop and start yarn and Hadoop dfs (distributed file system) as shown below." }, { "code": null, "e": 5649, "s": 4915, "text": "cd /$Hadoop_Home/sbin/ \n$ start-dfs.sh \nlocalhost: starting namenode, logging to\n /home/Hadoop/hadoop/logs/hadoop-Hadoop-namenode-localhost.localdomain.out \nlocalhost: starting datanode, logging to \n /home/Hadoop/hadoop/logs/hadoop-Hadoop-datanode-localhost.localdomain.out \nStarting secondary namenodes [0.0.0.0] \nstarting secondarynamenode, logging to \n /home/Hadoop/hadoop/logs/hadoop-Hadoop-secondarynamenode-localhost.localdomain.out\n \n$ start-yarn.sh \nstarting yarn daemons \nstarting resourcemanager, logging to \n /home/Hadoop/hadoop/logs/yarn-Hadoop-resourcemanager-localhost.localdomain.out \nlocalhost: starting nodemanager, logging to \n /home/Hadoop/hadoop/logs/yarn-Hadoop-nodemanager-localhost.localdomain.out \n" }, { "code": null, "e": 5821, "s": 5649, "text": "In Hadoop DFS, you can create directories using the command mkdir. Browse through it and create a directory with the name twitter_data in the required path as shown below." }, { "code": null, "e": 5912, "s": 5821, "text": "$cd /$Hadoop_Home/bin/ \n$ hdfs dfs -mkdir hdfs://localhost:9000/user/Hadoop/twitter_data \n" }, { "code": null, "e": 6163, "s": 5912, "text": "We have to configure the source, the channel, and the sink using the configuration file in the conf folder. The example given in this chapter uses an experimental source provided by Apache Flume named Twitter 1% Firehose Memory channel and HDFS sink." }, { "code": null, "e": 6380, "s": 6163, "text": "This source is highly experimental. It connects to the 1% sample Twitter Firehose using streaming API and continuously downloads tweets, converts them to Avro format, and sends Avro events to a downstream Flume sink." }, { "code": null, "e": 6545, "s": 6380, "text": "We will get this source by default along with the installation of Flume. The jar files corresponding to this source can be located in the lib folder as shown below." }, { "code": null, "e": 6636, "s": 6545, "text": "Set the classpath variable to the lib folder of Flume in Flume-env.sh file as shown below." }, { "code": null, "e": 6684, "s": 6636, "text": "export CLASSPATH=$CLASSPATH:/FLUME_HOME/lib/* \n" }, { "code": null, "e": 6905, "s": 6684, "text": "This source needs the details such as Consumer key, Consumer secret, Access token, and Access token secret of a Twitter application. While configuring this source, you have to provide values to the following properties −" }, { "code": null, "e": 6914, "s": 6905, "text": "Channels" }, { "code": null, "e": 6923, "s": 6914, "text": "Channels" }, { "code": null, "e": 6983, "s": 6923, "text": "Source type : org.apache.flume.source.twitter.TwitterSource" }, { "code": null, "e": 7043, "s": 6983, "text": "Source type : org.apache.flume.source.twitter.TwitterSource" }, { "code": null, "e": 7080, "s": 7043, "text": "consumerKey − The OAuth consumer key" }, { "code": null, "e": 7117, "s": 7080, "text": "consumerKey − The OAuth consumer key" }, { "code": null, "e": 7156, "s": 7117, "text": "consumerSecret − OAuth consumer secret" }, { "code": null, "e": 7195, "s": 7156, "text": "consumerSecret − OAuth consumer secret" }, { "code": null, "e": 7228, "s": 7195, "text": "accessToken − OAuth access token" }, { "code": null, "e": 7261, "s": 7228, "text": "accessToken − OAuth access token" }, { "code": null, "e": 7300, "s": 7261, "text": "accessTokenSecret − OAuth token secret" }, { "code": null, "e": 7339, "s": 7300, "text": "accessTokenSecret − OAuth token secret" }, { "code": null, "e": 7462, "s": 7339, "text": "maxBatchSize − Maximum number of twitter messages that should be in a twitter batch. The default value is 1000 (optional)." }, { "code": null, "e": 7585, "s": 7462, "text": "maxBatchSize − Maximum number of twitter messages that should be in a twitter batch. The default value is 1000 (optional)." }, { "code": null, "e": 7711, "s": 7585, "text": "maxBatchDurationMillis − Maximum number of milliseconds to wait before closing a batch. The default value is 1000 (optional)." }, { "code": null, "e": 7837, "s": 7711, "text": "maxBatchDurationMillis − Maximum number of milliseconds to wait before closing a batch. The default value is 1000 (optional)." }, { "code": null, "e": 7954, "s": 7837, "text": "We are using the memory channel. To configure the memory channel, you must provide value to the type of the channel." }, { "code": null, "e": 8035, "s": 7954, "text": "type − It holds the type of the channel. In our example, the type is MemChannel." }, { "code": null, "e": 8116, "s": 8035, "text": "type − It holds the type of the channel. In our example, the type is MemChannel." }, { "code": null, "e": 8222, "s": 8116, "text": "Capacity − It is the maximum number of events stored in the channel. Its default value is 100 (optional)." }, { "code": null, "e": 8328, "s": 8222, "text": "Capacity − It is the maximum number of events stored in the channel. Its default value is 100 (optional)." }, { "code": null, "e": 8452, "s": 8328, "text": "TransactionCapacity − It is the maximum number of events the channel accepts or sends. Its default value is 100 (optional)." }, { "code": null, "e": 8576, "s": 8452, "text": "TransactionCapacity − It is the maximum number of events the channel accepts or sends. Its default value is 100 (optional)." }, { "code": null, "e": 8677, "s": 8576, "text": "This sink writes data into the HDFS. To configure this sink, you must provide the following details." }, { "code": null, "e": 8685, "s": 8677, "text": "Channel" }, { "code": null, "e": 8693, "s": 8685, "text": "Channel" }, { "code": null, "e": 8705, "s": 8693, "text": "type − hdfs" }, { "code": null, "e": 8717, "s": 8705, "text": "type − hdfs" }, { "code": null, "e": 8791, "s": 8717, "text": "hdfs.path − the path of the directory in HDFS where data is to be stored." }, { "code": null, "e": 8865, "s": 8791, "text": "hdfs.path − the path of the directory in HDFS where data is to be stored." }, { "code": null, "e": 9029, "s": 8865, "text": "And we can provide some optional values based on the scenario. Given below are the optional properties of the HDFS sink that we are configuring in our application." }, { "code": null, "e": 9230, "s": 9029, "text": "fileType − This is the required file format of our HDFS file. SequenceFile, DataStream and CompressedStream are the three types available with this stream. In our example, we are using the DataStream." }, { "code": null, "e": 9431, "s": 9230, "text": "fileType − This is the required file format of our HDFS file. SequenceFile, DataStream and CompressedStream are the three types available with this stream. In our example, we are using the DataStream." }, { "code": null, "e": 9479, "s": 9431, "text": "writeFormat − Could be either text or writable." }, { "code": null, "e": 9527, "s": 9479, "text": "writeFormat − Could be either text or writable." }, { "code": null, "e": 9646, "s": 9527, "text": "batchSize − It is the number of events written to a file before it is flushed into the HDFS. Its default value is 100." }, { "code": null, "e": 9765, "s": 9646, "text": "batchSize − It is the number of events written to a file before it is flushed into the HDFS. Its default value is 100." }, { "code": null, "e": 9840, "s": 9765, "text": "rollsize − It is the file size to trigger a roll. It default value is 100." }, { "code": null, "e": 9915, "s": 9840, "text": "rollsize − It is the file size to trigger a roll. It default value is 100." }, { "code": null, "e": 10022, "s": 9915, "text": "rollCount − It is the number of events written into the file before it is rolled. Its default value is 10." }, { "code": null, "e": 10129, "s": 10022, "text": "rollCount − It is the number of events written into the file before it is rolled. Its default value is 10." }, { "code": null, "e": 10254, "s": 10129, "text": "Given below is an example of the configuration file. Copy this content and save as twitter.conf in the conf folder of Flume." }, { "code": null, "e": 11679, "s": 10254, "text": "# Naming the components on the current agent. \nTwitterAgent.sources = Twitter \nTwitterAgent.channels = MemChannel \nTwitterAgent.sinks = HDFS\n \n# Describing/Configuring the source \nTwitterAgent.sources.Twitter.type = org.apache.flume.source.twitter.TwitterSource\nTwitterAgent.sources.Twitter.consumerKey = Your OAuth consumer key\nTwitterAgent.sources.Twitter.consumerSecret = Your OAuth consumer secret \nTwitterAgent.sources.Twitter.accessToken = Your OAuth consumer key access token \nTwitterAgent.sources.Twitter.accessTokenSecret = Your OAuth consumer key access token secret \nTwitterAgent.sources.Twitter.keywords = tutorials point,java, bigdata, mapreduce, mahout, hbase, nosql\n \n# Describing/Configuring the sink \n\nTwitterAgent.sinks.HDFS.type = hdfs \nTwitterAgent.sinks.HDFS.hdfs.path = hdfs://localhost:9000/user/Hadoop/twitter_data/\nTwitterAgent.sinks.HDFS.hdfs.fileType = DataStream \nTwitterAgent.sinks.HDFS.hdfs.writeFormat = Text \nTwitterAgent.sinks.HDFS.hdfs.batchSize = 1000\nTwitterAgent.sinks.HDFS.hdfs.rollSize = 0 \nTwitterAgent.sinks.HDFS.hdfs.rollCount = 10000 \n \n# Describing/Configuring the channel \nTwitterAgent.channels.MemChannel.type = memory \nTwitterAgent.channels.MemChannel.capacity = 10000 \nTwitterAgent.channels.MemChannel.transactionCapacity = 100\n \n# Binding the source and sink to the channel \nTwitterAgent.sources.Twitter.channels = MemChannel\nTwitterAgent.sinks.HDFS.channel = MemChannel \n" }, { "code": null, "e": 11763, "s": 11679, "text": "Browse through the Flume home directory and execute the application as shown below." }, { "code": null, "e": 11889, "s": 11763, "text": "$ cd $FLUME_HOME \n$ bin/flume-ng agent --conf ./conf/ -f conf/twitter.conf \nDflume.root.logger=DEBUG,console -n TwitterAgent\n" }, { "code": null, "e": 12040, "s": 11889, "text": "If everything goes fine, the streaming of tweets into HDFS will start. Given below is the snapshot of the command prompt window while fetching tweets." }, { "code": null, "e": 12115, "s": 12040, "text": "You can access the Hadoop Administration Web UI using the URL given below." }, { "code": null, "e": 12141, "s": 12115, "text": "http://localhost:50070/ \n" }, { "code": null, "e": 12277, "s": 12141, "text": "Click on the dropdown named Utilities on the right-hand side of the page. You can see two options as shown in the snapshot given below." }, { "code": null, "e": 12525, "s": 12277, "text": "Click on Browse the file system and enter the path of the HDFS directory where you have stored the tweets. In our example, the path will be /user/Hadoop/twitter_data/. Then, you can see the list of twitter log files stored in HDFS as given below." }, { "code": null, "e": 12560, "s": 12525, "text": "\n 46 Lectures \n 3.5 hours \n" }, { "code": null, "e": 12579, "s": 12560, "text": " Arnab Chakraborty" }, { "code": null, "e": 12614, "s": 12579, "text": "\n 23 Lectures \n 1.5 hours \n" }, { "code": null, "e": 12635, "s": 12614, "text": " Mukund Kumar Mishra" }, { "code": null, "e": 12668, "s": 12635, "text": "\n 16 Lectures \n 1 hours \n" }, { "code": null, "e": 12681, "s": 12668, "text": " Nilay Mehta" }, { "code": null, "e": 12716, "s": 12681, "text": "\n 52 Lectures \n 1.5 hours \n" }, { "code": null, "e": 12734, "s": 12716, "text": " Bigdata Engineer" }, { "code": null, "e": 12767, "s": 12734, "text": "\n 14 Lectures \n 1 hours \n" }, { "code": null, "e": 12785, "s": 12767, "text": " Bigdata Engineer" }, { "code": null, "e": 12818, "s": 12785, "text": "\n 23 Lectures \n 1 hours \n" }, { "code": null, "e": 12836, "s": 12818, "text": " Bigdata Engineer" }, { "code": null, "e": 12843, "s": 12836, "text": " Print" }, { "code": null, "e": 12854, "s": 12843, "text": " Add Notes" } ]
net - Unix, Linux Command
This tool is part of the samba(7) suite. The Samba net utility is meant to work just like the net utility available for windows and DOS. The first argument should be used to specify the protocol to use when executing a certain command. ADS is used for ActiveDirectory, RAP is using for old (Win9x/NT3) clients and RPC can be used for NT4 and Windows 2000. If this argument is omitted, net will try to determine it automatically. Not all commands are available on all protocols. -h|--help Print a summary of command line options. -w target-workgroup Sets target workgroup or domain. You have to specify either this option or the IP address or the name of a server. -W workgroup Sets client workgroup or domain -U user User name to use -I ip-address IP address of target server to use. You have to specify either this option or a target workgroup or a target server. -p port Port on the target server to connect to (usually 139 or 445). Defaults to trying 445 first, then 139. -n <primary NetBIOS name> This option allows you to override the NetBIOS name that Samba uses for itself. This is identical to setting the netbios name parameter in the smb.conf file. However, a command line setting will take precedence over settings in smb.conf. -s <configuration file> The file specified contains the configuration details required by the server. The information in this file includes server-specific information such as what printcap file to use, as well as descriptions of all the services that the server is to provide. See smb.conf for more information. The default configuration file name is determined at compile time. -S server Name of target server. You should specify either this option or a target workgroup or a target IP address. -l When listing data, give more information on each item. -P Make queries to the external server using the machine account of the local server. -d|--debuglevel=level level is an integer from 0 to 10. The default value if this parameter is not specified is 0. The higher this value, the more detail will be logged to the log files about the activities of the server. At level 0, only critical errors and serious warnings will be logged. Level 1 is a reasonable level for day-to-day running - it generates a small amount of information about operations carried out. Levels above 1 will generate considerable amounts of log data, and should only be used when investigating a problem. Levels above 3 are designed for use only by developers and generate HUGE amounts of log data, most of which is extremely cryptic. Note that specifying this parameter here will override the log level parameter in the smb.conf file. This command allows the Samba machine account password to be set from an external application to a machine account password that has already been stored in Active Directory. DO NOT USE this command unless you know exactly what you are doing. The use of this command requires that the force flag (-f) be used also. There will be NO command prompt. Whatever information is piped into stdin, either by typing at the command line or otherwise, will be stored as the literal machine password. Do NOT use this without care and attention as it will overwrite a legitimate machine password without warning. YOU HAVE BEEN WARNED. The NET TIME command allows you to view the time on a remote server or synchronise the time on the local server with the time on the remote server. Without any options, the NET TIME command displays the time on the remote server. Displays the time on the remote server in a format ready for /bin/date. Tries to set the date and time of the local server to that on the remote server using /bin/date. Displays the timezone in hours from GMT on the remote computer. Join a domain. If the account already exists on the server, and [TYPE] is MEMBER, the machine will attempt to join automatically. (Assuming that the machine has been created in server manager) Otherwise, a password will be prompted for, and a new account may be created. [TYPE] may be PDC, BDC or MEMBER to specify the type of server joining the domain. [UPN] (ADS only) set the principalname attribute during the join. The default format is host/netbiosname@REALM. [OU] (ADS only) Precreate the computer account in a specific OU. The OU string reads from top to bottom without RDNs, and is delimited by a '/'. Please note that '\' is used for escape by both the shell and ldap, so it may need to be doubled or quadrupled to pass through, and it is not used as a delimiter. Join a domain. Use the OLDJOIN option to join the domain using the old style of domain joining - you need to create a trust account in server manager first. List all users Delete specified user List the domain groups of the specified user. Rename specified user. Add specified user. List user groups. Delete specified group. Create specified group. Enumerates all exported resources (network shares) on target server. Adds a share from a server (makes the export active). Maxusers specifies the number of users that can be connected to the share simultaneously. Delete specified share. List all open files on remote server. Close file with specified fileid on remote server. Print information on specified fileid. Currently listed are: file-id, username, locks, path, permissions. List files opened by specified user. Please note that net rap file user does not work against Samba servers. Without any other options, SESSION enumerates all active SMB/CIFS sessions on the target server. Close the specified sessions. Give a list with all the open files in specified session. List all servers in specified domain or workgroup. Defaults to local domain. Lists all domains and workgroups visible on the current network. Lists the specified print queue and print jobs on the server. If the QUEUE_NAME is omitted, all queues are listed. Delete job with specified id. Validate whether the specified user can log in to the remote server. If the password is not specified on the commandline, it will be prompted. Note Currently NOT implemented. List all members of the specified group. Delete member from group. Add member to group. Execute the specified command on the remote server. Only works with OS/2 servers. Note Currently NOT implemented. Start the specified service on the remote server. Not implemented yet. Note Currently NOT implemented. Stop the specified service on the remote server. Note Currently NOT implemented. Change password of USER from OLDPASS to NEWPASS. Lookup the IP address of the given host with the specified type (netbios suffix). The type defaults to 0x20 (workstation). Give IP address of LDAP server of specified DOMAIN. Defaults to local domain. Give IP address of KDC for the specified REALM. Defaults to local realm. Give IP's of Domain Controllers for specified DOMAIN. Defaults to local domain. Give IP of master browser for specified DOMAIN or workgroup. Defaults to local domain. Samba uses a general caching interface called 'gencache'. It can be controlled using 'NET CACHE'. All the timeout parameters support the suffixes: Add specified key+data to the cache with the given timeout. Delete key from the cache. Update data of existing cache entry. Search for the specified pattern in the cache data. List all current items in the cache. Remove all the current items from the cache. Prints the SID of the specified domain, or if the parameter is omitted, the SID of the local server. Sets SID for the local server to the specified SID. Prints the local machine SID and the SID of the current domain. Sets the SID of the current domain. Manage the mappings between Windows group SIDs and UNIX groups. Common options include: o o o o o o Add a new group mapping entry: net groupmap add {rid=int|sid=string} unixgroup=string \ [type={domain|local}] [ntgroup=string] [comment=string] Delete a group mapping entry. If more than one group name matches, the first entry found is deleted. net groupmap delete {ntgroup=string|sid=SID} Update en existing group entry. net groupmap modify {ntgroup=string|sid=SID} [unixgroup=string] \ [comment=string] [type={domain|local}] List existing group mapping entries. net groupmap list [verbose] [ntgroup=string] [sid=SID] Prints out the highest RID currently in use on the local server (by the active 'passdb backend'). Print information about the domain of the remote server, such as domain name, domain sid and number of users and groups. Check whether participation in a domain is still valid. Force change of domain trust password. Add a interdomain trust account for DOMAIN. This is in fact a Samba account named DOMAIN$ with the account flag 'I' (interdomain trust account). If the command is used against localhost it has the same effect as smbpasswd -a -i DOMAIN. Please note that both commands expect a appropriate UNIX account. Remove interdomain trust account for DOMAIN. If it is used against localhost it has the same effect as smbpasswd -x DOMAIN$. Establish a trust relationship to a trusting domain. Interdomain account must already be created on the remote PDC. Abandon relationship to trusted domain List all current interdomain trust relationships. This subcommand is used to view and manage Samba's rights assignments (also referred to as privileges). There are three options currently available: list, grant, and revoke. More details on Samba's privilege model and its use can be found in the Samba-HOWTO-Collection. Abort the shutdown of a remote server. Shut down the remote server. -r Reboot after shutdown. -f Force shutting down all applications. -t timeout Timeout before system will be shut down. An interactive user of the system can use this time to cancel the shutdown. '> -C message Display the specified message on the screen to announce the shutdown. Print out sam database of remote server. You need to run this against the PDC, from a Samba machine joined as a BDC. Export users, aliases and groups from remote server to local server. You need to run this against the PDC, from a Samba machine joined as a BDC. Fetch domain SID and store it in the local secrets.tdb. Make the remote host leave the domain it is part of. Print out status of machine account of the local machine in ADS. Prints out quite some debug info. Aimed at developers, regular users should use NET ADS TESTJOIN. Lookup info for PRINTER on SERVER. The printer name defaults to "*", the server name defaults to the local host. Publish specified printer using ADS. Remove specified printer from ADS directory. Perform a raw LDAP search on a ADS server and dump the results. The expression is a standard LDAP search expression, and the attributes are a list of LDAP fields to show in the results. Example: net ads search '(objectCategory=group)' sAMAccountName Perform a raw LDAP search on a ADS server and dump the results. The DN standard LDAP DN, and the attributes are a list of LDAP fields to show in the result. Example: net ads dn 'CN=administrator,CN=Users,DC=my,DC=domain' SAMAccountName Print out workgroup name for specified kerberos realm. (Re)Create a BUILTIN group. Only a wellknown set of BUILTIN groups can be created with this command. This is the list of currently recognized group names: Administrators, Users, Guests, Power Users, Account Operators, Server Operators, Print Operators, Backup Operators, Replicator, RAS Servers, Pre-Windows 2000 compatible Access. This command requires a running Winbindd with idmap allocation properly configured. The group gid will be allocated out of the winbindd range. Create a LOCAL group (also known as Alias). This command requires a running Winbindd with idmap allocation properly configured. The group gid will be allocated out of the winbindd range. Delete an existing LOCAL group (also known as Alias). Map an existing Unix group and make it a Domain Group, the domain group will have the same name. Remove an existing group mapping entry. Add a member to a Local group. The group can be specified only by name, the member can be specified by name or SID. Remove a member from a Local group. The group and the member must be specified by name. List Local group members. The group must be specified by name. List the specified set of accounts by name. If verbose is specified, the rid and description is also provided for each account. Show the full DOMAIN\\NAME the SID and the type for the corresponding account. Set the home directory for a user account. Set the profile path for a user account. Set the comment for a user or group account. Set the full name for a user account. Set the logon script for a user account. Set the home drive for a user account. Set the workstations a user account is allowed to log in from. Set the "disabled" flag for a user account. Set the "password not required" flag for a user account. Set the "autolock" flag for a user account. Set the "password do not expire" flag for a user account. Set or unset the "password must change" flag for a user account. List the available account policies. Show the account policy value. Set a value for the account policy. Valid values can be: "forever", "never", "off", or a number. Only available if ldapsam:editposix is set and winbindd is running. Properly populates the ldap tree with the basic accounts (Administrator) and groups (Domain Users, Domain Admins, Domain Guests) on the ldap tree. Dumps the mappings contained in the local tdb file specified. This command is useful to dump only the mappings produced by the idmap_tdb backend. Restore the mappings from the specified file or stdin. Store a secret for the specified domain, used primarily for domains that use idmap_ldap as a backend. In this case the secret is used as the password for the user DN used to bind to the ldap server. Starting with version 3.0.23, a Samba server now supports the ability for non-root users to add user defined shares to be exported using the "net usershare" commands. To set this up, first set up your smb.conf by adding to the [global] section: usershare path = /usr/local/samba/lib/usershares Next create the directory /usr/local/samba/lib/usershares, change the owner to root and set the group owner to the UNIX group who should have the ability to create usershares, for example a group called "serverops". Set the permissions on /usr/local/samba/lib/usershares to 01770. (Owner and group all access, no access for others, plus the sticky bit, which means that a file in that directory can be renamed or deleted only by the owner of the file). Finally, tell smbd how many usershares you will allow by adding to the [global] section of smb.conf a line such as : usershare max shares = 100. To allow 100 usershare definitions. Now, members of the UNIX group "serverops" can create user defined shares on demand using the commands below. The usershare commands are: Add or replace a new user defined share, with name "sharename". "path" specifies the absolute pathname on the system to be exported. Restrictions may be put on this, see the global smb.conf parameters: "usershare owner only", "usershare prefix allow list", and "usershare prefix deny list". The optional "comment" parameter is the comment that will appear on the share when browsed to by a client. The optional "acl" field specifies which users have read and write access to the entire share. Note that guest connections are not allowed unless the smb.conf parameter "usershare allow guests" has been set. The definition of a user defined share acl is: "user:permission", where user is a valid username on the system and permission can be "F", "R", or "D". "F" stands for "full permissions", ie. read and write permissions. "D" stands for "deny" for a user, ie. prevent this user from accessing this share. "R" stands for "read only", ie. only allow read access to this share (no creation of new files or directories or writing to files). The default if no "acl" is given is "Everyone:R", which means any authenticated user has read-only access. The optional "guest_ok" has the same effect as the parameter of the same name in smb.conf, in that it allows guest access to this user defined share. This parameter is only allowed if the global parameter "usershare allow guests" has been set to true in the smb.conf. There is no separate command to modify an existing user defined share, just use the "net usershare add [sharename]" command using the same sharename as the one you wish to modify and specify the new options you wish. The Samba smbd daemon notices user defined share modifications at connect time so will see the change immediately, there is no need to restart smbd on adding, deleting or changing a user defined share. Deletes the user defined share by name. The Samba smbd daemon immediately notices this change, although it will not disconnect any users currently connected to the deleted share. Get info on user defined shares owned by the current user matching the given pattern, or all users. net usershare info on its own dumps out info on the user defined shares that were created by the current user, or restricts them to share names that match the given wildcard pattern ('*' matches one or more characters, '?' matches only one character). If the '-l' or '--long' option is also given, it prints out info on user defined shares created by other users. The information given about a share looks like: [foobar] path=/home/jeremy comment=testme usershare_acl=Everyone:F guest_ok=n And is a list of the current settings of the user defined share that can be modified by the "net usershare add" command. List all the user defined shares owned by the current user matching the given pattern, or all users. net usershare list on its own list out the names of the user defined shares that were created by the current user, or restricts the list to share names that match the given wildcard pattern ('*' matches one or more characters, '?' matches only one character). If the '-l' or '--long' option is also given, it includes the names of user defined shares created by other users. Gives usage information for the specified command. This man page is complete for version 3.0 of the Samba suite. The original Samba software and related utilities were created by Andrew Tridgell. Samba is now developed by the Samba Team as an Open Source project similar to the way the Linux kernel is developed. The net manpage was written by Jelmer Vernooij. Advertisements 129 Lectures 23 hours Eduonix Learning Solutions 5 Lectures 4.5 hours Frahaan Hussain 35 Lectures 2 hours Pradeep D 41 Lectures 2.5 hours Musab Zayadneh 46 Lectures 4 hours GUHARAJANM 6 Lectures 4 hours Uplatz Print Add Notes Bookmark this page
[ { "code": null, "e": 10620, "s": 10577, "text": "\nThis tool is part of the\nsamba(7)\nsuite.\n" }, { "code": null, "e": 11059, "s": 10620, "text": "\nThe Samba net utility is meant to work just like the net utility available for windows and DOS. The first argument should be used to specify the protocol to use when executing a certain command. ADS is used for ActiveDirectory, RAP is using for old (Win9x/NT3) clients and RPC can be used for NT4 and Windows 2000. If this argument is omitted, net will try to determine it automatically. Not all commands are available on all protocols.\n" }, { "code": null, "e": 11112, "s": 11059, "text": "\n-h|--help\nPrint a summary of command line options.\n" }, { "code": null, "e": 11249, "s": 11112, "text": "\n-w target-workgroup\nSets target workgroup or domain. You have to specify either this option or the IP address or the name of a server.\n" }, { "code": null, "e": 11296, "s": 11249, "text": "\n-W workgroup\nSets client workgroup or domain\n" }, { "code": null, "e": 11323, "s": 11296, "text": "\n-U user\nUser name to use\n" }, { "code": null, "e": 11456, "s": 11323, "text": "\n-I ip-address\nIP address of target server to use. You have to specify either this option or a target workgroup or a target server.\n" }, { "code": null, "e": 11568, "s": 11456, "text": "\n-p port\nPort on the target server to connect to (usually 139 or 445). Defaults to trying 445 first, then 139.\n" }, { "code": null, "e": 11834, "s": 11568, "text": "\n-n <primary NetBIOS name>\nThis option allows you to override the NetBIOS name that Samba uses for itself. This is identical to setting the\nnetbios name\nparameter in the\nsmb.conf\nfile. However, a command line setting will take precedence over settings in\nsmb.conf.\n" }, { "code": null, "e": 12216, "s": 11834, "text": "\n-s <configuration file>\nThe file specified contains the configuration details required by the server. The information in this file includes server-specific information such as what printcap file to use, as well as descriptions of all the services that the server is to provide. See\nsmb.conf\nfor more information. The default configuration file name is determined at compile time.\n" }, { "code": null, "e": 12335, "s": 12216, "text": "\n-S server\nName of target server. You should specify either this option or a target workgroup or a target IP address.\n" }, { "code": null, "e": 12395, "s": 12335, "text": "\n-l\nWhen listing data, give more information on each item.\n" }, { "code": null, "e": 12483, "s": 12395, "text": "\n-P\nMake queries to the external server using the machine account of the local server.\n" }, { "code": null, "e": 12600, "s": 12483, "text": "\n-d|--debuglevel=level\nlevel\nis an integer from 0 to 10. The default value if this parameter is not specified is 0.\n" }, { "code": null, "e": 12907, "s": 12600, "text": "\nThe higher this value, the more detail will be logged to the log files about the activities of the server. At level 0, only critical errors and serious warnings will be logged. Level 1 is a reasonable level for day-to-day running - it generates a small amount of information about operations carried out.\n" }, { "code": null, "e": 13156, "s": 12907, "text": "\nLevels above 1 will generate considerable amounts of log data, and should only be used when investigating a problem. Levels above 3 are designed for use only by developers and generate HUGE amounts of log data, most of which is extremely cryptic.\n" }, { "code": null, "e": 13259, "s": 13156, "text": "\nNote that specifying this parameter here will override the\nlog level\nparameter in the\nsmb.conf\nfile.\n" }, { "code": null, "e": 13882, "s": 13259, "text": "\nThis command allows the Samba machine account password to be set from an external application to a machine account password that has already been stored in Active Directory. DO NOT USE this command unless you know exactly what you are doing. The use of this command requires that the force flag (-f) be used also. There will be NO command prompt. Whatever information is piped into stdin, either by typing at the command line or otherwise, will be stored as the literal machine password. Do NOT use this without care and attention as it will overwrite a legitimate machine password without warning. YOU HAVE BEEN WARNED.\n" }, { "code": null, "e": 14032, "s": 13882, "text": "\nThe\nNET TIME\ncommand allows you to view the time on a remote server or synchronise the time on the local server with the time on the remote server.\n" }, { "code": null, "e": 14116, "s": 14032, "text": "\nWithout any options, the\nNET TIME\ncommand displays the time on the remote server.\n" }, { "code": null, "e": 14190, "s": 14116, "text": "\nDisplays the time on the remote server in a format ready for\n/bin/date.\n" }, { "code": null, "e": 14289, "s": 14190, "text": "\nTries to set the date and time of the local server to that on the remote server using\n/bin/date.\n" }, { "code": null, "e": 14355, "s": 14289, "text": "\nDisplays the timezone in hours from GMT on the remote computer.\n" }, { "code": null, "e": 14628, "s": 14355, "text": "\nJoin a domain. If the account already exists on the server, and [TYPE] is MEMBER, the machine will attempt to join automatically. (Assuming that the machine has been created in server manager) Otherwise, a password will be prompted for, and a new account may be created.\n" }, { "code": null, "e": 14713, "s": 14628, "text": "\n[TYPE] may be PDC, BDC or MEMBER to specify the type of server joining the domain.\n" }, { "code": null, "e": 14827, "s": 14713, "text": "\n[UPN] (ADS only) set the principalname attribute during the join. The default format is host/netbiosname@REALM.\n" }, { "code": null, "e": 15137, "s": 14827, "text": "\n[OU] (ADS only) Precreate the computer account in a specific OU. The OU string reads from top to bottom without RDNs, and is delimited by a '/'. Please note that '\\' is used for escape by both the shell and ldap, so it may need to be doubled or quadrupled to pass through, and it is not used as a delimiter.\n" }, { "code": null, "e": 15296, "s": 15137, "text": "\nJoin a domain. Use the OLDJOIN option to join the domain using the old style of domain joining - you need to create a trust account in server manager first.\n" }, { "code": null, "e": 15313, "s": 15296, "text": "\nList all users\n" }, { "code": null, "e": 15337, "s": 15313, "text": "\nDelete specified user\n" }, { "code": null, "e": 15385, "s": 15337, "text": "\nList the domain groups of the specified user.\n" }, { "code": null, "e": 15410, "s": 15385, "text": "\nRename specified user.\n" }, { "code": null, "e": 15432, "s": 15410, "text": "\nAdd specified user.\n" }, { "code": null, "e": 15452, "s": 15432, "text": "\nList user groups.\n" }, { "code": null, "e": 15478, "s": 15452, "text": "\nDelete specified group.\n" }, { "code": null, "e": 15504, "s": 15478, "text": "\nCreate specified group.\n" }, { "code": null, "e": 15575, "s": 15504, "text": "\nEnumerates all exported resources (network shares) on target server.\n" }, { "code": null, "e": 15721, "s": 15575, "text": "\nAdds a share from a server (makes the export active). Maxusers specifies the number of users that can be connected to the share simultaneously.\n" }, { "code": null, "e": 15747, "s": 15721, "text": "\nDelete specified share.\n" }, { "code": null, "e": 15787, "s": 15747, "text": "\nList all open files on remote server.\n" }, { "code": null, "e": 15840, "s": 15787, "text": "\nClose file with specified\nfileid\non remote server.\n" }, { "code": null, "e": 15948, "s": 15840, "text": "\nPrint information on specified\nfileid. Currently listed are: file-id, username, locks, path, permissions.\n" }, { "code": null, "e": 16059, "s": 15948, "text": "\nList files opened by specified\nuser. Please note that\nnet rap file user\ndoes not work against Samba servers.\n" }, { "code": null, "e": 16158, "s": 16059, "text": "\nWithout any other options, SESSION enumerates all active SMB/CIFS sessions on the target server.\n" }, { "code": null, "e": 16190, "s": 16158, "text": "\nClose the specified sessions.\n" }, { "code": null, "e": 16250, "s": 16190, "text": "\nGive a list with all the open files in specified session.\n" }, { "code": null, "e": 16329, "s": 16250, "text": "\nList all servers in specified domain or workgroup. Defaults to local domain.\n" }, { "code": null, "e": 16396, "s": 16329, "text": "\nLists all domains and workgroups visible on the current network.\n" }, { "code": null, "e": 16513, "s": 16396, "text": "\nLists the specified print queue and print jobs on the server. If the\nQUEUE_NAME\nis omitted, all queues are listed.\n" }, { "code": null, "e": 16545, "s": 16513, "text": "\nDelete job with specified id.\n" }, { "code": null, "e": 16690, "s": 16545, "text": "\nValidate whether the specified user can log in to the remote server. If the password is not specified on the commandline, it will be prompted.\n" }, { "code": null, "e": 16698, "s": 16690, "text": "\n\nNote\n" }, { "code": null, "e": 16727, "s": 16698, "text": "\nCurrently NOT implemented.\n" }, { "code": null, "e": 16770, "s": 16727, "text": "\nList all members of the specified group.\n" }, { "code": null, "e": 16798, "s": 16770, "text": "\nDelete member from group.\n" }, { "code": null, "e": 16821, "s": 16798, "text": "\nAdd member to group.\n" }, { "code": null, "e": 16905, "s": 16821, "text": "\nExecute the specified\ncommand\non the remote server. Only works with OS/2 servers.\n" }, { "code": null, "e": 16913, "s": 16905, "text": "\n\nNote\n" }, { "code": null, "e": 16942, "s": 16913, "text": "\nCurrently NOT implemented.\n" }, { "code": null, "e": 17015, "s": 16942, "text": "\nStart the specified service on the remote server. Not implemented yet.\n" }, { "code": null, "e": 17023, "s": 17015, "text": "\n\nNote\n" }, { "code": null, "e": 17052, "s": 17023, "text": "\nCurrently NOT implemented.\n" }, { "code": null, "e": 17105, "s": 17054, "text": "\nStop the specified service on the remote server.\n" }, { "code": null, "e": 17113, "s": 17105, "text": "\n\nNote\n" }, { "code": null, "e": 17142, "s": 17113, "text": "\nCurrently NOT implemented.\n" }, { "code": null, "e": 17193, "s": 17142, "text": "\nChange password of\nUSER\nfrom\nOLDPASS\nto\nNEWPASS.\n" }, { "code": null, "e": 17318, "s": 17193, "text": "\nLookup the IP address of the given host with the specified type (netbios suffix). The type defaults to 0x20 (workstation).\n" }, { "code": null, "e": 17398, "s": 17318, "text": "\nGive IP address of LDAP server of specified\nDOMAIN. Defaults to local domain.\n" }, { "code": null, "e": 17473, "s": 17398, "text": "\nGive IP address of KDC for the specified\nREALM. Defaults to local realm.\n" }, { "code": null, "e": 17556, "s": 17473, "text": "\nGive IP's of Domain Controllers for specified\n DOMAIN. Defaults to local domain.\n" }, { "code": null, "e": 17645, "s": 17556, "text": "\nGive IP of master browser for specified\nDOMAIN\nor workgroup. Defaults to local domain.\n" }, { "code": null, "e": 17745, "s": 17645, "text": "\nSamba uses a general caching interface called 'gencache'. It can be controlled using 'NET CACHE'.\n" }, { "code": null, "e": 17796, "s": 17745, "text": "\nAll the timeout parameters support the suffixes:\n" }, { "code": null, "e": 17860, "s": 17798, "text": "\nAdd specified key+data to the cache with the given timeout.\n" }, { "code": null, "e": 17889, "s": 17860, "text": "\nDelete key from the cache.\n" }, { "code": null, "e": 17928, "s": 17889, "text": "\nUpdate data of existing cache entry.\n" }, { "code": null, "e": 17982, "s": 17928, "text": "\nSearch for the specified pattern in the cache data.\n" }, { "code": null, "e": 18021, "s": 17982, "text": "\nList all current items in the cache.\n" }, { "code": null, "e": 18068, "s": 18021, "text": "\nRemove all the current items from the cache.\n" }, { "code": null, "e": 18171, "s": 18068, "text": "\nPrints the SID of the specified domain, or if the parameter is omitted, the SID of the local server.\n" }, { "code": null, "e": 18225, "s": 18171, "text": "\nSets SID for the local server to the specified SID.\n" }, { "code": null, "e": 18291, "s": 18225, "text": "\nPrints the local machine SID and the SID of the current domain.\n" }, { "code": null, "e": 18329, "s": 18291, "text": "\nSets the SID of the current domain.\n" }, { "code": null, "e": 18419, "s": 18329, "text": "\nManage the mappings between Windows group SIDs and UNIX groups. Common options include:\n" }, { "code": null, "e": 18425, "s": 18419, "text": "\n\no\n\n" }, { "code": null, "e": 18433, "s": 18427, "text": "\n\no\n\n" }, { "code": null, "e": 18441, "s": 18435, "text": "\n\no\n\n" }, { "code": null, "e": 18449, "s": 18443, "text": "\n\no\n\n" }, { "code": null, "e": 18457, "s": 18451, "text": "\n\no\n\n" }, { "code": null, "e": 18465, "s": 18459, "text": "\n\no\n\n" }, { "code": null, "e": 18502, "s": 18469, "text": "\nAdd a new group mapping entry:\n" }, { "code": null, "e": 18626, "s": 18504, "text": "net groupmap add {rid=int|sid=string} unixgroup=string \\\n [type={domain|local}] [ntgroup=string] [comment=string]\n" }, { "code": null, "e": 18733, "s": 18630, "text": "\nDelete a group mapping entry. If more than one group name matches, the first entry found is deleted.\n" }, { "code": null, "e": 18780, "s": 18733, "text": "\nnet groupmap delete {ntgroup=string|sid=SID}\n" }, { "code": null, "e": 18814, "s": 18780, "text": "\nUpdate en existing group entry.\n" }, { "code": null, "e": 18933, "s": 18820, "text": "net groupmap modify {ntgroup=string|sid=SID} [unixgroup=string] \\\n [comment=string] [type={domain|local}]\n" }, { "code": null, "e": 18976, "s": 18937, "text": "\nList existing group mapping entries.\n" }, { "code": null, "e": 19033, "s": 18976, "text": "\nnet groupmap list [verbose] [ntgroup=string] [sid=SID]\n" }, { "code": null, "e": 19133, "s": 19033, "text": "\nPrints out the highest RID currently in use on the local server (by the active 'passdb backend').\n" }, { "code": null, "e": 19256, "s": 19133, "text": "\nPrint information about the domain of the remote server, such as domain name, domain sid and number of users and groups.\n" }, { "code": null, "e": 19314, "s": 19256, "text": "\nCheck whether participation in a domain is still valid.\n" }, { "code": null, "e": 19355, "s": 19314, "text": "\nForce change of domain trust password.\n" }, { "code": null, "e": 19659, "s": 19355, "text": "\nAdd a interdomain trust account for\nDOMAIN. This is in fact a Samba account named\nDOMAIN$\nwith the account flag\n'I'\n(interdomain trust account). If the command is used against localhost it has the same effect as\nsmbpasswd -a -i DOMAIN. Please note that both commands expect a appropriate UNIX account.\n" }, { "code": null, "e": 19786, "s": 19659, "text": "\nRemove interdomain trust account for\nDOMAIN. If it is used against localhost it has the same effect as\nsmbpasswd -x DOMAIN$.\n" }, { "code": null, "e": 19904, "s": 19786, "text": "\nEstablish a trust relationship to a trusting domain. Interdomain account must already be created on the remote PDC.\n" }, { "code": null, "e": 19945, "s": 19904, "text": "\nAbandon relationship to trusted domain\n" }, { "code": null, "e": 19997, "s": 19945, "text": "\nList all current interdomain trust relationships.\n" }, { "code": null, "e": 20269, "s": 19997, "text": "\nThis subcommand is used to view and manage Samba's rights assignments (also referred to as privileges). There are three options currently available:\nlist,\ngrant, and\nrevoke. More details on Samba's privilege model and its use can be found in the Samba-HOWTO-Collection.\n" }, { "code": null, "e": 20310, "s": 20269, "text": "\nAbort the shutdown of a remote server.\n" }, { "code": null, "e": 20341, "s": 20310, "text": "\nShut down the remote server.\n" }, { "code": null, "e": 20369, "s": 20341, "text": "\n-r\nReboot after shutdown.\n" }, { "code": null, "e": 20412, "s": 20369, "text": "\n-f\nForce shutting down all applications.\n" }, { "code": null, "e": 20545, "s": 20412, "text": "\n-t timeout\nTimeout before system will be shut down. An interactive user of the system can use this time to cancel the shutdown.\n'>\n" }, { "code": null, "e": 20628, "s": 20545, "text": "\n-C message\nDisplay the specified message on the screen to announce the shutdown.\n" }, { "code": null, "e": 20747, "s": 20628, "text": "\nPrint out sam database of remote server. You need to run this against the PDC, from a Samba machine joined as a BDC.\n" }, { "code": null, "e": 20894, "s": 20747, "text": "\nExport users, aliases and groups from remote server to local server. You need to run this against the PDC, from a Samba machine joined as a BDC.\n" }, { "code": null, "e": 20952, "s": 20894, "text": "\nFetch domain SID and store it in the local\nsecrets.tdb.\n" }, { "code": null, "e": 21007, "s": 20952, "text": "\nMake the remote host leave the domain it is part of.\n" }, { "code": null, "e": 21172, "s": 21007, "text": "\nPrint out status of machine account of the local machine in ADS. Prints out quite some debug info. Aimed at developers, regular users should use\nNET ADS TESTJOIN.\n" }, { "code": null, "e": 21287, "s": 21172, "text": "\nLookup info for\nPRINTER\non\nSERVER. The printer name defaults to \"*\", the server name defaults to the local host.\n" }, { "code": null, "e": 21326, "s": 21287, "text": "\nPublish specified printer using ADS.\n" }, { "code": null, "e": 21373, "s": 21326, "text": "\nRemove specified printer from ADS directory.\n" }, { "code": null, "e": 21561, "s": 21373, "text": "\nPerform a raw LDAP search on a ADS server and dump the results. The expression is a standard LDAP search expression, and the attributes are a list of LDAP fields to show in the results.\n" }, { "code": null, "e": 21627, "s": 21561, "text": "\nExample:\nnet ads search '(objectCategory=group)' sAMAccountName\n" }, { "code": null, "e": 21786, "s": 21627, "text": "\nPerform a raw LDAP search on a ADS server and dump the results. The DN standard LDAP DN, and the attributes are a list of LDAP fields to show in the result.\n" }, { "code": null, "e": 21867, "s": 21786, "text": "\nExample:\nnet ads dn 'CN=administrator,CN=Users,DC=my,DC=domain' SAMAccountName\n" }, { "code": null, "e": 21924, "s": 21867, "text": "\nPrint out workgroup name for specified kerberos realm.\n" }, { "code": null, "e": 22401, "s": 21924, "text": "\n(Re)Create a BUILTIN group. Only a wellknown set of BUILTIN groups can be created with this command. This is the list of currently recognized group names: Administrators, Users, Guests, Power Users, Account Operators, Server Operators, Print Operators, Backup Operators, Replicator, RAS Servers, Pre-Windows 2000 compatible Access. This command requires a running Winbindd with idmap allocation properly configured. The group gid will be allocated out of the winbindd range.\n" }, { "code": null, "e": 22590, "s": 22401, "text": "\nCreate a LOCAL group (also known as Alias). This command requires a running Winbindd with idmap allocation properly configured. The group gid will be allocated out of the winbindd range.\n" }, { "code": null, "e": 22646, "s": 22590, "text": "\nDelete an existing LOCAL group (also known as Alias).\n" }, { "code": null, "e": 22745, "s": 22646, "text": "\nMap an existing Unix group and make it a Domain Group, the domain group will have the same name.\n" }, { "code": null, "e": 22787, "s": 22745, "text": "\nRemove an existing group mapping entry.\n" }, { "code": null, "e": 22905, "s": 22787, "text": "\nAdd a member to a Local group. The group can be specified only by name, the member can be specified by name or SID.\n" }, { "code": null, "e": 22995, "s": 22905, "text": "\nRemove a member from a Local group. The group and the member must be specified by name.\n" }, { "code": null, "e": 23060, "s": 22995, "text": "\nList Local group members. The group must be specified by name.\n" }, { "code": null, "e": 23190, "s": 23060, "text": "\nList the specified set of accounts by name. If verbose is specified, the rid and description is also provided for each account.\n" }, { "code": null, "e": 23271, "s": 23190, "text": "\nShow the full DOMAIN\\\\NAME the SID and the type for the corresponding account.\n" }, { "code": null, "e": 23316, "s": 23271, "text": "\nSet the home directory for a user account.\n" }, { "code": null, "e": 23359, "s": 23316, "text": "\nSet the profile path for a user account.\n" }, { "code": null, "e": 23406, "s": 23359, "text": "\nSet the comment for a user or group account.\n" }, { "code": null, "e": 23446, "s": 23406, "text": "\nSet the full name for a user account.\n" }, { "code": null, "e": 23489, "s": 23446, "text": "\nSet the logon script for a user account.\n" }, { "code": null, "e": 23530, "s": 23489, "text": "\nSet the home drive for a user account.\n" }, { "code": null, "e": 23595, "s": 23530, "text": "\nSet the workstations a user account is allowed to log in from.\n" }, { "code": null, "e": 23641, "s": 23595, "text": "\nSet the \"disabled\" flag for a user account.\n" }, { "code": null, "e": 23700, "s": 23641, "text": "\nSet the \"password not required\" flag for a user account.\n" }, { "code": null, "e": 23746, "s": 23700, "text": "\nSet the \"autolock\" flag for a user account.\n" }, { "code": null, "e": 23806, "s": 23746, "text": "\nSet the \"password do not expire\" flag for a user account.\n" }, { "code": null, "e": 23873, "s": 23806, "text": "\nSet or unset the \"password must change\" flag for a user account.\n" }, { "code": null, "e": 23912, "s": 23873, "text": "\nList the available account policies.\n" }, { "code": null, "e": 23945, "s": 23912, "text": "\nShow the account policy value.\n" }, { "code": null, "e": 24044, "s": 23945, "text": "\nSet a value for the account policy. Valid values can be: \"forever\", \"never\", \"off\", or a number.\n" }, { "code": null, "e": 24261, "s": 24044, "text": "\nOnly available if ldapsam:editposix is set and winbindd is running. Properly populates the ldap tree with the basic accounts (Administrator) and groups (Domain Users, Domain Admins, Domain Guests) on the ldap tree.\n" }, { "code": null, "e": 24409, "s": 24261, "text": "\nDumps the mappings contained in the local tdb file specified. This command is useful to dump only the mappings produced by the idmap_tdb backend.\n" }, { "code": null, "e": 24466, "s": 24409, "text": "\nRestore the mappings from the specified file or stdin.\n" }, { "code": null, "e": 24667, "s": 24466, "text": "\nStore a secret for the specified domain, used primarily for domains that use idmap_ldap as a backend. In this case the secret is used as the password for the user DN used to bind to the ldap server.\n" }, { "code": null, "e": 24836, "s": 24667, "text": "\nStarting with version 3.0.23, a Samba server now supports the ability for non-root users to add user defined shares to be exported using the \"net usershare\" commands.\n" }, { "code": null, "e": 25709, "s": 24836, "text": "\nTo set this up, first set up your smb.conf by adding to the [global] section: usershare path = /usr/local/samba/lib/usershares Next create the directory /usr/local/samba/lib/usershares, change the owner to root and set the group owner to the UNIX group who should have the ability to create usershares, for example a group called \"serverops\". Set the permissions on /usr/local/samba/lib/usershares to 01770. (Owner and group all access, no access for others, plus the sticky bit, which means that a file in that directory can be renamed or deleted only by the owner of the file). Finally, tell smbd how many usershares you will allow by adding to the [global] section of smb.conf a line such as : usershare max shares = 100. To allow 100 usershare definitions. Now, members of the UNIX group \"serverops\" can create user defined shares on demand using the commands below.\n" }, { "code": null, "e": 25739, "s": 25709, "text": "\nThe usershare commands are:\n" }, { "code": null, "e": 25807, "s": 25741, "text": "\nAdd or replace a new user defined share, with name \"sharename\".\n" }, { "code": null, "e": 26036, "s": 25807, "text": "\n\"path\" specifies the absolute pathname on the system to be exported. Restrictions may be put on this, see the global smb.conf parameters: \"usershare owner only\", \"usershare prefix allow list\", and \"usershare prefix deny list\".\n" }, { "code": null, "e": 26145, "s": 26036, "text": "\nThe optional \"comment\" parameter is the comment that will appear on the share when browsed to by a client.\n" }, { "code": null, "e": 26788, "s": 26145, "text": "\nThe optional \"acl\" field specifies which users have read and write access to the entire share. Note that guest connections are not allowed unless the smb.conf parameter \"usershare allow guests\" has been set. The definition of a user defined share acl is: \"user:permission\", where user is a valid username on the system and permission can be \"F\", \"R\", or \"D\". \"F\" stands for \"full permissions\", ie. read and write permissions. \"D\" stands for \"deny\" for a user, ie. prevent this user from accessing this share. \"R\" stands for \"read only\", ie. only allow read access to this share (no creation of new files or directories or writing to files).\n" }, { "code": null, "e": 26897, "s": 26788, "text": "\nThe default if no \"acl\" is given is \"Everyone:R\", which means any authenticated user has read-only access.\n" }, { "code": null, "e": 27167, "s": 26897, "text": "\nThe optional \"guest_ok\" has the same effect as the parameter of the same name in smb.conf, in that it allows guest access to this user defined share. This parameter is only allowed if the global parameter \"usershare allow guests\" has been set to true in the smb.conf.\n" }, { "code": null, "e": 27590, "s": 27169, "text": "\nThere is no separate command to modify an existing user defined share,\njust use the \"net usershare add [sharename]\" command using the same\nsharename as the one you wish to modify and specify the new options\nyou wish. The Samba smbd daemon notices user defined share modifications\nat connect time so will see the change immediately, there is no need\nto restart smbd on adding, deleting or changing a user defined share.\n" }, { "code": null, "e": 27771, "s": 27590, "text": "\nDeletes the user defined share by name. The Samba smbd daemon immediately notices this change, although it will not disconnect any users currently connected to the deleted share.\n" }, { "code": null, "e": 27873, "s": 27771, "text": "\nGet info on user defined shares owned by the current user matching the given pattern, or all users.\n" }, { "code": null, "e": 28239, "s": 27873, "text": "\nnet usershare info on its own dumps out info on the user defined shares that were created by the current user, or restricts them to share names that match the given wildcard pattern ('*' matches one or more characters, '?' matches only one character). If the '-l' or '--long' option is also given, it prints out info on user defined shares created by other users.\n" }, { "code": null, "e": 28488, "s": 28239, "text": "\nThe information given about a share looks like: [foobar] path=/home/jeremy comment=testme usershare_acl=Everyone:F guest_ok=n And is a list of the current settings of the user defined share that can be modified by the \"net usershare add\" command.\n" }, { "code": null, "e": 28591, "s": 28488, "text": "\nList all the user defined shares owned by the current user matching the given pattern, or all users.\n" }, { "code": null, "e": 28968, "s": 28591, "text": "\nnet usershare list on its own list out the names of the user defined shares that were created by the current user, or restricts the list to share names that match the given wildcard pattern ('*' matches one or more characters, '?' matches only one character). If the '-l' or '--long' option is also given, it includes the names of user defined shares created by other users.\n" }, { "code": null, "e": 29021, "s": 28968, "text": "\nGives usage information for the specified command.\n" }, { "code": null, "e": 29085, "s": 29021, "text": "\nThis man page is complete for version 3.0 of the Samba suite.\n" }, { "code": null, "e": 29287, "s": 29085, "text": "\nThe original Samba software and related utilities were created by Andrew Tridgell. Samba is now developed by the Samba Team as an Open Source project similar to the way the Linux kernel is developed.\n" }, { "code": null, "e": 29346, "s": 29287, "text": "\nThe net manpage was written by Jelmer Vernooij.\n\n\n\n\n\n\n\n\n\n" }, { "code": null, "e": 29363, "s": 29346, "text": "\nAdvertisements\n" }, { "code": null, "e": 29398, "s": 29363, "text": "\n 129 Lectures \n 23 hours \n" }, { "code": null, "e": 29426, "s": 29398, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 29460, "s": 29426, "text": "\n 5 Lectures \n 4.5 hours \n" }, { "code": null, "e": 29477, "s": 29460, "text": " Frahaan Hussain" }, { "code": null, "e": 29510, "s": 29477, "text": "\n 35 Lectures \n 2 hours \n" }, { "code": null, "e": 29521, "s": 29510, "text": " Pradeep D" }, { "code": null, "e": 29556, "s": 29521, "text": "\n 41 Lectures \n 2.5 hours \n" }, { "code": null, "e": 29572, "s": 29556, "text": " Musab Zayadneh" }, { "code": null, "e": 29605, "s": 29572, "text": "\n 46 Lectures \n 4 hours \n" }, { "code": null, "e": 29617, "s": 29605, "text": " GUHARAJANM" }, { "code": null, "e": 29649, "s": 29617, "text": "\n 6 Lectures \n 4 hours \n" }, { "code": null, "e": 29657, "s": 29649, "text": " Uplatz" }, { "code": null, "e": 29664, "s": 29657, "text": " Print" }, { "code": null, "e": 29675, "s": 29664, "text": " Add Notes" } ]
Difference between 1's Complement representation and 2's Complement representation Technique - GeeksforGeeks
26 Apr, 2021 Prerequisite – Representation of Negative Binary Numbers 1’s complement of a binary number is another binary number obtained by toggling all bits in it, i.e., transforming the 0 bit to 1 and the 1 bit to 0. Examples: Let numbers be stored using 4 bits 1's complement of 7 (0111) is 8 (1000) 1's complement of 12 (1100) is 3 (0011) 2’s complement of a binary number is 1 added to the 1’s complement of the binary number.Examples: Let numbers be stored using 4 bits 2's complement of 7 (0111) is 9 (1001) 2's complement of 12 (1100) is 4 (0100) These representations are used for signed numbers. The main difference between 1′ s complement and 2′ s complement is that 1′ s complement has two representations of 0 (zero) – 00000000, which is positive zero (+0) and 11111111, which is negative zero (-0); whereas in 2′ s complement, there is only one representation for zero – 00000000 (+0) because if we add 1 to 11111111 (-1), we get 00000000 (+0) which is the same as positive zero. This is the reason why 2′ s complement is generally used. Another difference is that while adding numbers using 1′ s complement, we first do binary addition, then add in an end-around carry value. But, 2′ s complement has only one value for zero, and doesn’t require carry values. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above base-conversion complement Computer Organization & Architecture Difference Between Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Cache Memory in Computer Organization Addressing Modes Architecture of 8086 Logical and Physical Address in Operating System Random Access Memory (RAM) and Read Only Memory (ROM) Difference between BFS and DFS Class method vs Static method in Python Differences between TCP and UDP Difference between var, let and const keywords in JavaScript Difference between Process and Thread
[ { "code": null, "e": 26443, "s": 26415, "text": "\n26 Apr, 2021" }, { "code": null, "e": 26500, "s": 26443, "text": "Prerequisite – Representation of Negative Binary Numbers" }, { "code": null, "e": 26650, "s": 26500, "text": "1’s complement of a binary number is another binary number obtained by toggling all bits in it, i.e., transforming the 0 bit to 1 and the 1 bit to 0." }, { "code": null, "e": 26660, "s": 26650, "text": "Examples:" }, { "code": null, "e": 26776, "s": 26660, "text": "Let numbers be stored using 4 bits\n\n1's complement of 7 (0111) is 8 (1000)\n1's complement of 12 (1100) is 3 (0011)\n" }, { "code": null, "e": 26874, "s": 26776, "text": "2’s complement of a binary number is 1 added to the 1’s complement of the binary number.Examples:" }, { "code": null, "e": 26990, "s": 26874, "text": "Let numbers be stored using 4 bits\n\n2's complement of 7 (0111) is 9 (1001)\n2's complement of 12 (1100) is 4 (0100)\n" }, { "code": null, "e": 27043, "s": 26992, "text": "These representations are used for signed numbers." }, { "code": null, "e": 27489, "s": 27043, "text": "The main difference between 1′ s complement and 2′ s complement is that 1′ s complement has two representations of 0 (zero) – 00000000, which is positive zero (+0) and 11111111, which is negative zero (-0); whereas in 2′ s complement, there is only one representation for zero – 00000000 (+0) because if we add 1 to 11111111 (-1), we get 00000000 (+0) which is the same as positive zero. This is the reason why 2′ s complement is generally used." }, { "code": null, "e": 27712, "s": 27489, "text": "Another difference is that while adding numbers using 1′ s complement, we first do binary addition, then add in an end-around carry value. But, 2′ s complement has only one value for zero, and doesn’t require carry values." }, { "code": null, "e": 27836, "s": 27712, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above" }, { "code": null, "e": 27852, "s": 27836, "text": "base-conversion" }, { "code": null, "e": 27863, "s": 27852, "text": "complement" }, { "code": null, "e": 27900, "s": 27863, "text": "Computer Organization & Architecture" }, { "code": null, "e": 27919, "s": 27900, "text": "Difference Between" }, { "code": null, "e": 28017, "s": 27919, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28026, "s": 28017, "text": "Comments" }, { "code": null, "e": 28039, "s": 28026, "text": "Old Comments" }, { "code": null, "e": 28077, "s": 28039, "text": "Cache Memory in Computer Organization" }, { "code": null, "e": 28094, "s": 28077, "text": "Addressing Modes" }, { "code": null, "e": 28115, "s": 28094, "text": "Architecture of 8086" }, { "code": null, "e": 28164, "s": 28115, "text": "Logical and Physical Address in Operating System" }, { "code": null, "e": 28218, "s": 28164, "text": "Random Access Memory (RAM) and Read Only Memory (ROM)" }, { "code": null, "e": 28249, "s": 28218, "text": "Difference between BFS and DFS" }, { "code": null, "e": 28289, "s": 28249, "text": "Class method vs Static method in Python" }, { "code": null, "e": 28321, "s": 28289, "text": "Differences between TCP and UDP" }, { "code": null, "e": 28382, "s": 28321, "text": "Difference between var, let and const keywords in JavaScript" } ]
SAP ABAP - Object Events
An event is a set of outcomes that are defined in a class to trigger the event handlers in other classes. When an event is triggered, we can call any number of event handler methods. The link between a trigger and its handler method is actually decided dynamically at run-time. In a normal method call, a calling program determines which method of an object or a class needs to be called. As fixed handler method is not registered for every event, in case of event handling, the handler method determines the event that needs to be triggered. An event of a class can trigger an event handler method of the same class by using the RAISE EVENT statement. For an event, the event handler method can be defined in the same or different class by using the FOR EVENT clause, as shown in the following syntax − FOR EVENT <event_name> OF <class_name>. Similar to the methods of a class, an event can have parameter interface but it has only output parameters. The output parameters are passed to the event handler method by the RAISE EVENT statement that receives them as input parameters. An event is linked to its handler method dynamically in a program by using the SET HANDLER statement. When an event is triggered, appropriate event handler methods are supposed to be executed in all the handling classes. REPORT ZEVENT1. CLASS CL_main DEFINITION. PUBLIC SECTION. DATA: num1 TYPE I. METHODS: PRO IMPORTING num2 TYPE I. EVENTS: CUTOFF. ENDCLASS. CLASS CL_eventhandler DEFINITION. PUBLIC SECTION. METHODS: handling_CUTOFF FOR EVENT CUTOFF OF CL_main. ENDCLASS. START-OF-SELECTION. DATA: main1 TYPE REF TO CL_main. DATA: eventhandler1 TYPE REF TO CL_eventhandler. CREATE OBJECT main1. CREATE OBJECT eventhandler1. SET HANDLER eventhandler1→handling_CUTOFF FOR main1. main1→PRO( 4 ). CLASS CL_main IMPLEMENTATION. METHOD PRO. num1 = num2. IF num2 ≥ 2. RAISE EVENT CUTOFF. ENDIF. ENDMETHOD. ENDCLASS. CLASS CL_eventhandler IMPLEMENTATION. METHOD handling_CUTOFF. WRITE: 'Handling the CutOff'. WRITE: / 'Event has been processed'. ENDMETHOD. ENDCLASS. The above code produces the following output − Handling the CutOff Event has been processed 25 Lectures 6 hours Sanjo Thomas 26 Lectures 2 hours Neha Gupta 30 Lectures 2.5 hours Sumit Agarwal 30 Lectures 4 hours Sumit Agarwal 14 Lectures 1.5 hours Neha Malik 13 Lectures 1.5 hours Neha Malik Print Add Notes Bookmark this page
[ { "code": null, "e": 3176, "s": 2898, "text": "An event is a set of outcomes that are defined in a class to trigger the event handlers in other classes. When an event is triggered, we can call any number of event handler methods. The link between a trigger and its handler method is actually decided dynamically at run-time." }, { "code": null, "e": 3441, "s": 3176, "text": "In a normal method call, a calling program determines which method of an object or a class needs to be called. As fixed handler method is not registered for every event, in case of event handling, the handler method determines the event that needs to be triggered." }, { "code": null, "e": 3702, "s": 3441, "text": "An event of a class can trigger an event handler method of the same class by using the RAISE EVENT statement. For an event, the event handler method can be defined in the same or different class by using the FOR EVENT clause, as shown in the following syntax −" }, { "code": null, "e": 3743, "s": 3702, "text": "FOR EVENT <event_name> OF <class_name>.\n" }, { "code": null, "e": 4083, "s": 3743, "text": "Similar to the methods of a class, an event can have parameter interface but it has only output parameters. The output parameters are passed to the event handler method by the RAISE EVENT statement that receives them as input parameters. An event is linked to its handler method dynamically in a program by using the SET HANDLER statement." }, { "code": null, "e": 4202, "s": 4083, "text": "When an event is triggered, appropriate event handler methods are supposed to be executed in all the handling classes." }, { "code": null, "e": 4968, "s": 4202, "text": "REPORT ZEVENT1. \nCLASS CL_main DEFINITION. \nPUBLIC SECTION. \nDATA: num1 TYPE I. \nMETHODS: PRO IMPORTING num2 TYPE I. \nEVENTS: CUTOFF. \nENDCLASS. \n\nCLASS CL_eventhandler DEFINITION. \nPUBLIC SECTION. \nMETHODS: handling_CUTOFF FOR EVENT CUTOFF OF CL_main. \nENDCLASS. \n\nSTART-OF-SELECTION. \nDATA: main1 TYPE REF TO CL_main. \nDATA: eventhandler1 TYPE REF TO CL_eventhandler. \n\nCREATE OBJECT main1. \nCREATE OBJECT eventhandler1. \n\nSET HANDLER eventhandler1→handling_CUTOFF FOR main1. \nmain1→PRO( 4 ).\nCLASS CL_main IMPLEMENTATION.\nMETHOD PRO.\nnum1 = num2.\nIF num2 ≥ 2. \nRAISE EVENT CUTOFF.\nENDIF. \nENDMETHOD.\nENDCLASS.\n\nCLASS CL_eventhandler IMPLEMENTATION.\nMETHOD handling_CUTOFF.\nWRITE: 'Handling the CutOff'. \nWRITE: / 'Event has been processed'. \nENDMETHOD. ENDCLASS." }, { "code": null, "e": 5015, "s": 4968, "text": "The above code produces the following output −" }, { "code": null, "e": 5062, "s": 5015, "text": "Handling the CutOff \nEvent has been processed\n" }, { "code": null, "e": 5095, "s": 5062, "text": "\n 25 Lectures \n 6 hours \n" }, { "code": null, "e": 5109, "s": 5095, "text": " Sanjo Thomas" }, { "code": null, "e": 5142, "s": 5109, "text": "\n 26 Lectures \n 2 hours \n" }, { "code": null, "e": 5154, "s": 5142, "text": " Neha Gupta" }, { "code": null, "e": 5189, "s": 5154, "text": "\n 30 Lectures \n 2.5 hours \n" }, { "code": null, "e": 5204, "s": 5189, "text": " Sumit Agarwal" }, { "code": null, "e": 5237, "s": 5204, "text": "\n 30 Lectures \n 4 hours \n" }, { "code": null, "e": 5252, "s": 5237, "text": " Sumit Agarwal" }, { "code": null, "e": 5287, "s": 5252, "text": "\n 14 Lectures \n 1.5 hours \n" }, { "code": null, "e": 5299, "s": 5287, "text": " Neha Malik" }, { "code": null, "e": 5334, "s": 5299, "text": "\n 13 Lectures \n 1.5 hours \n" }, { "code": null, "e": 5346, "s": 5334, "text": " Neha Malik" }, { "code": null, "e": 5353, "s": 5346, "text": " Print" }, { "code": null, "e": 5364, "s": 5353, "text": " Add Notes" } ]
Plot a quadrilateral mesh in Python using Matplotlib - GeeksforGeeks
03 Jun, 2020 Matplotlib a multiplatform data visualization library built on NumPy arrays, and designed to work with the broader SciPy stack. Matplotlib has the ability to play well with many operating systems and graphics backends as well. matplotlib.pyplot can also be used for MATLAB-like plotting framework. pcolormesh() function of the pyplot module is used which is similar to pcolor() function, but pcolor returns PolyCollection whereas pcolormesh returns matplotlib.collections.QuadMesh. pcolormesh is much faster and hence can deal with larger arrays. Syntax : pcolormesh(cmap = [None | Colormap], alpha = [0<=scalar<=1 | None], edgecolors = [None | color | 'face'], shading = ['gouraud' | 'flat'], norm = [None | Normalize], vimax = [scalar | None], vimin = [scalar | None]) Parameters: cmap : It can be None or matplotlib has a number of built-in colormaps accessible via matplotlib.cm.get_cmapalpha : It can be None or alpha value between 0 to 1.edgecolors :If its None, edges will not be visible.‘face’ represents the same color as faces.color sequence will set a color.shading : It can be either ‘flat’ or ‘gouraud’norm : If its None defaults to normalize().vimax : It can be either None or the scalar value.vimin : It can be either None or the scalar value. ( vimax and vimin are used in conjunction with normalize data) cmap : It can be None or matplotlib has a number of built-in colormaps accessible via matplotlib.cm.get_cmap alpha : It can be None or alpha value between 0 to 1. edgecolors :If its None, edges will not be visible.‘face’ represents the same color as faces.color sequence will set a color. If its None, edges will not be visible. ‘face’ represents the same color as faces. color sequence will set a color. shading : It can be either ‘flat’ or ‘gouraud’ norm : If its None defaults to normalize(). vimax : It can be either None or the scalar value. vimin : It can be either None or the scalar value. ( vimax and vimin are used in conjunction with normalize data) Example 1 : import matplotlib.pyplot as pltimport numpy as np x1, y1 = 0.1, 0.05 # generate 2-D grids for the# x & y boundsy, x = np.mgrid[slice(-3, 3 + y1, y1), slice(-3, 4 + x1, x1)]z = (1 - x / 2. + x ** 5 + y ** 3) * np.exp(-x ** 2 - y ** 2) # Remove the last value from the# z array as z must be inside x# and y bounds.z = z[:-1, :-1]z_min, z_max = -np.abs(z).max(), np.abs(z).max() plt.subplot() plt.pcolormesh(x, y, z, cmap ='YlGn', vmin = z_min, vmax = z_max, edgecolors = 'face', shading ='flat') plt.title('pcolormesh_example') # set the limits of the plot# to the limits of the dataplt.axis([x.min(), x.max(), y.min(), y.max()]) plt.colorbar()plt.show() Output : Example 2 : import matplotlib.pyplot as pltimport numpy as np x = np.array([[0, 1, 2, 3], [0, 1, 2, 3], [0, 1, 2, 3], [0, 1, 2, 3]]) y = np.array([[0.0, 0.0, 0.0, 0], [1.0, 1.0, 1.0, 1], [2.0, 2.0, 2.0, 2], [3, 3, 3, 3]]) values = np.array([[0, 0.5, 1], [1, 1.5, 2], [2, 2.5, 3]]) fig, ax = plt.subplots() ax.pcolormesh(x, y, values)ax.set_aspect('equal')ax.set_title("pcolormesh_example2") Output : Python-matplotlib Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Enumerate() in Python How to Install PIP on Windows ? Different ways to create Pandas Dataframe Python String | replace() sum() function in Python Create a Pandas DataFrame from Lists How to drop one or multiple columns in Pandas Dataframe *args and **kwargs in Python Graph Plotting in Python | Set 1 Print lists in Python (4 Different Ways)
[ { "code": null, "e": 23899, "s": 23871, "text": "\n03 Jun, 2020" }, { "code": null, "e": 24197, "s": 23899, "text": "Matplotlib a multiplatform data visualization library built on NumPy arrays, and designed to work with the broader SciPy stack. Matplotlib has the ability to play well with many operating systems and graphics backends as well. matplotlib.pyplot can also be used for MATLAB-like plotting framework." }, { "code": null, "e": 24446, "s": 24197, "text": "pcolormesh() function of the pyplot module is used which is similar to pcolor() function, but pcolor returns PolyCollection whereas pcolormesh returns matplotlib.collections.QuadMesh. pcolormesh is much faster and hence can deal with larger arrays." }, { "code": null, "e": 24670, "s": 24446, "text": "Syntax : pcolormesh(cmap = [None | Colormap], alpha = [0<=scalar<=1 | None], edgecolors = [None | color | 'face'], shading = ['gouraud' | 'flat'], norm = [None | Normalize], vimax = [scalar | None], vimin = [scalar | None])" }, { "code": null, "e": 24682, "s": 24670, "text": "Parameters:" }, { "code": null, "e": 25221, "s": 24682, "text": "cmap : It can be None or matplotlib has a number of built-in colormaps accessible via matplotlib.cm.get_cmapalpha : It can be None or alpha value between 0 to 1.edgecolors :If its None, edges will not be visible.‘face’ represents the same color as faces.color sequence will set a color.shading : It can be either ‘flat’ or ‘gouraud’norm : If its None defaults to normalize().vimax : It can be either None or the scalar value.vimin : It can be either None or the scalar value. ( vimax and vimin are used in conjunction with normalize data)" }, { "code": null, "e": 25330, "s": 25221, "text": "cmap : It can be None or matplotlib has a number of built-in colormaps accessible via matplotlib.cm.get_cmap" }, { "code": null, "e": 25384, "s": 25330, "text": "alpha : It can be None or alpha value between 0 to 1." }, { "code": null, "e": 25510, "s": 25384, "text": "edgecolors :If its None, edges will not be visible.‘face’ represents the same color as faces.color sequence will set a color." }, { "code": null, "e": 25550, "s": 25510, "text": "If its None, edges will not be visible." }, { "code": null, "e": 25593, "s": 25550, "text": "‘face’ represents the same color as faces." }, { "code": null, "e": 25626, "s": 25593, "text": "color sequence will set a color." }, { "code": null, "e": 25673, "s": 25626, "text": "shading : It can be either ‘flat’ or ‘gouraud’" }, { "code": null, "e": 25717, "s": 25673, "text": "norm : If its None defaults to normalize()." }, { "code": null, "e": 25768, "s": 25717, "text": "vimax : It can be either None or the scalar value." }, { "code": null, "e": 25882, "s": 25768, "text": "vimin : It can be either None or the scalar value. ( vimax and vimin are used in conjunction with normalize data)" }, { "code": null, "e": 25894, "s": 25882, "text": "Example 1 :" }, { "code": "import matplotlib.pyplot as pltimport numpy as np x1, y1 = 0.1, 0.05 # generate 2-D grids for the# x & y boundsy, x = np.mgrid[slice(-3, 3 + y1, y1), slice(-3, 4 + x1, x1)]z = (1 - x / 2. + x ** 5 + y ** 3) * np.exp(-x ** 2 - y ** 2) # Remove the last value from the# z array as z must be inside x# and y bounds.z = z[:-1, :-1]z_min, z_max = -np.abs(z).max(), np.abs(z).max() plt.subplot() plt.pcolormesh(x, y, z, cmap ='YlGn', vmin = z_min, vmax = z_max, edgecolors = 'face', shading ='flat') plt.title('pcolormesh_example') # set the limits of the plot# to the limits of the dataplt.axis([x.min(), x.max(), y.min(), y.max()]) plt.colorbar()plt.show()", "e": 26630, "s": 25894, "text": null }, { "code": null, "e": 26639, "s": 26630, "text": "Output :" }, { "code": null, "e": 26651, "s": 26639, "text": "Example 2 :" }, { "code": "import matplotlib.pyplot as pltimport numpy as np x = np.array([[0, 1, 2, 3], [0, 1, 2, 3], [0, 1, 2, 3], [0, 1, 2, 3]]) y = np.array([[0.0, 0.0, 0.0, 0], [1.0, 1.0, 1.0, 1], [2.0, 2.0, 2.0, 2], [3, 3, 3, 3]]) values = np.array([[0, 0.5, 1], [1, 1.5, 2], [2, 2.5, 3]]) fig, ax = plt.subplots() ax.pcolormesh(x, y, values)ax.set_aspect('equal')ax.set_title(\"pcolormesh_example2\")", "e": 27156, "s": 26651, "text": null }, { "code": null, "e": 27165, "s": 27156, "text": "Output :" }, { "code": null, "e": 27183, "s": 27165, "text": "Python-matplotlib" }, { "code": null, "e": 27190, "s": 27183, "text": "Python" }, { "code": null, "e": 27288, "s": 27190, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27297, "s": 27288, "text": "Comments" }, { "code": null, "e": 27310, "s": 27297, "text": "Old Comments" }, { "code": null, "e": 27332, "s": 27310, "text": "Enumerate() in Python" }, { "code": null, "e": 27364, "s": 27332, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27406, "s": 27364, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 27432, "s": 27406, "text": "Python String | replace()" }, { "code": null, "e": 27457, "s": 27432, "text": "sum() function in Python" }, { "code": null, "e": 27494, "s": 27457, "text": "Create a Pandas DataFrame from Lists" }, { "code": null, "e": 27550, "s": 27494, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 27579, "s": 27550, "text": "*args and **kwargs in Python" }, { "code": null, "e": 27612, "s": 27579, "text": "Graph Plotting in Python | Set 1" } ]
Dynamic axis in Power BI — DAXis. Have you ever tried to dynamically... | by Nikola Ilic | Towards Data Science
A few months ago, I wrote a blog post about dynamic filtering in Power BI — and how to display different measures within one visual, depending on the user’s selection — without using bookmarks! Last week, I’ve got a similar request from my client. In fact, this time the request was the other way around — they want to see the same metric (measure), but from different perspectives — for example, total sales amount per country and brand name, depending on user’s choice. Again, this could have been done using bookmarks and switching between different page states. However, I’ve wanted to find a different, flexible, and more scalable solution — just in case that in the future they want to extend the list of possible “perspectives”, by adding, for example, customer gender, or region to this list. I like to call this solution: DAXis — because we play with DAX to achieve a dynamic axis:) While searching for possible solutions, I’ve come across this great blog post from Kasper de Jonge, which basically gave me an idea of how to handle this request. As usual, I will use the Contoso sample database for demo purposes. In this illustration, you can see that my visual shows the total sales amount per brand name. The idea is to “somehow” enable the user to switch the axis to country, persisting existing measure in the visual. No bookmarks allowed:) The first step is to generate a new table, that will in essence be a Cartesian product of all distinct values from brands and countries columns from our data model. This table will be later used for building the axis for our visual. Brands & Countries = UNION( CROSSJOIN(VALUES('Product'[BrandName]),ROW("Axis","Brands")), CROSSJOIN(VALUES(Geography[RegionCountryName]), ROW("Axis","Countries") )) I’ve just renamed the BrandName column to “Value”, as it includes not only brands, but also countries. Going back to our report, let’s put the Axis from this table in the slicer, and BrandName as the axis in our visual: As you can spot, we are getting grand total for each axis category. That’s because our main measure (Sales Amt) is summing values coming from the Online Sales table, and there is no relationship between this table and our newly created Brands & Countries table. So, our main measure (Sales Amt), needs to be rewritten in order to display correct results. We will leverage the usage of TREATAS DAX function. In the most simple way, TREATAS applies the result of a table expression as filters to columns from an unrelated table. This function comes with some limitations, but it should work in our specific scenario: Sales Amt TREATAS = IF( HASONEVALUE('Brands & Countries'[Axis]), SWITCH(VALUES('Brands & Countries'[Axis]) ,"Countries", CALCULATE(SUM('Online Sales'[SalesAmount]) ,TREATAS(VALUES('Brands & Countries'[Value]) ,Geography[RegionCountryName])) ,"Brands", CALCULATE(SUM('Online Sales'[SalesAmount]) ,TREATAS(VALUES('Brands & Countries'[Value]) ,'Product'[BrandName])))) In this case, TREATAS will push filters from our newly created table to a “real” dimension table! And, once I drag this new measure to a visual, I’m able to dynamically change the y-axis based on user’s selection within the slicer: How cool is that! Thanks to Kasper for the brilliant idea:) As you may witness, we found a very cool and elegant solution to a common business request. As for almost any problem, not just Power BI related, there are multiple valid and legitimate solutions. We could handle this request using buttons and bookmarks, but in the longer run, I believe that this solution with a dynamic axis and separate table offers more scalability and is easier to maintain. Thanks for reading! Become a member and read every story on Medium!
[ { "code": null, "e": 366, "s": 172, "text": "A few months ago, I wrote a blog post about dynamic filtering in Power BI — and how to display different measures within one visual, depending on the user’s selection — without using bookmarks!" }, { "code": null, "e": 644, "s": 366, "text": "Last week, I’ve got a similar request from my client. In fact, this time the request was the other way around — they want to see the same metric (measure), but from different perspectives — for example, total sales amount per country and brand name, depending on user’s choice." }, { "code": null, "e": 973, "s": 644, "text": "Again, this could have been done using bookmarks and switching between different page states. However, I’ve wanted to find a different, flexible, and more scalable solution — just in case that in the future they want to extend the list of possible “perspectives”, by adding, for example, customer gender, or region to this list." }, { "code": null, "e": 1064, "s": 973, "text": "I like to call this solution: DAXis — because we play with DAX to achieve a dynamic axis:)" }, { "code": null, "e": 1227, "s": 1064, "text": "While searching for possible solutions, I’ve come across this great blog post from Kasper de Jonge, which basically gave me an idea of how to handle this request." }, { "code": null, "e": 1295, "s": 1227, "text": "As usual, I will use the Contoso sample database for demo purposes." }, { "code": null, "e": 1527, "s": 1295, "text": "In this illustration, you can see that my visual shows the total sales amount per brand name. The idea is to “somehow” enable the user to switch the axis to country, persisting existing measure in the visual. No bookmarks allowed:)" }, { "code": null, "e": 1760, "s": 1527, "text": "The first step is to generate a new table, that will in essence be a Cartesian product of all distinct values from brands and countries columns from our data model. This table will be later used for building the axis for our visual." }, { "code": null, "e": 1985, "s": 1760, "text": "Brands & Countries = UNION( CROSSJOIN(VALUES('Product'[BrandName]),ROW(\"Axis\",\"Brands\")), CROSSJOIN(VALUES(Geography[RegionCountryName]), ROW(\"Axis\",\"Countries\") ))" }, { "code": null, "e": 2088, "s": 1985, "text": "I’ve just renamed the BrandName column to “Value”, as it includes not only brands, but also countries." }, { "code": null, "e": 2205, "s": 2088, "text": "Going back to our report, let’s put the Axis from this table in the slicer, and BrandName as the axis in our visual:" }, { "code": null, "e": 2467, "s": 2205, "text": "As you can spot, we are getting grand total for each axis category. That’s because our main measure (Sales Amt) is summing values coming from the Online Sales table, and there is no relationship between this table and our newly created Brands & Countries table." }, { "code": null, "e": 2820, "s": 2467, "text": "So, our main measure (Sales Amt), needs to be rewritten in order to display correct results. We will leverage the usage of TREATAS DAX function. In the most simple way, TREATAS applies the result of a table expression as filters to columns from an unrelated table. This function comes with some limitations, but it should work in our specific scenario:" }, { "code": null, "e": 3387, "s": 2820, "text": "Sales Amt TREATAS = IF( HASONEVALUE('Brands & Countries'[Axis]), SWITCH(VALUES('Brands & Countries'[Axis]) ,\"Countries\", CALCULATE(SUM('Online Sales'[SalesAmount]) ,TREATAS(VALUES('Brands & Countries'[Value]) ,Geography[RegionCountryName])) ,\"Brands\", CALCULATE(SUM('Online Sales'[SalesAmount]) ,TREATAS(VALUES('Brands & Countries'[Value]) ,'Product'[BrandName]))))" }, { "code": null, "e": 3619, "s": 3387, "text": "In this case, TREATAS will push filters from our newly created table to a “real” dimension table! And, once I drag this new measure to a visual, I’m able to dynamically change the y-axis based on user’s selection within the slicer:" }, { "code": null, "e": 3679, "s": 3619, "text": "How cool is that! Thanks to Kasper for the brilliant idea:)" }, { "code": null, "e": 3771, "s": 3679, "text": "As you may witness, we found a very cool and elegant solution to a common business request." }, { "code": null, "e": 4076, "s": 3771, "text": "As for almost any problem, not just Power BI related, there are multiple valid and legitimate solutions. We could handle this request using buttons and bookmarks, but in the longer run, I believe that this solution with a dynamic axis and separate table offers more scalability and is easier to maintain." }, { "code": null, "e": 4096, "s": 4076, "text": "Thanks for reading!" } ]
Clone a stack without using extra space | Set 2 - GeeksforGeeks
25 Aug, 2021 Given a stack S, the task is to copy the content of the given stack S to another stack T maintaining the same order. Examples: Input: Source:- |5| |4| |3| |2| |1|Output: Destination:- |5| |4| |3| |2| |1| Input: Source:- |12| |13| |14| |15| |16|Output: Destination:- |12| |13| |14| |15| |16| Reversing the Stack-Based Approach: Please refer to the previous post of this article for reversing the stack-based approach. Time Complexity: O(N2)Auxiliary Space: O(1) Linked List-Based Approach: Please refer to the previous post of this article for the linked list-based approach. Time Complexity: O(N)Auxiliary Space: O(1) Recursion-Based Approach: The given problem can also be solved by using recursion. Follow the steps below to solve the problem: Define a recursive function, say RecursiveCloneStack(stack<int> S, stack<int>Des) where S is the source stack and Des is the destination stack:Define a base case as if S.size() is 0 then return from the function.Store the top element of the source stack in a variable, say val, and then remove the top element of the stack S.Now call the recursive function with updated Source stack S i.e., RecursiveCloneStack(S, Des).After the above step, push the val into the Des stack. Define a base case as if S.size() is 0 then return from the function. Store the top element of the source stack in a variable, say val, and then remove the top element of the stack S. Now call the recursive function with updated Source stack S i.e., RecursiveCloneStack(S, Des). After the above step, push the val into the Des stack. Initialize a stack, say Des to store the destination stack. Now call the function RecursiveCloneStack(S, Des) to copy the elements of the source stack to the destination stack. After completing the above steps, print the elements of the stack Des as the result. 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; // Auxiliary function to copy elements// of source stack to destination stackvoid RecursiveCloneStack(stack<int>& S, stack<int>& Des){ // Base case for Recursion if (S.size() == 0) return; // Stores the top element of the // source stack int val = S.top(); // Removes the top element of the // source stack S.pop(); // Recursive call to the function // with remaining stack RecursiveCloneStack(S, Des); // Push the top element of the source // stack into the Destination stack Des.push(val);} // Function to copy the elements of the// source stack to destination stackvoid cloneStack(stack<int>& S){ // Stores the destination stack stack<int> Des; // Recursive function call to copy // the source stack to the // destination stack RecursiveCloneStack(S, Des); cout << "Destination:- "; int f = 0; // Iterate until stack Des is // non-empty while (!Des.empty()) { if (f == 0) { cout << Des.top(); f = 1; } else cout << " " << Des.top(); Des.pop(); cout << '\n'; }} // Driver Codeint main(){ stack<int> S; S.push(1); S.push(2); S.push(3); S.push(4); S.push(5); cloneStack(S); return 0;} // Java program for the above approachimport java.util.*;public class Main{ static Stack<Integer> S = new Stack<Integer>(); static Stack<Integer> Des = new Stack<Integer>(); // Stores the destination stack // Auxiliary function to copy elements // of source stack to destination stack static void RecursiveCloneStack() { // Base case for Recursion if (S.size() == 0) return; // Stores the top element of the // source stack int val = S.peek(); // Removes the top element of the // source stack S.pop(); // Recursive call to the function // with remaining stack RecursiveCloneStack(); // Push the top element of the source // stack into the Destination stack Des.push(val); } // Function to copy the elements of the // source stack to destination stack static void cloneStack() { // Recursive function call to copy // the source stack to the // destination stack RecursiveCloneStack(); System.out.print("Destination:- "); int f = 0; // Iterate until stack Des is // non-empty while (Des.size() > 0) { if (f == 0) { System.out.print(Des.peek()); f = 1; } else System.out.print(" " + Des.peek()); Des.pop(); System.out.println(); } } // Driver code public static void main(String[] args) { S.push(1); S.push(2); S.push(3); S.push(4); S.push(5); cloneStack(); }} // This code is contributed by mukesh07. # Python3 program for the above approach S = []Des = [] # Stores the destination stack # Auxiliary function to copy elements# of source stack to destination stackdef RecursiveCloneStack(): # Base case for Recursion if (len(S) == 0): return # Stores the top element of the # source stack val = S[-1] # Removes the top element of the # source stack S.pop() # Recursive call to the function # with remaining stack RecursiveCloneStack() # Push the top element of the source # stack into the Destination stack Des.append(val) # Function to copy the elements of the# source stack to destination stackdef cloneStack(): # Recursive function call to copy # the source stack to the # destination stack RecursiveCloneStack() print("Destination:- ", end = "") f = 0 # Iterate until stack Des is # non-empty while len(Des) > 0: if (f == 0): print(Des[-1], end = "") f = 1 else: print(" ", Des[-1], end = "") Des.pop() print() S.append(1)S.append(2)S.append(3)S.append(4)S.append(5)cloneStack() # This code is contributed by decode2207. // C# program for the above approachusing System;using System.Collections;class GFG { static Stack S = new Stack(); static Stack Des = new Stack(); // Stores the destination stack // Auxiliary function to copy elements // of source stack to destination stack static void RecursiveCloneStack() { // Base case for Recursion if (S.Count == 0) return; // Stores the top element of the // source stack int val = (int)S.Peek(); // Removes the top element of the // source stack S.Pop(); // Recursive call to the function // with remaining stack RecursiveCloneStack(); // Push the top element of the source // stack into the Destination stack Des.Push(val); } // Function to copy the elements of the // source stack to destination stack static void cloneStack() { // Recursive function call to copy // the source stack to the // destination stack RecursiveCloneStack(); Console.Write("Destination:- "); int f = 0; // Iterate until stack Des is // non-empty while (Des.Count > 0) { if (f == 0) { Console.Write(Des.Peek()); f = 1; } else Console.Write(" " + Des.Peek()); Des.Pop(); Console.WriteLine(); } } static void Main() { S.Push(1); S.Push(2); S.Push(3); S.Push(4); S.Push(5); cloneStack(); }} // This code is contributed by divyesh072019. <script> // Javascript program for the above approach S = []; Des = []; // Stores the destination stack // Auxiliary function to copy elements // of source stack to destination stack function RecursiveCloneStack() { // Base case for Recursion if (S.length == 0) return; // Stores the top element of the // source stack let val = S[S.length - 1]; // Removes the top element of the // source stack S.pop(); // Recursive call to the function // with remaining stack RecursiveCloneStack(); // Push the top element of the source // stack into the Destination stack Des.push(val); } // Function to copy the elements of the // source stack to destination stack function cloneStack() { // Recursive function call to copy // the source stack to the // destination stack RecursiveCloneStack(); document.write("Destination:- "); let f = 0; // Iterate until stack Des is // non-empty while (Des.length > 0) { if (f == 0) { document.write(Des[Des.length - 1]); f = 1; } else{ document.write(" " + Des[Des.length - 1]); } Des.pop(); document.write("</br>"); } } S.push(1); S.push(2); S.push(3); S.push(4); S.push(5); cloneStack(); // This code is contributed by suresh07.</script> Destination:- 5 4 3 2 1 Time Complexity: O(N) Auxiliary Space: O(1) divyesh072019 mukesh07 suresh07 decode2207 cpp-stack cpp-stack-functions Data Structures Recursion Stack Data Structures Recursion Stack Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Introduction to Tree Data Structure Program to implement Singly Linked List in C++ using class Insertion in a B+ tree Hash Functions and list/types of Hash functions Shortest path in a directed graph by Dijkstra’s algorithm Write a program to print all permutations of a given string Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum) Recursion Program for Tower of Hanoi Program for Sum of the digits of a given number
[ { "code": null, "e": 25054, "s": 25026, "text": "\n25 Aug, 2021" }, { "code": null, "e": 25171, "s": 25054, "text": "Given a stack S, the task is to copy the content of the given stack S to another stack T maintaining the same order." }, { "code": null, "e": 25181, "s": 25171, "text": "Examples:" }, { "code": null, "e": 25492, "s": 25181, "text": "Input: Source:- |5| |4| |3| |2| |1|Output: Destination:- |5| |4| |3| |2| |1|" }, { "code": null, "e": 25813, "s": 25492, "text": "Input: Source:- |12| |13| |14| |15| |16|Output: Destination:- |12| |13| |14| |15| |16|" }, { "code": null, "e": 25939, "s": 25813, "text": "Reversing the Stack-Based Approach: Please refer to the previous post of this article for reversing the stack-based approach." }, { "code": null, "e": 25983, "s": 25939, "text": "Time Complexity: O(N2)Auxiliary Space: O(1)" }, { "code": null, "e": 26097, "s": 25983, "text": "Linked List-Based Approach: Please refer to the previous post of this article for the linked list-based approach." }, { "code": null, "e": 26140, "s": 26097, "text": "Time Complexity: O(N)Auxiliary Space: O(1)" }, { "code": null, "e": 26268, "s": 26140, "text": "Recursion-Based Approach: The given problem can also be solved by using recursion. Follow the steps below to solve the problem:" }, { "code": null, "e": 26742, "s": 26268, "text": "Define a recursive function, say RecursiveCloneStack(stack<int> S, stack<int>Des) where S is the source stack and Des is the destination stack:Define a base case as if S.size() is 0 then return from the function.Store the top element of the source stack in a variable, say val, and then remove the top element of the stack S.Now call the recursive function with updated Source stack S i.e., RecursiveCloneStack(S, Des).After the above step, push the val into the Des stack." }, { "code": null, "e": 26812, "s": 26742, "text": "Define a base case as if S.size() is 0 then return from the function." }, { "code": null, "e": 26926, "s": 26812, "text": "Store the top element of the source stack in a variable, say val, and then remove the top element of the stack S." }, { "code": null, "e": 27021, "s": 26926, "text": "Now call the recursive function with updated Source stack S i.e., RecursiveCloneStack(S, Des)." }, { "code": null, "e": 27076, "s": 27021, "text": "After the above step, push the val into the Des stack." }, { "code": null, "e": 27136, "s": 27076, "text": "Initialize a stack, say Des to store the destination stack." }, { "code": null, "e": 27253, "s": 27136, "text": "Now call the function RecursiveCloneStack(S, Des) to copy the elements of the source stack to the destination stack." }, { "code": null, "e": 27338, "s": 27253, "text": "After completing the above steps, print the elements of the stack Des as the result." }, { "code": null, "e": 27389, "s": 27338, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 27393, "s": 27389, "text": "C++" }, { "code": null, "e": 27398, "s": 27393, "text": "Java" }, { "code": null, "e": 27406, "s": 27398, "text": "Python3" }, { "code": null, "e": 27409, "s": 27406, "text": "C#" }, { "code": null, "e": 27420, "s": 27409, "text": "Javascript" }, { "code": "// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Auxiliary function to copy elements// of source stack to destination stackvoid RecursiveCloneStack(stack<int>& S, stack<int>& Des){ // Base case for Recursion if (S.size() == 0) return; // Stores the top element of the // source stack int val = S.top(); // Removes the top element of the // source stack S.pop(); // Recursive call to the function // with remaining stack RecursiveCloneStack(S, Des); // Push the top element of the source // stack into the Destination stack Des.push(val);} // Function to copy the elements of the// source stack to destination stackvoid cloneStack(stack<int>& S){ // Stores the destination stack stack<int> Des; // Recursive function call to copy // the source stack to the // destination stack RecursiveCloneStack(S, Des); cout << \"Destination:- \"; int f = 0; // Iterate until stack Des is // non-empty while (!Des.empty()) { if (f == 0) { cout << Des.top(); f = 1; } else cout << \" \" << Des.top(); Des.pop(); cout << '\\n'; }} // Driver Codeint main(){ stack<int> S; S.push(1); S.push(2); S.push(3); S.push(4); S.push(5); cloneStack(S); return 0;}", "e": 28828, "s": 27420, "text": null }, { "code": "// Java program for the above approachimport java.util.*;public class Main{ static Stack<Integer> S = new Stack<Integer>(); static Stack<Integer> Des = new Stack<Integer>(); // Stores the destination stack // Auxiliary function to copy elements // of source stack to destination stack static void RecursiveCloneStack() { // Base case for Recursion if (S.size() == 0) return; // Stores the top element of the // source stack int val = S.peek(); // Removes the top element of the // source stack S.pop(); // Recursive call to the function // with remaining stack RecursiveCloneStack(); // Push the top element of the source // stack into the Destination stack Des.push(val); } // Function to copy the elements of the // source stack to destination stack static void cloneStack() { // Recursive function call to copy // the source stack to the // destination stack RecursiveCloneStack(); System.out.print(\"Destination:- \"); int f = 0; // Iterate until stack Des is // non-empty while (Des.size() > 0) { if (f == 0) { System.out.print(Des.peek()); f = 1; } else System.out.print(\" \" + Des.peek()); Des.pop(); System.out.println(); } } // Driver code public static void main(String[] args) { S.push(1); S.push(2); S.push(3); S.push(4); S.push(5); cloneStack(); }} // This code is contributed by mukesh07.", "e": 30601, "s": 28828, "text": null }, { "code": "# Python3 program for the above approach S = []Des = [] # Stores the destination stack # Auxiliary function to copy elements# of source stack to destination stackdef RecursiveCloneStack(): # Base case for Recursion if (len(S) == 0): return # Stores the top element of the # source stack val = S[-1] # Removes the top element of the # source stack S.pop() # Recursive call to the function # with remaining stack RecursiveCloneStack() # Push the top element of the source # stack into the Destination stack Des.append(val) # Function to copy the elements of the# source stack to destination stackdef cloneStack(): # Recursive function call to copy # the source stack to the # destination stack RecursiveCloneStack() print(\"Destination:- \", end = \"\") f = 0 # Iterate until stack Des is # non-empty while len(Des) > 0: if (f == 0): print(Des[-1], end = \"\") f = 1 else: print(\" \", Des[-1], end = \"\") Des.pop() print() S.append(1)S.append(2)S.append(3)S.append(4)S.append(5)cloneStack() # This code is contributed by decode2207.", "e": 31821, "s": 30601, "text": null }, { "code": "// C# program for the above approachusing System;using System.Collections;class GFG { static Stack S = new Stack(); static Stack Des = new Stack(); // Stores the destination stack // Auxiliary function to copy elements // of source stack to destination stack static void RecursiveCloneStack() { // Base case for Recursion if (S.Count == 0) return; // Stores the top element of the // source stack int val = (int)S.Peek(); // Removes the top element of the // source stack S.Pop(); // Recursive call to the function // with remaining stack RecursiveCloneStack(); // Push the top element of the source // stack into the Destination stack Des.Push(val); } // Function to copy the elements of the // source stack to destination stack static void cloneStack() { // Recursive function call to copy // the source stack to the // destination stack RecursiveCloneStack(); Console.Write(\"Destination:- \"); int f = 0; // Iterate until stack Des is // non-empty while (Des.Count > 0) { if (f == 0) { Console.Write(Des.Peek()); f = 1; } else Console.Write(\" \" + Des.Peek()); Des.Pop(); Console.WriteLine(); } } static void Main() { S.Push(1); S.Push(2); S.Push(3); S.Push(4); S.Push(5); cloneStack(); }} // This code is contributed by divyesh072019.", "e": 33485, "s": 31821, "text": null }, { "code": "<script> // Javascript program for the above approach S = []; Des = []; // Stores the destination stack // Auxiliary function to copy elements // of source stack to destination stack function RecursiveCloneStack() { // Base case for Recursion if (S.length == 0) return; // Stores the top element of the // source stack let val = S[S.length - 1]; // Removes the top element of the // source stack S.pop(); // Recursive call to the function // with remaining stack RecursiveCloneStack(); // Push the top element of the source // stack into the Destination stack Des.push(val); } // Function to copy the elements of the // source stack to destination stack function cloneStack() { // Recursive function call to copy // the source stack to the // destination stack RecursiveCloneStack(); document.write(\"Destination:- \"); let f = 0; // Iterate until stack Des is // non-empty while (Des.length > 0) { if (f == 0) { document.write(Des[Des.length - 1]); f = 1; } else{ document.write(\" \" + Des[Des.length - 1]); } Des.pop(); document.write(\"</br>\"); } } S.push(1); S.push(2); S.push(3); S.push(4); S.push(5); cloneStack(); // This code is contributed by suresh07.</script>", "e": 35122, "s": 33485, "text": null }, { "code": null, "e": 35202, "s": 35122, "text": "Destination:- 5\n 4\n 3\n 2\n 1" }, { "code": null, "e": 35248, "s": 35204, "text": "Time Complexity: O(N) Auxiliary Space: O(1)" }, { "code": null, "e": 35262, "s": 35248, "text": "divyesh072019" }, { "code": null, "e": 35271, "s": 35262, "text": "mukesh07" }, { "code": null, "e": 35280, "s": 35271, "text": "suresh07" }, { "code": null, "e": 35291, "s": 35280, "text": "decode2207" }, { "code": null, "e": 35301, "s": 35291, "text": "cpp-stack" }, { "code": null, "e": 35321, "s": 35301, "text": "cpp-stack-functions" }, { "code": null, "e": 35337, "s": 35321, "text": "Data Structures" }, { "code": null, "e": 35347, "s": 35337, "text": "Recursion" }, { "code": null, "e": 35353, "s": 35347, "text": "Stack" }, { "code": null, "e": 35369, "s": 35353, "text": "Data Structures" }, { "code": null, "e": 35379, "s": 35369, "text": "Recursion" }, { "code": null, "e": 35385, "s": 35379, "text": "Stack" }, { "code": null, "e": 35483, "s": 35385, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 35519, "s": 35483, "text": "Introduction to Tree Data Structure" }, { "code": null, "e": 35578, "s": 35519, "text": "Program to implement Singly Linked List in C++ using class" }, { "code": null, "e": 35601, "s": 35578, "text": "Insertion in a B+ tree" }, { "code": null, "e": 35649, "s": 35601, "text": "Hash Functions and list/types of Hash functions" }, { "code": null, "e": 35707, "s": 35649, "text": "Shortest path in a directed graph by Dijkstra’s algorithm" }, { "code": null, "e": 35767, "s": 35707, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 35852, "s": 35767, "text": "Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)" }, { "code": null, "e": 35862, "s": 35852, "text": "Recursion" }, { "code": null, "e": 35889, "s": 35862, "text": "Program for Tower of Hanoi" } ]
ASP.NET - Data Caching
Caching is a technique of storing frequently used data/information in memory, so that, when the same data/information is needed next time, it could be directly retrieved from the memory instead of being generated by the application. Caching is extremely important for performance boosting in ASP.NET, as the pages and controls are dynamically generated here. It is especially important for data related transactions, as these are expensive in terms of response time. Caching places frequently used data in quickly accessed media such as the random access memory of the computer. The ASP.NET runtime includes a key-value map of CLR objects called cache. This resides with the application and is available via the HttpContext and System.Web.UI.Page. In some respect, caching is similar to storing the state objects. However, the storing information in state objects is deterministic, i.e., you can count on the data being stored there, and caching of data is nondeterministic. The data will not be available in the following cases: If its lifetime expires, If the application releases its memory, If caching does not take place for some reason. You can access items in the cache using an indexer and may control the lifetime of objects in the cache and set up links between the cached objects and their physical sources. ASP.NET provides the following different types of caching: Output Caching : Output cache stores a copy of the finally rendered HTML pages or part of pages sent to the client. When the next client requests for this page, instead of regenerating the page, a cached copy of the page is sent, thus saving time. Output Caching : Output cache stores a copy of the finally rendered HTML pages or part of pages sent to the client. When the next client requests for this page, instead of regenerating the page, a cached copy of the page is sent, thus saving time. Data Caching : Data caching means caching data from a data source. As long as the cache is not expired, a request for the data will be fulfilled from the cache. When the cache is expired, fresh data is obtained by the data source and the cache is refilled. Data Caching : Data caching means caching data from a data source. As long as the cache is not expired, a request for the data will be fulfilled from the cache. When the cache is expired, fresh data is obtained by the data source and the cache is refilled. Object Caching : Object caching is caching the objects on a page, such as data-bound controls. The cached data is stored in server memory. Object Caching : Object caching is caching the objects on a page, such as data-bound controls. The cached data is stored in server memory. Class Caching : Web pages or web services are compiled into a page class in the assembly, when run for the first time. Then the assembly is cached in the server. Next time when a request is made for the page or service, the cached assembly is referred to. When the source code is changed, the CLR recompiles the assembly. Class Caching : Web pages or web services are compiled into a page class in the assembly, when run for the first time. Then the assembly is cached in the server. Next time when a request is made for the page or service, the cached assembly is referred to. When the source code is changed, the CLR recompiles the assembly. Configuration Caching : Application wide configuration information is stored in a configuration file. Configuration caching stores the configuration information in the server memory. Configuration Caching : Application wide configuration information is stored in a configuration file. Configuration caching stores the configuration information in the server memory. In this tutorial, we will consider output caching, data caching, and object caching. Rendering a page may involve some complex processes such as, database access, rendering complex controls etc. Output caching allows bypassing the round trips to server by caching data in memory. Even the whole page could be cached. The OutputCache directive is responsible of output caching. It enables output caching and provides certain control over its behaviour. Syntax for OutputCache directive: <%@ OutputCache Duration="15" VaryByParam="None" %> Put this directive under the page directive. This tells the environment to cache the page for 15 seconds. The following event handler for page load would help in testing that the page was really cached. protected void Page_Load(object sender, EventArgs e) { Thread.Sleep(10000); Response.Write("This page was generated and cache at:" + DateTime.Now.ToString()); } The Thread.Sleep() method stops the process thread for the specified time. In this example, the thread is stopped for 10 seconds, so when the page is loaded for first time, it takes 10 seconds. However, next time you refresh the page it does not take any time, as the page is retrieved from the cache without being loaded. The OutputCache directive has the following attributes, which helps in controlling the behaviour of the output cache: None * * Header names Browser Custom string Any Client Downstream Server None Any: page may be cached anywhere. Client: cached content remains at browser. Downstream: cached content stored in downstream and server both. Server: cached content saved only on server. None: disables caching. Let us add a text box and a button to the previous example and add this event handler for the button. protected void btnmagic_Click(object sender, EventArgs e) { Response.Write("<br><br>"); Response.Write("<h2> Hello, " + this.txtname.Text + "</h2>"); } Change the OutputCache directive: <%@ OutputCache Duration="60" VaryByParam="txtname" %> When the program is executed, ASP.NET caches the page on the basis of the name in the text box. The main aspect of data caching is caching the data source controls. We have already discussed that the data source controls represent data in a data source, like a database or an XML file. These controls derive from the abstract class DataSourceControl and have the following inherited properties for implementing caching: CacheDuration - It sets the number of seconds for which the data source will cache data. CacheDuration - It sets the number of seconds for which the data source will cache data. CacheExpirationPolicy - It defines the cache behavior when the data in cache has expired. CacheExpirationPolicy - It defines the cache behavior when the data in cache has expired. CacheKeyDependency - It identifies a key for the controls that auto-expires the content of its cache when removed. CacheKeyDependency - It identifies a key for the controls that auto-expires the content of its cache when removed. EnableCaching - It specifies whether or not to cache the data. EnableCaching - It specifies whether or not to cache the data. To demonstrate data caching, create a new website and add a new web form on it. Add a SqlDataSource control with the database connection already used in the data access tutorials. For this example, add a label to the page, which would show the response time for the page. <asp:Label ID="lbltime" runat="server"></asp:Label> Apart from the label, the content page is same as in the data access tutorial. Add an event handler for the page load event: protected void Page_Load(object sender, EventArgs e) { lbltime.Text = String.Format("Page posted at: {0}", DateTime.Now.ToLongTimeString()); } The designed page should look as shown: When you execute the page for the first time, nothing different happens, the label shows that, each time you refresh the page, the page is reloaded and the time shown on the label changes. Next, set the EnableCaching attribute of the data source control to be 'true' and set the Cacheduration attribute to '60'. It will implement caching and the cache will expire every 60 seconds. The timestamp changes with every refresh, but if you change the data in the table within these 60 seconds, it is not shown before the cache expires. <asp:SqlDataSource ID = "SqlDataSource1" runat = "server" ConnectionString = "<%$ ConnectionStrings: ASPDotNetStepByStepConnectionString %>" ProviderName = "<%$ ConnectionStrings: ASPDotNetStepByStepConnectionString.ProviderName %>" SelectCommand = "SELECT * FROM [DotNetReferences]" EnableCaching = "true" CacheDuration = "60"> </asp:SqlDataSource> Object caching provides more flexibility than other cache techniques. You can use object caching to place any object in the cache. The object can be of any type - a data type, a web control, a class, a dataset object, etc. The item is added to the cache simply by assigning a new key name, shown as follows Like: Cache["key"] = item; ASP.NET also provides the Insert() method for inserting an object to the cache. This method has four overloaded versions. Let us see them: Sliding expiration is used to remove an item from the cache when it is not used for the specified time span. The following code snippet stores an item with a sliding expiration of 10 minutes with no dependencies. Cache.Insert("my_item", obj, null, DateTime.MaxValue, TimeSpan.FromMinutes(10)); Create a page with just a button and a label. Write the following code in the page load event: protected void Page_Load(object sender, EventArgs e) { if (this.IsPostBack) { lblinfo.Text += "Page Posted Back.<br/>"; } else { lblinfo.Text += "page Created.<br/>"; } if (Cache["testitem"] == null) { lblinfo.Text += "Creating test item.<br/>"; DateTime testItem = DateTime.Now; lblinfo.Text += "Storing test item in cache "; lblinfo.Text += "for 30 seconds.<br/>"; Cache.Insert("testitem", testItem, null, DateTime.Now.AddSeconds(30), TimeSpan.Zero); } else { lblinfo.Text += "Retrieving test item.<br/>"; DateTime testItem = (DateTime)Cache["testitem"]; lblinfo.Text += "Test item is: " + testItem.ToString(); lblinfo.Text += "<br/>"; } lblinfo.Text += "<br/>"; } When the page is loaded for the first time, it says: Page Created. Creating test item. Storing test item in cache for 30 seconds. If you click on the button again within 30 seconds, the page is posted back but the label control gets its information from the cache as shown: Page Posted Back. Retrieving test item. Test item is: 14-07-2010 01:25:04 51 Lectures 5.5 hours Anadi Sharma 44 Lectures 4.5 hours Kaushik Roy Chowdhury 42 Lectures 18 hours SHIVPRASAD KOIRALA 57 Lectures 3.5 hours University Code 40 Lectures 2.5 hours University Code 138 Lectures 9 hours Bhrugen Patel Print Add Notes Bookmark this page
[ { "code": null, "e": 2580, "s": 2347, "text": "Caching is a technique of storing frequently used data/information in memory, so that, when the same data/information is needed next time, it could be directly retrieved from the memory instead of being generated by the application." }, { "code": null, "e": 2814, "s": 2580, "text": "Caching is extremely important for performance boosting in ASP.NET, as the pages and controls are dynamically generated here. It is especially important for data related transactions, as these are expensive in terms of response time." }, { "code": null, "e": 3095, "s": 2814, "text": "Caching places frequently used data in quickly accessed media such as the random access memory of the computer. The ASP.NET runtime includes a key-value map of CLR objects called cache. This resides with the application and is available via the HttpContext and System.Web.UI.Page." }, { "code": null, "e": 3322, "s": 3095, "text": "In some respect, caching is similar to storing the state objects. However, the storing information in state objects is deterministic, i.e., you can count on the data being stored there, and caching of data is nondeterministic." }, { "code": null, "e": 3377, "s": 3322, "text": "The data will not be available in the following cases:" }, { "code": null, "e": 3402, "s": 3377, "text": "If its lifetime expires," }, { "code": null, "e": 3442, "s": 3402, "text": "If the application releases its memory," }, { "code": null, "e": 3490, "s": 3442, "text": "If caching does not take place for some reason." }, { "code": null, "e": 3666, "s": 3490, "text": "You can access items in the cache using an indexer and may control the lifetime of objects in the cache and set up links between the cached objects and their physical sources." }, { "code": null, "e": 3725, "s": 3666, "text": "ASP.NET provides the following different types of caching:" }, { "code": null, "e": 3973, "s": 3725, "text": "Output Caching : Output cache stores a copy of the finally rendered HTML pages or part of pages sent to the client. When the next client requests for this page, instead of regenerating the page, a cached copy of the page is sent, thus saving time." }, { "code": null, "e": 4221, "s": 3973, "text": "Output Caching : Output cache stores a copy of the finally rendered HTML pages or part of pages sent to the client. When the next client requests for this page, instead of regenerating the page, a cached copy of the page is sent, thus saving time." }, { "code": null, "e": 4478, "s": 4221, "text": "Data Caching : Data caching means caching data from a data source. As long as the cache is not expired, a request for the data will be fulfilled from the cache. When the cache is expired, fresh data is obtained by the data source and the cache is refilled." }, { "code": null, "e": 4735, "s": 4478, "text": "Data Caching : Data caching means caching data from a data source. As long as the cache is not expired, a request for the data will be fulfilled from the cache. When the cache is expired, fresh data is obtained by the data source and the cache is refilled." }, { "code": null, "e": 4874, "s": 4735, "text": "Object Caching : Object caching is caching the objects on a page, such as data-bound controls. The cached data is stored in server memory." }, { "code": null, "e": 5013, "s": 4874, "text": "Object Caching : Object caching is caching the objects on a page, such as data-bound controls. The cached data is stored in server memory." }, { "code": null, "e": 5335, "s": 5013, "text": "Class Caching : Web pages or web services are compiled into a page class in the assembly, when run for the first time. Then the assembly is cached in the server. Next time when a request is made for the page or service, the cached assembly is referred to. When the source code is changed, the CLR recompiles the assembly." }, { "code": null, "e": 5657, "s": 5335, "text": "Class Caching : Web pages or web services are compiled into a page class in the assembly, when run for the first time. Then the assembly is cached in the server. Next time when a request is made for the page or service, the cached assembly is referred to. When the source code is changed, the CLR recompiles the assembly." }, { "code": null, "e": 5840, "s": 5657, "text": "Configuration Caching : Application wide configuration information is stored in a configuration file. Configuration caching stores the configuration information in the server memory." }, { "code": null, "e": 6023, "s": 5840, "text": "Configuration Caching : Application wide configuration information is stored in a configuration file. Configuration caching stores the configuration information in the server memory." }, { "code": null, "e": 6108, "s": 6023, "text": "In this tutorial, we will consider output caching, data caching, and object caching." }, { "code": null, "e": 6341, "s": 6108, "text": "Rendering a page may involve some complex processes such as, database access, rendering complex controls etc. Output caching allows bypassing the round trips to server by caching data in memory. Even the whole page could be cached. " }, { "code": null, "e": 6476, "s": 6341, "text": "The OutputCache directive is responsible of output caching. It enables output caching and provides certain control over its behaviour." }, { "code": null, "e": 6510, "s": 6476, "text": "Syntax for OutputCache directive:" }, { "code": null, "e": 6562, "s": 6510, "text": "<%@ OutputCache Duration=\"15\" VaryByParam=\"None\" %>" }, { "code": null, "e": 6765, "s": 6562, "text": "Put this directive under the page directive. This tells the environment to cache the page for 15 seconds. The following event handler for page load would help in testing that the page was really cached." }, { "code": null, "e": 6937, "s": 6765, "text": "protected void Page_Load(object sender, EventArgs e)\n{\n Thread.Sleep(10000); \n Response.Write(\"This page was generated and cache at:\" +\n DateTime.Now.ToString());\n}" }, { "code": null, "e": 7260, "s": 6937, "text": "The Thread.Sleep() method stops the process thread for the specified time. In this example, the thread is stopped for 10 seconds, so when the page is loaded for first time, it takes 10 seconds. However, next time you refresh the page it does not take any time, as the page is retrieved from the cache without being loaded." }, { "code": null, "e": 7378, "s": 7260, "text": "The OutputCache directive has the following attributes, which helps in controlling the behaviour of the output cache:" }, { "code": null, "e": 7383, "s": 7378, "text": "None" }, { "code": null, "e": 7385, "s": 7383, "text": "*" }, { "code": null, "e": 7387, "s": 7385, "text": "*" }, { "code": null, "e": 7400, "s": 7387, "text": "Header names" }, { "code": null, "e": 7408, "s": 7400, "text": "Browser" }, { "code": null, "e": 7422, "s": 7408, "text": "Custom string" }, { "code": null, "e": 7426, "s": 7422, "text": "Any" }, { "code": null, "e": 7433, "s": 7426, "text": "Client" }, { "code": null, "e": 7444, "s": 7433, "text": "Downstream" }, { "code": null, "e": 7451, "s": 7444, "text": "Server" }, { "code": null, "e": 7456, "s": 7451, "text": "None" }, { "code": null, "e": 7490, "s": 7456, "text": "Any: page may be cached anywhere." }, { "code": null, "e": 7533, "s": 7490, "text": "Client: cached content remains at browser." }, { "code": null, "e": 7598, "s": 7533, "text": "Downstream: cached content stored in downstream and server both." }, { "code": null, "e": 7643, "s": 7598, "text": "Server: cached content saved only on server." }, { "code": null, "e": 7667, "s": 7643, "text": "None: disables caching." }, { "code": null, "e": 7769, "s": 7667, "text": "Let us add a text box and a button to the previous example and add this event handler for the button." }, { "code": null, "e": 7927, "s": 7769, "text": "protected void btnmagic_Click(object sender, EventArgs e)\n{\n Response.Write(\"<br><br>\");\n Response.Write(\"<h2> Hello, \" + this.txtname.Text + \"</h2>\");\n}" }, { "code": null, "e": 7961, "s": 7927, "text": "Change the OutputCache directive:" }, { "code": null, "e": 8016, "s": 7961, "text": "<%@ OutputCache Duration=\"60\" VaryByParam=\"txtname\" %>" }, { "code": null, "e": 8112, "s": 8016, "text": "When the program is executed, ASP.NET caches the page on the basis of the name in the text box." }, { "code": null, "e": 8436, "s": 8112, "text": "The main aspect of data caching is caching the data source controls. We have already discussed that the data source controls represent data in a data source, like a database or an XML file. These controls derive from the abstract class DataSourceControl and have the following inherited properties for implementing caching:" }, { "code": null, "e": 8525, "s": 8436, "text": "CacheDuration - It sets the number of seconds for which the data source will cache data." }, { "code": null, "e": 8614, "s": 8525, "text": "CacheDuration - It sets the number of seconds for which the data source will cache data." }, { "code": null, "e": 8704, "s": 8614, "text": "CacheExpirationPolicy - It defines the cache behavior when the data in cache has expired." }, { "code": null, "e": 8794, "s": 8704, "text": "CacheExpirationPolicy - It defines the cache behavior when the data in cache has expired." }, { "code": null, "e": 8909, "s": 8794, "text": "CacheKeyDependency - It identifies a key for the controls that auto-expires the content of its cache when removed." }, { "code": null, "e": 9024, "s": 8909, "text": "CacheKeyDependency - It identifies a key for the controls that auto-expires the content of its cache when removed." }, { "code": null, "e": 9087, "s": 9024, "text": "EnableCaching - It specifies whether or not to cache the data." }, { "code": null, "e": 9150, "s": 9087, "text": "EnableCaching - It specifies whether or not to cache the data." }, { "code": null, "e": 9330, "s": 9150, "text": "To demonstrate data caching, create a new website and add a new web form on it. Add a SqlDataSource control with the database connection already used in the data access tutorials." }, { "code": null, "e": 9422, "s": 9330, "text": "For this example, add a label to the page, which would show the response time for the page." }, { "code": null, "e": 9474, "s": 9422, "text": "<asp:Label ID=\"lbltime\" runat=\"server\"></asp:Label>" }, { "code": null, "e": 9599, "s": 9474, "text": "Apart from the label, the content page is same as in the data access tutorial. Add an event handler for the page load event:" }, { "code": null, "e": 9745, "s": 9599, "text": "protected void Page_Load(object sender, EventArgs e)\n{\n lbltime.Text = String.Format(\"Page posted at: {0}\", DateTime.Now.ToLongTimeString());\n}" }, { "code": null, "e": 9785, "s": 9745, "text": "The designed page should look as shown:" }, { "code": null, "e": 9974, "s": 9785, "text": "When you execute the page for the first time, nothing different happens, the label shows that, each time you refresh the page, the page is reloaded and the time shown on the label changes." }, { "code": null, "e": 10167, "s": 9974, "text": "Next, set the EnableCaching attribute of the data source control to be 'true' and set the Cacheduration attribute to '60'. It will implement caching and the cache will expire every 60 seconds." }, { "code": null, "e": 10316, "s": 10167, "text": "The timestamp changes with every refresh, but if you change the data in the table within these 60 seconds, it is not shown before the cache expires." }, { "code": null, "e": 10690, "s": 10316, "text": "<asp:SqlDataSource ID = \"SqlDataSource1\" runat = \"server\" \n ConnectionString = \"<%$ ConnectionStrings: ASPDotNetStepByStepConnectionString %>\" \n ProviderName = \"<%$ ConnectionStrings: ASPDotNetStepByStepConnectionString.ProviderName %>\" \n SelectCommand = \"SELECT * FROM [DotNetReferences]\"\n EnableCaching = \"true\" CacheDuration = \"60\"> \n</asp:SqlDataSource>" }, { "code": null, "e": 11004, "s": 10690, "text": "Object caching provides more flexibility than other cache techniques. You can use object caching to place any object in the cache. The object can be of any type - a data type, a web control, a class, a dataset object, etc. The item is added to the cache simply by assigning a new key name, shown as follows Like:" }, { "code": null, "e": 11025, "s": 11004, "text": "Cache[\"key\"] = item;" }, { "code": null, "e": 11164, "s": 11025, "text": "ASP.NET also provides the Insert() method for inserting an object to the cache. This method has four overloaded versions. Let us see them:" }, { "code": null, "e": 11377, "s": 11164, "text": "Sliding expiration is used to remove an item from the cache when it is not used for the specified time span. The following code snippet stores an item with a sliding expiration of 10 minutes with no dependencies." }, { "code": null, "e": 11458, "s": 11377, "text": "Cache.Insert(\"my_item\", obj, null, DateTime.MaxValue, TimeSpan.FromMinutes(10));" }, { "code": null, "e": 11553, "s": 11458, "text": "Create a page with just a button and a label. Write the following code in the page load event:" }, { "code": null, "e": 12343, "s": 11553, "text": "protected void Page_Load(object sender, EventArgs e)\n{\n if (this.IsPostBack)\n {\n lblinfo.Text += \"Page Posted Back.<br/>\";\n }\n else\n {\n lblinfo.Text += \"page Created.<br/>\";\n }\n \n if (Cache[\"testitem\"] == null)\n {\n lblinfo.Text += \"Creating test item.<br/>\";\n DateTime testItem = DateTime.Now;\n lblinfo.Text += \"Storing test item in cache \";\n lblinfo.Text += \"for 30 seconds.<br/>\";\n Cache.Insert(\"testitem\", testItem, null, \n DateTime.Now.AddSeconds(30), TimeSpan.Zero);\n }\n else\n {\n lblinfo.Text += \"Retrieving test item.<br/>\";\n DateTime testItem = (DateTime)Cache[\"testitem\"];\n lblinfo.Text += \"Test item is: \" + testItem.ToString();\n lblinfo.Text += \"<br/>\";\n }\n \n lblinfo.Text += \"<br/>\";\n}" }, { "code": null, "e": 12396, "s": 12343, "text": "When the page is loaded for the first time, it says:" }, { "code": null, "e": 12474, "s": 12396, "text": "Page Created.\nCreating test item.\nStoring test item in cache for 30 seconds.\n" }, { "code": null, "e": 12618, "s": 12474, "text": "If you click on the button again within 30 seconds, the page is posted back but the label control gets its information from the cache as shown:" }, { "code": null, "e": 12693, "s": 12618, "text": "Page Posted Back.\nRetrieving test item.\nTest item is: 14-07-2010 01:25:04\n" }, { "code": null, "e": 12728, "s": 12693, "text": "\n 51 Lectures \n 5.5 hours \n" }, { "code": null, "e": 12742, "s": 12728, "text": " Anadi Sharma" }, { "code": null, "e": 12777, "s": 12742, "text": "\n 44 Lectures \n 4.5 hours \n" }, { "code": null, "e": 12800, "s": 12777, "text": " Kaushik Roy Chowdhury" }, { "code": null, "e": 12834, "s": 12800, "text": "\n 42 Lectures \n 18 hours \n" }, { "code": null, "e": 12854, "s": 12834, "text": " SHIVPRASAD KOIRALA" }, { "code": null, "e": 12889, "s": 12854, "text": "\n 57 Lectures \n 3.5 hours \n" }, { "code": null, "e": 12906, "s": 12889, "text": " University Code" }, { "code": null, "e": 12941, "s": 12906, "text": "\n 40 Lectures \n 2.5 hours \n" }, { "code": null, "e": 12958, "s": 12941, "text": " University Code" }, { "code": null, "e": 12992, "s": 12958, "text": "\n 138 Lectures \n 9 hours \n" }, { "code": null, "e": 13007, "s": 12992, "text": " Bhrugen Patel" }, { "code": null, "e": 13014, "s": 13007, "text": " Print" }, { "code": null, "e": 13025, "s": 13014, "text": " Add Notes" } ]
How to get the selected index of a RadioGroup in Android using Kotlin?
This example demonstrates how to get the selected index of a RadioGroup in Android using Kotlin. Step 1 − Create a new project in Android Studio, go to File ? New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main.xml. <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/rl" android:layout_width="match_parent" android:layout_height="match_parent" android:padding="10dp" tools:context=".MainActivity"> <TextView android:layout_marginTop="30dp" android:id="@+id/textView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Which is your most favorite?" android:textSize="16sp" android:textStyle="bold" /> <RadioGroup android:id="@+id/radioGroup" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@id/textView" android:orientation="vertical" android:padding="15dp" android:paddingTop="30dp"> <RadioButton android:id="@+id/rbNetflix" android:layout_width="match_parent" android:layout_height="wrap_content" android:paddingEnd="15dp" android:text="Netflix" /> <RadioButton android:id="@+id/rbAmazonPrime" android:layout_width="match_parent" android:layout_height="wrap_content" android:paddingEnd="15dp" android:text="Amazon Prime" /> </RadioGroup> <Button android:id="@+id/btnGetItem" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@+id/radioGroup" android:text="Get Selected Radio Button" /> <TextView android:id="@+id/tvResult" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@id/btnGetItem" android:paddingBottom="15dp" /> </RelativeLayout> Step 3 − Add the following code to src/MainActivity.kt import android.os.Bundle import android.widget.Button import android.widget.RadioButton import android.widget.RadioGroup import android.widget.TextView import androidx.appcompat.app.AppCompatActivity class MainActivity : AppCompatActivity() { private lateinit var textView: TextView private lateinit var button: Button private lateinit var radioGroup: RadioGroup private lateinit var selectedRadioButton: RadioButton override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) title = "KotlinApp" textView = findViewById(R.id.textView) button = findViewById(R.id.btnGetItem) radioGroup = findViewById(R.id.radioGroup) button.setOnClickListener { val selectedRadioButtonId: Int = radioGroup.checkedRadioButtonId if (selectedRadioButtonId != -1) { selectedRadioButton = findViewById(selectedRadioButtonId) val string: String = selectedRadioButton.text.toString() textView.text = "$string is Selected" } else { textView.text = "Nothing selected from the radio group" } } } } Step 4 − Add the following code to androidManifest.xml <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="app.com.q15"> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest> Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click the Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen
[ { "code": null, "e": 1159, "s": 1062, "text": "This example demonstrates how to get the selected index of a RadioGroup in Android using Kotlin." }, { "code": null, "e": 1246, "s": 1159, "text": "Step 1 − Create a new project in Android Studio, go to File ? New Project and fill all" }, { "code": null, "e": 1288, "s": 1246, "text": "required details to create a new project." }, { "code": null, "e": 1353, "s": 1288, "text": "Step 2 − Add the following code to res/layout/activity_main.xml." }, { "code": null, "e": 3117, "s": 1353, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\nxmlns:tools=\"http://schemas.android.com/tools\"\n android:id=\"@+id/rl\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n android:padding=\"10dp\"\n tools:context=\".MainActivity\">\n <TextView\n android:layout_marginTop=\"30dp\"\n android:id=\"@+id/textView\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:text=\"Which is your most favorite?\"\n android:textSize=\"16sp\"\n android:textStyle=\"bold\" />\n <RadioGroup\n android:id=\"@+id/radioGroup\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_below=\"@id/textView\"\n android:orientation=\"vertical\"\n android:padding=\"15dp\"\n android:paddingTop=\"30dp\">\n <RadioButton\n android:id=\"@+id/rbNetflix\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"wrap_content\"\n android:paddingEnd=\"15dp\"\n android:text=\"Netflix\" />\n <RadioButton\n android:id=\"@+id/rbAmazonPrime\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"wrap_content\"\n android:paddingEnd=\"15dp\"\n android:text=\"Amazon Prime\" />\n </RadioGroup>\n <Button\n android:id=\"@+id/btnGetItem\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_below=\"@+id/radioGroup\"\n android:text=\"Get Selected Radio Button\" />\n <TextView\n android:id=\"@+id/tvResult\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_below=\"@id/btnGetItem\"\n android:paddingBottom=\"15dp\" />\n</RelativeLayout>" }, { "code": null, "e": 3172, "s": 3117, "text": "Step 3 − Add the following code to src/MainActivity.kt" }, { "code": null, "e": 4361, "s": 3172, "text": "import android.os.Bundle\nimport android.widget.Button\nimport android.widget.RadioButton\nimport android.widget.RadioGroup\nimport android.widget.TextView\nimport androidx.appcompat.app.AppCompatActivity\nclass MainActivity : AppCompatActivity() {\n private lateinit var textView: TextView\n private lateinit var button: Button\n private lateinit var radioGroup: RadioGroup\n private lateinit var selectedRadioButton: RadioButton\n override fun onCreate(savedInstanceState: Bundle?) {\n super.onCreate(savedInstanceState)\n setContentView(R.layout.activity_main)\n title = \"KotlinApp\"\n textView = findViewById(R.id.textView)\n button = findViewById(R.id.btnGetItem)\n radioGroup = findViewById(R.id.radioGroup)\n button.setOnClickListener {\n val selectedRadioButtonId: Int = radioGroup.checkedRadioButtonId\n if (selectedRadioButtonId != -1) {\n selectedRadioButton = findViewById(selectedRadioButtonId)\n val string: String = selectedRadioButton.text.toString()\n textView.text = \"$string is Selected\"\n } else {\n textView.text = \"Nothing selected from the radio group\"\n }\n }\n }\n}" }, { "code": null, "e": 4416, "s": 4361, "text": "Step 4 − Add the following code to androidManifest.xml" }, { "code": null, "e": 5083, "s": 4416, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\" package=\"app.com.q15\">\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": 5431, "s": 5083, "text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click the Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen" } ]
A Complete Beginners Guide to Document Similarity Algorithms | by GreekDataGuy | Towards Data Science
I’ve deployed a few recommender systems into production. Not surprisingly, the simplest turned out to be the most effective. At the core of most recommender systems lies collaborative filtering. And at the core of collaborative filtering is document similarity. We’ll walk through 3 algorithms for calculating document similarity. 1) Euclidean Distance2) Cosine Similarity3) Pearsons Correlation Coefficient Even a general intuition for how they work will help you pick the right tool for the job and build a more intelligent engine. Keep these caveats to keep in the back of your mind while we discuss the algorithms. Calculations are performed on vector representations of objects. Each object must first be converted to a numeric vector.Similarity/distance is calculated between a single pair of vectors at a time.Regardless of the algorithm, feature selection will have a huge impact on your results. Calculations are performed on vector representations of objects. Each object must first be converted to a numeric vector. Similarity/distance is calculated between a single pair of vectors at a time. Regardless of the algorithm, feature selection will have a huge impact on your results. Euclidean distance is the distance between 2 points in a multidimensional space. Closer points are more similar to each other. Further points are more different from each other. So above, Mario and Carlos are more similar than Carlos and Jenny. I’ve intentionally chosen 2 dimensions (aka. features: [wealth, friends]) because it’s easy to plot. We can still calculate distance beyond 2 dimension but a formula is required. Intuitively this method makes sense as a distance measure. You plot your documents as points and can literally measure the distance between them with a ruler. Let’s compare 3 cities: New York, Toronto and Paris. Toronto = [3,7]New York = [7,8]Paris = [2,10] The feature vector contains 2 features: [population, temperature]. Population is in millions. Temperature is in celsius. Now because we’ve again framed the problem as 2 dimensional, we could measure the distance between points with a ruler, but we’re going to use the formula here instead. The formula works whether there are 2 or 1000 dimensions. Nobody hates math notation more than me but below is the formula for Euclidean distance. Let’s write a function that implements it and calculates the distance between 2 points. from math import sqrtdef euclidean_dist(doc1, doc2): ''' For every (x,y) pair, square the difference Then take the square root of the sum ''' pre_square_sum = 0 for idx,_ in enumerate(doc1): pre_square_sum += (doc1[idx] - doc2[idx]) ** 2 return sqrt(pre_square_sum)toronto = [3,7]new_york = [7,8]euclidean_dist(toronto, new_york)#=> 4.123105625617661 Alright. The distance between Toronto and New York is 4.12. The function we wrote above is a little inefficient. Sklearn implements a faster version using Numpy. In production we’d just use this. toronto = [3,7]new_york = [7,8]import numpy as npfrom sklearn.metrics.pairwise import euclidean_distancest = np.array(toronto).reshape(1,-1)n = np.array(new_york).reshape(1,-1)euclidean_distances(t, n)[0][0]#=> 4.123105625617661 Note that it requires arrays instead of lists as inputs, but we get the same result. Booya! Cosine similarity is the cosine of the angle between 2 points in a multidimensional space. Points with smaller angles are more similar. Points with larger angles are more different. While harder to wrap your head around, cosine similarity solves some problems with Euclidean distance. Namely, magnitude. In the above drawing, we compare 3 documents based on how many times they contain the words “cooking” and “restaurant”. Euclidean distance tells us the blog and magazine are more similar than the blog and newspaper. But I think that’s misleading. The blog and newspaper could have similar content but are distant in a Euclidean sense because the newspaper is longer and contains more words. In reality, they both mention “restaurant” more than “cooking” and are probably more similar to each other than not. Cosine similarity doesn’t fall into this trap. Let’s work through our above example. We’ll compare documents based on the count of specific words magazine_article = [7,1]blog_post = [2,10]newspaper_article = [2,20] Rather than taking the distance between each, we’ll now take the cosine of the angle between them from the point of origin. Now even just eyeballing it, the blog and the newspaper look more similar. Note that cosine similarity is not the angle itself, but the cosine of the angle. So a smaller angle (sub 90 degrees) returns a larger similarity. Let’s implement a function to calculate this ourselves. import numpy as npfrom math import sqrtdef my_cosine_similarity(A, B): numerator = np.dot(A,B) denominator = sqrt(A.dot(A)) * sqrt(B.dot(B)) return numerator / denominator magazine_article = [7,1]blog_post = [2,10]newspaper_article = [2,20]m = np.array(magazine_article)b = np.array(blog_post)n = np.array(newspaper_article) print( my_cosine_similarity(m,b) ) #=> 0.3328201177351375print( my_cosine_similarity(b,n) ) #=> 0.9952285251199801print( my_cosine_similarity(n,m) ) #=> 0.2392231652082992 Now we see that the blog and newspaper are indeed more similar to each other. In production, we’re better off just importing Sklearn’s more efficient implementation. from sklearn.metrics.pairwise import cosine_similaritym = np.array(magazine_article).reshape(1,-1)b = np.array(blog_post).reshape(1,-1)n = np.array(newspaper_article).reshape(1,-1)print( cosine_similarity(m,b)[0,0] ) #=> 0.3328201177351375print( cosine_similarity(b,n)[0,0] ) #=> 0.9952285251199801print( cosine_similarity(n,m)[0,0] ) #=> 0.2392231652082992 Same values. Great! This typically quantifies the relationship between 2 variables. Like for example, education and income. But we can also use it to measure the similarity between 2 documents where we treat the 1st document’s vector as x and the 2nd document’s vector as y. Because of the Pearson correlation coefficient, r, returns a value between 1 and -1, Pearson distance can then be calculated as 1 — r to return a value between 0 and 2. Let’s implement the formula ourselves to develop an understanding of how it works. We’re going to generate some fake data representing a few people. We’ll compare how similar they are based on a 3-feature vector. emily = [1,2,5]kartik = [1,3,5]todd = [5,3,5] Our implementation. import numpy as npdef pearsons_correlation_coef(x, y): x = np.array(x) y = np.array(y) x_mean = x.mean() y_mean = y.mean() x_less_mean = x - x_mean y_less_mean = y - y_mean numerator = np.sum(xm * ym) denominator = np.sqrt( np.sum(xm**2) * np.sum(ym**2) ) return r_num / r_denpearsons_correlation_coef(emily,kartik)#=> 0.9607689228305226 Cool. Emily and Kartik appear pretty similar. We’ll compare all 3 with Scipy in a second. Scipy implements a more efficient and robust calculation. emily = [1,2,5]kartik = [1,3,5]todd = [5,3,5]pearsonr2(emily,kartik)print( pearsonr2(emily, kartik) ) #=> (0.9607689228305226, 0.1789123750220673)print( pearsonr2(kartik, todd) ) #=> (0.0, 1.0)print( pearsonr2(todd, emily) ) #=> (0.27735009811261446, 0.8210876249779328) Albeit I’ve chosen random numbers as data points, we can see that Emily and Kartik are more similar than Emily and Todd. While we’ve covered one piece of the puzzle, the road to a fully fledged recommender is not complete. In the context of an e-commerce engine, we’d next build a matrix of similarity scores between every pair of users. We could then use that to recommend products that similar users purchased. That said, a good recommender might also incorporate domain-based rules and users preferences.
[ { "code": null, "e": 297, "s": 172, "text": "I’ve deployed a few recommender systems into production. Not surprisingly, the simplest turned out to be the most effective." }, { "code": null, "e": 434, "s": 297, "text": "At the core of most recommender systems lies collaborative filtering. And at the core of collaborative filtering is document similarity." }, { "code": null, "e": 503, "s": 434, "text": "We’ll walk through 3 algorithms for calculating document similarity." }, { "code": null, "e": 580, "s": 503, "text": "1) Euclidean Distance2) Cosine Similarity3) Pearsons Correlation Coefficient" }, { "code": null, "e": 706, "s": 580, "text": "Even a general intuition for how they work will help you pick the right tool for the job and build a more intelligent engine." }, { "code": null, "e": 791, "s": 706, "text": "Keep these caveats to keep in the back of your mind while we discuss the algorithms." }, { "code": null, "e": 1077, "s": 791, "text": "Calculations are performed on vector representations of objects. Each object must first be converted to a numeric vector.Similarity/distance is calculated between a single pair of vectors at a time.Regardless of the algorithm, feature selection will have a huge impact on your results." }, { "code": null, "e": 1199, "s": 1077, "text": "Calculations are performed on vector representations of objects. Each object must first be converted to a numeric vector." }, { "code": null, "e": 1277, "s": 1199, "text": "Similarity/distance is calculated between a single pair of vectors at a time." }, { "code": null, "e": 1365, "s": 1277, "text": "Regardless of the algorithm, feature selection will have a huge impact on your results." }, { "code": null, "e": 1446, "s": 1365, "text": "Euclidean distance is the distance between 2 points in a multidimensional space." }, { "code": null, "e": 1610, "s": 1446, "text": "Closer points are more similar to each other. Further points are more different from each other. So above, Mario and Carlos are more similar than Carlos and Jenny." }, { "code": null, "e": 1789, "s": 1610, "text": "I’ve intentionally chosen 2 dimensions (aka. features: [wealth, friends]) because it’s easy to plot. We can still calculate distance beyond 2 dimension but a formula is required." }, { "code": null, "e": 1948, "s": 1789, "text": "Intuitively this method makes sense as a distance measure. You plot your documents as points and can literally measure the distance between them with a ruler." }, { "code": null, "e": 2001, "s": 1948, "text": "Let’s compare 3 cities: New York, Toronto and Paris." }, { "code": null, "e": 2047, "s": 2001, "text": "Toronto = [3,7]New York = [7,8]Paris = [2,10]" }, { "code": null, "e": 2168, "s": 2047, "text": "The feature vector contains 2 features: [population, temperature]. Population is in millions. Temperature is in celsius." }, { "code": null, "e": 2337, "s": 2168, "text": "Now because we’ve again framed the problem as 2 dimensional, we could measure the distance between points with a ruler, but we’re going to use the formula here instead." }, { "code": null, "e": 2395, "s": 2337, "text": "The formula works whether there are 2 or 1000 dimensions." }, { "code": null, "e": 2484, "s": 2395, "text": "Nobody hates math notation more than me but below is the formula for Euclidean distance." }, { "code": null, "e": 2572, "s": 2484, "text": "Let’s write a function that implements it and calculates the distance between 2 points." }, { "code": null, "e": 2955, "s": 2572, "text": "from math import sqrtdef euclidean_dist(doc1, doc2): ''' For every (x,y) pair, square the difference Then take the square root of the sum ''' pre_square_sum = 0 for idx,_ in enumerate(doc1): pre_square_sum += (doc1[idx] - doc2[idx]) ** 2 return sqrt(pre_square_sum)toronto = [3,7]new_york = [7,8]euclidean_dist(toronto, new_york)#=> 4.123105625617661" }, { "code": null, "e": 3015, "s": 2955, "text": "Alright. The distance between Toronto and New York is 4.12." }, { "code": null, "e": 3151, "s": 3015, "text": "The function we wrote above is a little inefficient. Sklearn implements a faster version using Numpy. In production we’d just use this." }, { "code": null, "e": 3380, "s": 3151, "text": "toronto = [3,7]new_york = [7,8]import numpy as npfrom sklearn.metrics.pairwise import euclidean_distancest = np.array(toronto).reshape(1,-1)n = np.array(new_york).reshape(1,-1)euclidean_distances(t, n)[0][0]#=> 4.123105625617661" }, { "code": null, "e": 3472, "s": 3380, "text": "Note that it requires arrays instead of lists as inputs, but we get the same result. Booya!" }, { "code": null, "e": 3654, "s": 3472, "text": "Cosine similarity is the cosine of the angle between 2 points in a multidimensional space. Points with smaller angles are more similar. Points with larger angles are more different." }, { "code": null, "e": 3776, "s": 3654, "text": "While harder to wrap your head around, cosine similarity solves some problems with Euclidean distance. Namely, magnitude." }, { "code": null, "e": 3896, "s": 3776, "text": "In the above drawing, we compare 3 documents based on how many times they contain the words “cooking” and “restaurant”." }, { "code": null, "e": 4023, "s": 3896, "text": "Euclidean distance tells us the blog and magazine are more similar than the blog and newspaper. But I think that’s misleading." }, { "code": null, "e": 4167, "s": 4023, "text": "The blog and newspaper could have similar content but are distant in a Euclidean sense because the newspaper is longer and contains more words." }, { "code": null, "e": 4331, "s": 4167, "text": "In reality, they both mention “restaurant” more than “cooking” and are probably more similar to each other than not. Cosine similarity doesn’t fall into this trap." }, { "code": null, "e": 4430, "s": 4331, "text": "Let’s work through our above example. We’ll compare documents based on the count of specific words" }, { "code": null, "e": 4499, "s": 4430, "text": "magazine_article = [7,1]blog_post = [2,10]newspaper_article = [2,20]" }, { "code": null, "e": 4698, "s": 4499, "text": "Rather than taking the distance between each, we’ll now take the cosine of the angle between them from the point of origin. Now even just eyeballing it, the blog and the newspaper look more similar." }, { "code": null, "e": 4845, "s": 4698, "text": "Note that cosine similarity is not the angle itself, but the cosine of the angle. So a smaller angle (sub 90 degrees) returns a larger similarity." }, { "code": null, "e": 4901, "s": 4845, "text": "Let’s implement a function to calculate this ourselves." }, { "code": null, "e": 5417, "s": 4901, "text": "import numpy as npfrom math import sqrtdef my_cosine_similarity(A, B): numerator = np.dot(A,B) denominator = sqrt(A.dot(A)) * sqrt(B.dot(B)) return numerator / denominator magazine_article = [7,1]blog_post = [2,10]newspaper_article = [2,20]m = np.array(magazine_article)b = np.array(blog_post)n = np.array(newspaper_article) print( my_cosine_similarity(m,b) ) #=> 0.3328201177351375print( my_cosine_similarity(b,n) ) #=> 0.9952285251199801print( my_cosine_similarity(n,m) ) #=> 0.2392231652082992" }, { "code": null, "e": 5495, "s": 5417, "text": "Now we see that the blog and newspaper are indeed more similar to each other." }, { "code": null, "e": 5583, "s": 5495, "text": "In production, we’re better off just importing Sklearn’s more efficient implementation." }, { "code": null, "e": 5941, "s": 5583, "text": "from sklearn.metrics.pairwise import cosine_similaritym = np.array(magazine_article).reshape(1,-1)b = np.array(blog_post).reshape(1,-1)n = np.array(newspaper_article).reshape(1,-1)print( cosine_similarity(m,b)[0,0] ) #=> 0.3328201177351375print( cosine_similarity(b,n)[0,0] ) #=> 0.9952285251199801print( cosine_similarity(n,m)[0,0] ) #=> 0.2392231652082992" }, { "code": null, "e": 5961, "s": 5941, "text": "Same values. Great!" }, { "code": null, "e": 6065, "s": 5961, "text": "This typically quantifies the relationship between 2 variables. Like for example, education and income." }, { "code": null, "e": 6216, "s": 6065, "text": "But we can also use it to measure the similarity between 2 documents where we treat the 1st document’s vector as x and the 2nd document’s vector as y." }, { "code": null, "e": 6385, "s": 6216, "text": "Because of the Pearson correlation coefficient, r, returns a value between 1 and -1, Pearson distance can then be calculated as 1 — r to return a value between 0 and 2." }, { "code": null, "e": 6468, "s": 6385, "text": "Let’s implement the formula ourselves to develop an understanding of how it works." }, { "code": null, "e": 6598, "s": 6468, "text": "We’re going to generate some fake data representing a few people. We’ll compare how similar they are based on a 3-feature vector." }, { "code": null, "e": 6644, "s": 6598, "text": "emily = [1,2,5]kartik = [1,3,5]todd = [5,3,5]" }, { "code": null, "e": 6664, "s": 6644, "text": "Our implementation." }, { "code": null, "e": 7051, "s": 6664, "text": "import numpy as npdef pearsons_correlation_coef(x, y): x = np.array(x) y = np.array(y) x_mean = x.mean() y_mean = y.mean() x_less_mean = x - x_mean y_less_mean = y - y_mean numerator = np.sum(xm * ym) denominator = np.sqrt( np.sum(xm**2) * np.sum(ym**2) ) return r_num / r_denpearsons_correlation_coef(emily,kartik)#=> 0.9607689228305226" }, { "code": null, "e": 7141, "s": 7051, "text": "Cool. Emily and Kartik appear pretty similar. We’ll compare all 3 with Scipy in a second." }, { "code": null, "e": 7199, "s": 7141, "text": "Scipy implements a more efficient and robust calculation." }, { "code": null, "e": 7470, "s": 7199, "text": "emily = [1,2,5]kartik = [1,3,5]todd = [5,3,5]pearsonr2(emily,kartik)print( pearsonr2(emily, kartik) ) #=> (0.9607689228305226, 0.1789123750220673)print( pearsonr2(kartik, todd) ) #=> (0.0, 1.0)print( pearsonr2(todd, emily) ) #=> (0.27735009811261446, 0.8210876249779328)" }, { "code": null, "e": 7591, "s": 7470, "text": "Albeit I’ve chosen random numbers as data points, we can see that Emily and Kartik are more similar than Emily and Todd." }, { "code": null, "e": 7693, "s": 7591, "text": "While we’ve covered one piece of the puzzle, the road to a fully fledged recommender is not complete." }, { "code": null, "e": 7883, "s": 7693, "text": "In the context of an e-commerce engine, we’d next build a matrix of similarity scores between every pair of users. We could then use that to recommend products that similar users purchased." } ]
How to deal with security certificates using Selenium?
We can deal with security certificates using Selenium webdriver. We can have certificates like the SSL certificate and insecure certificate. All these can be handled with the help of the DesiredCapabilities and ChromeOptions class. We shall create an object of the DesiredCapabilities class and apply setCapability method on it. Then pass the CapabilityType and value as parameters to that method. These general browser chrome profiles shall be fed to the object of the ChromeOptions class for the local browser with the help of the merge method. Finally, this information needs to be passed to the webdriver object. DesiredCapabilities c=DesiredCapabilities.chrome(); c.setCapability(CapabilityType.ACCEPT_INSECURE_CERTS, true); c.setCapability(CapabilityType.ACCEPT_SSL_CERTS, true); ChromeOptions opt= new ChromeOptions(); opt.merge(c); Example of a SSL certificate is shown below. We need to click on the Proceed anyway button to accept this certificate. Example of Insecure certificate is shown below − import org.openqa.selenium.WebDriver; import org.openqa.selenium.Capabilities; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.chrome.ChromeOptions; import org.openqa.selenium.remote.CapabilityType; import org.openqa.selenium.remote.DesiredCapabilities; public class SecurityCertAccepts{ public static void main(String[] args) { //DesiredCapabilities object DesiredCapabilities c=DesiredCapabilities.chrome(); //accept insecure certificates c.setCapability(CapabilityType.ACCEPT_INSECURE_CERTS, true); //accept SSL certificates c.setCapability(CapabilityType.ACCEPT_SSL_CERTS, true); //ChromeOptions object ChromeOptions opt= new ChromeOptions(); //merging browser profiles opt.merge(c); System.setProperty("webdriver.chrome.driver", "C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe"); // configure options parameter to Chrome driver WebDriver driver = new ChromeDriver(opt); } }
[ { "code": null, "e": 1294, "s": 1062, "text": "We can deal with security certificates using Selenium webdriver. We can have certificates like the SSL certificate and insecure certificate. All these can be handled with the help of the DesiredCapabilities and ChromeOptions class." }, { "code": null, "e": 1460, "s": 1294, "text": "We shall create an object of the DesiredCapabilities class and apply setCapability method on it. Then pass the CapabilityType and value as parameters to that method." }, { "code": null, "e": 1679, "s": 1460, "text": "These general browser chrome profiles shall be fed to the object of the ChromeOptions class for the local browser with the help of the merge method. Finally, this information needs to be passed to the webdriver object." }, { "code": null, "e": 1902, "s": 1679, "text": "DesiredCapabilities c=DesiredCapabilities.chrome();\nc.setCapability(CapabilityType.ACCEPT_INSECURE_CERTS, true);\nc.setCapability(CapabilityType.ACCEPT_SSL_CERTS, true);\nChromeOptions opt= new ChromeOptions();\nopt.merge(c);" }, { "code": null, "e": 2021, "s": 1902, "text": "Example of a SSL certificate is shown below. We need to click on the Proceed anyway button to accept this certificate." }, { "code": null, "e": 2070, "s": 2021, "text": "Example of Insecure certificate is shown below −" }, { "code": null, "e": 3071, "s": 2070, "text": "import org.openqa.selenium.WebDriver;\nimport org.openqa.selenium.Capabilities;\nimport org.openqa.selenium.chrome.ChromeDriver;\nimport org.openqa.selenium.chrome.ChromeOptions;\nimport org.openqa.selenium.remote.CapabilityType;\nimport org.openqa.selenium.remote.DesiredCapabilities;\npublic class SecurityCertAccepts{\n public static void main(String[] args) {\n //DesiredCapabilities object\n DesiredCapabilities c=DesiredCapabilities.chrome();\n //accept insecure certificates\n c.setCapability(CapabilityType.ACCEPT_INSECURE_CERTS, true);\n //accept SSL certificates\n c.setCapability(CapabilityType.ACCEPT_SSL_CERTS, true);\n //ChromeOptions object\n ChromeOptions opt= new ChromeOptions();\n //merging browser profiles\n opt.merge(c);\n System.setProperty(\"webdriver.chrome.driver\",\n \"C:\\\\Users\\\\ghs6kor\\\\Desktop\\\\Java\\\\chromedriver.exe\");\n // configure options parameter to Chrome driver\n WebDriver driver = new ChromeDriver(opt);\n }\n}" } ]
Beautiful decision tree visualizations with dtreeviz | by Eryk Lewinson | Towards Data Science
Decision trees are a very important class of machine learning models and they are also building blocks of many more advanced algorithms, such as Random Forest or the famous XGBoost. The trees are also a good starting point for a baseline model, which we subsequently try to improve upon with more complex algorithms. One of the biggest advantages of the decision trees is their interpretability — after fitting the model, it is effectively a set of rules that can be used to predict the target variable. That is also why it is easy to plot the rules and show them to stakeholders, so they can easily understand the model’s underlying logic. Of course, provided that the tree is not too deep. Visualizing the decision trees can be really simple using a combination of scikit-learn and matplotlib. However, there is a nice library called dtreeviz, which brings much more to the table and creates visualizations that are not only prettier but also convey more information about the decision process. In this article, I will first show the “old way” of plotting the decision trees and then introduce the improved approach using dtreeviz. As always, we need to start by importing the required libraries. Then, we load the Iris data set from scikit-learn. We will also go over a regression example, but we will load the Boston housing data set for this later on. The next step involves creating the training/test sets and fitting the decision tree classifier to the Iris data set. In this article, we focus purely on visualizing the decision trees. Thus, we do not pay any attention to fitting the model or finding a good set of hyperparameters (there are a lot of articles on these topics). The only thing that we will “tune” is the maximum depth of the tree — we constraint it to 3, so the trees can still fit in the image and remain readable. Now that we have a fitted decision tree model and we can proceed to visualize the tree. We start with the easiest approach — using the plot_tree function from scikit-learn. tree.plot_tree(clf); OK, not bad for a one-liner. But it is not very readable, for example, there are no feature names (only their column indices) or class labels. We can easily improve that by running the following snippet. Much better! Now, we can quite easily interpret the decision tree. It is also possible to use the graphviz library for visualizing the decision trees, however, the outcome is very similar, with the same set of elements as the graph above. That is why we will skip it here, but you can find the implementation in the Notebook on GitHub. Having seen the old way of plotting the decision trees, let’s jump right into the dtreeviz approach. The code snippet is pretty much self-explanatory, so we can move on to the outcome. First of all, let’s take a moment to acknowledge how big of an improvement it is, especially given that the function call is very similar. Let’s go over the plot step by step. At each node, we can see a stacked histogram of the feature that is used for splitting the observations, colored by class. This way, we can see how the classes are segregated by each split. The small triangle with the value at the x-axis is the splitting point. In the first histogram, we can clearly see that all observations of the setosa class have petal length smaller than 2.45 cm. The right branches of the tree indicate selecting the values larger or equal to the splitting value, while the left one lesser than the splitting value. The leaf nodes are represented as pie charts, which show what fraction of the observations within the leaf belongs to which class. This way, we easily see which class is the majority one, so also the model’s prediction. One thing we do not see at this plot is the value of the Gini coefficient at each node. In my opinion, the histogram provides more intuition about the split and the value of the coefficient might not be that relevant in case of a presentation for the stakeholders either way. Note: We can also create a similar visualization for the test set, we just need to replace the x_data and y_data arguments while calling the function. If you are not a fan of the histograms and want to simplify the plot, you can specify fancy=False to receive the following simplified plot. Another handy feature of dtreeviz which improves the model’s interpretability is path highlighting of a particular observation on the plot. This way, we clearly see which features contributed to the class prediction. Using the snippet below, we highlight the path of the first observation of the test set. The plot is very similar to the previous one, however, the orange highlight clearly shows which path the observation followed. Additionally, we can see the orange triangle at each of the histograms. It represents the indicated observation’s value of the given feature. At the very end, we see the values of all the features of this observation, with the ones used for decision highlighted in orange. In this case, only two features were used for predicting that the observation belongs to the versicolor class. Tip: We can also change the orientation of the plots from top-to-bottom to left-to-right by setting orientation=”LR”. We do not show it in this article, as the charts will not be scaled that nicely for devices with a narrower screen. Lastly, we can print the decisions used for this observation’s prediction in plain English. To do so, we run the following command. This way, we can clearly see the conditions that this observation fulfills. We have already covered a classification example, which showed most of the interesting functionalities of the library. But for completeness’ sake, we also go over an example of a regression problem, to show how the plots differ. We use another popular data set — the Boston housing one. It’s a problem in which we use a set of different areas to predict the median housing price within certain areas of Boston. The code already feels similar. The only change is that we added show_node_labels = True. It can be especially handy for larger decision trees. So while discussing the plot with a group, it is very easy to indicate which split we are discussing by the node’s number. Let’s dive into the differences between classification trees and regression ones. This time, instead of looking at histograms, we inspect scatterplots of the feature used for the split vs. the target. On those scatterplots, we see some dashed lines. Their interpretation is as follows: horizontal lines are the target’s mean for the left and right buckets in decision nodes. vertical lines are the split point. It is the very same information as represented by the black triangle, however, it makes comparing the horizontal lines easier -> easy separation between the sides. In the leaf nodes, the dashed line shows the mean of the target within the leaf, which is also the model’s prediction. We already showed that we can highlight the decision path for a certain observation. We can take it a step further and only plot the nodes used for that prediction. We do so by specifying show_just_path=True. The following plot shows only the selected nodes from the tree above. In this article, I showed how to use the dtreeviz library for creating elegant and insightful visualizations of decision trees. Having played around with it for a bit, I will definitely keep on using it as the go-to tool for visualizing decision trees. I do believe that the plots created using this library are much easier to understand for people who do not work with ML on a daily basis and can help in conveying the model’s logic to the stakeholders. It is also worth mentioning that dtreeviz supports some visualizations for XGBoost and Spark MLlib trees. You can find the code used for this article on my GitHub. As always, any constructive feedback is welcome. You can reach out to me on Twitter or in the comments. Found this article interesting? Become a Medium member to continue learning by reading without limits. If you use this link to become a member, you will support me at no extra cost to you. Thanks in advance and see you around! If you liked this article, you might also be interested in one of the following:
[ { "code": null, "e": 489, "s": 172, "text": "Decision trees are a very important class of machine learning models and they are also building blocks of many more advanced algorithms, such as Random Forest or the famous XGBoost. The trees are also a good starting point for a baseline model, which we subsequently try to improve upon with more complex algorithms." }, { "code": null, "e": 864, "s": 489, "text": "One of the biggest advantages of the decision trees is their interpretability — after fitting the model, it is effectively a set of rules that can be used to predict the target variable. That is also why it is easy to plot the rules and show them to stakeholders, so they can easily understand the model’s underlying logic. Of course, provided that the tree is not too deep." }, { "code": null, "e": 1169, "s": 864, "text": "Visualizing the decision trees can be really simple using a combination of scikit-learn and matplotlib. However, there is a nice library called dtreeviz, which brings much more to the table and creates visualizations that are not only prettier but also convey more information about the decision process." }, { "code": null, "e": 1306, "s": 1169, "text": "In this article, I will first show the “old way” of plotting the decision trees and then introduce the improved approach using dtreeviz." }, { "code": null, "e": 1371, "s": 1306, "text": "As always, we need to start by importing the required libraries." }, { "code": null, "e": 1529, "s": 1371, "text": "Then, we load the Iris data set from scikit-learn. We will also go over a regression example, but we will load the Boston housing data set for this later on." }, { "code": null, "e": 2012, "s": 1529, "text": "The next step involves creating the training/test sets and fitting the decision tree classifier to the Iris data set. In this article, we focus purely on visualizing the decision trees. Thus, we do not pay any attention to fitting the model or finding a good set of hyperparameters (there are a lot of articles on these topics). The only thing that we will “tune” is the maximum depth of the tree — we constraint it to 3, so the trees can still fit in the image and remain readable." }, { "code": null, "e": 2185, "s": 2012, "text": "Now that we have a fitted decision tree model and we can proceed to visualize the tree. We start with the easiest approach — using the plot_tree function from scikit-learn." }, { "code": null, "e": 2206, "s": 2185, "text": "tree.plot_tree(clf);" }, { "code": null, "e": 2410, "s": 2206, "text": "OK, not bad for a one-liner. But it is not very readable, for example, there are no feature names (only their column indices) or class labels. We can easily improve that by running the following snippet." }, { "code": null, "e": 2746, "s": 2410, "text": "Much better! Now, we can quite easily interpret the decision tree. It is also possible to use the graphviz library for visualizing the decision trees, however, the outcome is very similar, with the same set of elements as the graph above. That is why we will skip it here, but you can find the implementation in the Notebook on GitHub." }, { "code": null, "e": 2847, "s": 2746, "text": "Having seen the old way of plotting the decision trees, let’s jump right into the dtreeviz approach." }, { "code": null, "e": 3070, "s": 2847, "text": "The code snippet is pretty much self-explanatory, so we can move on to the outcome. First of all, let’s take a moment to acknowledge how big of an improvement it is, especially given that the function call is very similar." }, { "code": null, "e": 3494, "s": 3070, "text": "Let’s go over the plot step by step. At each node, we can see a stacked histogram of the feature that is used for splitting the observations, colored by class. This way, we can see how the classes are segregated by each split. The small triangle with the value at the x-axis is the splitting point. In the first histogram, we can clearly see that all observations of the setosa class have petal length smaller than 2.45 cm." }, { "code": null, "e": 3867, "s": 3494, "text": "The right branches of the tree indicate selecting the values larger or equal to the splitting value, while the left one lesser than the splitting value. The leaf nodes are represented as pie charts, which show what fraction of the observations within the leaf belongs to which class. This way, we easily see which class is the majority one, so also the model’s prediction." }, { "code": null, "e": 4143, "s": 3867, "text": "One thing we do not see at this plot is the value of the Gini coefficient at each node. In my opinion, the histogram provides more intuition about the split and the value of the coefficient might not be that relevant in case of a presentation for the stakeholders either way." }, { "code": null, "e": 4294, "s": 4143, "text": "Note: We can also create a similar visualization for the test set, we just need to replace the x_data and y_data arguments while calling the function." }, { "code": null, "e": 4434, "s": 4294, "text": "If you are not a fan of the histograms and want to simplify the plot, you can specify fancy=False to receive the following simplified plot." }, { "code": null, "e": 4651, "s": 4434, "text": "Another handy feature of dtreeviz which improves the model’s interpretability is path highlighting of a particular observation on the plot. This way, we clearly see which features contributed to the class prediction." }, { "code": null, "e": 4740, "s": 4651, "text": "Using the snippet below, we highlight the path of the first observation of the test set." }, { "code": null, "e": 5251, "s": 4740, "text": "The plot is very similar to the previous one, however, the orange highlight clearly shows which path the observation followed. Additionally, we can see the orange triangle at each of the histograms. It represents the indicated observation’s value of the given feature. At the very end, we see the values of all the features of this observation, with the ones used for decision highlighted in orange. In this case, only two features were used for predicting that the observation belongs to the versicolor class." }, { "code": null, "e": 5485, "s": 5251, "text": "Tip: We can also change the orientation of the plots from top-to-bottom to left-to-right by setting orientation=”LR”. We do not show it in this article, as the charts will not be scaled that nicely for devices with a narrower screen." }, { "code": null, "e": 5617, "s": 5485, "text": "Lastly, we can print the decisions used for this observation’s prediction in plain English. To do so, we run the following command." }, { "code": null, "e": 5693, "s": 5617, "text": "This way, we can clearly see the conditions that this observation fulfills." }, { "code": null, "e": 6104, "s": 5693, "text": "We have already covered a classification example, which showed most of the interesting functionalities of the library. But for completeness’ sake, we also go over an example of a regression problem, to show how the plots differ. We use another popular data set — the Boston housing one. It’s a problem in which we use a set of different areas to predict the median housing price within certain areas of Boston." }, { "code": null, "e": 6371, "s": 6104, "text": "The code already feels similar. The only change is that we added show_node_labels = True. It can be especially handy for larger decision trees. So while discussing the plot with a group, it is very easy to indicate which split we are discussing by the node’s number." }, { "code": null, "e": 6657, "s": 6371, "text": "Let’s dive into the differences between classification trees and regression ones. This time, instead of looking at histograms, we inspect scatterplots of the feature used for the split vs. the target. On those scatterplots, we see some dashed lines. Their interpretation is as follows:" }, { "code": null, "e": 6746, "s": 6657, "text": "horizontal lines are the target’s mean for the left and right buckets in decision nodes." }, { "code": null, "e": 6946, "s": 6746, "text": "vertical lines are the split point. It is the very same information as represented by the black triangle, however, it makes comparing the horizontal lines easier -> easy separation between the sides." }, { "code": null, "e": 7065, "s": 6946, "text": "In the leaf nodes, the dashed line shows the mean of the target within the leaf, which is also the model’s prediction." }, { "code": null, "e": 7344, "s": 7065, "text": "We already showed that we can highlight the decision path for a certain observation. We can take it a step further and only plot the nodes used for that prediction. We do so by specifying show_just_path=True. The following plot shows only the selected nodes from the tree above." }, { "code": null, "e": 7799, "s": 7344, "text": "In this article, I showed how to use the dtreeviz library for creating elegant and insightful visualizations of decision trees. Having played around with it for a bit, I will definitely keep on using it as the go-to tool for visualizing decision trees. I do believe that the plots created using this library are much easier to understand for people who do not work with ML on a daily basis and can help in conveying the model’s logic to the stakeholders." }, { "code": null, "e": 7905, "s": 7799, "text": "It is also worth mentioning that dtreeviz supports some visualizations for XGBoost and Spark MLlib trees." }, { "code": null, "e": 8067, "s": 7905, "text": "You can find the code used for this article on my GitHub. As always, any constructive feedback is welcome. You can reach out to me on Twitter or in the comments." }, { "code": null, "e": 8294, "s": 8067, "text": "Found this article interesting? Become a Medium member to continue learning by reading without limits. If you use this link to become a member, you will support me at no extra cost to you. Thanks in advance and see you around!" } ]
Java Examples - Find min & max from a List
How to find min & max of a List ? Following example uses min & max Methods to find minimum & maximum of the List. import java.util.*; public class Main { public static void main(String[] args) { List list = Arrays.asList("one Two three Four five six one three Four".split(" ")); System.out.println(list); System.out.println("max: " + Collections.max(list)); System.out.println("min: " + Collections.min(list)); } } The above code sample will produce the following result. [one, Two, three, Four, five, six, one, three, Four] max: three min: Four Print Add Notes Bookmark this page
[ { "code": null, "e": 2102, "s": 2068, "text": "How to find min & max of a List ?" }, { "code": null, "e": 2182, "s": 2102, "text": "Following example uses min & max Methods to find minimum & maximum of the List." }, { "code": null, "e": 2514, "s": 2182, "text": "import java.util.*;\n\npublic class Main {\n public static void main(String[] args) {\n List list = Arrays.asList(\"one Two three Four five six one three Four\".split(\" \"));\n System.out.println(list);\n System.out.println(\"max: \" + Collections.max(list));\n System.out.println(\"min: \" + Collections.min(list));\n }\n}" }, { "code": null, "e": 2571, "s": 2514, "text": "The above code sample will produce the following result." }, { "code": null, "e": 2646, "s": 2571, "text": "[one, Two, three, Four, five, six, one, three, Four]\nmax: three\nmin: Four\n" }, { "code": null, "e": 2653, "s": 2646, "text": " Print" }, { "code": null, "e": 2664, "s": 2653, "text": " Add Notes" } ]
Hashtable get() Method in Java - GeeksforGeeks
28 Jun, 2018 The java.util.Hashtable.get() method of Hashtable class is used to retrieve or fetch the value mapped by a particular key mentioned in the parameter. It returns NULL when the table contains no such mapping for the key. Syntax: Hash_Table.get(Object key_element) Parameter: The method takes one parameter key_element of object type and refers to the key whose associated value is supposed to be fetched. Return Value: The method returns the value associated with the key_element in the parameter. Below programs illustrates the working of java.util.Hashtable.get() method:Program 1: // Java code to illustrate the get() methodimport java.util.*; public class Hash_Table_Demo { public static void main(String[] args) { // Creating an empty Hashtable Hashtable<Integer, String> hash_table = new Hashtable<Integer, String>(); // Inserting the values into table hash_table.put(10, "Geeks"); hash_table.put(15, "4"); hash_table.put(20, "Geeks"); hash_table.put(25, "Welcomes"); hash_table.put(30, "You"); // Displaying the Hashtable System.out.println("Initial Table is: " + hash_table); // Getting the value of 25 System.out.println("The Value is: " + hash_table.get(25)); // Getting the value of 10 System.out.println("The Value is: " + hash_table.get(10)); }} Initial Table is: {10=Geeks, 20=Geeks, 30=You, 15=4, 25=Welcomes} The Value is: Welcomes The Value is: Geeks Program 2: // Java code to illustrate the get() methodimport java.util.*; public class Hash_Table_Demo { public static void main(String[] args) { // Creating an empty Hashtable Hashtable<String, Integer> hash_table = new Hashtable<String, Integer>(); // Inserting the values into table hash_table.put("Geeks", 10); hash_table.put("4", 15); hash_table.put("Geeks", 20); hash_table.put("Welcomes", 25); hash_table.put("You", 30); // Displaying the Hashtable System.out.println("Initial table is: " + hash_table); // Getting the value of "Geeks" System.out.println("The Value is: " + hash_table.get("Geeks")); // Getting the value of "You" System.out.println("The Value is: " + hash_table.get("You")); }} Initial table is: {You=30, Welcomes=25, 4=15, Geeks=20} The Value is: 20 The Value is: 30 Note: The same operation can be performed with any type of variation and combination of different data types. Java-Collections Java-HashTable Java Java Java-Collections Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Arrays in Java Split() String method in Java with examples For-each loop in Java Arrays.sort() in Java with examples Reverse a string in Java Initialize an ArrayList in Java Object Oriented Programming (OOPs) Concept in Java HashMap in Java with Examples Interfaces in Java How to iterate any Map in Java
[ { "code": null, "e": 23544, "s": 23516, "text": "\n28 Jun, 2018" }, { "code": null, "e": 23763, "s": 23544, "text": "The java.util.Hashtable.get() method of Hashtable class is used to retrieve or fetch the value mapped by a particular key mentioned in the parameter. It returns NULL when the table contains no such mapping for the key." }, { "code": null, "e": 23771, "s": 23763, "text": "Syntax:" }, { "code": null, "e": 23806, "s": 23771, "text": "Hash_Table.get(Object key_element)" }, { "code": null, "e": 23947, "s": 23806, "text": "Parameter: The method takes one parameter key_element of object type and refers to the key whose associated value is supposed to be fetched." }, { "code": null, "e": 24040, "s": 23947, "text": "Return Value: The method returns the value associated with the key_element in the parameter." }, { "code": null, "e": 24126, "s": 24040, "text": "Below programs illustrates the working of java.util.Hashtable.get() method:Program 1:" }, { "code": "// Java code to illustrate the get() methodimport java.util.*; public class Hash_Table_Demo { public static void main(String[] args) { // Creating an empty Hashtable Hashtable<Integer, String> hash_table = new Hashtable<Integer, String>(); // Inserting the values into table hash_table.put(10, \"Geeks\"); hash_table.put(15, \"4\"); hash_table.put(20, \"Geeks\"); hash_table.put(25, \"Welcomes\"); hash_table.put(30, \"You\"); // Displaying the Hashtable System.out.println(\"Initial Table is: \" + hash_table); // Getting the value of 25 System.out.println(\"The Value is: \" + hash_table.get(25)); // Getting the value of 10 System.out.println(\"The Value is: \" + hash_table.get(10)); }}", "e": 24946, "s": 24126, "text": null }, { "code": null, "e": 25056, "s": 24946, "text": "Initial Table is: {10=Geeks, 20=Geeks, 30=You, 15=4, 25=Welcomes}\nThe Value is: Welcomes\nThe Value is: Geeks\n" }, { "code": null, "e": 25067, "s": 25056, "text": "Program 2:" }, { "code": "// Java code to illustrate the get() methodimport java.util.*; public class Hash_Table_Demo { public static void main(String[] args) { // Creating an empty Hashtable Hashtable<String, Integer> hash_table = new Hashtable<String, Integer>(); // Inserting the values into table hash_table.put(\"Geeks\", 10); hash_table.put(\"4\", 15); hash_table.put(\"Geeks\", 20); hash_table.put(\"Welcomes\", 25); hash_table.put(\"You\", 30); // Displaying the Hashtable System.out.println(\"Initial table is: \" + hash_table); // Getting the value of \"Geeks\" System.out.println(\"The Value is: \" + hash_table.get(\"Geeks\")); // Getting the value of \"You\" System.out.println(\"The Value is: \" + hash_table.get(\"You\")); }}", "e": 25904, "s": 25067, "text": null }, { "code": null, "e": 25995, "s": 25904, "text": "Initial table is: {You=30, Welcomes=25, 4=15, Geeks=20}\nThe Value is: 20\nThe Value is: 30\n" }, { "code": null, "e": 26105, "s": 25995, "text": "Note: The same operation can be performed with any type of variation and combination of different data types." }, { "code": null, "e": 26122, "s": 26105, "text": "Java-Collections" }, { "code": null, "e": 26137, "s": 26122, "text": "Java-HashTable" }, { "code": null, "e": 26142, "s": 26137, "text": "Java" }, { "code": null, "e": 26147, "s": 26142, "text": "Java" }, { "code": null, "e": 26164, "s": 26147, "text": "Java-Collections" }, { "code": null, "e": 26262, "s": 26164, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26277, "s": 26262, "text": "Arrays in Java" }, { "code": null, "e": 26321, "s": 26277, "text": "Split() String method in Java with examples" }, { "code": null, "e": 26343, "s": 26321, "text": "For-each loop in Java" }, { "code": null, "e": 26379, "s": 26343, "text": "Arrays.sort() in Java with examples" }, { "code": null, "e": 26404, "s": 26379, "text": "Reverse a string in Java" }, { "code": null, "e": 26436, "s": 26404, "text": "Initialize an ArrayList in Java" }, { "code": null, "e": 26487, "s": 26436, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 26517, "s": 26487, "text": "HashMap in Java with Examples" }, { "code": null, "e": 26536, "s": 26517, "text": "Interfaces in Java" } ]
How to build a music recommender system. | Towards Data Science
Have you ever wondered how Spotify recommends songs and playlists based on your listening history? Do you wonder how Spotify manages to find songs that sound similar to the ones you’ve already listened to? Interestingly, Spotify has a web API that developers can use to retrieve audio features and metadata about songs such as the song’s popularity, tempo, loudness, key, and the year in which it was released. We can use this data to build music recommendation systems that recommend songs to users based on both the audio features and the metadata of the songs that they have listened to. In this article, I will demonstrate how I used a Spotify song dataset and Spotipy, a Python client for Spotify, to build a content-based music recommendation system. Spotipy is a Python client for the Spotify Web API that makes it easy for developers to fetch data and query Spotify’s catalog for songs. In this project, I used Spotipy to fetch data for songs that did not exist in the original Spotify Song Dataset that I accessed from Kaggle. You can install Spotipy with pip using the command below. pip install spotipy After installing Spotipy, you will need to create an app on the Spotify Developer’s page and save your Client ID and secret key. In the code below, I imported Spotipy and some other basic libraries for data manipulation and visualization. You can find the full code for this project on GitHub. import numpy as npimport pandas as pdimport matplotlib.pyplot as pltimport seaborn as snsimport spotipyimport os%matplotlib inline In order to build a music recommendation system, I used the Spotify Dataset, which is publicly available on Kaggle and contains metadata and audio features for over 170,000 different songs. I used three data files from this dataset. The first one contains data for individual songs while the next two files contain the data grouped the genres and years in which the songs were released. spotify_data = pd.read_csv('./data/data.csv.zip')genre_data = pd.read_csv('./data/data_by_genres.csv')data_by_year = pd.read_csv('./data/data_by_year.csv') I have included the column metadata below that was generated by calling the Pandas info function for each data frame. spotify_data <class 'pandas.core.frame.DataFrame'>RangeIndex: 170653 entries, 0 to 170652Data columns (total 19 columns): # Column Non-Null Count Dtype --- ------ -------------- ----- 0 valence 170653 non-null float64 1 year 170653 non-null int64 2 acousticness 170653 non-null float64 3 artists 170653 non-null object 4 danceability 170653 non-null float64 5 duration_ms 170653 non-null int64 6 energy 170653 non-null float64 7 explicit 170653 non-null int64 8 id 170653 non-null object 9 instrumentalness 170653 non-null float64 10 key 170653 non-null int64 11 liveness 170653 non-null float64 12 loudness 170653 non-null float64 13 mode 170653 non-null int64 14 name 170653 non-null object 15 popularity 170653 non-null int64 16 release_date 170653 non-null object 17 speechiness 170653 non-null float64 18 tempo 170653 non-null float64dtypes: float64(9), int64(6), object(4)memory usage: 24.7+ MB genre_data <class 'pandas.core.frame.DataFrame'>RangeIndex: 2973 entries, 0 to 2972Data columns (total 14 columns): # Column Non-Null Count Dtype --- ------ -------------- ----- 0 mode 2973 non-null int64 1 genres 2973 non-null object 2 acousticness 2973 non-null float64 3 danceability 2973 non-null float64 4 duration_ms 2973 non-null float64 5 energy 2973 non-null float64 6 instrumentalness 2973 non-null float64 7 liveness 2973 non-null float64 8 loudness 2973 non-null float64 9 speechiness 2973 non-null float64 10 tempo 2973 non-null float64 11 valence 2973 non-null float64 12 popularity 2973 non-null float64 13 key 2973 non-null int64 dtypes: float64(11), int64(2), object(1)memory usage: 325.3+ KB data_by_year <class 'pandas.core.frame.DataFrame'>RangeIndex: 2973 entries, 0 to 2972Data columns (total 14 columns): # Column Non-Null Count Dtype --- ------ -------------- ----- 0 mode 2973 non-null int64 1 genres 2973 non-null object 2 acousticness 2973 non-null float64 3 danceability 2973 non-null float64 4 duration_ms 2973 non-null float64 5 energy 2973 non-null float64 6 instrumentalness 2973 non-null float64 7 liveness 2973 non-null float64 8 loudness 2973 non-null float64 9 speechiness 2973 non-null float64 10 tempo 2973 non-null float64 11 valence 2973 non-null float64 12 popularity 2973 non-null float64 13 key 2973 non-null int64 dtypes: float64(11), int64(2), object(1)memory usage: 325.3+ KBExploratory Data Analysis Based on the column descriptions above, we can see that each dataframe has information about the audio features such as the danceability and loudness of different songs, that have also been aggregated across genres and specific years. This dataset is extremely useful and can be used for a wide range of tasks. Before building a recommendation system, I decided to create some visualizations to better understand the data and the trends in music over the last 100 years. Using the data grouped by year, we can understand how the overall sound of music has changed from 1921 to 2020. In the code below, I used Plotly to visualize the values of different audio features for songs over the past 100 years. import plotly.express as px sound_features = ['acousticness', 'danceability', 'energy', 'instrumentalness', 'liveness', 'valence']fig = px.line(data_by_year, x='year', y=sound_features)fig.show() Based on the plot above, we can see that music has transitioned from the more acoustic and instrumental sound of the early 1900s to the more danceable and energetic sound of the 2000s. The majority of the tracks from the 1920s were likely instrumental pieces from classical and jazz genres. The music of the 2000s sounds very different due to the advent of computers and advanced audio engineering technology that allows us to create electronic music with a wide range of effects and beats. We can also take a look at how the average tempo or speed of music has changed over the years. The drastic shift in sound towards electronic music is supported by the graph produced by the code below as well. fig = px.line(data_by_year, x='year', y='tempo')fig.show() Based on the graph above, we can clearly see that music has gotten significantly faster over the last century. This trend is not only the result of new genres in the 1960s such as psychedelic rock but also advancements in audio engineering technology. This dataset contains the audio features for different songs along with the audio features for different genres. We can use this information to compare different genres and understand their unique differences in sound. In the code below, I selected the ten most popular genres from the dataset and visualized audio features for each of them. top10_genres = genre_data.nlargest(10, 'popularity')fig = px.bar(top10_genres, x='genres', y=['valence', 'energy', 'danceability', 'acousticness'], barmode='group')fig.show() Many of the genres above, such as Chinese electropop are extremely specific and likely belong to one or more broad genres such as pop or electronic music. We can take these highly specific genres and understand how similar they are to other genres by clustering them based on their audio features. In the code below, I used the famous and simple K-means clustering algorithm to divide the over 2,900 genres in this dataset into ten clusters based on the numerical audio features of each genre. from sklearn.cluster import KMeansfrom sklearn.preprocessing import StandardScalerfrom sklearn.pipeline import Pipelinecluster_pipeline = Pipeline([('scaler', StandardScaler()), ('kmeans', KMeans(n_clusters=10, n_jobs=-1))])X = genre_data.select_dtypes(np.number)cluster_pipeline.fit(X)genre_data['cluster'] = cluster_pipeline.predict(X) Now that the genres have been assigned to clusters, we can take this analysis a step further by visualizing the clusters in a two-dimensional space. There are many audio features for each genre and it is difficult to visualize clusters in a high-dimensional space. However, we can use a dimensionality reduction technique known as t-Distributed Stochastic Neighbor Embedding to compress the data into a two-dimensional space as demonstrated in the code below. from sklearn.manifold import TSNEtsne_pipeline = Pipeline([('scaler', StandardScaler()), ('tsne', TSNE(n_components=2, verbose=2))])genre_embedding = tsne_pipeline.fit_transform(X)projection = pd.DataFrame(columns=['x', 'y'], data=genre_embedding)projection['genres'] = genre_data['genres']projection['cluster'] = genre_data['cluster'] Now, we can easily visualize the genre clusters in a two-dimensional coordinate plane by using Plotly’s scatter function. import plotly.express as pxfig = px.scatter( projection, x='x', y='y', color='cluster', hover_data=['x', 'y', 'genres'])fig.show() We can also cluster the songs using K-means as demonstrated below in order to understand how to build a better recommendation system. song_cluster_pipeline = Pipeline([('scaler', StandardScaler()), ('kmeans', KMeans(n_clusters=20, verbose=2, n_jobs=4))],verbose=True)X = spotify_data.select_dtypes(np.number)number_cols = list(X.columns)song_cluster_pipeline.fit(X)song_cluster_labels = song_cluster_pipeline.predict(X)spotify_data['cluster_label'] = song_cluster_labels The song data frame is much larger than the genre data frame so I decided to use PCA for dimensionality reduction rather than t-SNE because it runs significantly faster. from sklearn.decomposition import PCApca_pipeline = Pipeline([('scaler', StandardScaler()), ('PCA', PCA(n_components=2))])song_embedding = pca_pipeline.fit_transform(X)projection = pd.DataFrame(columns=['x', 'y'], data=song_embedding)projection['title'] = spotify_data['name']projection['cluster'] = spotify_data['cluster_label'] Now, we can visualize the song cluster in a two-dimensional space using the code below. import plotly.express as pxfig = px.scatter(projection, x='x', y='y', color='cluster', hover_data=['x', 'y', 'title'])fig.show() The plot above is interactive, so you can see the title of each song when you hover over the points. If you spend some time exploring the plot above you’ll find that similar songs tend to be located close to each other and songs within clusters tend to be at least somewhat similar. This observation is the key idea behind the content-based recommendation system that I created in the next section. Based on the analysis and visualizations in the previous section, it’s clear that similar genres tend to have data points that are located close to each other while similar types of songs are also clustered together. At a practical level, this observation makes perfect sense. Similar genres will sound similar and will come from similar time periods while the same can be said for songs within those genres. We can use this idea to build a recommendation system by taking the data points of the songs a user has listened to and recommending songs corresponding to nearby data points. Before we build this recommendation system, we need to be able to accommodate songs that don’t exist in the original Spotify Songs Dataset. The find_song function that I defined below fetches the data for any song from Spotify’s catalog given the song’s name and release year. The results are returned as a Pandas Dataframe with the data fields present in the original dataset that I downloaded from Kaggle. For detailed examples on how to use Spotipy, please refer to the documentation page here. Now we can finally build the music recommendation system! The recommendation algorithm I used is pretty simple and follows three steps: Compute the average vector of the audio and metadata features for each song the user has listened to.Find the n-closest data points in the dataset (excluding the points from the songs in the user’s listening history) to this average vector.Take these n points and recommend the songs corresponding to them Compute the average vector of the audio and metadata features for each song the user has listened to. Find the n-closest data points in the dataset (excluding the points from the songs in the user’s listening history) to this average vector. Take these n points and recommend the songs corresponding to them This algorithm follows a common approach that is used in content-based recommender systems and is generalizable because we can mathematically define the term closest with a wide range of distance metrics ranging from the classic Euclidean distance to the cosine distance. For the purpose of this project, I used the cosine distance, which is defined below for two vectors u and v. In other words, the cosine distance is one minus the cosine similarity — the cosine of the angle between the two vectors. The cosine distance is commonly used in recommender systems and can work well even when the vectors being used have different magnitudes. If the vectors for two songs are parallel, the angle between them will be zero, meaning the cosine distance between them will also be zero because the cosine of zero is 1. The functions that I have defined below implement this simple algorithm with the help of Scipy’s cdist function for finding the distances between two pairs of collections of points. The logic behind the algorithm sounds convincing but does this recommender system really work? The only way to find out is by testing it with practical examples. Let’s say that we want to recommend music for someone who listens to 1990s grunge, specifically songs by Nirvana. We can use the recommend_songs function to specify their listening history and generate recommendations as shown below. recommend_songs([{'name': 'Come As You Are', 'year':1991}, {'name': 'Smells Like Teen Spirit', 'year': 1991}, {'name': 'Lithium', 'year': 1992}, {'name': 'All Apologies', 'year': 1993}, {'name': 'Stay Away', 'year': 1993}], spotify_data) Running this function produces the list of songs below. [{'name': 'Life is a Highway - From "Cars"', 'year': 2009, 'artists': "['Rascal Flatts']"}, {'name': 'Of Wolf And Man', 'year': 1991, 'artists': "['Metallica']"}, {'name': 'Somebody Like You', 'year': 2002, 'artists': "['Keith Urban']"}, {'name': 'Kayleigh', 'year': 1992, 'artists': "['Marillion']"}, {'name': 'Little Secrets', 'year': 2009, 'artists': "['Passion Pit']"}, {'name': 'No Excuses', 'year': 1994, 'artists': "['Alice In Chains']"}, {'name': 'Corazón Mágico', 'year': 1995, 'artists': "['Los Fugitivos']"}, {'name': 'If Today Was Your Last Day', 'year': 2008, 'artists': "['Nickelback']"}, {'name': "Let's Get Rocked", 'year': 1992, 'artists': "['Def Leppard']"}, {'name': "Breakfast At Tiffany's", 'year': 1995, 'artists': "['Deep Blue Something']"}] As we can see from the list above, the recommendation algorithm produced a list of rock songs from the 1990s and 2000s. Bands in the list such as Metallica, Alice in Chains, and Nickelback are similar to Nirvana. The top song on the list, “Life is a Highway” is not a grunge song, but the rhythm of the guitar riff actually sounds similar to Nirvana’s “Smells Like Teen Spirit” if you listen closely. What if we wanted to do the same for someone who listens to Michael Jackson songs? recommend_songs([{'name':'Beat It', 'year': 1982}, {'name': 'Billie Jean', 'year': 1988}, {'name': 'Thriller', 'year': 1982}], spotify_data) The recommendation function gives us the output below. [{'name': 'Hot Legs', 'year': 1977, 'artists': "['Rod Stewart']"}, {'name': 'Thriller - 2003 Edit', 'year': 2003, 'artists': "['Michael Jackson']"}, {'name': "I Didn't Mean To Turn You On", 'year': 1984, 'artists': "['Cherrelle']"}, {'name': 'Stars On 45 - Original Single Version', 'year': 1981, 'artists': "['Stars On 45']"}, {'name': "Stars On '89 Remix - Radio Version", 'year': 1984, 'artists': "['Stars On 45']"}, {'name': 'Take Me to the River - Live', 'year': 1984, 'artists': "['Talking Heads']"}, {'name': 'Nothing Can Stop Us', 'year': 1992, 'artists': "['Saint Etienne']"}] The top song on the list is by Rod Stewart, who like Michael Jackson, rose to fame in the 1980s. The list also contains a 2003 edit of Michael Jackson’s Thriller, which makes sense given that the user has already heard the original 1982 version of this song. The list also includes pop and rock songs from 1980s groups such as Stars On 45 and Talking Heads. There are many more examples that we could work with, but these examples should be enough to demonstrate how the recommender system produces song recommendations. For a more complete set of examples, check out the GitHub repository for this project. Feel free to create your own playlists with this code! Spotify keeps track of metadata and audio features for songs that we can use to build music recommendation systems. In this article, I demonstrated how you can use this data to build a simple content-based music recommender system with the cosine distance metric. As usual, you can find the full code for this project on GitHub. If you enjoyed this article and want to learn more about recommender systems, check out some of my previous articles listed below. towardsdatascience.com towardsdatascience.com Do you want to get better at data science and machine learning? Do you want to stay up to date with the latest libraries, developments, and research in the data science and machine learning community? Join my mailing list to get updates on my data science content. You’ll also get my free Step-By-Step Guide to Solving Machine Learning Problems when you sign up! Y. E. Ay, Spotify Dataset 1921–2020, 160k+ Tracks, (2020), Kaggle.L. van der Maaten and G. Hinton, Visualizing Data using t-SNE, (2008), Journal of Machine Learning Research.P. Virtanen et. al, SciPy 1.0: Fundamental Algorithms for Scientific Computing in Python, (2020), Nature Methods. Y. E. Ay, Spotify Dataset 1921–2020, 160k+ Tracks, (2020), Kaggle. L. van der Maaten and G. Hinton, Visualizing Data using t-SNE, (2008), Journal of Machine Learning Research. P. Virtanen et. al, SciPy 1.0: Fundamental Algorithms for Scientific Computing in Python, (2020), Nature Methods.
[ { "code": null, "e": 378, "s": 172, "text": "Have you ever wondered how Spotify recommends songs and playlists based on your listening history? Do you wonder how Spotify manages to find songs that sound similar to the ones you’ve already listened to?" }, { "code": null, "e": 763, "s": 378, "text": "Interestingly, Spotify has a web API that developers can use to retrieve audio features and metadata about songs such as the song’s popularity, tempo, loudness, key, and the year in which it was released. We can use this data to build music recommendation systems that recommend songs to users based on both the audio features and the metadata of the songs that they have listened to." }, { "code": null, "e": 929, "s": 763, "text": "In this article, I will demonstrate how I used a Spotify song dataset and Spotipy, a Python client for Spotify, to build a content-based music recommendation system." }, { "code": null, "e": 1266, "s": 929, "text": "Spotipy is a Python client for the Spotify Web API that makes it easy for developers to fetch data and query Spotify’s catalog for songs. In this project, I used Spotipy to fetch data for songs that did not exist in the original Spotify Song Dataset that I accessed from Kaggle. You can install Spotipy with pip using the command below." }, { "code": null, "e": 1286, "s": 1266, "text": "pip install spotipy" }, { "code": null, "e": 1415, "s": 1286, "text": "After installing Spotipy, you will need to create an app on the Spotify Developer’s page and save your Client ID and secret key." }, { "code": null, "e": 1580, "s": 1415, "text": "In the code below, I imported Spotipy and some other basic libraries for data manipulation and visualization. You can find the full code for this project on GitHub." }, { "code": null, "e": 1711, "s": 1580, "text": "import numpy as npimport pandas as pdimport matplotlib.pyplot as pltimport seaborn as snsimport spotipyimport os%matplotlib inline" }, { "code": null, "e": 2098, "s": 1711, "text": "In order to build a music recommendation system, I used the Spotify Dataset, which is publicly available on Kaggle and contains metadata and audio features for over 170,000 different songs. I used three data files from this dataset. The first one contains data for individual songs while the next two files contain the data grouped the genres and years in which the songs were released." }, { "code": null, "e": 2254, "s": 2098, "text": "spotify_data = pd.read_csv('./data/data.csv.zip')genre_data = pd.read_csv('./data/data_by_genres.csv')data_by_year = pd.read_csv('./data/data_by_year.csv')" }, { "code": null, "e": 2372, "s": 2254, "text": "I have included the column metadata below that was generated by calling the Pandas info function for each data frame." }, { "code": null, "e": 2385, "s": 2372, "text": "spotify_data" }, { "code": null, "e": 3542, "s": 2385, "text": "<class 'pandas.core.frame.DataFrame'>RangeIndex: 170653 entries, 0 to 170652Data columns (total 19 columns): # Column Non-Null Count Dtype --- ------ -------------- ----- 0 valence 170653 non-null float64 1 year 170653 non-null int64 2 acousticness 170653 non-null float64 3 artists 170653 non-null object 4 danceability 170653 non-null float64 5 duration_ms 170653 non-null int64 6 energy 170653 non-null float64 7 explicit 170653 non-null int64 8 id 170653 non-null object 9 instrumentalness 170653 non-null float64 10 key 170653 non-null int64 11 liveness 170653 non-null float64 12 loudness 170653 non-null float64 13 mode 170653 non-null int64 14 name 170653 non-null object 15 popularity 170653 non-null int64 16 release_date 170653 non-null object 17 speechiness 170653 non-null float64 18 tempo 170653 non-null float64dtypes: float64(9), int64(6), object(4)memory usage: 24.7+ MB" }, { "code": null, "e": 3553, "s": 3542, "text": "genre_data" }, { "code": null, "e": 4457, "s": 3553, "text": "<class 'pandas.core.frame.DataFrame'>RangeIndex: 2973 entries, 0 to 2972Data columns (total 14 columns): # Column Non-Null Count Dtype --- ------ -------------- ----- 0 mode 2973 non-null int64 1 genres 2973 non-null object 2 acousticness 2973 non-null float64 3 danceability 2973 non-null float64 4 duration_ms 2973 non-null float64 5 energy 2973 non-null float64 6 instrumentalness 2973 non-null float64 7 liveness 2973 non-null float64 8 loudness 2973 non-null float64 9 speechiness 2973 non-null float64 10 tempo 2973 non-null float64 11 valence 2973 non-null float64 12 popularity 2973 non-null float64 13 key 2973 non-null int64 dtypes: float64(11), int64(2), object(1)memory usage: 325.3+ KB" }, { "code": null, "e": 4470, "s": 4457, "text": "data_by_year" }, { "code": null, "e": 5399, "s": 4470, "text": "<class 'pandas.core.frame.DataFrame'>RangeIndex: 2973 entries, 0 to 2972Data columns (total 14 columns): # Column Non-Null Count Dtype --- ------ -------------- ----- 0 mode 2973 non-null int64 1 genres 2973 non-null object 2 acousticness 2973 non-null float64 3 danceability 2973 non-null float64 4 duration_ms 2973 non-null float64 5 energy 2973 non-null float64 6 instrumentalness 2973 non-null float64 7 liveness 2973 non-null float64 8 loudness 2973 non-null float64 9 speechiness 2973 non-null float64 10 tempo 2973 non-null float64 11 valence 2973 non-null float64 12 popularity 2973 non-null float64 13 key 2973 non-null int64 dtypes: float64(11), int64(2), object(1)memory usage: 325.3+ KBExploratory Data Analysis" }, { "code": null, "e": 5634, "s": 5399, "text": "Based on the column descriptions above, we can see that each dataframe has information about the audio features such as the danceability and loudness of different songs, that have also been aggregated across genres and specific years." }, { "code": null, "e": 5870, "s": 5634, "text": "This dataset is extremely useful and can be used for a wide range of tasks. Before building a recommendation system, I decided to create some visualizations to better understand the data and the trends in music over the last 100 years." }, { "code": null, "e": 6102, "s": 5870, "text": "Using the data grouped by year, we can understand how the overall sound of music has changed from 1921 to 2020. In the code below, I used Plotly to visualize the values of different audio features for songs over the past 100 years." }, { "code": null, "e": 6298, "s": 6102, "text": "import plotly.express as px sound_features = ['acousticness', 'danceability', 'energy', 'instrumentalness', 'liveness', 'valence']fig = px.line(data_by_year, x='year', y=sound_features)fig.show()" }, { "code": null, "e": 6789, "s": 6298, "text": "Based on the plot above, we can see that music has transitioned from the more acoustic and instrumental sound of the early 1900s to the more danceable and energetic sound of the 2000s. The majority of the tracks from the 1920s were likely instrumental pieces from classical and jazz genres. The music of the 2000s sounds very different due to the advent of computers and advanced audio engineering technology that allows us to create electronic music with a wide range of effects and beats." }, { "code": null, "e": 6998, "s": 6789, "text": "We can also take a look at how the average tempo or speed of music has changed over the years. The drastic shift in sound towards electronic music is supported by the graph produced by the code below as well." }, { "code": null, "e": 7057, "s": 6998, "text": "fig = px.line(data_by_year, x='year', y='tempo')fig.show()" }, { "code": null, "e": 7309, "s": 7057, "text": "Based on the graph above, we can clearly see that music has gotten significantly faster over the last century. This trend is not only the result of new genres in the 1960s such as psychedelic rock but also advancements in audio engineering technology." }, { "code": null, "e": 7651, "s": 7309, "text": "This dataset contains the audio features for different songs along with the audio features for different genres. We can use this information to compare different genres and understand their unique differences in sound. In the code below, I selected the ten most popular genres from the dataset and visualized audio features for each of them." }, { "code": null, "e": 7826, "s": 7651, "text": "top10_genres = genre_data.nlargest(10, 'popularity')fig = px.bar(top10_genres, x='genres', y=['valence', 'energy', 'danceability', 'acousticness'], barmode='group')fig.show()" }, { "code": null, "e": 8124, "s": 7826, "text": "Many of the genres above, such as Chinese electropop are extremely specific and likely belong to one or more broad genres such as pop or electronic music. We can take these highly specific genres and understand how similar they are to other genres by clustering them based on their audio features." }, { "code": null, "e": 8320, "s": 8124, "text": "In the code below, I used the famous and simple K-means clustering algorithm to divide the over 2,900 genres in this dataset into ten clusters based on the numerical audio features of each genre." }, { "code": null, "e": 8658, "s": 8320, "text": "from sklearn.cluster import KMeansfrom sklearn.preprocessing import StandardScalerfrom sklearn.pipeline import Pipelinecluster_pipeline = Pipeline([('scaler', StandardScaler()), ('kmeans', KMeans(n_clusters=10, n_jobs=-1))])X = genre_data.select_dtypes(np.number)cluster_pipeline.fit(X)genre_data['cluster'] = cluster_pipeline.predict(X)" }, { "code": null, "e": 8807, "s": 8658, "text": "Now that the genres have been assigned to clusters, we can take this analysis a step further by visualizing the clusters in a two-dimensional space." }, { "code": null, "e": 9118, "s": 8807, "text": "There are many audio features for each genre and it is difficult to visualize clusters in a high-dimensional space. However, we can use a dimensionality reduction technique known as t-Distributed Stochastic Neighbor Embedding to compress the data into a two-dimensional space as demonstrated in the code below." }, { "code": null, "e": 9454, "s": 9118, "text": "from sklearn.manifold import TSNEtsne_pipeline = Pipeline([('scaler', StandardScaler()), ('tsne', TSNE(n_components=2, verbose=2))])genre_embedding = tsne_pipeline.fit_transform(X)projection = pd.DataFrame(columns=['x', 'y'], data=genre_embedding)projection['genres'] = genre_data['genres']projection['cluster'] = genre_data['cluster']" }, { "code": null, "e": 9576, "s": 9454, "text": "Now, we can easily visualize the genre clusters in a two-dimensional coordinate plane by using Plotly’s scatter function." }, { "code": null, "e": 9710, "s": 9576, "text": "import plotly.express as pxfig = px.scatter( projection, x='x', y='y', color='cluster', hover_data=['x', 'y', 'genres'])fig.show()" }, { "code": null, "e": 9844, "s": 9710, "text": "We can also cluster the songs using K-means as demonstrated below in order to understand how to build a better recommendation system." }, { "code": null, "e": 10250, "s": 9844, "text": "song_cluster_pipeline = Pipeline([('scaler', StandardScaler()), ('kmeans', KMeans(n_clusters=20, verbose=2, n_jobs=4))],verbose=True)X = spotify_data.select_dtypes(np.number)number_cols = list(X.columns)song_cluster_pipeline.fit(X)song_cluster_labels = song_cluster_pipeline.predict(X)spotify_data['cluster_label'] = song_cluster_labels" }, { "code": null, "e": 10420, "s": 10250, "text": "The song data frame is much larger than the genre data frame so I decided to use PCA for dimensionality reduction rather than t-SNE because it runs significantly faster." }, { "code": null, "e": 10750, "s": 10420, "text": "from sklearn.decomposition import PCApca_pipeline = Pipeline([('scaler', StandardScaler()), ('PCA', PCA(n_components=2))])song_embedding = pca_pipeline.fit_transform(X)projection = pd.DataFrame(columns=['x', 'y'], data=song_embedding)projection['title'] = spotify_data['name']projection['cluster'] = spotify_data['cluster_label']" }, { "code": null, "e": 10838, "s": 10750, "text": "Now, we can visualize the song cluster in a two-dimensional space using the code below." }, { "code": null, "e": 10967, "s": 10838, "text": "import plotly.express as pxfig = px.scatter(projection, x='x', y='y', color='cluster', hover_data=['x', 'y', 'title'])fig.show()" }, { "code": null, "e": 11366, "s": 10967, "text": "The plot above is interactive, so you can see the title of each song when you hover over the points. If you spend some time exploring the plot above you’ll find that similar songs tend to be located close to each other and songs within clusters tend to be at least somewhat similar. This observation is the key idea behind the content-based recommendation system that I created in the next section." }, { "code": null, "e": 11583, "s": 11366, "text": "Based on the analysis and visualizations in the previous section, it’s clear that similar genres tend to have data points that are located close to each other while similar types of songs are also clustered together." }, { "code": null, "e": 11951, "s": 11583, "text": "At a practical level, this observation makes perfect sense. Similar genres will sound similar and will come from similar time periods while the same can be said for songs within those genres. We can use this idea to build a recommendation system by taking the data points of the songs a user has listened to and recommending songs corresponding to nearby data points." }, { "code": null, "e": 12359, "s": 11951, "text": "Before we build this recommendation system, we need to be able to accommodate songs that don’t exist in the original Spotify Songs Dataset. The find_song function that I defined below fetches the data for any song from Spotify’s catalog given the song’s name and release year. The results are returned as a Pandas Dataframe with the data fields present in the original dataset that I downloaded from Kaggle." }, { "code": null, "e": 12449, "s": 12359, "text": "For detailed examples on how to use Spotipy, please refer to the documentation page here." }, { "code": null, "e": 12585, "s": 12449, "text": "Now we can finally build the music recommendation system! The recommendation algorithm I used is pretty simple and follows three steps:" }, { "code": null, "e": 12891, "s": 12585, "text": "Compute the average vector of the audio and metadata features for each song the user has listened to.Find the n-closest data points in the dataset (excluding the points from the songs in the user’s listening history) to this average vector.Take these n points and recommend the songs corresponding to them" }, { "code": null, "e": 12993, "s": 12891, "text": "Compute the average vector of the audio and metadata features for each song the user has listened to." }, { "code": null, "e": 13133, "s": 12993, "text": "Find the n-closest data points in the dataset (excluding the points from the songs in the user’s listening history) to this average vector." }, { "code": null, "e": 13199, "s": 13133, "text": "Take these n points and recommend the songs corresponding to them" }, { "code": null, "e": 13580, "s": 13199, "text": "This algorithm follows a common approach that is used in content-based recommender systems and is generalizable because we can mathematically define the term closest with a wide range of distance metrics ranging from the classic Euclidean distance to the cosine distance. For the purpose of this project, I used the cosine distance, which is defined below for two vectors u and v." }, { "code": null, "e": 14012, "s": 13580, "text": "In other words, the cosine distance is one minus the cosine similarity — the cosine of the angle between the two vectors. The cosine distance is commonly used in recommender systems and can work well even when the vectors being used have different magnitudes. If the vectors for two songs are parallel, the angle between them will be zero, meaning the cosine distance between them will also be zero because the cosine of zero is 1." }, { "code": null, "e": 14194, "s": 14012, "text": "The functions that I have defined below implement this simple algorithm with the help of Scipy’s cdist function for finding the distances between two pairs of collections of points." }, { "code": null, "e": 14356, "s": 14194, "text": "The logic behind the algorithm sounds convincing but does this recommender system really work? The only way to find out is by testing it with practical examples." }, { "code": null, "e": 14590, "s": 14356, "text": "Let’s say that we want to recommend music for someone who listens to 1990s grunge, specifically songs by Nirvana. We can use the recommend_songs function to specify their listening history and generate recommendations as shown below." }, { "code": null, "e": 14889, "s": 14590, "text": "recommend_songs([{'name': 'Come As You Are', 'year':1991}, {'name': 'Smells Like Teen Spirit', 'year': 1991}, {'name': 'Lithium', 'year': 1992}, {'name': 'All Apologies', 'year': 1993}, {'name': 'Stay Away', 'year': 1993}], spotify_data)" }, { "code": null, "e": 14945, "s": 14889, "text": "Running this function produces the list of songs below." }, { "code": null, "e": 15718, "s": 14945, "text": "[{'name': 'Life is a Highway - From \"Cars\"', 'year': 2009, 'artists': \"['Rascal Flatts']\"}, {'name': 'Of Wolf And Man', 'year': 1991, 'artists': \"['Metallica']\"}, {'name': 'Somebody Like You', 'year': 2002, 'artists': \"['Keith Urban']\"}, {'name': 'Kayleigh', 'year': 1992, 'artists': \"['Marillion']\"}, {'name': 'Little Secrets', 'year': 2009, 'artists': \"['Passion Pit']\"}, {'name': 'No Excuses', 'year': 1994, 'artists': \"['Alice In Chains']\"}, {'name': 'Corazón Mágico', 'year': 1995, 'artists': \"['Los Fugitivos']\"}, {'name': 'If Today Was Your Last Day', 'year': 2008, 'artists': \"['Nickelback']\"}, {'name': \"Let's Get Rocked\", 'year': 1992, 'artists': \"['Def Leppard']\"}, {'name': \"Breakfast At Tiffany's\", 'year': 1995, 'artists': \"['Deep Blue Something']\"}]" }, { "code": null, "e": 16119, "s": 15718, "text": "As we can see from the list above, the recommendation algorithm produced a list of rock songs from the 1990s and 2000s. Bands in the list such as Metallica, Alice in Chains, and Nickelback are similar to Nirvana. The top song on the list, “Life is a Highway” is not a grunge song, but the rhythm of the guitar riff actually sounds similar to Nirvana’s “Smells Like Teen Spirit” if you listen closely." }, { "code": null, "e": 16202, "s": 16119, "text": "What if we wanted to do the same for someone who listens to Michael Jackson songs?" }, { "code": null, "e": 16375, "s": 16202, "text": "recommend_songs([{'name':'Beat It', 'year': 1982}, {'name': 'Billie Jean', 'year': 1988}, {'name': 'Thriller', 'year': 1982}], spotify_data)" }, { "code": null, "e": 16430, "s": 16375, "text": "The recommendation function gives us the output below." }, { "code": null, "e": 17026, "s": 16430, "text": "[{'name': 'Hot Legs', 'year': 1977, 'artists': \"['Rod Stewart']\"}, {'name': 'Thriller - 2003 Edit', 'year': 2003, 'artists': \"['Michael Jackson']\"}, {'name': \"I Didn't Mean To Turn You On\", 'year': 1984, 'artists': \"['Cherrelle']\"}, {'name': 'Stars On 45 - Original Single Version', 'year': 1981, 'artists': \"['Stars On 45']\"}, {'name': \"Stars On '89 Remix - Radio Version\", 'year': 1984, 'artists': \"['Stars On 45']\"}, {'name': 'Take Me to the River - Live', 'year': 1984, 'artists': \"['Talking Heads']\"}, {'name': 'Nothing Can Stop Us', 'year': 1992, 'artists': \"['Saint Etienne']\"}]" }, { "code": null, "e": 17384, "s": 17026, "text": "The top song on the list is by Rod Stewart, who like Michael Jackson, rose to fame in the 1980s. The list also contains a 2003 edit of Michael Jackson’s Thriller, which makes sense given that the user has already heard the original 1982 version of this song. The list also includes pop and rock songs from 1980s groups such as Stars On 45 and Talking Heads." }, { "code": null, "e": 17689, "s": 17384, "text": "There are many more examples that we could work with, but these examples should be enough to demonstrate how the recommender system produces song recommendations. For a more complete set of examples, check out the GitHub repository for this project. Feel free to create your own playlists with this code!" }, { "code": null, "e": 18018, "s": 17689, "text": "Spotify keeps track of metadata and audio features for songs that we can use to build music recommendation systems. In this article, I demonstrated how you can use this data to build a simple content-based music recommender system with the cosine distance metric. As usual, you can find the full code for this project on GitHub." }, { "code": null, "e": 18149, "s": 18018, "text": "If you enjoyed this article and want to learn more about recommender systems, check out some of my previous articles listed below." }, { "code": null, "e": 18172, "s": 18149, "text": "towardsdatascience.com" }, { "code": null, "e": 18195, "s": 18172, "text": "towardsdatascience.com" }, { "code": null, "e": 18396, "s": 18195, "text": "Do you want to get better at data science and machine learning? Do you want to stay up to date with the latest libraries, developments, and research in the data science and machine learning community?" }, { "code": null, "e": 18558, "s": 18396, "text": "Join my mailing list to get updates on my data science content. You’ll also get my free Step-By-Step Guide to Solving Machine Learning Problems when you sign up!" }, { "code": null, "e": 18846, "s": 18558, "text": "Y. E. Ay, Spotify Dataset 1921–2020, 160k+ Tracks, (2020), Kaggle.L. van der Maaten and G. Hinton, Visualizing Data using t-SNE, (2008), Journal of Machine Learning Research.P. Virtanen et. al, SciPy 1.0: Fundamental Algorithms for Scientific Computing in Python, (2020), Nature Methods." }, { "code": null, "e": 18913, "s": 18846, "text": "Y. E. Ay, Spotify Dataset 1921–2020, 160k+ Tracks, (2020), Kaggle." }, { "code": null, "e": 19022, "s": 18913, "text": "L. van der Maaten and G. Hinton, Visualizing Data using t-SNE, (2008), Journal of Machine Learning Research." } ]
Typecasting in C
20 Jan, 2021 Typecasting: It is a data type is converted into another data type by the programmer using the casting operator during the program design. In typecasting, the destination data type may be smaller than the source data type when converting the data type to another data type, that’s why it is also called narrowing conversion. There are some cases where if the datatype remains unchanged, it can give incorrect output. In such cases, typecasting can help to get correct output and reduce the time of compilation. Program 1: Below is the C program to illustrate the need for typecasting: C // C program to illustrate the use of// typecasting#include <stdio.h> // Function to divide a and bvoid division(int a, int b){ float div; // Division of a and b div = a / b; printf("The result is %f\n", div);} // Driver Codeint main(){ // Given a & b int a = 15, b = 2; // Function Call division(a, b); return 0;} The result is 7.000000 Explanation: Here, the actual output needed is 7.500000, but the result is 7.000000. So to get the correct output one way is to change the data type of a given variable. But correct output can also be done by typecasting. This consists of putting a pair of parentheses around the name of the data type like division = (float) a/b. Program 2: Below is the C program to showcase the use of typecasting: C // C program to showcase the use of// typecasting#include <stdio.h> // Function to divide a and bvoid division(int a, int b){ float div; // Typecasting in float div = (float)a / b; printf("The result is %f\n", div);} // Driver Codeint main(){ // Given a & b int a = 15, b = 2; // Function Call division(a, b); return 0;} The result is 7.500000 Explanation: In the above C program, the expression (float) converts variable a from type int to type float before the operation. C Basics Data Type C Language C Programs Programming Language Technical Scripter Data Type Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Unordered Sets in C++ Standard Template Library Operators in C / C++ Exception Handling in C++ What is the purpose of a function prototype? TCP Server-Client implementation in C Strings in C Arrow operator -> in C/C++ with Examples Basics of File Handling in C Header files in C/C++ and its uses UDP Server-Client implementation in C
[ { "code": null, "e": 53, "s": 25, "text": "\n20 Jan, 2021" }, { "code": null, "e": 378, "s": 53, "text": "Typecasting: It is a data type is converted into another data type by the programmer using the casting operator during the program design. In typecasting, the destination data type may be smaller than the source data type when converting the data type to another data type, that’s why it is also called narrowing conversion." }, { "code": null, "e": 564, "s": 378, "text": "There are some cases where if the datatype remains unchanged, it can give incorrect output. In such cases, typecasting can help to get correct output and reduce the time of compilation." }, { "code": null, "e": 575, "s": 564, "text": "Program 1:" }, { "code": null, "e": 638, "s": 575, "text": "Below is the C program to illustrate the need for typecasting:" }, { "code": null, "e": 640, "s": 638, "text": "C" }, { "code": "// C program to illustrate the use of// typecasting#include <stdio.h> // Function to divide a and bvoid division(int a, int b){ float div; // Division of a and b div = a / b; printf(\"The result is %f\\n\", div);} // Driver Codeint main(){ // Given a & b int a = 15, b = 2; // Function Call division(a, b); return 0;}", "e": 992, "s": 640, "text": null }, { "code": null, "e": 1016, "s": 992, "text": "The result is 7.000000\n" }, { "code": null, "e": 1347, "s": 1016, "text": "Explanation: Here, the actual output needed is 7.500000, but the result is 7.000000. So to get the correct output one way is to change the data type of a given variable. But correct output can also be done by typecasting. This consists of putting a pair of parentheses around the name of the data type like division = (float) a/b." }, { "code": null, "e": 1358, "s": 1347, "text": "Program 2:" }, { "code": null, "e": 1417, "s": 1358, "text": "Below is the C program to showcase the use of typecasting:" }, { "code": null, "e": 1419, "s": 1417, "text": "C" }, { "code": "// C program to showcase the use of// typecasting#include <stdio.h> // Function to divide a and bvoid division(int a, int b){ float div; // Typecasting in float div = (float)a / b; printf(\"The result is %f\\n\", div);} // Driver Codeint main(){ // Given a & b int a = 15, b = 2; // Function Call division(a, b); return 0;}", "e": 1777, "s": 1419, "text": null }, { "code": null, "e": 1801, "s": 1777, "text": "The result is 7.500000\n" }, { "code": null, "e": 1931, "s": 1801, "text": "Explanation: In the above C program, the expression (float) converts variable a from type int to type float before the operation." }, { "code": null, "e": 1940, "s": 1931, "text": "C Basics" }, { "code": null, "e": 1950, "s": 1940, "text": "Data Type" }, { "code": null, "e": 1961, "s": 1950, "text": "C Language" }, { "code": null, "e": 1972, "s": 1961, "text": "C Programs" }, { "code": null, "e": 1993, "s": 1972, "text": "Programming Language" }, { "code": null, "e": 2012, "s": 1993, "text": "Technical Scripter" }, { "code": null, "e": 2022, "s": 2012, "text": "Data Type" }, { "code": null, "e": 2120, "s": 2022, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2168, "s": 2120, "text": "Unordered Sets in C++ Standard Template Library" }, { "code": null, "e": 2189, "s": 2168, "text": "Operators in C / C++" }, { "code": null, "e": 2215, "s": 2189, "text": "Exception Handling in C++" }, { "code": null, "e": 2260, "s": 2215, "text": "What is the purpose of a function prototype?" }, { "code": null, "e": 2298, "s": 2260, "text": "TCP Server-Client implementation in C" }, { "code": null, "e": 2311, "s": 2298, "text": "Strings in C" }, { "code": null, "e": 2352, "s": 2311, "text": "Arrow operator -> in C/C++ with Examples" }, { "code": null, "e": 2381, "s": 2352, "text": "Basics of File Handling in C" }, { "code": null, "e": 2416, "s": 2381, "text": "Header files in C/C++ and its uses" } ]
Finding Position | Practice | GeeksforGeeks
Some people(n) are standing in a queue. A selection process follows a rule where people standing on even positions are selected. Of the selected people a queue is formed and again out of these only people on even position are selected. This continues until we are left with one person. Find out the position of that person in the original queue. Example 1: Input: n = 5 Output: 4 Explanation: 1,2,3,4,5 -> 2,4 -> 4. Example 2: Input: n = 9 Output: 8 Explanation: 1,2,3,4,5,6,7,8,9 ->2,4,6,8 -> 4,8 -> 8. Your Task: You dont need to read input or print anything. Complete the function nthPosition() which takes n as input parameter and returns the position(original queue) of that person who is left. Expected Time Complexity: O(logn) Expected Auxiliary Space: O(1) Constraints: 1<= n <=108 0 sujeetkr25082 weeks ago C++ long long int nthPosition(long long int n){ // code here if(n==1) return 1; return nthPosition(n>>1)<<1; } 0 bhabalomkar4211 month ago long long int nthPosition(long long int n){ // code here return pow(2, int(log2(n))); } +2 debasishtewary53 months ago 0.11/15.52 static long find(long i,long n){ if(i>n) return i/2; else{ i=i*2; return find(i,n); } } static long nthPosition(long n){ // code here return Solution.find(1,n); } +6 rajsinh21814 months ago Easy Recursive solution long long int nthPosition(long long int n){ if(n==1) return 1; return nthPosition(n/2)*2; } 0 abhishekbajpaiamity5 months ago class Solution { static long nthPosition(long n){ int value=(int)(Math.log(n) /Math.log(2)); int pow=(int)Math.pow(2,value); return pow; }} 0 aminul015 months ago Simple java solution 0.1 time taken class Solution { static long nthPosition(long n){ // code here long ans = 1; while (n != 1) { ans = 2 * ans; n /= 2; } return ans; }} 0 harshitsharma60915 months ago long long int nthPosition(long long int n) { if(n<2) return 0; while(( n & (n-1)) !=0) { n=n&(n-1); } return n; } 0 uday_wahi5 months ago java simple one liner solution time complexity : O(1) time 0.1/15.5 static long nthPosition(long n){ return (long) Math.pow(2,(long) (Math.log(n)/Math.log(2))); } 0 programmingdopractice6 months ago long long int nthPosition(long long int n){ // code here int len = log2(n); return pow(2,len); } Didn't do anything 0 user_990i6 months ago Iterative solution in 0 sec execution class Solution { public: long long int nthPosition(long long int n){ long long int count =1; while(n!=1){ count=2*count; n=n/2; } return count; }}; We strongly recommend solving this problem on your own before viewing its editorial. Do you still want to view the editorial? Login to access your submissions. Problem Contest Reset the IDE using the second button on the top right corner. Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values. Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints. You can access the hints to get an idea about what is expected of you as well as the final solution code. You can view the solutions submitted by other users from the submission tab. Make sure you are not using ad-blockers. Disable browser extensions. We recommend using latest version of your browser for best experience. Avoid using static/global variables in coding problems as your code is tested against multiple test cases and these tend to retain their previous values. Passing the Sample/Custom Test cases in coding problems does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
[ { "code": null, "e": 596, "s": 238, "text": "Some people(n) are standing in a queue. A selection process follows a rule where people standing on even positions are selected. Of the selected people a queue is formed and again out of these only people on even position are selected. This continues until we are left with one person. Find out the position of that person in the original queue.\n\nExample 1:" }, { "code": null, "e": 657, "s": 596, "text": "Input: n = 5\nOutput: 4 \nExplanation: 1,2,3,4,5 -> 2,4 -> 4.\n" }, { "code": null, "e": 669, "s": 657, "text": "\nExample 2:" }, { "code": null, "e": 748, "s": 669, "text": "Input: n = 9\nOutput: 8\nExplanation: 1,2,3,4,5,6,7,8,9\n->2,4,6,8 -> 4,8 -> 8. \n" }, { "code": null, "e": 1039, "s": 748, "text": "\nYour Task: \nYou dont need to read input or print anything. Complete the function nthPosition() which takes n as input parameter and returns the position(original queue) of that person who is left.\n\nExpected Time Complexity: O(logn)\nExpected Auxiliary Space: O(1)\n\nConstraints:\n1<= n <=108" }, { "code": null, "e": 1041, "s": 1039, "text": "0" }, { "code": null, "e": 1065, "s": 1041, "text": "sujeetkr25082 weeks ago" }, { "code": null, "e": 1069, "s": 1065, "text": "C++" }, { "code": null, "e": 1196, "s": 1069, "text": "long long int nthPosition(long long int n){ // code here if(n==1) return 1; return nthPosition(n>>1)<<1; }" }, { "code": null, "e": 1198, "s": 1196, "text": "0" }, { "code": null, "e": 1224, "s": 1198, "text": "bhabalomkar4211 month ago" }, { "code": null, "e": 1326, "s": 1224, "text": "long long int nthPosition(long long int n){ // code here return pow(2, int(log2(n))); }" }, { "code": null, "e": 1329, "s": 1326, "text": "+2" }, { "code": null, "e": 1357, "s": 1329, "text": "debasishtewary53 months ago" }, { "code": null, "e": 1368, "s": 1357, "text": "0.11/15.52" }, { "code": null, "e": 1592, "s": 1368, "text": "static long find(long i,long n){ if(i>n) return i/2; else{ i=i*2; return find(i,n); } } static long nthPosition(long n){ // code here return Solution.find(1,n); }" }, { "code": null, "e": 1595, "s": 1592, "text": "+6" }, { "code": null, "e": 1619, "s": 1595, "text": "rajsinh21814 months ago" }, { "code": null, "e": 1643, "s": 1619, "text": "Easy Recursive solution" }, { "code": null, "e": 1775, "s": 1643, "text": "long long int nthPosition(long long int n){\n if(n==1)\n return 1;\n \n return nthPosition(n/2)*2;\n }" }, { "code": null, "e": 1777, "s": 1775, "text": "0" }, { "code": null, "e": 1809, "s": 1777, "text": "abhishekbajpaiamity5 months ago" }, { "code": null, "e": 1969, "s": 1809, "text": "class Solution { static long nthPosition(long n){ int value=(int)(Math.log(n) /Math.log(2)); int pow=(int)Math.pow(2,value); return pow; }}" }, { "code": null, "e": 1971, "s": 1969, "text": "0" }, { "code": null, "e": 1992, "s": 1971, "text": "aminul015 months ago" }, { "code": null, "e": 2028, "s": 1992, "text": "Simple java solution 0.1 time taken" }, { "code": null, "e": 2227, "s": 2028, "text": "class Solution { static long nthPosition(long n){ // code here long ans = 1; while (n != 1) { ans = 2 * ans; n /= 2; } return ans; }}" }, { "code": null, "e": 2229, "s": 2227, "text": "0" }, { "code": null, "e": 2259, "s": 2229, "text": "harshitsharma60915 months ago" }, { "code": null, "e": 2418, "s": 2259, "text": " long long int nthPosition(long long int n) { if(n<2) return 0; while(( n & (n-1)) !=0) { n=n&(n-1); } return n; }" }, { "code": null, "e": 2420, "s": 2418, "text": "0" }, { "code": null, "e": 2442, "s": 2420, "text": "uday_wahi5 months ago" }, { "code": null, "e": 2473, "s": 2442, "text": "java simple one liner solution" }, { "code": null, "e": 2496, "s": 2473, "text": "time complexity : O(1)" }, { "code": null, "e": 2510, "s": 2496, "text": "time 0.1/15.5" }, { "code": null, "e": 2617, "s": 2512, "text": "static long nthPosition(long n){\n return (long) Math.pow(2,(long) (Math.log(n)/Math.log(2)));\n }" }, { "code": null, "e": 2619, "s": 2617, "text": "0" }, { "code": null, "e": 2653, "s": 2619, "text": "programmingdopractice6 months ago" }, { "code": null, "e": 2801, "s": 2653, "text": "long long int nthPosition(long long int n){\n // code here\n int len = log2(n);\n return pow(2,len);\n }\n Didn't do anything" }, { "code": null, "e": 2803, "s": 2801, "text": "0" }, { "code": null, "e": 2825, "s": 2803, "text": "user_990i6 months ago" }, { "code": null, "e": 2863, "s": 2825, "text": "Iterative solution in 0 sec execution" }, { "code": null, "e": 3037, "s": 2863, "text": "class Solution { public: long long int nthPosition(long long int n){ long long int count =1; while(n!=1){ count=2*count; n=n/2; } return count; }};" }, { "code": null, "e": 3183, "s": 3037, "text": "We strongly recommend solving this problem on your own before viewing its editorial. Do you still\n want to view the editorial?" }, { "code": null, "e": 3219, "s": 3183, "text": " Login to access your submissions. " }, { "code": null, "e": 3229, "s": 3219, "text": "\nProblem\n" }, { "code": null, "e": 3239, "s": 3229, "text": "\nContest\n" }, { "code": null, "e": 3302, "s": 3239, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 3487, "s": 3302, "text": "Avoid using static/global variables in your code as your code is tested \n against multiple test cases and these tend to retain their previous values." }, { "code": null, "e": 3771, "s": 3487, "text": "Passing the Sample/Custom Test cases does not guarantee the correctness of code.\n On submission, your code is tested against multiple test cases consisting of all\n possible corner cases and stress constraints." }, { "code": null, "e": 3917, "s": 3771, "text": "You can access the hints to get an idea about what is expected of you as well as\n the final solution code." }, { "code": null, "e": 3994, "s": 3917, "text": "You can view the solutions submitted by other users from the submission tab." }, { "code": null, "e": 4035, "s": 3994, "text": "Make sure you are not using ad-blockers." }, { "code": null, "e": 4063, "s": 4035, "text": "Disable browser extensions." }, { "code": null, "e": 4134, "s": 4063, "text": "We recommend using latest version of your browser for best experience." }, { "code": null, "e": 4321, "s": 4134, "text": "Avoid using static/global variables in coding problems as your code is tested \n against multiple test cases and these tend to retain their previous values." } ]
How to Sort the Elements of the ComboBox in C#?
27 Jun, 2019 In Windows forms, ComboBox provides two different features in a single control, it means ComboBox works as both TextBox and ListBox. In ComboBox, only one item is displayed at a time and the rest of the items are present in the drop-down menu. You are allowed to sort the elements present in the ComboBox by using the Sorted Property.If you want to sort the elements of the ComboBox, then set the value of this property to true, otherwise, false. The default value of this property is false. This sorting is case-insensitive and the elements are sort in ascending order. You can set this property using two different methods: 1. Design-Time: It is the easiest method to sort the elements present in the ComboBox control using the following steps: Step 1: Create a windows form as shown in the below image:Visual Studio -> File -> New -> Project -> WindowsFormApp Step 2: Drag the ComboBox control from the ToolBox and Drop it on the windows form. You are allowed to place a ComboBox control anywhere on the windows form according to your need. Step 3: After drag and drop you will go to the properties of the ComboBox control to sort the elements present in the ComboBox.Output: Output: 2. Run-Time: It is a little bit trickier than the above method. In this method, you can sort the elements present in the ComboBox programmatically with the help of given syntax: public bool Sorted { get; set; } Here, the value of this property is of System.Boolean type. Following steps are used to sort the ComboBox elements: Step 1: Create a combobox using the ComboBox() constructor is provided by the ComboBox class.// Creating ComboBox using ComboBox class ComboBox mybox = new ComboBox(); // Creating ComboBox using ComboBox class ComboBox mybox = new ComboBox(); Step 2: After creating ComboBox, sort the elements of the ComboBox.// Sort the elements of the ComboBox mybox.Sorted = true; // Sort the elements of the ComboBox mybox.Sorted = true; Step 3: And last add this combobox control to form using Add() method.// Add this ComboBox to form this.Controls.Add(mybox); Example:using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms; namespace WindowsFormsApp11 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { // Creating and setting the properties of label Label l = new Label(); l.Location = new Point(222, 80); l.Size = new Size(99, 18); l.Text = "Select city name"; // Adding this label to the form this.Controls.Add(l); // Creating and setting the properties of comboBox ComboBox mybox = new ComboBox(); mybox.Location = new Point(327, 77); mybox.Size = new Size(216, 26); mybox.Sorted = true; mybox.Name = "My_Cobo_Box"; mybox.Items.Add("Mumbai"); mybox.Items.Add("Delhi"); mybox.Items.Add("Jaipur"); mybox.Items.Add("Kolkata"); mybox.Items.Add("Bengaluru"); // Adding this ComboBox to the form this.Controls.Add(mybox); }}}Output:Before sorting:After sorting: // Add this ComboBox to form this.Controls.Add(mybox); Example: using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms; namespace WindowsFormsApp11 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { // Creating and setting the properties of label Label l = new Label(); l.Location = new Point(222, 80); l.Size = new Size(99, 18); l.Text = "Select city name"; // Adding this label to the form this.Controls.Add(l); // Creating and setting the properties of comboBox ComboBox mybox = new ComboBox(); mybox.Location = new Point(327, 77); mybox.Size = new Size(216, 26); mybox.Sorted = true; mybox.Name = "My_Cobo_Box"; mybox.Items.Add("Mumbai"); mybox.Items.Add("Delhi"); mybox.Items.Add("Jaipur"); mybox.Items.Add("Kolkata"); mybox.Items.Add("Bengaluru"); // Adding this ComboBox to the form this.Controls.Add(mybox); }}} Output: Before sorting: After sorting: C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n27 Jun, 2019" }, { "code": null, "e": 654, "s": 28, "text": "In Windows forms, ComboBox provides two different features in a single control, it means ComboBox works as both TextBox and ListBox. In ComboBox, only one item is displayed at a time and the rest of the items are present in the drop-down menu. You are allowed to sort the elements present in the ComboBox by using the Sorted Property.If you want to sort the elements of the ComboBox, then set the value of this property to true, otherwise, false. The default value of this property is false. This sorting is case-insensitive and the elements are sort in ascending order. You can set this property using two different methods:" }, { "code": null, "e": 775, "s": 654, "text": "1. Design-Time: It is the easiest method to sort the elements present in the ComboBox control using the following steps:" }, { "code": null, "e": 891, "s": 775, "text": "Step 1: Create a windows form as shown in the below image:Visual Studio -> File -> New -> Project -> WindowsFormApp" }, { "code": null, "e": 1072, "s": 891, "text": "Step 2: Drag the ComboBox control from the ToolBox and Drop it on the windows form. You are allowed to place a ComboBox control anywhere on the windows form according to your need." }, { "code": null, "e": 1207, "s": 1072, "text": "Step 3: After drag and drop you will go to the properties of the ComboBox control to sort the elements present in the ComboBox.Output:" }, { "code": null, "e": 1215, "s": 1207, "text": "Output:" }, { "code": null, "e": 1393, "s": 1215, "text": "2. Run-Time: It is a little bit trickier than the above method. In this method, you can sort the elements present in the ComboBox programmatically with the help of given syntax:" }, { "code": null, "e": 1426, "s": 1393, "text": "public bool Sorted { get; set; }" }, { "code": null, "e": 1542, "s": 1426, "text": "Here, the value of this property is of System.Boolean type. Following steps are used to sort the ComboBox elements:" }, { "code": null, "e": 1711, "s": 1542, "text": "Step 1: Create a combobox using the ComboBox() constructor is provided by the ComboBox class.// Creating ComboBox using ComboBox class\nComboBox mybox = new ComboBox();\n" }, { "code": null, "e": 1787, "s": 1711, "text": "// Creating ComboBox using ComboBox class\nComboBox mybox = new ComboBox();\n" }, { "code": null, "e": 1914, "s": 1787, "text": "Step 2: After creating ComboBox, sort the elements of the ComboBox.// Sort the elements of the ComboBox \nmybox.Sorted = true;\n" }, { "code": null, "e": 1974, "s": 1914, "text": "// Sort the elements of the ComboBox \nmybox.Sorted = true;\n" }, { "code": null, "e": 3309, "s": 1974, "text": "Step 3: And last add this combobox control to form using Add() method.// Add this ComboBox to form\nthis.Controls.Add(mybox);\nExample:using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms; namespace WindowsFormsApp11 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { // Creating and setting the properties of label Label l = new Label(); l.Location = new Point(222, 80); l.Size = new Size(99, 18); l.Text = \"Select city name\"; // Adding this label to the form this.Controls.Add(l); // Creating and setting the properties of comboBox ComboBox mybox = new ComboBox(); mybox.Location = new Point(327, 77); mybox.Size = new Size(216, 26); mybox.Sorted = true; mybox.Name = \"My_Cobo_Box\"; mybox.Items.Add(\"Mumbai\"); mybox.Items.Add(\"Delhi\"); mybox.Items.Add(\"Jaipur\"); mybox.Items.Add(\"Kolkata\"); mybox.Items.Add(\"Bengaluru\"); // Adding this ComboBox to the form this.Controls.Add(mybox); }}}Output:Before sorting:After sorting:" }, { "code": null, "e": 3365, "s": 3309, "text": "// Add this ComboBox to form\nthis.Controls.Add(mybox);\n" }, { "code": null, "e": 3374, "s": 3365, "text": "Example:" }, { "code": "using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms; namespace WindowsFormsApp11 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { // Creating and setting the properties of label Label l = new Label(); l.Location = new Point(222, 80); l.Size = new Size(99, 18); l.Text = \"Select city name\"; // Adding this label to the form this.Controls.Add(l); // Creating and setting the properties of comboBox ComboBox mybox = new ComboBox(); mybox.Location = new Point(327, 77); mybox.Size = new Size(216, 26); mybox.Sorted = true; mybox.Name = \"My_Cobo_Box\"; mybox.Items.Add(\"Mumbai\"); mybox.Items.Add(\"Delhi\"); mybox.Items.Add(\"Jaipur\"); mybox.Items.Add(\"Kolkata\"); mybox.Items.Add(\"Bengaluru\"); // Adding this ComboBox to the form this.Controls.Add(mybox); }}}", "e": 4540, "s": 3374, "text": null }, { "code": null, "e": 4548, "s": 4540, "text": "Output:" }, { "code": null, "e": 4564, "s": 4548, "text": "Before sorting:" }, { "code": null, "e": 4579, "s": 4564, "text": "After sorting:" }, { "code": null, "e": 4582, "s": 4579, "text": "C#" } ]
PHP | is_numeric() Function
05 Feb, 2021 The is_numeric() function is an inbuilt function in PHP which is used to check whether a variable passed in function as a parameter is a number or a numeric string or not. The function returns a boolean value. Syntax: bool is_numeric ( $var ) Parameters: The function accepts a single parameter which is mandatory and described below: $var: This input parameter is the variable which the function checks for whether it is a number or a numeric string. Based on this verification, the function returns a boolean value. Return Value: The function returns TRUE if $var is a number or a numeric string and returns FALSE otherwise. Examples: Input : $var = 12 Output : True Input : $var = "Geeks for Geeks" Output : False Below programs illustrate the is_numeric() function: Program 1: In this program, a number is passed as input. PHP <?php $num = 12;if (is_numeric($num)) { echo $num . " is numeric"; } else { echo $num . " is not numeric"; } ?> 12 is numeric Program 2: In this program, a string is passed as input. PHP <?php $element = "Geeks for Geeks";if (is_numeric($element)) { echo $element . " is numeric"; } else { echo $element . " is not numeric"; } ?> Geeks for Geeks is not numeric Program 3: In this program, a numeric string is passed as input. PHP <?php $num = "467291";if (is_numeric($num)) { echo $num . " is numeric"; } else { echo $num . " is not numeric"; } ?> 467291 is numeric Program 4: PHP <?php$array = array( "21/06/2018", 4743, 0x381, 01641, 0b1010010011, "Geek Classes"); foreach ($array as $i) { if (is_numeric($i)) { echo $i . " is numeric"."\n"; } else { echo $i . " is NOT numeric"."\n"; }}?> 21/06/2018 is NOT numeric 4743 is numeric 897 is numeric 929 is numeric 659 is numeric Geek Classes is NOT numeric Reference: http://php.net/manual/en/function.is-numeric.php arorakashish0911 PHP-function PHP Web Technologies PHP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to fetch data from localserver database and display on HTML table using PHP ? Difference between HTTP GET and POST Methods Different ways for passing data to view in Laravel PHP | file_exists( ) Function PHP | Ternary Operator Top 10 Projects For Beginners To Practice HTML and CSS Skills Installation of Node.js on Linux 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": "\n05 Feb, 2021" }, { "code": null, "e": 238, "s": 28, "text": "The is_numeric() function is an inbuilt function in PHP which is used to check whether a variable passed in function as a parameter is a number or a numeric string or not. The function returns a boolean value." }, { "code": null, "e": 247, "s": 238, "text": "Syntax: " }, { "code": null, "e": 272, "s": 247, "text": "bool is_numeric ( $var )" }, { "code": null, "e": 365, "s": 272, "text": "Parameters: The function accepts a single parameter which is mandatory and described below: " }, { "code": null, "e": 548, "s": 365, "text": "$var: This input parameter is the variable which the function checks for whether it is a number or a numeric string. Based on this verification, the function returns a boolean value." }, { "code": null, "e": 657, "s": 548, "text": "Return Value: The function returns TRUE if $var is a number or a numeric string and returns FALSE otherwise." }, { "code": null, "e": 669, "s": 657, "text": "Examples: " }, { "code": null, "e": 750, "s": 669, "text": "Input : $var = 12\nOutput : True\n\nInput : $var = \"Geeks for Geeks\"\nOutput : False" }, { "code": null, "e": 803, "s": 750, "text": "Below programs illustrate the is_numeric() function:" }, { "code": null, "e": 862, "s": 803, "text": "Program 1: In this program, a number is passed as input. " }, { "code": null, "e": 866, "s": 862, "text": "PHP" }, { "code": "<?php $num = 12;if (is_numeric($num)) { echo $num . \" is numeric\"; } else { echo $num . \" is not numeric\"; } ?>", "e": 1001, "s": 866, "text": null }, { "code": null, "e": 1015, "s": 1001, "text": "12 is numeric" }, { "code": null, "e": 1075, "s": 1017, "text": "Program 2: In this program, a string is passed as input. " }, { "code": null, "e": 1079, "s": 1075, "text": "PHP" }, { "code": "<?php $element = \"Geeks for Geeks\";if (is_numeric($element)) { echo $element . \" is numeric\"; } else { echo $element . \" is not numeric\"; } ?>", "e": 1245, "s": 1079, "text": null }, { "code": null, "e": 1276, "s": 1245, "text": "Geeks for Geeks is not numeric" }, { "code": null, "e": 1344, "s": 1278, "text": "Program 3: In this program, a numeric string is passed as input. " }, { "code": null, "e": 1348, "s": 1344, "text": "PHP" }, { "code": "<?php $num = \"467291\";if (is_numeric($num)) { echo $num . \" is numeric\"; } else { echo $num . \" is not numeric\"; } ?>", "e": 1489, "s": 1348, "text": null }, { "code": null, "e": 1507, "s": 1489, "text": "467291 is numeric" }, { "code": null, "e": 1520, "s": 1509, "text": "Program 4:" }, { "code": null, "e": 1524, "s": 1520, "text": "PHP" }, { "code": "<?php$array = array( \"21/06/2018\", 4743, 0x381, 01641, 0b1010010011, \"Geek Classes\"); foreach ($array as $i) { if (is_numeric($i)) { echo $i . \" is numeric\".\"\\n\"; } else { echo $i . \" is NOT numeric\".\"\\n\"; }}?>", "e": 1775, "s": 1524, "text": null }, { "code": null, "e": 1890, "s": 1775, "text": "21/06/2018 is NOT numeric\n4743 is numeric\n897 is numeric\n929 is numeric\n659 is numeric\nGeek Classes is NOT numeric" }, { "code": null, "e": 1953, "s": 1892, "text": "Reference: http://php.net/manual/en/function.is-numeric.php " }, { "code": null, "e": 1970, "s": 1953, "text": "arorakashish0911" }, { "code": null, "e": 1983, "s": 1970, "text": "PHP-function" }, { "code": null, "e": 1987, "s": 1983, "text": "PHP" }, { "code": null, "e": 2004, "s": 1987, "text": "Web Technologies" }, { "code": null, "e": 2008, "s": 2004, "text": "PHP" }, { "code": null, "e": 2106, "s": 2008, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2188, "s": 2106, "text": "How to fetch data from localserver database and display on HTML table using PHP ?" }, { "code": null, "e": 2233, "s": 2188, "text": "Difference between HTTP GET and POST Methods" }, { "code": null, "e": 2284, "s": 2233, "text": "Different ways for passing data to view in Laravel" }, { "code": null, "e": 2314, "s": 2284, "text": "PHP | file_exists( ) Function" }, { "code": null, "e": 2337, "s": 2314, "text": "PHP | Ternary Operator" }, { "code": null, "e": 2399, "s": 2337, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 2432, "s": 2399, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 2493, "s": 2432, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 2543, "s": 2493, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
Lodash _.assignIn() Method
09 Sep, 2020 The Lodash _.assignIn() Method is like the _.assign() method except that it iterates over its own and inherited source properties. Subsequent source objects overwrite property assignments of previous sources. This method mutates the object. Syntax: _.assignIn( dest_object, [src_obj]) Parameters: This method accepts two parameters as mentioned above and described below: dest_object: This is the destination object. src_obj: These are the source objects. Return Value: This method returns an object. Example 1: Javascript // Defining Lodash variable const _ = require('lodash'); function Gfg1() { this.a = 1;} function Gfg2() { this.c = 3;} Gfg1.prototype.b = 10;Gfg2.prototype.d = 40; console.log(_.assignIn( { a: 4 }, new Gfg1, new Gfg2)); Output: { a: 1, b: 10, c: 3, d: 40 } Example 2: Javascript // Defining Lodash variable const _ = require('lodash'); function Gfg1() { this.a = 1;} function Gfg2() { this.c = 3;} console.log(_.assignIn( { a: 4 }, new Gfg1, new Gfg2)); Output: { a: 1, c: 3 } JavaScript-Lodash JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n09 Sep, 2020" }, { "code": null, "e": 269, "s": 28, "text": "The Lodash _.assignIn() Method is like the _.assign() method except that it iterates over its own and inherited source properties. Subsequent source objects overwrite property assignments of previous sources. This method mutates the object." }, { "code": null, "e": 277, "s": 269, "text": "Syntax:" }, { "code": null, "e": 314, "s": 277, "text": "_.assignIn( dest_object, [src_obj])\n" }, { "code": null, "e": 401, "s": 314, "text": "Parameters: This method accepts two parameters as mentioned above and described below:" }, { "code": null, "e": 446, "s": 401, "text": "dest_object: This is the destination object." }, { "code": null, "e": 485, "s": 446, "text": "src_obj: These are the source objects." }, { "code": null, "e": 530, "s": 485, "text": "Return Value: This method returns an object." }, { "code": null, "e": 541, "s": 530, "text": "Example 1:" }, { "code": null, "e": 552, "s": 541, "text": "Javascript" }, { "code": "// Defining Lodash variable const _ = require('lodash'); function Gfg1() { this.a = 1;} function Gfg2() { this.c = 3;} Gfg1.prototype.b = 10;Gfg2.prototype.d = 40; console.log(_.assignIn( { a: 4 }, new Gfg1, new Gfg2));", "e": 786, "s": 552, "text": null }, { "code": null, "e": 794, "s": 786, "text": "Output:" }, { "code": null, "e": 823, "s": 794, "text": "{ a: 1, b: 10, c: 3, d: 40 }" }, { "code": null, "e": 834, "s": 823, "text": "Example 2:" }, { "code": null, "e": 845, "s": 834, "text": "Javascript" }, { "code": "// Defining Lodash variable const _ = require('lodash'); function Gfg1() { this.a = 1;} function Gfg2() { this.c = 3;} console.log(_.assignIn( { a: 4 }, new Gfg1, new Gfg2));", "e": 1032, "s": 845, "text": null }, { "code": null, "e": 1040, "s": 1032, "text": "Output:" }, { "code": null, "e": 1055, "s": 1040, "text": "{ a: 1, c: 3 }" }, { "code": null, "e": 1073, "s": 1055, "text": "JavaScript-Lodash" }, { "code": null, "e": 1084, "s": 1073, "text": "JavaScript" }, { "code": null, "e": 1101, "s": 1084, "text": "Web Technologies" } ]
How to connect to SQLite database that resides in the memory using Python ?
12 Oct, 2021 In this article, we will learn how to Connect an SQLite database connection to a database that resides in the memory using Python. But first let brief about what is sqlite. SQLite is a lightweight database software library that provides a relational database management system. Generally, it is a server-less database that can be used within almost all programming languages including Python. A server-less database means that it has not required a separate server process to operate. The following diagram showing the SQLite server-less architecture: Image 1.1 (SQLite server-less architecture) Step 1: Importing SQLite module To Connect an SQLite database connection to a database that resides in the memory using Python firstly we will import SQLite in our programming so that we can use its libraries in our program. Syntax to import SQLite in the program: import sqlite3 Step 2: Creating a connection In this step, we will create a connection object which will connect us to the database and will let us execute the SQL statements. To create a connection object we will use connect() function which can create a connection object. connect() function is available in SQLite library. Syntax: conn = sqlite3.connect('gfgdatabase.db') It will create a database with the name ‘gfgdatabase.db’ and connection will be created and a connection object also will be created with the name ‘conn’. Below is the .db file formed: image 1.2 ( gfgdatabase in memory ) Step 3: Creating a database in memory We can create a database in memory by using the following syntax. conn = sqlite3.connect(':memory:') It creates a database in RAM with the name ‘gfgdatabase.db’. Step 4: Creating a cursor In the program To execute SQLite statements, we have to need a cursor object. To create a cursor we will use the cursor() method. The cursor is a method of the connection object. To execute the SQLite3 statements, we should establish a connection at first and then create an object of the cursor using the connection object. Syntax: cursor_object = connection.cursor() Step 5: Importing Error from SQLite In case of any exceptions or run time errors occurred in database creation and connecting to memory then it should be handled. To handle that we will import Error from SQLite. Syntax: from sqlite3 import Error Step 6: Finally close the connections Once we have created a connection with SQLite in step 2 and then created a database in RAM having the name “gfgdatabase.db” in step3 apart from that till step5 we have done all the procedures to Connect an SQLite database connection to a database that resides in the memory. In this step finally, we will close the connections. To do that we will use the close() function. Syntax: conn.close() Below is the complete program based on the above approach: Python3 # import required modulesimport sqlite3from sqlite3 import Error as Err # explicit function to connect database# that resides in the memorydef SQLite_connection(): try: # connect to the database conn = sqlite3.connect('gfgdatabase.db') print("Database connection is established successfully!") # connect a database connection to the # database that resides in the memory conn = sqlite3.connect(':memory:') print("Established database connection to a database\ that resides in the memory!") # if any interruption or error occurs except Err: print(Err) # terminate the connection finally: conn.close() # function call SQLite_connection() Output: akshaysingh98088 ruhelaa48 sweetyty Picked Python-SQLite 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 Python OOPs Concepts Iterate over a list in Python
[ { "code": null, "e": 28, "s": 0, "text": "\n12 Oct, 2021" }, { "code": null, "e": 201, "s": 28, "text": "In this article, we will learn how to Connect an SQLite database connection to a database that resides in the memory using Python. But first let brief about what is sqlite." }, { "code": null, "e": 513, "s": 201, "text": "SQLite is a lightweight database software library that provides a relational database management system. Generally, it is a server-less database that can be used within almost all programming languages including Python. A server-less database means that it has not required a separate server process to operate." }, { "code": null, "e": 580, "s": 513, "text": "The following diagram showing the SQLite server-less architecture:" }, { "code": null, "e": 624, "s": 580, "text": "Image 1.1 (SQLite server-less architecture)" }, { "code": null, "e": 656, "s": 624, "text": "Step 1: Importing SQLite module" }, { "code": null, "e": 849, "s": 656, "text": "To Connect an SQLite database connection to a database that resides in the memory using Python firstly we will import SQLite in our programming so that we can use its libraries in our program." }, { "code": null, "e": 889, "s": 849, "text": "Syntax to import SQLite in the program:" }, { "code": null, "e": 904, "s": 889, "text": "import sqlite3" }, { "code": null, "e": 934, "s": 904, "text": "Step 2: Creating a connection" }, { "code": null, "e": 1215, "s": 934, "text": "In this step, we will create a connection object which will connect us to the database and will let us execute the SQL statements. To create a connection object we will use connect() function which can create a connection object. connect() function is available in SQLite library." }, { "code": null, "e": 1223, "s": 1215, "text": "Syntax:" }, { "code": null, "e": 1267, "s": 1223, "text": "conn = sqlite3.connect('gfgdatabase.db') " }, { "code": null, "e": 1452, "s": 1267, "text": "It will create a database with the name ‘gfgdatabase.db’ and connection will be created and a connection object also will be created with the name ‘conn’. Below is the .db file formed:" }, { "code": null, "e": 1488, "s": 1452, "text": "image 1.2 ( gfgdatabase in memory )" }, { "code": null, "e": 1526, "s": 1488, "text": "Step 3: Creating a database in memory" }, { "code": null, "e": 1592, "s": 1526, "text": "We can create a database in memory by using the following syntax." }, { "code": null, "e": 1628, "s": 1592, "text": "conn = sqlite3.connect(':memory:') " }, { "code": null, "e": 1690, "s": 1628, "text": "It creates a database in RAM with the name ‘gfgdatabase.db’. " }, { "code": null, "e": 1716, "s": 1690, "text": "Step 4: Creating a cursor" }, { "code": null, "e": 2041, "s": 1716, "text": "In the program To execute SQLite statements, we have to need a cursor object. To create a cursor we will use the cursor() method. The cursor is a method of the connection object. To execute the SQLite3 statements, we should establish a connection at first and then create an object of the cursor using the connection object." }, { "code": null, "e": 2049, "s": 2041, "text": "Syntax:" }, { "code": null, "e": 2085, "s": 2049, "text": "cursor_object = connection.cursor()" }, { "code": null, "e": 2121, "s": 2085, "text": "Step 5: Importing Error from SQLite" }, { "code": null, "e": 2297, "s": 2121, "text": "In case of any exceptions or run time errors occurred in database creation and connecting to memory then it should be handled. To handle that we will import Error from SQLite." }, { "code": null, "e": 2305, "s": 2297, "text": "Syntax:" }, { "code": null, "e": 2331, "s": 2305, "text": "from sqlite3 import Error" }, { "code": null, "e": 2369, "s": 2331, "text": "Step 6: Finally close the connections" }, { "code": null, "e": 2742, "s": 2369, "text": "Once we have created a connection with SQLite in step 2 and then created a database in RAM having the name “gfgdatabase.db” in step3 apart from that till step5 we have done all the procedures to Connect an SQLite database connection to a database that resides in the memory. In this step finally, we will close the connections. To do that we will use the close() function." }, { "code": null, "e": 2750, "s": 2742, "text": "Syntax:" }, { "code": null, "e": 2763, "s": 2750, "text": "conn.close()" }, { "code": null, "e": 2822, "s": 2763, "text": "Below is the complete program based on the above approach:" }, { "code": null, "e": 2830, "s": 2822, "text": "Python3" }, { "code": "# import required modulesimport sqlite3from sqlite3 import Error as Err # explicit function to connect database# that resides in the memorydef SQLite_connection(): try: # connect to the database conn = sqlite3.connect('gfgdatabase.db') print(\"Database connection is established successfully!\") # connect a database connection to the # database that resides in the memory conn = sqlite3.connect(':memory:') print(\"Established database connection to a database\\ that resides in the memory!\") # if any interruption or error occurs except Err: print(Err) # terminate the connection finally: conn.close() # function call SQLite_connection()", "e": 3567, "s": 2830, "text": null }, { "code": null, "e": 3577, "s": 3567, "text": "Output: " }, { "code": null, "e": 3596, "s": 3579, "text": "akshaysingh98088" }, { "code": null, "e": 3606, "s": 3596, "text": "ruhelaa48" }, { "code": null, "e": 3615, "s": 3606, "text": "sweetyty" }, { "code": null, "e": 3622, "s": 3615, "text": "Picked" }, { "code": null, "e": 3636, "s": 3622, "text": "Python-SQLite" }, { "code": null, "e": 3643, "s": 3636, "text": "Python" }, { "code": null, "e": 3741, "s": 3643, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3759, "s": 3741, "text": "Python Dictionary" }, { "code": null, "e": 3801, "s": 3759, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 3823, "s": 3801, "text": "Enumerate() in Python" }, { "code": null, "e": 3858, "s": 3823, "text": "Read a file line by line in Python" }, { "code": null, "e": 3884, "s": 3858, "text": "Python String | replace()" }, { "code": null, "e": 3916, "s": 3884, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 3945, "s": 3916, "text": "*args and **kwargs in Python" }, { "code": null, "e": 3972, "s": 3945, "text": "Python Classes and Objects" }, { "code": null, "e": 3993, "s": 3972, "text": "Python OOPs Concepts" } ]
Docker – COPY Instruction
29 Oct, 2020 In Docker, there are two ways to copy a file, namely, ADD and COPY. Though there is a slight difference between them in regard to the scope of the functions, they more or less perform the same task. In this article, we will primarily focus on the COPY instruction of Docker. If you want to copy files and directories inside a Docker Container from your Local machine, you can use the COPY instruction inside your Dockerfile. The general form of a COPY instruction is: Syntax: COPY <src-path> <destination-path> In this article, we will discuss how to use the COPY Instruction to copy files and directories inside a Docker Container. To do so follow the below steps: In this example, we will create a directory and a file which we will copy using the COPY command. Create a folder and inside it create a file called “dockerfile” which we will edit in the next step. Create another folder in the same directory where you have created the Dockerfile and a file inside it. We will copy this folder to our Docker Container. The final directory structure will be – After you have created the directory structure, edit the Dockerfile that we created in the previous step. FROM ubuntu:latest RUN apt-get -y update COPY to-be-copied . In the above Dockerfile, we have tried to pull the Ubuntu base image OS with the latest tag and run an update inside the Container. We have then included the COPY instruction to copy the directory created previously. After creating the Dockerfile, we can now build the Docker Image using the Docker Build command. sudo docker build -t sample-image . After you have built the Docker Image, you can verify it by using the Docker Images command to list all the images in your system. sudo docker images After you have built the Docker Image with the COPY Instruction, you can now run the Docker container using the Docker RUN command. sudo docker run -it sample-image bash You can now verify whether the directory has been copied or not by listing the directories inside the Container. Docker Container linux Advanced Computer Subject Articles Linux-Unix TechTips Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. System Design Tutorial ML | Linear Regression Reinforcement learning Supervised and Unsupervised learning Decision Tree Introduction with example Tree Traversals (Inorder, Preorder and Postorder) SQL | Join (Inner, Left, Right and Full Joins) find command in Linux with examples Analysis of Algorithms | Set 1 (Asymptotic Analysis) SQL Interview Questions
[ { "code": null, "e": 28, "s": 0, "text": "\n29 Oct, 2020" }, { "code": null, "e": 496, "s": 28, "text": "In Docker, there are two ways to copy a file, namely, ADD and COPY. Though there is a slight difference between them in regard to the scope of the functions, they more or less perform the same task. In this article, we will primarily focus on the COPY instruction of Docker. If you want to copy files and directories inside a Docker Container from your Local machine, you can use the COPY instruction inside your Dockerfile. The general form of a COPY instruction is:" }, { "code": null, "e": 541, "s": 496, "text": "Syntax: COPY <src-path> <destination-path>\n\n" }, { "code": null, "e": 696, "s": 541, "text": "In this article, we will discuss how to use the COPY Instruction to copy files and directories inside a Docker Container. To do so follow the below steps:" }, { "code": null, "e": 1089, "s": 696, "text": "In this example, we will create a directory and a file which we will copy using the COPY command. Create a folder and inside it create a file called “dockerfile” which we will edit in the next step. Create another folder in the same directory where you have created the Dockerfile and a file inside it. We will copy this folder to our Docker Container. The final directory structure will be –" }, { "code": null, "e": 1195, "s": 1089, "text": "After you have created the directory structure, edit the Dockerfile that we created in the previous step." }, { "code": null, "e": 1257, "s": 1195, "text": "FROM ubuntu:latest\nRUN apt-get -y update\nCOPY to-be-copied .\n" }, { "code": null, "e": 1474, "s": 1257, "text": "In the above Dockerfile, we have tried to pull the Ubuntu base image OS with the latest tag and run an update inside the Container. We have then included the COPY instruction to copy the directory created previously." }, { "code": null, "e": 1571, "s": 1474, "text": "After creating the Dockerfile, we can now build the Docker Image using the Docker Build command." }, { "code": null, "e": 1609, "s": 1571, "text": "sudo docker build -t sample-image .\n\n" }, { "code": null, "e": 1740, "s": 1609, "text": "After you have built the Docker Image, you can verify it by using the Docker Images command to list all the images in your system." }, { "code": null, "e": 1760, "s": 1740, "text": "sudo docker images\n" }, { "code": null, "e": 1892, "s": 1760, "text": "After you have built the Docker Image with the COPY Instruction, you can now run the Docker container using the Docker RUN command." }, { "code": null, "e": 1932, "s": 1892, "text": "sudo docker run -it sample-image bash\n\n" }, { "code": null, "e": 2045, "s": 1932, "text": "You can now verify whether the directory has been copied or not by listing the directories inside the Container." }, { "code": null, "e": 2062, "s": 2045, "text": "Docker Container" }, { "code": null, "e": 2068, "s": 2062, "text": "linux" }, { "code": null, "e": 2094, "s": 2068, "text": "Advanced Computer Subject" }, { "code": null, "e": 2103, "s": 2094, "text": "Articles" }, { "code": null, "e": 2114, "s": 2103, "text": "Linux-Unix" }, { "code": null, "e": 2123, "s": 2114, "text": "TechTips" }, { "code": null, "e": 2221, "s": 2123, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2244, "s": 2221, "text": "System Design Tutorial" }, { "code": null, "e": 2267, "s": 2244, "text": "ML | Linear Regression" }, { "code": null, "e": 2290, "s": 2267, "text": "Reinforcement learning" }, { "code": null, "e": 2327, "s": 2290, "text": "Supervised and Unsupervised learning" }, { "code": null, "e": 2367, "s": 2327, "text": "Decision Tree Introduction with example" }, { "code": null, "e": 2417, "s": 2367, "text": "Tree Traversals (Inorder, Preorder and Postorder)" }, { "code": null, "e": 2464, "s": 2417, "text": "SQL | Join (Inner, Left, Right and Full Joins)" }, { "code": null, "e": 2500, "s": 2464, "text": "find command in Linux with examples" }, { "code": null, "e": 2553, "s": 2500, "text": "Analysis of Algorithms | Set 1 (Asymptotic Analysis)" } ]
Sort function in Lua programming
One of the most used functions in Lua is the sort function which is provided by the Lua library which tables a table as an argument and sorts the values that are present inside the table. The sort function also takes one more argument with the table and that argument is a function which is known as the order function. This order function is used to provide the logic if we want to sort the elements of the table in a certain order. The order function takes two arguments, and these two arguments must return true if the first argument should come first in the sorted array. If this function is not provided, sort uses the default less-than operation (corresponding to the `< ́ operator). table.sort(x,f) In the above syntax, the x identifier is used to represent the name of the table which entries we want to sort, and the f identifier is used to represent the order function which is not necessary to provide if you are okay with the default order of sorting. Let’s consider a simple example of a table where we have different strings stored in it and we are printing the values of the table using the generic for loop. Consider the example shown below − Live Demo t = { "the", "quick", "brown", "fox" } for i,v in ipairs(t) do print(v) end the quick brown fox Now, let’s consider the scenario that we want to sort the elements of the above table, for that we just need to use the sort function that the Lua library provides us. Consider the example shown below − Live Demo t = { "the", "quick", "brown", "fox" } table.sort(t) for i,v in ipairs(t) do print(v) end brown fox quick the Now let’s consider a more complex example, where we will try to use an order function. Consider the example shown below − Live Demo t = { { str = 42, dex = 10, wis = 100 }, { str = 18, dex = 30, wis = 5 } } table.sort(t, function (k1, k2) return k1.str < k2.str end ) for i,v in ipairs(t) do print(v.str,v.dex,v.wis) end In the above example, the idea is to sort the values in the table based on the “str” field, and hence when I print the values of the fields, they will be in that order. 18 30 5 42 10 100
[ { "code": null, "e": 1375, "s": 1187, "text": "One of the most used functions in Lua is the sort function which is provided by the Lua library which tables a table as an argument and sorts the values that are present inside the table." }, { "code": null, "e": 1621, "s": 1375, "text": "The sort function also takes one more argument with the table and that argument is a function which is known as the order function. This order function is used to provide the logic if we want to sort the elements of the table in a certain order." }, { "code": null, "e": 1877, "s": 1621, "text": "The order function takes two arguments, and these two arguments must return true if the first argument should come first in the sorted array. If this function is not provided, sort uses the default less-than operation (corresponding to the `< ́ operator)." }, { "code": null, "e": 1893, "s": 1877, "text": "table.sort(x,f)" }, { "code": null, "e": 2151, "s": 1893, "text": "In the above syntax, the x identifier is used to represent the name of the table which entries we want to sort, and the f identifier is used to represent the order function which is not necessary to provide if you are okay with the default order of sorting." }, { "code": null, "e": 2311, "s": 2151, "text": "Let’s consider a simple example of a table where we have different strings stored in it and we are printing the values of the table using the generic for loop." }, { "code": null, "e": 2346, "s": 2311, "text": "Consider the example shown below −" }, { "code": null, "e": 2357, "s": 2346, "text": " Live Demo" }, { "code": null, "e": 2433, "s": 2357, "text": "t = { \"the\", \"quick\", \"brown\", \"fox\" }\nfor i,v in ipairs(t) do print(v) end" }, { "code": null, "e": 2453, "s": 2433, "text": "the\nquick\nbrown\nfox" }, { "code": null, "e": 2621, "s": 2453, "text": "Now, let’s consider the scenario that we want to sort the elements of the above table, for that we just need to use the sort function that the Lua library provides us." }, { "code": null, "e": 2656, "s": 2621, "text": "Consider the example shown below −" }, { "code": null, "e": 2667, "s": 2656, "text": " Live Demo" }, { "code": null, "e": 2757, "s": 2667, "text": "t = { \"the\", \"quick\", \"brown\", \"fox\" }\ntable.sort(t)\nfor i,v in ipairs(t) do print(v) end" }, { "code": null, "e": 2777, "s": 2757, "text": "brown\nfox\nquick\nthe" }, { "code": null, "e": 2864, "s": 2777, "text": "Now let’s consider a more complex example, where we will try to use an order function." }, { "code": null, "e": 2899, "s": 2864, "text": "Consider the example shown below −" }, { "code": null, "e": 2910, "s": 2899, "text": " Live Demo" }, { "code": null, "e": 3105, "s": 2910, "text": "t = {\n { str = 42, dex = 10, wis = 100 },\n { str = 18, dex = 30, wis = 5 }\n}\ntable.sort(t, function (k1, k2) return k1.str < k2.str end )\nfor i,v in ipairs(t) do print(v.str,v.dex,v.wis) end" }, { "code": null, "e": 3274, "s": 3105, "text": "In the above example, the idea is to sort the values in the table based on the “str” field, and hence when I print the values of the fields, they will be in that order." }, { "code": null, "e": 3298, "s": 3274, "text": "18 30 5\n42 10 100" } ]
File.Open(String, FileMode, FileAccess, FileShare) Method in C# with Examples
13 Apr, 2021 File.Open(String, FileMode, FileAccess, FileShare) is an inbuilt File class method that is used to open a FileStream on the specified path, having the specified mode with read, write, or read/write access and the specified sharing option.Syntax: public static System.IO.FileStream Open (string path, System.IO.FileMode mode, System.IO.FileAccess access, System.IO.FileShare share); Parameter: This function accepts three parameters which are illustrated below: path: This is the specified file to open. mode: This mode value specifies whether a new file is created if one does not exist, and also determines whether the existing file’s contents are retained or overwritten. access: This value specifies the operations that can be performed on the file. share: This value specifying the type of access other threads have to the file. Exceptions: ArgumentException: The path is a zero-length string, contains only white space, or one or more invalid characters as defined by InvalidPathChars. OR access specified Read and mode specified Create, CreateNew, Truncate, or Append. ArgumentNullException: The path is null. PathTooLongException: The specified path, file name, or both exceed the system-defined maximum length. DirectoryNotFoundException: The specified path is invalid. IOException: An I/O error occurred while opening the file. UnauthorizedAccessException: The path specified a file that is read-only and access is not Read. OR path specified a directory. OR the caller does not have the required permission. OR mode is Create and the specified file is a hidden file. ArgumentOutOfRangeException: The mode, access, or share specified an invalid value. FileNotFoundException: The file specified in the path was not found. NotSupportedException: The path is in an invalid format. Return Value: Returns a FileStream on the specified path, having the specified mode with read, write, or read/write access and the specified sharing option.Below are the programs to illustrate the File.Open(String, FileMode, FileAccess, FileShare) method.Program 1: Below code creates a temporary file, writes some specified contents into it, open that file and print its contents. Here file sharing is not allowed. CSharp // C# program to illustrate the usage// of File.Open(String, FileMode,// FileAccess, FileShare) method // Using System, System.IO and// System.Text namespacesusing System;using System.IO;using System.Text; class GFG { public static void Main() { // Creating a temporary file string path = Path.GetTempFileName(); using(FileStream fs = File.Open(path, FileMode.Open)) { // Putting some contents Byte[] info = new UTF8Encoding(true).GetBytes("GFG is a CS Portal."); fs.Write(info, 0, info.Length); } // Opening the stream and reading it back. using(FileStream fs = File.Open(path, FileMode.Open, FileAccess.Read, FileShare.None)) { byte[] b = new byte[1024]; UTF8Encoding temp = new UTF8Encoding(true); while (fs.Read(b, 0, b.Length) > 0) { Console.WriteLine(temp.GetString(b)); } } }} Executing: GFG is a CS Portal. Program 2: Initially, a file file.txt is created with some contents shown below: This code will open the file file.txt and will print its contents with file sharing is not allowed. CSharp // C# program to illustrate the usage// of File.Open(String, FileMode,// FileAccess, FileShare) method // Using System, System.IO and// System.Text namespacesusing System;using System.IO;using System.Text; class GFG { public static void Main() { // Specifying a file path string path = @"file.txt"; // Opening above file and reading it back. using(FileStream fs = File.Open(path, FileMode.Open, FileAccess.Read, FileShare.None)) { byte[] b = new byte[1024]; UTF8Encoding temp = new UTF8Encoding(true); while (fs.Read(b, 0, b.Length) > 0) { // Printing the file contents Console.WriteLine(temp.GetString(b)); } } }} Executing: GeeksforGeeks arorakashish0911 CSharp-File-Handling C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. C# | Delegates C# | Abstract Classes Introduction to .NET Framework C# | Arrays C# | Method Overriding C# Dictionary with examples Differences Between .NET Core and .NET Framework C# | Data Types C# | .NET Framework (Basic Architecture and Component Stack) C# | Constructors
[ { "code": null, "e": 28, "s": 0, "text": "\n13 Apr, 2021" }, { "code": null, "e": 275, "s": 28, "text": "File.Open(String, FileMode, FileAccess, FileShare) is an inbuilt File class method that is used to open a FileStream on the specified path, having the specified mode with read, write, or read/write access and the specified sharing option.Syntax: " }, { "code": null, "e": 413, "s": 275, "text": "public static System.IO.FileStream Open (string path, System.IO.FileMode mode, System.IO.FileAccess access, System.IO.FileShare share); " }, { "code": null, "e": 494, "s": 413, "text": "Parameter: This function accepts three parameters which are illustrated below: " }, { "code": null, "e": 536, "s": 494, "text": "path: This is the specified file to open." }, { "code": null, "e": 707, "s": 536, "text": "mode: This mode value specifies whether a new file is created if one does not exist, and also determines whether the existing file’s contents are retained or overwritten." }, { "code": null, "e": 786, "s": 707, "text": "access: This value specifies the operations that can be performed on the file." }, { "code": null, "e": 866, "s": 786, "text": "share: This value specifying the type of access other threads have to the file." }, { "code": null, "e": 879, "s": 866, "text": "Exceptions: " }, { "code": null, "e": 1109, "s": 879, "text": "ArgumentException: The path is a zero-length string, contains only white space, or one or more invalid characters as defined by InvalidPathChars. OR access specified Read and mode specified Create, CreateNew, Truncate, or Append." }, { "code": null, "e": 1150, "s": 1109, "text": "ArgumentNullException: The path is null." }, { "code": null, "e": 1253, "s": 1150, "text": "PathTooLongException: The specified path, file name, or both exceed the system-defined maximum length." }, { "code": null, "e": 1312, "s": 1253, "text": "DirectoryNotFoundException: The specified path is invalid." }, { "code": null, "e": 1371, "s": 1312, "text": "IOException: An I/O error occurred while opening the file." }, { "code": null, "e": 1611, "s": 1371, "text": "UnauthorizedAccessException: The path specified a file that is read-only and access is not Read. OR path specified a directory. OR the caller does not have the required permission. OR mode is Create and the specified file is a hidden file." }, { "code": null, "e": 1695, "s": 1611, "text": "ArgumentOutOfRangeException: The mode, access, or share specified an invalid value." }, { "code": null, "e": 1764, "s": 1695, "text": "FileNotFoundException: The file specified in the path was not found." }, { "code": null, "e": 1821, "s": 1764, "text": "NotSupportedException: The path is in an invalid format." }, { "code": null, "e": 2238, "s": 1821, "text": "Return Value: Returns a FileStream on the specified path, having the specified mode with read, write, or read/write access and the specified sharing option.Below are the programs to illustrate the File.Open(String, FileMode, FileAccess, FileShare) method.Program 1: Below code creates a temporary file, writes some specified contents into it, open that file and print its contents. Here file sharing is not allowed. " }, { "code": null, "e": 2245, "s": 2238, "text": "CSharp" }, { "code": "// C# program to illustrate the usage// of File.Open(String, FileMode,// FileAccess, FileShare) method // Using System, System.IO and// System.Text namespacesusing System;using System.IO;using System.Text; class GFG { public static void Main() { // Creating a temporary file string path = Path.GetTempFileName(); using(FileStream fs = File.Open(path, FileMode.Open)) { // Putting some contents Byte[] info = new UTF8Encoding(true).GetBytes(\"GFG is a CS Portal.\"); fs.Write(info, 0, info.Length); } // Opening the stream and reading it back. using(FileStream fs = File.Open(path, FileMode.Open, FileAccess.Read, FileShare.None)) { byte[] b = new byte[1024]; UTF8Encoding temp = new UTF8Encoding(true); while (fs.Read(b, 0, b.Length) > 0) { Console.WriteLine(temp.GetString(b)); } } }}", "e": 3221, "s": 2245, "text": null }, { "code": null, "e": 3234, "s": 3221, "text": "Executing: " }, { "code": null, "e": 3254, "s": 3234, "text": "GFG is a CS Portal." }, { "code": null, "e": 3336, "s": 3254, "text": "Program 2: Initially, a file file.txt is created with some contents shown below: " }, { "code": null, "e": 3437, "s": 3336, "text": "This code will open the file file.txt and will print its contents with file sharing is not allowed. " }, { "code": null, "e": 3444, "s": 3437, "text": "CSharp" }, { "code": "// C# program to illustrate the usage// of File.Open(String, FileMode,// FileAccess, FileShare) method // Using System, System.IO and// System.Text namespacesusing System;using System.IO;using System.Text; class GFG { public static void Main() { // Specifying a file path string path = @\"file.txt\"; // Opening above file and reading it back. using(FileStream fs = File.Open(path, FileMode.Open, FileAccess.Read, FileShare.None)) { byte[] b = new byte[1024]; UTF8Encoding temp = new UTF8Encoding(true); while (fs.Read(b, 0, b.Length) > 0) { // Printing the file contents Console.WriteLine(temp.GetString(b)); } } }}", "e": 4212, "s": 3444, "text": null }, { "code": null, "e": 4225, "s": 4212, "text": "Executing: " }, { "code": null, "e": 4239, "s": 4225, "text": "GeeksforGeeks" }, { "code": null, "e": 4258, "s": 4241, "text": "arorakashish0911" }, { "code": null, "e": 4279, "s": 4258, "text": "CSharp-File-Handling" }, { "code": null, "e": 4282, "s": 4279, "text": "C#" }, { "code": null, "e": 4380, "s": 4282, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4395, "s": 4380, "text": "C# | Delegates" }, { "code": null, "e": 4417, "s": 4395, "text": "C# | Abstract Classes" }, { "code": null, "e": 4448, "s": 4417, "text": "Introduction to .NET Framework" }, { "code": null, "e": 4460, "s": 4448, "text": "C# | Arrays" }, { "code": null, "e": 4483, "s": 4460, "text": "C# | Method Overriding" }, { "code": null, "e": 4511, "s": 4483, "text": "C# Dictionary with examples" }, { "code": null, "e": 4560, "s": 4511, "text": "Differences Between .NET Core and .NET Framework" }, { "code": null, "e": 4576, "s": 4560, "text": "C# | Data Types" }, { "code": null, "e": 4637, "s": 4576, "text": "C# | .NET Framework (Basic Architecture and Component Stack)" } ]
Django form field custom widgets
29 Dec, 2019 A widget is Django’s representation of an HTML input element. The widget handles the rendering of the HTML, and the extraction of data from a GET/POST dictionary that corresponds to the widget. Whenever you specify a field on a form, Django will use a default widget that is appropriate to the type of data that is to be displayed. To find which widget is used on which field, see the documentation about Built-in Field classes. This post revolves about the advanced use of widgets to modify the form structure and input type. Every field has a predefined widget, for example IntegerField has a default widget of NumberInput. Let’s demonstrate this with help of our base project geeksforgeeks. Refer to the following articles to check how to create a project and an app in Django. How to Create a Basic Project using MVT in Django? How to Create an App in Django ? Now let’s create a demo form in “geeks/forms.py”, from django import forms // creating a django formclass GeeksForm(forms.Form): title = forms.CharField() description = forms.CharField() views = forms.IntegerField() available = forms.BooleanField() Now to render this form we need to create the view and template which will be used to display the form to user. In geeks/views.py, create a view from django.shortcuts import renderfrom .forms import GeeksForm # creating a home viewdef home_view(request): context = {} form = GeeksForm(request.POST or None) context['form'] = form return render(request, "home.html", context) and in templates/home.html, <form method="POST"> {% csrf_token %} {{ form.as_p }} <input type="submit" value="Submit"></form> Now let’s display the form by running Python manage.py runserver visit http://127.0.0.1:8000/ As seen in above screenshot, there is a different type of input field for IntegerField, BooleanField, etc. One can modify this using the following ways. One can override the default widget of each field for various purposes. The list of widgets can be seen here – Widgets | Django Documentation. To override the default widget we need to explicitly define the widget we want to assign to a field.Make following changes to geeks/forms.py, from django import forms class GeeksForm(forms.Form): title = forms.CharField(widget = forms.Textarea) description = forms.CharField(widget = forms.CheckboxInput) views = forms.IntegerField(widget = forms.TextInput) available = forms.BooleanField(widget = forms.Textarea) Now visit http://127.0.0.1:8000/,Thus we can assign, any widget to any field using widget attribute. Note – The validations imposed on fields would still remain same, for example even if an IntegerField is made the same as CharField, it will only accept Integer inputs. widgets have a great use in Form Fields especially using Select type of widgets where one wants to limit the type and number of inputs form a user. Let’s demonstrate this with help of modifying DateField. Consider forms.py as, from django import forms class GeeksForm(forms.Form): title = forms.CharField() description = forms.CharField() views = forms.IntegerField() date = forms.DateField() By default, DateField as widget TextInput. It can be seen as Now let’s change the widget for better and convenient input from user of a date. Add SelectDateWidget to DateField in forms.py, from django import forms class GeeksForm(forms.Form): title = forms.CharField() description = forms.CharField() views = forms.IntegerField() date = forms.DateField(widget = forms.SelectDateWidget) Now input of date can be seen as very easy and helpful in the front end of the application. This way we can use multiple widgets for modifying the input fields. Django-forms Python Django Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n29 Dec, 2019" }, { "code": null, "e": 581, "s": 54, "text": "A widget is Django’s representation of an HTML input element. The widget handles the rendering of the HTML, and the extraction of data from a GET/POST dictionary that corresponds to the widget. Whenever you specify a field on a form, Django will use a default widget that is appropriate to the type of data that is to be displayed. To find which widget is used on which field, see the documentation about Built-in Field classes. This post revolves about the advanced use of widgets to modify the form structure and input type." }, { "code": null, "e": 748, "s": 581, "text": "Every field has a predefined widget, for example IntegerField has a default widget of NumberInput. Let’s demonstrate this with help of our base project geeksforgeeks." }, { "code": null, "e": 835, "s": 748, "text": "Refer to the following articles to check how to create a project and an app in Django." }, { "code": null, "e": 886, "s": 835, "text": "How to Create a Basic Project using MVT in Django?" }, { "code": null, "e": 919, "s": 886, "text": "How to Create an App in Django ?" }, { "code": null, "e": 969, "s": 919, "text": "Now let’s create a demo form in “geeks/forms.py”," }, { "code": "from django import forms // creating a django formclass GeeksForm(forms.Form): title = forms.CharField() description = forms.CharField() views = forms.IntegerField() available = forms.BooleanField()", "e": 1181, "s": 969, "text": null }, { "code": null, "e": 1326, "s": 1181, "text": "Now to render this form we need to create the view and template which will be used to display the form to user. In geeks/views.py, create a view" }, { "code": "from django.shortcuts import renderfrom .forms import GeeksForm # creating a home viewdef home_view(request): context = {} form = GeeksForm(request.POST or None) context['form'] = form return render(request, \"home.html\", context)", "e": 1569, "s": 1326, "text": null }, { "code": null, "e": 1597, "s": 1569, "text": "and in templates/home.html," }, { "code": "<form method=\"POST\"> {% csrf_token %} {{ form.as_p }} <input type=\"submit\" value=\"Submit\"></form>", "e": 1704, "s": 1597, "text": null }, { "code": null, "e": 1742, "s": 1704, "text": "Now let’s display the form by running" }, { "code": null, "e": 1769, "s": 1742, "text": "Python manage.py runserver" }, { "code": null, "e": 1798, "s": 1769, "text": "visit http://127.0.0.1:8000/" }, { "code": null, "e": 1951, "s": 1798, "text": "As seen in above screenshot, there is a different type of input field for IntegerField, BooleanField, etc. One can modify this using the following ways." }, { "code": null, "e": 2236, "s": 1951, "text": "One can override the default widget of each field for various purposes. The list of widgets can be seen here – Widgets | Django Documentation. To override the default widget we need to explicitly define the widget we want to assign to a field.Make following changes to geeks/forms.py," }, { "code": "from django import forms class GeeksForm(forms.Form): title = forms.CharField(widget = forms.Textarea) description = forms.CharField(widget = forms.CheckboxInput) views = forms.IntegerField(widget = forms.TextInput) available = forms.BooleanField(widget = forms.Textarea)", "e": 2521, "s": 2236, "text": null }, { "code": null, "e": 2791, "s": 2521, "text": "Now visit http://127.0.0.1:8000/,Thus we can assign, any widget to any field using widget attribute. Note – The validations imposed on fields would still remain same, for example even if an IntegerField is made the same as CharField, it will only accept Integer inputs." }, { "code": null, "e": 3018, "s": 2791, "text": "widgets have a great use in Form Fields especially using Select type of widgets where one wants to limit the type and number of inputs form a user. Let’s demonstrate this with help of modifying DateField. Consider forms.py as," }, { "code": "from django import forms class GeeksForm(forms.Form): title = forms.CharField() description = forms.CharField() views = forms.IntegerField() date = forms.DateField()", "e": 3197, "s": 3018, "text": null }, { "code": null, "e": 3258, "s": 3197, "text": "By default, DateField as widget TextInput. It can be seen as" }, { "code": null, "e": 3386, "s": 3258, "text": "Now let’s change the widget for better and convenient input from user of a date. Add SelectDateWidget to DateField in forms.py," }, { "code": "from django import forms class GeeksForm(forms.Form): title = forms.CharField() description = forms.CharField() views = forms.IntegerField() date = forms.DateField(widget = forms.SelectDateWidget)", "e": 3596, "s": 3386, "text": null }, { "code": null, "e": 3757, "s": 3596, "text": "Now input of date can be seen as very easy and helpful in the front end of the application. This way we can use multiple widgets for modifying the input fields." }, { "code": null, "e": 3770, "s": 3757, "text": "Django-forms" }, { "code": null, "e": 3784, "s": 3770, "text": "Python Django" }, { "code": null, "e": 3791, "s": 3784, "text": "Python" } ]
Write a C macro PRINT(x) which prints x
13 May, 2022 At the first look, it seems that writing a C macro which prints its argument is child’s play. Following program should work i.e. it should print x c #define PRINT(x) (x)int main(){ printf("%s", PRINT(x)); return 0;} But it would issue compile error because the data type of x, which is taken as variable by the compiler, is unknown. Now it doesn’t look so obvious. Isn’t it? Guess what, the followings also won’t work c #define PRINT(x) ('x')#define PRINT(x) ("x") But if we know one of the lesser known traits of C language, writing such a macro is really a child’s play. In C, there’s a # directive, also called ‘Stringizing Operator’, which does this magic. Basically # directive converts its argument in a string. Voila! it is so simple to do the rest. So the above program can be modified as below. c #include <stdio.h>#define PRINT(x) (#x)int main(){ printf("%s", PRINT(x)); return 0;} Now if the input is PRINT(x), it would print x. In fact, if the input is PRINT(geeks), it would print geeks. You may find the details of this directive from Microsoft portal here. mdsaif0405 C Macro C-Macro & Preprocessor c-puzzle C Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n13 May, 2022" }, { "code": null, "e": 201, "s": 52, "text": "At the first look, it seems that writing a C macro which prints its argument is child’s play. Following program should work i.e. it should print x " }, { "code": null, "e": 203, "s": 201, "text": "c" }, { "code": "#define PRINT(x) (x)int main(){ printf(\"%s\", PRINT(x)); return 0;}", "e": 276, "s": 203, "text": null }, { "code": null, "e": 479, "s": 276, "text": "But it would issue compile error because the data type of x, which is taken as variable by the compiler, is unknown. Now it doesn’t look so obvious. Isn’t it? Guess what, the followings also won’t work " }, { "code": null, "e": 481, "s": 479, "text": "c" }, { "code": "#define PRINT(x) ('x')#define PRINT(x) (\"x\")", "e": 526, "s": 481, "text": null }, { "code": null, "e": 867, "s": 526, "text": "But if we know one of the lesser known traits of C language, writing such a macro is really a child’s play. In C, there’s a # directive, also called ‘Stringizing Operator’, which does this magic. Basically # directive converts its argument in a string. Voila! it is so simple to do the rest. So the above program can be modified as below. " }, { "code": null, "e": 869, "s": 867, "text": "c" }, { "code": "#include <stdio.h>#define PRINT(x) (#x)int main(){ printf(\"%s\", PRINT(x)); return 0;}", "e": 961, "s": 869, "text": null }, { "code": null, "e": 1141, "s": 961, "text": "Now if the input is PRINT(x), it would print x. In fact, if the input is PRINT(geeks), it would print geeks. You may find the details of this directive from Microsoft portal here." }, { "code": null, "e": 1152, "s": 1141, "text": "mdsaif0405" }, { "code": null, "e": 1160, "s": 1152, "text": "C Macro" }, { "code": null, "e": 1183, "s": 1160, "text": "C-Macro & Preprocessor" }, { "code": null, "e": 1192, "s": 1183, "text": "c-puzzle" }, { "code": null, "e": 1203, "s": 1192, "text": "C Language" } ]
Finding Network ID of a Subnet (using Subnet Mask)
08 Aug, 2019 In order to find network id (NID) of a Subnet, one must be fully acquainted with the Subnet mask. Subnet Mask:It is used to find which IP address belongs to which Subnet. It is a 32 bit number, containing 0’s and 1’s. Here network id part and Subnet ID part is represented by all 1’s and host ID part is represented by all 0’s. Example:If Network id of a entire network = 193.1.2.0 (it is class C IP). For more about class C IP see Classful Addressing. In the above diagram entire network is divided into four parts, which means there are four subnets each having two bits for Subnet ID part. Subnet-1: 193.1.2.0 to 193.1.2.63 Subnet-2: 193.1.2.64 to 193.1.2.127 Subnet-3: 193.1.2.128 to 193.1.2.191 Subnet-4: 193.1.2.192 to 193.1.2.255 The above IP is class C, so it has 24 bits in network id part and 8 bits in host id part but you choose two bits for subnet id from host id part, so now there are two bits in subnet id part and six bits in host id part, i.e., 24 bits in network id + 2 bits in subnet id = 26 (1's) and 6 bits in host id = 6 (0's) Therefore, Subnet Mask = 11111111.11111111.11111111.11000000 = 255.255.255.192 If any given IP address performs bit wise AND operation with the subnet mask, then you get the network id of the subnet to which the given IP belongs.Example-1: If IP address = 193.1.2.129 (convert it into binary form) = 11000001.00000001.00000010.10000001 Subnet mask = 11111111.11111111.11111111.11000000 Bit Wise AND = 11000001.00000001.00000010.10000000 Therefore, Nid = 193.1.2.128 Hence, this IP address belongs to subnet:3 which has Nid = 193.1.2.128Example-2: If IP address = 193.1.2.67 (convert it into binary form) = 11000001.00000001.00000010.01000011 Subnet Mask = 11111111.11111111.11111111.11000000 Bit Wise AND = 11000001.00000001.00000010.01000000 Therefore, Nid = 193.1.2.64 Hence, this IP address belongs to subnet:2 which has Nid = 193.1.2.64 Computer Networks GATE CS Computer Networks Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Types of Network Topology RSA Algorithm in Cryptography TCP Server-Client implementation in C Socket Programming in Python GSM in Wireless Communication ACID Properties in DBMS Types of Operating Systems Normal Forms in DBMS Page Replacement Algorithms in Operating Systems Introduction of Operating System - Set 1
[ { "code": null, "e": 53, "s": 25, "text": "\n08 Aug, 2019" }, { "code": null, "e": 151, "s": 53, "text": "In order to find network id (NID) of a Subnet, one must be fully acquainted with the Subnet mask." }, { "code": null, "e": 381, "s": 151, "text": "Subnet Mask:It is used to find which IP address belongs to which Subnet. It is a 32 bit number, containing 0’s and 1’s. Here network id part and Subnet ID part is represented by all 1’s and host ID part is represented by all 0’s." }, { "code": null, "e": 506, "s": 381, "text": "Example:If Network id of a entire network = 193.1.2.0 (it is class C IP). For more about class C IP see Classful Addressing." }, { "code": null, "e": 646, "s": 506, "text": "In the above diagram entire network is divided into four parts, which means there are four subnets each having two bits for Subnet ID part." }, { "code": null, "e": 791, "s": 646, "text": "Subnet-1: 193.1.2.0 to 193.1.2.63\nSubnet-2: 193.1.2.64 to 193.1.2.127\nSubnet-3: 193.1.2.128 to 193.1.2.191\nSubnet-4: 193.1.2.192 to 193.1.2.255 " }, { "code": null, "e": 1017, "s": 791, "text": "The above IP is class C, so it has 24 bits in network id part and 8 bits in host id part but you choose two bits for subnet id from host id part, so now there are two bits in subnet id part and six bits in host id part, i.e.," }, { "code": null, "e": 1105, "s": 1017, "text": "24 bits in network id + 2 bits in subnet id = 26 (1's) and\n6 bits in host id = 6 (0's) " }, { "code": null, "e": 1116, "s": 1105, "text": "Therefore," }, { "code": null, "e": 1201, "s": 1116, "text": "Subnet Mask = 11111111.11111111.11111111.11000000\n = 255.255.255.192" }, { "code": null, "e": 1362, "s": 1201, "text": "If any given IP address performs bit wise AND operation with the subnet mask, then you get the network id of the subnet to which the given IP belongs.Example-1:" }, { "code": null, "e": 1605, "s": 1362, "text": "If IP address = 193.1.2.129 (convert it into binary form)\n = 11000001.00000001.00000010.10000001\nSubnet mask = 11111111.11111111.11111111.11000000\nBit Wise AND = 11000001.00000001.00000010.10000000\nTherefore, Nid = 193.1.2.128" }, { "code": null, "e": 1686, "s": 1605, "text": "Hence, this IP address belongs to subnet:3 which has Nid = 193.1.2.128Example-2:" }, { "code": null, "e": 1927, "s": 1686, "text": "If IP address = 193.1.2.67 (convert it into binary form)\n = 11000001.00000001.00000010.01000011\nSubnet Mask = 11111111.11111111.11111111.11000000\nBit Wise AND = 11000001.00000001.00000010.01000000\nTherefore, Nid = 193.1.2.64" }, { "code": null, "e": 1997, "s": 1927, "text": "Hence, this IP address belongs to subnet:2 which has Nid = 193.1.2.64" }, { "code": null, "e": 2015, "s": 1997, "text": "Computer Networks" }, { "code": null, "e": 2023, "s": 2015, "text": "GATE CS" }, { "code": null, "e": 2041, "s": 2023, "text": "Computer Networks" }, { "code": null, "e": 2139, "s": 2041, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2165, "s": 2139, "text": "Types of Network Topology" }, { "code": null, "e": 2195, "s": 2165, "text": "RSA Algorithm in Cryptography" }, { "code": null, "e": 2233, "s": 2195, "text": "TCP Server-Client implementation in C" }, { "code": null, "e": 2262, "s": 2233, "text": "Socket Programming in Python" }, { "code": null, "e": 2292, "s": 2262, "text": "GSM in Wireless Communication" }, { "code": null, "e": 2316, "s": 2292, "text": "ACID Properties in DBMS" }, { "code": null, "e": 2343, "s": 2316, "text": "Types of Operating Systems" }, { "code": null, "e": 2364, "s": 2343, "text": "Normal Forms in DBMS" }, { "code": null, "e": 2413, "s": 2364, "text": "Page Replacement Algorithms in Operating Systems" } ]
Global Variable in Ruby
25 Sep, 2019 Global Variable has global scope and accessible from anywhere in the program. Assigning to global variables from any point in the program has global implications. Global variable are always prefixed with a dollar sign ($). If we want to have a single variable, which is available across classes, we need to define a global variable. By default, an uninitialized global variable has a nil value and its use can cause the programs to be cryptic and complex. Global variable can be change anywhere in program.Syntax : $global_variable = 5 Example : # Ruby Program to understand Global Variable # global variable $global_variable = 10 # Defining classclass Class1 def print_global puts "Global variable in Class1 is #$global_variable" endend # Defining Another Classclass Class2 def print_global puts "Global variable in Class2 is #$global_variable" endend # Creating objectclass1obj = Class1.newclass1obj.print_global # Creating another objectclass2obj = Class2.newclass2obj.print_global Output : Global variable in Class1 is 10 Global variable in Class2 is 10 In above example, a global variable define whose value is 10. This global variable can be access anywhere in the program.Example : # Ruby Program to understand global variable $global_variable1 = "GFG" # Defining Classclass Author def instance_method puts "global vars can be used everywhere. See? #{$global_variable1}, #{$another_global_var}" end def self.class_method $another_global_var = "Welcome to GeeksForGeeks" puts "global vars can be used everywhere. See? #{$global_variable1}" endend Author.class_method# "global vars can be used everywhere. See? GFG"# => "global vars can be used everywhere. See? GFG" Author = Author.newAuthor.instance_method# "global vars can be used everywhere. See? # GFG, Welcome to GeeksForGeeks"# => "global vars can be used everywhere. See?# GFG, Welcome to GeeksForGeeks" Output : global vars can be used everywhere. See? GFG global vars can be used everywhere. See? GFG, Welcome to GeeksForGeeks In above example, We define two global variable in a class. we create a object of class Author than call method. Ruby-Basics Ruby Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n25 Sep, 2019" }, { "code": null, "e": 543, "s": 28, "text": "Global Variable has global scope and accessible from anywhere in the program. Assigning to global variables from any point in the program has global implications. Global variable are always prefixed with a dollar sign ($). If we want to have a single variable, which is available across classes, we need to define a global variable. By default, an uninitialized global variable has a nil value and its use can cause the programs to be cryptic and complex. Global variable can be change anywhere in program.Syntax :" }, { "code": null, "e": 564, "s": 543, "text": "$global_variable = 5" }, { "code": null, "e": 574, "s": 564, "text": "Example :" }, { "code": "# Ruby Program to understand Global Variable # global variable $global_variable = 10 # Defining classclass Class1 def print_global puts \"Global variable in Class1 is #$global_variable\" endend # Defining Another Classclass Class2 def print_global puts \"Global variable in Class2 is #$global_variable\" endend # Creating objectclass1obj = Class1.newclass1obj.print_global # Creating another objectclass2obj = Class2.newclass2obj.print_global ", "e": 1024, "s": 574, "text": null }, { "code": null, "e": 1033, "s": 1024, "text": "Output :" }, { "code": null, "e": 1097, "s": 1033, "text": "Global variable in Class1 is 10\nGlobal variable in Class2 is 10" }, { "code": null, "e": 1228, "s": 1097, "text": "In above example, a global variable define whose value is 10. This global variable can be access anywhere in the program.Example :" }, { "code": "# Ruby Program to understand global variable $global_variable1 = \"GFG\" # Defining Classclass Author def instance_method puts \"global vars can be used everywhere. See? #{$global_variable1}, #{$another_global_var}\" end def self.class_method $another_global_var = \"Welcome to GeeksForGeeks\" puts \"global vars can be used everywhere. See? #{$global_variable1}\" endend Author.class_method# \"global vars can be used everywhere. See? GFG\"# => \"global vars can be used everywhere. See? GFG\" Author = Author.newAuthor.instance_method# \"global vars can be used everywhere. See? # GFG, Welcome to GeeksForGeeks\"# => \"global vars can be used everywhere. See?# GFG, Welcome to GeeksForGeeks\"", "e": 1923, "s": 1228, "text": null }, { "code": null, "e": 1932, "s": 1923, "text": "Output :" }, { "code": null, "e": 2048, "s": 1932, "text": "global vars can be used everywhere. See? GFG\nglobal vars can be used everywhere. See? GFG, Welcome to GeeksForGeeks" }, { "code": null, "e": 2161, "s": 2048, "text": "In above example, We define two global variable in a class. we create a object of class Author than call method." }, { "code": null, "e": 2173, "s": 2161, "text": "Ruby-Basics" }, { "code": null, "e": 2178, "s": 2173, "text": "Ruby" } ]
outtext() function in C
06 Dec, 2019 The header file graphics.h contains outtext() function which displays text at current position. Syntax : void outtext(char *string); Examples : Input : string = "Hello Geek, Have a good day !" Output : Input : string = "GeeksforGeeks is the best !" Output : Note : Do not use text mode functions like printf while working in graphics mode. Ensure that the text doesn’t go beyond the screen while using outtext. Below is the implementation for outtext() function: // C Implementation for outtext()#include <graphics.h> // driver codeint main(){ // gm is Graphics mode which is // a computer display mode that // generates image using pixels. // DETECT is a macro defined in // "graphics.h" header file int gd = DETECT, gm; // initgraph initializes the // graphics system by loading a // graphics driver from disk initgraph(&gd, &gm, ""); // outtext function outtext("Hello Geek, Have a good day !"); getch(); // closegraph function closes the // graphics mode and deallocates // all memory allocated by // graphics system . closegraph(); return 0;} Output : Akanksha_Rai c-graphics computer-graphics C Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Unordered Sets in C++ Standard Template Library What is the purpose of a function prototype? Operators in C / C++ Exception Handling in C++ TCP Server-Client implementation in C Smart Pointers in C++ and How to Use Them 'this' pointer in C++ Ways to copy a vector in C++ Storage Classes in C Understanding "extern" keyword in C
[ { "code": null, "e": 54, "s": 26, "text": "\n06 Dec, 2019" }, { "code": null, "e": 150, "s": 54, "text": "The header file graphics.h contains outtext() function which displays text at current position." }, { "code": null, "e": 159, "s": 150, "text": "Syntax :" }, { "code": null, "e": 188, "s": 159, "text": "void outtext(char *string);\n" }, { "code": null, "e": 199, "s": 188, "text": "Examples :" }, { "code": null, "e": 318, "s": 199, "text": "Input : string = \"Hello Geek, Have a good day !\"\nOutput : \n\nInput : string = \"GeeksforGeeks is the best !\"\nOutput : \n" }, { "code": null, "e": 471, "s": 318, "text": "Note : Do not use text mode functions like printf while working in graphics mode. Ensure that the text doesn’t go beyond the screen while using outtext." }, { "code": null, "e": 523, "s": 471, "text": "Below is the implementation for outtext() function:" }, { "code": "// C Implementation for outtext()#include <graphics.h> // driver codeint main(){ // gm is Graphics mode which is // a computer display mode that // generates image using pixels. // DETECT is a macro defined in // \"graphics.h\" header file int gd = DETECT, gm; // initgraph initializes the // graphics system by loading a // graphics driver from disk initgraph(&gd, &gm, \"\"); // outtext function outtext(\"Hello Geek, Have a good day !\"); getch(); // closegraph function closes the // graphics mode and deallocates // all memory allocated by // graphics system . closegraph(); return 0;}", "e": 1176, "s": 523, "text": null }, { "code": null, "e": 1185, "s": 1176, "text": "Output :" }, { "code": null, "e": 1200, "s": 1187, "text": "Akanksha_Rai" }, { "code": null, "e": 1211, "s": 1200, "text": "c-graphics" }, { "code": null, "e": 1229, "s": 1211, "text": "computer-graphics" }, { "code": null, "e": 1240, "s": 1229, "text": "C Language" }, { "code": null, "e": 1338, "s": 1240, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1386, "s": 1338, "text": "Unordered Sets in C++ Standard Template Library" }, { "code": null, "e": 1431, "s": 1386, "text": "What is the purpose of a function prototype?" }, { "code": null, "e": 1452, "s": 1431, "text": "Operators in C / C++" }, { "code": null, "e": 1478, "s": 1452, "text": "Exception Handling in C++" }, { "code": null, "e": 1516, "s": 1478, "text": "TCP Server-Client implementation in C" }, { "code": null, "e": 1558, "s": 1516, "text": "Smart Pointers in C++ and How to Use Them" }, { "code": null, "e": 1580, "s": 1558, "text": "'this' pointer in C++" }, { "code": null, "e": 1609, "s": 1580, "text": "Ways to copy a vector in C++" }, { "code": null, "e": 1630, "s": 1609, "text": "Storage Classes in C" } ]
MYBATIS - Update Operation
We discussed, in the last chapter, how to perform READ operation on a table using MyBatis. This chapter explains how you can update records in a table using it. We have the following STUDENT table in MySQL − CREATE TABLE details.student( ID int(10) NOT NULL AUTO_INCREMENT, NAME varchar(100) NOT NULL, BRANCH varchar(255) NOT NULL, PERCENTAGE int(3) NOT NULL, PHONE int(11) NOT NULL, EMAIL varchar(255) NOT NULL, PRIMARY KEY (`ID`) ); Assume this table has two record as follows − mysql> select * from STUDENT; +----+----------+--------+------------+-----------+--------------------+ | ID | NAME | BRANCH | PERCENTAGE | PHONE | EMAIL | +----+----------+--------+------------+-----------+--------------------+ | 1 | Mohammad | It | 80 | 984803322 | [email protected] | | 2 | shyam | It | 75 | 984800000 | [email protected] | +----+----------+--------+------------+-----------+--------------------+ To perform update operation, you would need to modify Student.java file as − public class Student { private int id; private String name; private String branch; private int percentage; private int phone; private String email; public Student(int id, String name, String branch, int percentage, int phone, String email) { super(); this.id = id; this.name = name; this.setBranch(branch); this.setPercentage(percentage); this.phone = phone; this.email = email; } public Student() {} public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getPhone() { return phone; } public void setPhone(int phone) { this.phone = phone; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getBranch() { return branch; } public void setBranch(String branch) { this.branch = branch; } public int getPercentage() { return percentage; } public void setPercentage(int percentage) { this.percentage = percentage; } public String toString(){ StringBuilder sb = new StringBuilder(); sb.append("Id = ").append(id).append(" - "); sb.append("Name = ").append(name).append(" - "); sb.append("Branch = ").append(branch).append(" - "); sb.append("Percentage = ").append(percentage).append(" - "); sb.append("Phone = ").append(phone).append(" - "); sb.append("Email = ").append(email); return sb.toString(); } } To define SQL mapping statement using MyBatis, we would add <update> tag in Student.xml and inside this tag definition, we would define an "id" which will be used in mybatisUpdate.java file for executing SQL UPDATE query on database. <?xml version = "1.0" encoding = "UTF-8"?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace = "Student"> <resultMap id = "result" type = "Student"> <result property = "id" column = "ID"/> <result property = "name" column = "NAME"/> <result property = "branch" column = "BRANCH"/> <result property = "percentage" column = "PERCENTAGE"/> <result property = "phone" column = "PHONE"/> <result property = "email" column = "EMAIL"/> </resultMap> <select id = "getById" parameterType = "int" resultMap = "result"> SELECT * FROM STUDENT WHERE ID = #{id}; </select> <update id = "update" parameterType = "Student"> UPDATE STUDENT SET NAME = #{name}, BRANCH = #{branch}, PERCENTAGE = #{percentage}, PHONE = #{phone}, EMAIL = #{email} WHERE ID = #{id}; </update> </mapper> This file has application level logic to update records into the Student table − import java.io.IOException; import java.io.Reader; import org.apache.ibatis.io.Resources; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; public class mybatisUpdate { public static void main(String args[]) throws IOException{ Reader reader = Resources.getResourceAsReader("SqlMapConfig.xml"); SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader); SqlSession session = sqlSessionFactory.openSession(); //select a particular student using id Student student = (Student) session.selectOne("Student.getById", 1); System.out.println("Current details of the student are" ); System.out.println(student.toString()); //Set new values to the mail and phone number of the student student.setEmail("[email protected]"); student.setPhone(90000000); //Update the student record session.update("Student.update",student); System.out.println("Record updated successfully"); session.commit(); session.close(); //verifying the record Student std = (Student) session.selectOne("Student.getById", 1); System.out.println("Details of the student after update operation" ); System.out.println(std.toString()); session.commit(); session.close(); } } Here are the steps to compile and run mybatisUpdate.java. Make sure, you have set PATH and CLASSPATH appropriately before proceeding for compilation and execution. Create Student.xml as shown above. Create Student.xml as shown above. Create SqlMapConfig.xml as shown in the MYBATIS - Configuration XML chapter of this tutorial. Create SqlMapConfig.xml as shown in the MYBATIS - Configuration XML chapter of this tutorial. Create Student.java as shown above and compile it. Create Student.java as shown above and compile it. Create mybatisUpdate.java as shown above and compile it. Create mybatisUpdate.java as shown above and compile it. Execute mybatisUpdate binary to run the program. Execute mybatisUpdate binary to run the program. You would get following result. You can see the details of a particular record initially, and that record would be updated in STUDENT table and later, you can also see the updated record. Current details of the student are Id = 1 - Name = Mohammad - Branch = It - Percentage = 80 - Phone = 984802233 - Email = [email protected] Record updated successfully Details of the student after update operation Id = 1 - Name = Mohammad - Branch = It - Percentage = 80 - Phone = 90000000 - Email = [email protected] If you check the STUDENT table, it should display the following result − mysql> select * from student; +----+----------+--------+------------+-----------+----------------------+ | ID | NAME | BRANCH | PERCENTAGE | PHONE | EMAIL | +----+----------+--------+------------+-----------+----------------------+ | 1 | Mohammad | It | 80 | 90000000 | [email protected] | | 2 | shyam | It | 75 | 984800000 | [email protected] | +----+----------+--------+------------+-----------+----------------------+ 2 rows in set (0.00 sec)
[ { "code": null, "e": 2166, "s": 2005, "text": "We discussed, in the last chapter, how to perform READ operation on a table using MyBatis. This chapter explains how you can update records in a table using it." }, { "code": null, "e": 2213, "s": 2166, "text": "We have the following STUDENT table in MySQL −" }, { "code": null, "e": 2462, "s": 2213, "text": "CREATE TABLE details.student(\n ID int(10) NOT NULL AUTO_INCREMENT,\n NAME varchar(100) NOT NULL,\n BRANCH varchar(255) NOT NULL,\n PERCENTAGE int(3) NOT NULL,\n PHONE int(11) NOT NULL,\n EMAIL varchar(255) NOT NULL,\n PRIMARY KEY (`ID`)\n);\n" }, { "code": null, "e": 2508, "s": 2462, "text": "Assume this table has two record as follows −" }, { "code": null, "e": 2977, "s": 2508, "text": "mysql> select * from STUDENT;\n+----+----------+--------+------------+-----------+--------------------+\n| ID | NAME | BRANCH | PERCENTAGE | PHONE | EMAIL |\n+----+----------+--------+------------+-----------+--------------------+\n| 1 | Mohammad | It | 80 | 984803322 | [email protected] |\n| 2 | shyam | It | 75 | 984800000 | [email protected] |\n+----+----------+--------+------------+-----------+--------------------+\n" }, { "code": null, "e": 3054, "s": 2977, "text": "To perform update operation, you would need to modify Student.java file as −" }, { "code": null, "e": 4750, "s": 3054, "text": "public class Student {\n\n private int id;\n private String name;\n private String branch;\n private int percentage;\n private int phone;\n private String email;\n\n public Student(int id, String name, String branch, int percentage, int phone, String email) {\n super();\n this.id = id;\n this.name = name;\n this.setBranch(branch);\n this.setPercentage(percentage);\n this.phone = phone;\n this.email = email;\n }\n\t\n public Student() {}\n\n public int getId() {\n return id;\n }\n\t\n public void setId(int id) {\n this.id = id;\n }\n\t\n public String getName() {\n return name;\n }\n\t\n public void setName(String name) {\n this.name = name;\n }\n\t\n public int getPhone() {\n return phone;\n }\n\t\n public void setPhone(int phone) {\n this.phone = phone;\n }\n\t\n public String getEmail() {\n return email;\n }\n\t\n public void setEmail(String email) {\n this.email = email;\n }\n\n public String getBranch() {\n return branch;\n }\n\n public void setBranch(String branch) {\n this.branch = branch;\n }\n\n public int getPercentage() {\n return percentage;\n }\n\n public void setPercentage(int percentage) {\n this.percentage = percentage;\n }\n\t\n public String toString(){\n StringBuilder sb = new StringBuilder();\n\t\t\n sb.append(\"Id = \").append(id).append(\" - \");\n sb.append(\"Name = \").append(name).append(\" - \");\n sb.append(\"Branch = \").append(branch).append(\" - \");\n sb.append(\"Percentage = \").append(percentage).append(\" - \");\n sb.append(\"Phone = \").append(phone).append(\" - \");\n sb.append(\"Email = \").append(email);\n\t\t\n return sb.toString();\n }\n\t\n}" }, { "code": null, "e": 4984, "s": 4750, "text": "To define SQL mapping statement using MyBatis, we would add <update> tag in Student.xml and inside this tag definition, we would define an \"id\" which will be used in mybatisUpdate.java file for executing SQL UPDATE query on database." }, { "code": null, "e": 5956, "s": 4984, "text": "<?xml version = \"1.0\" encoding = \"UTF-8\"?>\n\n<!DOCTYPE mapper PUBLIC \"-//mybatis.org//DTD Mapper 3.0//EN\" \"http://mybatis.org/dtd/mybatis-3-mapper.dtd\">\n\t\n<mapper namespace = \"Student\">\t\n <resultMap id = \"result\" type = \"Student\">\n <result property = \"id\" column = \"ID\"/>\n <result property = \"name\" column = \"NAME\"/>\n <result property = \"branch\" column = \"BRANCH\"/>\n <result property = \"percentage\" column = \"PERCENTAGE\"/>\n <result property = \"phone\" column = \"PHONE\"/>\n <result property = \"email\" column = \"EMAIL\"/>\n </resultMap>\n \n <select id = \"getById\" parameterType = \"int\" resultMap = \"result\">\n SELECT * FROM STUDENT WHERE ID = #{id};\n </select>\n \t\n <update id = \"update\" parameterType = \"Student\">\n UPDATE STUDENT SET NAME = #{name}, \n BRANCH = #{branch}, \n PERCENTAGE = #{percentage}, \n PHONE = #{phone}, \n EMAIL = #{email} \n WHERE ID = #{id};\n </update>\n \t\n</mapper>" }, { "code": null, "e": 6037, "s": 5956, "text": "This file has application level logic to update records into the Student table −" }, { "code": null, "e": 7497, "s": 6037, "text": "import java.io.IOException;\nimport java.io.Reader;\n\nimport org.apache.ibatis.io.Resources;\nimport org.apache.ibatis.session.SqlSession;\nimport org.apache.ibatis.session.SqlSessionFactory;\nimport org.apache.ibatis.session.SqlSessionFactoryBuilder;\n\npublic class mybatisUpdate { \n\n public static void main(String args[]) throws IOException{\n \n Reader reader = Resources.getResourceAsReader(\"SqlMapConfig.xml\");\n SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);\t\t\n SqlSession session = sqlSessionFactory.openSession();\n \n //select a particular student using id\t\t\n Student student = (Student) session.selectOne(\"Student.getById\", 1);\n System.out.println(\"Current details of the student are\" );\n System.out.println(student.toString()); \n \n //Set new values to the mail and phone number of the student\n student.setEmail(\"[email protected]\");\n student.setPhone(90000000);\n \n //Update the student record\n session.update(\"Student.update\",student);\n System.out.println(\"Record updated successfully\"); \n session.commit(); \n session.close();\t \n\t \n //verifying the record \n Student std = (Student) session.selectOne(\"Student.getById\", 1);\n System.out.println(\"Details of the student after update operation\" );\n System.out.println(std.toString()); \n session.commit(); \n session.close();\n\t\t\t\n }\n}" }, { "code": null, "e": 7661, "s": 7497, "text": "Here are the steps to compile and run mybatisUpdate.java. Make sure, you have set PATH and CLASSPATH appropriately before proceeding for compilation and execution." }, { "code": null, "e": 7696, "s": 7661, "text": "Create Student.xml as shown above." }, { "code": null, "e": 7731, "s": 7696, "text": "Create Student.xml as shown above." }, { "code": null, "e": 7825, "s": 7731, "text": "Create SqlMapConfig.xml as shown in the MYBATIS - Configuration XML chapter of this tutorial." }, { "code": null, "e": 7919, "s": 7825, "text": "Create SqlMapConfig.xml as shown in the MYBATIS - Configuration XML chapter of this tutorial." }, { "code": null, "e": 7970, "s": 7919, "text": "Create Student.java as shown above and compile it." }, { "code": null, "e": 8021, "s": 7970, "text": "Create Student.java as shown above and compile it." }, { "code": null, "e": 8078, "s": 8021, "text": "Create mybatisUpdate.java as shown above and compile it." }, { "code": null, "e": 8135, "s": 8078, "text": "Create mybatisUpdate.java as shown above and compile it." }, { "code": null, "e": 8184, "s": 8135, "text": "Execute mybatisUpdate binary to run the program." }, { "code": null, "e": 8233, "s": 8184, "text": "Execute mybatisUpdate binary to run the program." }, { "code": null, "e": 8421, "s": 8233, "text": "You would get following result. You can see the details of a particular record initially, and that record would be updated in STUDENT table and later, you can also see the updated record." }, { "code": null, "e": 8744, "s": 8421, "text": "Current details of the student are\nId = 1 - Name = Mohammad - Branch = It - Percentage = 80 - Phone = 984802233 - Email = [email protected]\nRecord updated successfully\nDetails of the student after update operation\nId = 1 - Name = Mohammad - Branch = It - Percentage = 80 - Phone = 90000000 - Email = [email protected]\n" }, { "code": null, "e": 8817, "s": 8744, "text": "If you check the STUDENT table, it should display the following result −" } ]
Reverse Cuthill Mckee Algorithm
09 Apr, 2022 The Cuthill-Mckee algorithm is used for reordering of a symmetric square matrix. It is based on Breadth First Search algorithm of a graph, whose adjacency matrix is the sparsified version of the input square matrix.The ordering is frequently used when a matrix is to be generated whose rows and columns are numbered according to the numbering of the nodes. By an appropriate renumbering of the nodes, it is often possible to produce a matrix with a much smaller bandwidth. Sparsified version of a matrix is a matrix in which most of the elements are zero.The Reverse Cuthill-Mckee Algorithm is the same as the Cuthill-Mckee algorithm, the only difference is that the final indices obtained using the Cuthill-Mckee algorithm are reversed in the Reverse Cuthill-Mckee Algorithm. Below are the steps of Reverse Cuthill-Mckee algorithm: Instantiate an empty queue Q and empty array for permutation order of the objects R.S1: We first find the object with minimum degree whose index has not yet been added to R. Say, object corresponding to pth row has been identified as the object with a minimum degree. Add p to R.S2: As an index is added to R, and add all neighbors of the corresponding object at the index, in increasing order of degree, to Q. The neighbors are nodes with non-zero value amongst the non-diagonal elements in the pth row.S3: Extract the first node in Q, say C. If C has not been inserted in R, add it to R, add to Q the neighbors of C in increasing order of degree.S4: If Q is not empty, repeat S3.S5: If Q is empty, but there are objects in the matrix which have not been included in R, start from S1, once again. (This could happen if there are disjoint graphs)S6: Terminate this algorithm once all objects are included in R.S7: Finally, reverse the indices in R, i.e. (swap(R[i], R[P-i+1])). Instantiate an empty queue Q and empty array for permutation order of the objects R. S1: We first find the object with minimum degree whose index has not yet been added to R. Say, object corresponding to pth row has been identified as the object with a minimum degree. Add p to R. S2: As an index is added to R, and add all neighbors of the corresponding object at the index, in increasing order of degree, to Q. The neighbors are nodes with non-zero value amongst the non-diagonal elements in the pth row. S3: Extract the first node in Q, say C. If C has not been inserted in R, add it to R, add to Q the neighbors of C in increasing order of degree. S4: If Q is not empty, repeat S3. S5: If Q is empty, but there are objects in the matrix which have not been included in R, start from S1, once again. (This could happen if there are disjoint graphs) S6: Terminate this algorithm once all objects are included in R. S7: Finally, reverse the indices in R, i.e. (swap(R[i], R[P-i+1])). Degree: Definition of a degree is not constant, it changes according to the dataset you are working with. For the example given below, the degree of a node is defined as the sum of non-diagonal elements in the corresponding row. Generalized definition of the degree of a node ‘A’ is the number of nodes connected to ‘A’. Example: Given a symmetric matrix: | 0.0 0.78 0.79 0.8 0.23 | | 0.9 0.0 0.43 0.771 0.752 | | 0.82 0.0 0.0 0.79 0.34 | | 0.8 0.8 0.8 0.0 0.8 | | 0.54 0.97 0.12 0.78 0.0 | Degree here is defined as sum of non-diagonal elements in the corresponding row. Specification for a matrix is defined as, if the element of the matrix at i, j has a value less than 0.75 its made to 0 otherwise its made to 1. Matrix after Specification: Degree of node 0 = 2.6 Degree of node 1 = 2.803 Degree of node 2 = 2.55 Degree of node 3 = 3.2 Degree of node 4 = 2.41 Permutation order of objects (R) : 0 2 1 3 4 The new permutation order is just the ordering of the nodes, i.e. convert node ‘R[i]’ to node ‘i’. Therefore, convert node ‘R[0] = 0’, to 0; node ‘R[1] = 2’, to 1; node ‘R[2] = 1’, to 2; node ‘R[3] = 3’, to 3; and node ‘R[4] = 4’, to 4;Let’s take a bigger example to understand the result of the reordering: Give a adjacency matrix : | 0 1 0 0 0 0 1 0 1 0 | | 1 0 0 0 1 0 1 0 0 1 | | 0 0 0 0 1 0 1 0 0 0 | | 0 0 0 0 1 1 0 0 1 0 | | 0 1 1 1 0 1 0 0 0 1 | | 0 0 0 1 1 0 0 0 0 0 | | 1 1 1 0 0 0 0 0 0 0 | | 0 0 0 0 0 0 0 0 1 1 | | 1 0 0 1 0 0 0 1 0 0 | | 0 1 0 0 1 0 0 1 0 0 | Degree of node 'A' is defined as number of nodes connected to 'A' Output : Permutation order of objects (R) : 7 8 9 3 5 1 0 4 6 2 Now convert node ‘R[i]’ to node ‘i’ So the graph becomes: The result of reordering can be seen by the adjacency matrix of the two graph: Original Matrix RCM Reordered Matrix From here we can clearly see that how the Cuthill-Mckee algorithm helps in the reordering of a square matrix into a non-distributed matrix. Below is the implementation of the above algorithm. Taking the general definition of degree. C++ Python3 // C++ program for Implementation of// Reverse Cuthill Mckee Algorithm #include <bits/stdc++.h>using namespace std; vector<double> globalDegree; int findIndex(vector<pair<int, double> > a, int x){ for (int i = 0; i < a.size(); i++) if (a[i].first == x) return i; return -1;} bool compareDegree(int i, int j){ return ::globalDegree[i] < ::globalDegree[j];} template <typename T>ostream& operator<<(ostream& out, vector<T> const& v){ for (int i = 0; i < v.size(); i++) out << v[i] << ' '; return out;} class ReorderingSSM {private: vector<vector<double> > _matrix; public: // Constructor and Destructor ReorderingSSM(vector<vector<double> > m) { _matrix = m; } ReorderingSSM() {} ~ReorderingSSM() {} // class methods // Function to generate degree of all the nodes vector<double> degreeGenerator() { vector<double> degrees; for (int i = 0; i < _matrix.size(); i++) { double count = 0; for (int j = 0; j < _matrix[0].size(); j++) { count += _matrix[i][j]; } degrees.push_back(count); } return degrees; } // Implementation of Cuthill-Mckee algorithm vector<int> CuthillMckee() { vector<double> degrees = degreeGenerator(); ::globalDegree = degrees; queue<int> Q; vector<int> R; vector<pair<int, double> > notVisited; for (int i = 0; i < degrees.size(); i++) notVisited.push_back(make_pair(i, degrees[i])); // Vector notVisited helps in running BFS // even when there are dijoind graphs while (notVisited.size()) { int minNodeIndex = 0; for (int i = 0; i < notVisited.size(); i++) if (notVisited[i].second < notVisited[minNodeIndex].second) minNodeIndex = i; Q.push(notVisited[minNodeIndex].first); notVisited.erase(notVisited.begin() + findIndex(notVisited, notVisited[Q.front()].first)); // Simple BFS while (!Q.empty()) { vector<int> toSort; for (int i = 0; i < _matrix[0].size(); i++) { if (i != Q.front() && _matrix[Q.front()][i] == 1 && findIndex(notVisited, i) != -1) { toSort.push_back(i); notVisited.erase(notVisited.begin() + findIndex(notVisited, i)); } } sort(toSort.begin(), toSort.end(), compareDegree); for (int i = 0; i < toSort.size(); i++) Q.push(toSort[i]); R.push_back(Q.front()); Q.pop(); } } return R; } // Implementation of reverse Cuthill-Mckee algorithm vector<int> ReverseCuthillMckee() { vector<int> cuthill = CuthillMckee(); int n = cuthill.size(); if (n % 2 == 0) n -= 1; n = n / 2; for (int i = 0; i <= n; i++) { int j = cuthill[cuthill.size() - 1 - i]; cuthill[cuthill.size() - 1 - i] = cuthill[i]; cuthill[i] = j; } return cuthill; }}; // Driver Codeint main(){ int num_rows = 10; vector<vector<double> > matrix; for (int i = 0; i < num_rows; i++) { vector<double> datai; for (int j = 0; j < num_rows; j++) datai.push_back(0.0); matrix.push_back(datai); } // This is the test graph, // check out the above graph photo matrix[0] = { 0, 1, 0, 0, 0, 0, 1, 0, 1, 0 }; matrix[1] = { 1, 0, 0, 0, 1, 0, 1, 0, 0, 1 }; matrix[2] = { 0, 0, 0, 0, 1, 0, 1, 0, 0, 0 }; matrix[3] = { 0, 0, 0, 0, 1, 1, 0, 0, 1, 0 }; matrix[4] = { 0, 1, 1, 1, 0, 1, 0, 0, 0, 1 }; matrix[5] = { 0, 0, 0, 1, 1, 0, 0, 0, 0, 0 }; matrix[6] = { 1, 1, 1, 0, 0, 0, 0, 0, 0, 0 }; matrix[7] = { 0, 0, 0, 0, 0, 0, 0, 0, 1, 1 }; matrix[8] = { 1, 0, 0, 1, 0, 0, 0, 1, 0, 0 }; matrix[9] = { 0, 1, 0, 0, 1, 0, 0, 1, 0, 0 }; ReorderingSSM m(matrix); vector<int> r = m.ReverseCuthillMckee(); cout << "Permutation order of objects: " << r << endl; return 0;} # C++ program for Implementation of# Reverse Cuthill Mckee Algorithmfrom collections import deque as Queue globalDegree = [] def findIndex(a, x): for i in range(len(a)): if a[i][0] == x: return i return -1 class ReorderingSSM: __matrix = [] # Constructor and Destructor def __init__(self, m): self.__matrix = m # class methods # Function to generate degree of all the nodes def degreeGenerator(self): degrees = [] for i in range(len(self.__matrix)): count = 0 for j in range(len(self.__matrix[0])): count += self.__matrix[i][j] degrees.append(count) return degrees # Implementation of Cuthill-Mckee algorithm def CuthillMckee(self): global globalDegree degrees = self.degreeGenerator() globalDegree = degrees Q = Queue() R = [] notVisited = [] for i in range(len(degrees)): notVisited.append((i, degrees[i])) # Vector notVisited helps in running BFS # even when there are dijoind graphs while len(notVisited): minNodeIndex = 0 for i in range(len(notVisited)): if notVisited[i][1] < notVisited[minNodeIndex][1]: minNodeIndex = i Q.append(notVisited[minNodeIndex][0]) notVisited.pop(findIndex(notVisited, notVisited[Q[0]][0])) # Simple BFS while Q: toSort = [] for i in range(len(self.__matrix[0])): if ( i != Q[0] and self.__matrix[Q[0]][i] == 1 and findIndex(notVisited, i) != -1 ): toSort.append(i) notVisited.pop(findIndex(notVisited, i)) toSort.sort(key=lambda x: globalDegree[x]) for i in range(len(toSort)): Q.append(toSort[i]) R.append(Q[0]) Q.popleft() return R # Implementation of reverse Cuthill-Mckee algorithm def ReverseCuthillMckee(self): cuthill = self.CuthillMckee() n = len(cuthill) if n % 2 == 0: n -= 1 n = n // 2 for i in range(n + 1): j = cuthill[len(cuthill) - 1 - i] cuthill[len(cuthill) - 1 - i] = cuthill[i] cuthill[i] = j return cuthill # Driver Codeif __name__ == "__main__": num_rows = 10 matrix = [[0.0] * num_rows for _ in range(num_rows)] # This is the test graph, # check out the above graph photo matrix[0] = [0, 1, 0, 0, 0, 0, 1, 0, 1, 0] matrix[1] = [1, 0, 0, 0, 1, 0, 1, 0, 0, 1] matrix[2] = [0, 0, 0, 0, 1, 0, 1, 0, 0, 0] matrix[3] = [0, 0, 0, 0, 1, 1, 0, 0, 1, 0] matrix[4] = [0, 1, 1, 1, 0, 1, 0, 0, 0, 1] matrix[5] = [0, 0, 0, 1, 1, 0, 0, 0, 0, 0] matrix[6] = [1, 1, 1, 0, 0, 0, 0, 0, 0, 0] matrix[7] = [0, 0, 0, 0, 0, 0, 0, 0, 1, 1] matrix[8] = [1, 0, 0, 1, 0, 0, 0, 1, 0, 0] matrix[9] = [0, 1, 0, 0, 1, 0, 0, 1, 0, 0] m = ReorderingSSM(matrix) r = m.ReverseCuthillMckee() print("Permutation order of objects:", r) Permutation order of objects: 7 8 9 3 5 1 0 4 6 2 Reference: https://en.wikipedia.org/wiki/Cuthill%E2%80%93McKee_algorithm gneogeo simranarora5sos as5853535 amartyaghoshgfg 000shobhitchaurasia Algorithms Queue Queue Algorithms Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. What is Hashing | A Complete Tutorial Find if there is a path between two vertices in an undirected graph How to Start Learning DSA? Complete Roadmap To Learn DSA From Scratch Types of Complexity Classes | P, NP, CoNP, NP hard and NP complete Breadth First Search or BFS for a Graph Level Order Binary Tree Traversal Queue in Python Queue Interface In Java Introduction to Data Structures
[ { "code": null, "e": 54, "s": 26, "text": "\n09 Apr, 2022" }, { "code": null, "e": 528, "s": 54, "text": "The Cuthill-Mckee algorithm is used for reordering of a symmetric square matrix. It is based on Breadth First Search algorithm of a graph, whose adjacency matrix is the sparsified version of the input square matrix.The ordering is frequently used when a matrix is to be generated whose rows and columns are numbered according to the numbering of the nodes. By an appropriate renumbering of the nodes, it is often possible to produce a matrix with a much smaller bandwidth. " }, { "code": null, "e": 832, "s": 528, "text": "Sparsified version of a matrix is a matrix in which most of the elements are zero.The Reverse Cuthill-Mckee Algorithm is the same as the Cuthill-Mckee algorithm, the only difference is that the final indices obtained using the Cuthill-Mckee algorithm are reversed in the Reverse Cuthill-Mckee Algorithm." }, { "code": null, "e": 889, "s": 832, "text": "Below are the steps of Reverse Cuthill-Mckee algorithm: " }, { "code": null, "e": 1867, "s": 889, "text": "Instantiate an empty queue Q and empty array for permutation order of the objects R.S1: We first find the object with minimum degree whose index has not yet been added to R. Say, object corresponding to pth row has been identified as the object with a minimum degree. Add p to R.S2: As an index is added to R, and add all neighbors of the corresponding object at the index, in increasing order of degree, to Q. The neighbors are nodes with non-zero value amongst the non-diagonal elements in the pth row.S3: Extract the first node in Q, say C. If C has not been inserted in R, add it to R, add to Q the neighbors of C in increasing order of degree.S4: If Q is not empty, repeat S3.S5: If Q is empty, but there are objects in the matrix which have not been included in R, start from S1, once again. (This could happen if there are disjoint graphs)S6: Terminate this algorithm once all objects are included in R.S7: Finally, reverse the indices in R, i.e. (swap(R[i], R[P-i+1]))." }, { "code": null, "e": 1952, "s": 1867, "text": "Instantiate an empty queue Q and empty array for permutation order of the objects R." }, { "code": null, "e": 2148, "s": 1952, "text": "S1: We first find the object with minimum degree whose index has not yet been added to R. Say, object corresponding to pth row has been identified as the object with a minimum degree. Add p to R." }, { "code": null, "e": 2374, "s": 2148, "text": "S2: As an index is added to R, and add all neighbors of the corresponding object at the index, in increasing order of degree, to Q. The neighbors are nodes with non-zero value amongst the non-diagonal elements in the pth row." }, { "code": null, "e": 2519, "s": 2374, "text": "S3: Extract the first node in Q, say C. If C has not been inserted in R, add it to R, add to Q the neighbors of C in increasing order of degree." }, { "code": null, "e": 2553, "s": 2519, "text": "S4: If Q is not empty, repeat S3." }, { "code": null, "e": 2719, "s": 2553, "text": "S5: If Q is empty, but there are objects in the matrix which have not been included in R, start from S1, once again. (This could happen if there are disjoint graphs)" }, { "code": null, "e": 2784, "s": 2719, "text": "S6: Terminate this algorithm once all objects are included in R." }, { "code": null, "e": 2852, "s": 2784, "text": "S7: Finally, reverse the indices in R, i.e. (swap(R[i], R[P-i+1]))." }, { "code": null, "e": 3081, "s": 2852, "text": "Degree: Definition of a degree is not constant, it changes according to the dataset you are working with. For the example given below, the degree of a node is defined as the sum of non-diagonal elements in the corresponding row." }, { "code": null, "e": 3174, "s": 3081, "text": "Generalized definition of the degree of a node ‘A’ is the number of nodes connected to ‘A’. " }, { "code": null, "e": 3184, "s": 3174, "text": "Example: " }, { "code": null, "e": 3648, "s": 3184, "text": "Given a symmetric matrix: \n| 0.0 0.78 0.79 0.8 0.23 |\n| 0.9 0.0 0.43 0.771 0.752 |\n| 0.82 0.0 0.0 0.79 0.34 |\n| 0.8 0.8 0.8 0.0 0.8 |\n| 0.54 0.97 0.12 0.78 0.0 | \n\nDegree here is defined as sum of non-diagonal \nelements in the corresponding row.\nSpecification for a matrix is defined as, \nif the element of the matrix at i, j has a value \nless than 0.75 its made to 0 otherwise its made to 1." }, { "code": null, "e": 3677, "s": 3648, "text": "Matrix after Specification: " }, { "code": null, "e": 3842, "s": 3677, "text": "Degree of node 0 = 2.6\nDegree of node 1 = 2.803\nDegree of node 2 = 2.55\nDegree of node 3 = 3.2\nDegree of node 4 = 2.41\n\nPermutation order of objects (R) : 0 2 1 3 4" }, { "code": null, "e": 4151, "s": 3842, "text": "The new permutation order is just the ordering of the nodes, i.e. convert node ‘R[i]’ to node ‘i’. Therefore, convert node ‘R[0] = 0’, to 0; node ‘R[1] = 2’, to 1; node ‘R[2] = 1’, to 2; node ‘R[3] = 3’, to 3; and node ‘R[4] = 4’, to 4;Let’s take a bigger example to understand the result of the reordering: " }, { "code": null, "e": 4669, "s": 4151, "text": "Give a adjacency matrix : \n\n| 0 1 0 0 0 0 1 0 1 0 |\n| 1 0 0 0 1 0 1 0 0 1 |\n| 0 0 0 0 1 0 1 0 0 0 |\n| 0 0 0 0 1 1 0 0 1 0 |\n| 0 1 1 1 0 1 0 0 0 1 | \n| 0 0 0 1 1 0 0 0 0 0 |\n| 1 1 1 0 0 0 0 0 0 0 |\n| 0 0 0 0 0 0 0 0 1 1 |\n| 1 0 0 1 0 0 0 1 0 0 |\n| 0 1 0 0 1 0 0 1 0 0 | \n\nDegree of node 'A' is defined as number of \nnodes connected to 'A'" }, { "code": null, "e": 4735, "s": 4669, "text": "Output : \nPermutation order of objects (R) : \n7 8 9 3 5 1 0 4 6 2" }, { "code": null, "e": 4795, "s": 4735, "text": "Now convert node ‘R[i]’ to node ‘i’ So the graph becomes: " }, { "code": null, "e": 4876, "s": 4795, "text": "The result of reordering can be seen by the adjacency matrix of the two graph: " }, { "code": null, "e": 4892, "s": 4876, "text": "Original Matrix" }, { "code": null, "e": 4913, "s": 4892, "text": "RCM Reordered Matrix" }, { "code": null, "e": 5053, "s": 4913, "text": "From here we can clearly see that how the Cuthill-Mckee algorithm helps in the reordering of a square matrix into a non-distributed matrix." }, { "code": null, "e": 5147, "s": 5053, "text": "Below is the implementation of the above algorithm. Taking the general definition of degree. " }, { "code": null, "e": 5151, "s": 5147, "text": "C++" }, { "code": null, "e": 5159, "s": 5151, "text": "Python3" }, { "code": "// C++ program for Implementation of// Reverse Cuthill Mckee Algorithm #include <bits/stdc++.h>using namespace std; vector<double> globalDegree; int findIndex(vector<pair<int, double> > a, int x){ for (int i = 0; i < a.size(); i++) if (a[i].first == x) return i; return -1;} bool compareDegree(int i, int j){ return ::globalDegree[i] < ::globalDegree[j];} template <typename T>ostream& operator<<(ostream& out, vector<T> const& v){ for (int i = 0; i < v.size(); i++) out << v[i] << ' '; return out;} class ReorderingSSM {private: vector<vector<double> > _matrix; public: // Constructor and Destructor ReorderingSSM(vector<vector<double> > m) { _matrix = m; } ReorderingSSM() {} ~ReorderingSSM() {} // class methods // Function to generate degree of all the nodes vector<double> degreeGenerator() { vector<double> degrees; for (int i = 0; i < _matrix.size(); i++) { double count = 0; for (int j = 0; j < _matrix[0].size(); j++) { count += _matrix[i][j]; } degrees.push_back(count); } return degrees; } // Implementation of Cuthill-Mckee algorithm vector<int> CuthillMckee() { vector<double> degrees = degreeGenerator(); ::globalDegree = degrees; queue<int> Q; vector<int> R; vector<pair<int, double> > notVisited; for (int i = 0; i < degrees.size(); i++) notVisited.push_back(make_pair(i, degrees[i])); // Vector notVisited helps in running BFS // even when there are dijoind graphs while (notVisited.size()) { int minNodeIndex = 0; for (int i = 0; i < notVisited.size(); i++) if (notVisited[i].second < notVisited[minNodeIndex].second) minNodeIndex = i; Q.push(notVisited[minNodeIndex].first); notVisited.erase(notVisited.begin() + findIndex(notVisited, notVisited[Q.front()].first)); // Simple BFS while (!Q.empty()) { vector<int> toSort; for (int i = 0; i < _matrix[0].size(); i++) { if (i != Q.front() && _matrix[Q.front()][i] == 1 && findIndex(notVisited, i) != -1) { toSort.push_back(i); notVisited.erase(notVisited.begin() + findIndex(notVisited, i)); } } sort(toSort.begin(), toSort.end(), compareDegree); for (int i = 0; i < toSort.size(); i++) Q.push(toSort[i]); R.push_back(Q.front()); Q.pop(); } } return R; } // Implementation of reverse Cuthill-Mckee algorithm vector<int> ReverseCuthillMckee() { vector<int> cuthill = CuthillMckee(); int n = cuthill.size(); if (n % 2 == 0) n -= 1; n = n / 2; for (int i = 0; i <= n; i++) { int j = cuthill[cuthill.size() - 1 - i]; cuthill[cuthill.size() - 1 - i] = cuthill[i]; cuthill[i] = j; } return cuthill; }}; // Driver Codeint main(){ int num_rows = 10; vector<vector<double> > matrix; for (int i = 0; i < num_rows; i++) { vector<double> datai; for (int j = 0; j < num_rows; j++) datai.push_back(0.0); matrix.push_back(datai); } // This is the test graph, // check out the above graph photo matrix[0] = { 0, 1, 0, 0, 0, 0, 1, 0, 1, 0 }; matrix[1] = { 1, 0, 0, 0, 1, 0, 1, 0, 0, 1 }; matrix[2] = { 0, 0, 0, 0, 1, 0, 1, 0, 0, 0 }; matrix[3] = { 0, 0, 0, 0, 1, 1, 0, 0, 1, 0 }; matrix[4] = { 0, 1, 1, 1, 0, 1, 0, 0, 0, 1 }; matrix[5] = { 0, 0, 0, 1, 1, 0, 0, 0, 0, 0 }; matrix[6] = { 1, 1, 1, 0, 0, 0, 0, 0, 0, 0 }; matrix[7] = { 0, 0, 0, 0, 0, 0, 0, 0, 1, 1 }; matrix[8] = { 1, 0, 0, 1, 0, 0, 0, 1, 0, 0 }; matrix[9] = { 0, 1, 0, 0, 1, 0, 0, 1, 0, 0 }; ReorderingSSM m(matrix); vector<int> r = m.ReverseCuthillMckee(); cout << \"Permutation order of objects: \" << r << endl; return 0;}", "e": 9468, "s": 5159, "text": null }, { "code": "# C++ program for Implementation of# Reverse Cuthill Mckee Algorithmfrom collections import deque as Queue globalDegree = [] def findIndex(a, x): for i in range(len(a)): if a[i][0] == x: return i return -1 class ReorderingSSM: __matrix = [] # Constructor and Destructor def __init__(self, m): self.__matrix = m # class methods # Function to generate degree of all the nodes def degreeGenerator(self): degrees = [] for i in range(len(self.__matrix)): count = 0 for j in range(len(self.__matrix[0])): count += self.__matrix[i][j] degrees.append(count) return degrees # Implementation of Cuthill-Mckee algorithm def CuthillMckee(self): global globalDegree degrees = self.degreeGenerator() globalDegree = degrees Q = Queue() R = [] notVisited = [] for i in range(len(degrees)): notVisited.append((i, degrees[i])) # Vector notVisited helps in running BFS # even when there are dijoind graphs while len(notVisited): minNodeIndex = 0 for i in range(len(notVisited)): if notVisited[i][1] < notVisited[minNodeIndex][1]: minNodeIndex = i Q.append(notVisited[minNodeIndex][0]) notVisited.pop(findIndex(notVisited, notVisited[Q[0]][0])) # Simple BFS while Q: toSort = [] for i in range(len(self.__matrix[0])): if ( i != Q[0] and self.__matrix[Q[0]][i] == 1 and findIndex(notVisited, i) != -1 ): toSort.append(i) notVisited.pop(findIndex(notVisited, i)) toSort.sort(key=lambda x: globalDegree[x]) for i in range(len(toSort)): Q.append(toSort[i]) R.append(Q[0]) Q.popleft() return R # Implementation of reverse Cuthill-Mckee algorithm def ReverseCuthillMckee(self): cuthill = self.CuthillMckee() n = len(cuthill) if n % 2 == 0: n -= 1 n = n // 2 for i in range(n + 1): j = cuthill[len(cuthill) - 1 - i] cuthill[len(cuthill) - 1 - i] = cuthill[i] cuthill[i] = j return cuthill # Driver Codeif __name__ == \"__main__\": num_rows = 10 matrix = [[0.0] * num_rows for _ in range(num_rows)] # This is the test graph, # check out the above graph photo matrix[0] = [0, 1, 0, 0, 0, 0, 1, 0, 1, 0] matrix[1] = [1, 0, 0, 0, 1, 0, 1, 0, 0, 1] matrix[2] = [0, 0, 0, 0, 1, 0, 1, 0, 0, 0] matrix[3] = [0, 0, 0, 0, 1, 1, 0, 0, 1, 0] matrix[4] = [0, 1, 1, 1, 0, 1, 0, 0, 0, 1] matrix[5] = [0, 0, 0, 1, 1, 0, 0, 0, 0, 0] matrix[6] = [1, 1, 1, 0, 0, 0, 0, 0, 0, 0] matrix[7] = [0, 0, 0, 0, 0, 0, 0, 0, 1, 1] matrix[8] = [1, 0, 0, 1, 0, 0, 0, 1, 0, 0] matrix[9] = [0, 1, 0, 0, 1, 0, 0, 1, 0, 0] m = ReorderingSSM(matrix) r = m.ReverseCuthillMckee() print(\"Permutation order of objects:\", r)", "e": 12677, "s": 9468, "text": null }, { "code": null, "e": 12728, "s": 12677, "text": "Permutation order of objects: 7 8 9 3 5 1 0 4 6 2 " }, { "code": null, "e": 12802, "s": 12728, "text": "Reference: https://en.wikipedia.org/wiki/Cuthill%E2%80%93McKee_algorithm " }, { "code": null, "e": 12810, "s": 12802, "text": "gneogeo" }, { "code": null, "e": 12826, "s": 12810, "text": "simranarora5sos" }, { "code": null, "e": 12836, "s": 12826, "text": "as5853535" }, { "code": null, "e": 12852, "s": 12836, "text": "amartyaghoshgfg" }, { "code": null, "e": 12872, "s": 12852, "text": "000shobhitchaurasia" }, { "code": null, "e": 12883, "s": 12872, "text": "Algorithms" }, { "code": null, "e": 12889, "s": 12883, "text": "Queue" }, { "code": null, "e": 12895, "s": 12889, "text": "Queue" }, { "code": null, "e": 12906, "s": 12895, "text": "Algorithms" }, { "code": null, "e": 13004, "s": 12906, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 13042, "s": 13004, "text": "What is Hashing | A Complete Tutorial" }, { "code": null, "e": 13110, "s": 13042, "text": "Find if there is a path between two vertices in an undirected graph" }, { "code": null, "e": 13137, "s": 13110, "text": "How to Start Learning DSA?" }, { "code": null, "e": 13180, "s": 13137, "text": "Complete Roadmap To Learn DSA From Scratch" }, { "code": null, "e": 13247, "s": 13180, "text": "Types of Complexity Classes | P, NP, CoNP, NP hard and NP complete" }, { "code": null, "e": 13287, "s": 13247, "text": "Breadth First Search or BFS for a Graph" }, { "code": null, "e": 13321, "s": 13287, "text": "Level Order Binary Tree Traversal" }, { "code": null, "e": 13337, "s": 13321, "text": "Queue in Python" }, { "code": null, "e": 13361, "s": 13337, "text": "Queue Interface In Java" } ]
Method Overloading and Ambiguity in Varargs in Java
03 Sep, 2018 Prerequisite – Varargs , Method Overloading Method Overloading in Varargs Overloading allows different methods to have same name, but different signatures where signature can differ by number of input parameters or type of input parameters or both. We can overload a method that takes a variable-length argument by following ways: Case 1 – Methods with only Varargs parameters: In this case, Java uses the type difference to determine which overloaded method to call. If one method signature is strictly more specific than the other, then Java chooses it without an error.//Java program to illustrate //method overloading in varargspublic class varargsDemo{ public static void main(String[] args) { fun(); } //varargs method with float datatype static void fun(float... x) { System.out.println("float varargs"); } //varargs method with int datatype static void fun(int... x) { System.out.println("int varargs"); } //varargs method with double datatype static void fun(double... x) { System.out.println("double varargs"); }}Output:int varargs This output is due to the fact that int is more specific than double. As specified in the JLS section 15.12.2.5, If more than one member method is both accessible and applicable to a method invocation, it is necessary to choose one to provide the descriptor for the run-time method dispatch. The Java programming language uses the rule that the most specific method is chosen according to type promotion. The following rules define the direct supertype relation among the primitive types in this case:double > floatfloat > longlong > intint > charint > shortshort > byte //Java program to illustrate //method overloading in varargspublic class varargsDemo{ public static void main(String[] args) { fun(); } //varargs method with float datatype static void fun(float... x) { System.out.println("float varargs"); } //varargs method with int datatype static void fun(int... x) { System.out.println("int varargs"); } //varargs method with double datatype static void fun(double... x) { System.out.println("double varargs"); }} Output: int varargs This output is due to the fact that int is more specific than double. As specified in the JLS section 15.12.2.5, If more than one member method is both accessible and applicable to a method invocation, it is necessary to choose one to provide the descriptor for the run-time method dispatch. The Java programming language uses the rule that the most specific method is chosen according to type promotion. The following rules define the direct supertype relation among the primitive types in this case: double > float float > long long > int int > char int > short short > byte Case 2 – Methods with Varargs alongwith other parameters In this case, Java uses both the number of arguments and the type of the arguments to determine which method to call.Below is the java program that overloads fun( ) method three times:// Java program to demonstrate Varargs // and overloading.class Test { // A method that takes varargs(here integers). static void fun(int ... a) { System.out.print("fun(int ...): " + "Number of args: " + a.length + " Contents: "); // using for each loop to display contents of a for(int x : a) System.out.print(x + " "); System.out.println(); } // A method that takes varargs(here booleans). static void fun(boolean ... a) { System.out.print("fun(boolean ...) " + "Number of args: " + a.length + " Contents: "); // using for each loop to display contents of a for(boolean x : a) System.out.print(x + " "); System.out.println(); } // A method takes string as a argument followed by varargs(here integers). static void fun(String msg, int ... a) { System.out.print("fun(String, int ...): " + msg + a.length + " Contents: "); // using for each loop to display contents of a for(int x : a) System.out.print(x + " "); System.out.println(); } public static void main(String args[]) { // Calling overloaded fun() with different parameter fun(1, 2, 3); fun("Testing: ", 10, 20); fun(true, false, false); }}Output:fun(int ...): Number of args: 3 Contents: 1 2 3 fun(String, int ...): Testing: 2 Contents: 10 20 fun(boolean ...) Number of args: 3 Contents: true false false Below is the java program that overloads fun( ) method three times: // Java program to demonstrate Varargs // and overloading.class Test { // A method that takes varargs(here integers). static void fun(int ... a) { System.out.print("fun(int ...): " + "Number of args: " + a.length + " Contents: "); // using for each loop to display contents of a for(int x : a) System.out.print(x + " "); System.out.println(); } // A method that takes varargs(here booleans). static void fun(boolean ... a) { System.out.print("fun(boolean ...) " + "Number of args: " + a.length + " Contents: "); // using for each loop to display contents of a for(boolean x : a) System.out.print(x + " "); System.out.println(); } // A method takes string as a argument followed by varargs(here integers). static void fun(String msg, int ... a) { System.out.print("fun(String, int ...): " + msg + a.length + " Contents: "); // using for each loop to display contents of a for(int x : a) System.out.print(x + " "); System.out.println(); } public static void main(String args[]) { // Calling overloaded fun() with different parameter fun(1, 2, 3); fun("Testing: ", 10, 20); fun(true, false, false); }} Output: fun(int ...): Number of args: 3 Contents: 1 2 3 fun(String, int ...): Testing: 2 Contents: 10 20 fun(boolean ...) Number of args: 3 Contents: true false false Varargs and Ambiguity Sometimes unexpected errors can result when overloading a method that takes a variable length argument. These errors involve ambiguity because both the methods are valid candidates for invocation. The compiler cannot decide onto which method to bind the method call. // Java program to illustrate Varargs and ambiguityclass Test { // A method that takes varargs(here integers). static void fun(int ... a) { System.out.print("fun(int ...): " + "Number of args: " + a.length + " Contents: "); // using for each loop to display contents of a for(int x : a) System.out.print(x + " "); System.out.println(); } // A method that takes varargs(here booleans). static void fun(boolean ... a) { System.out.print("fun(boolean ...) " + "Number of args: " + a.length + " Contents: "); // using for each loop to display contents of a for(boolean x : a) System.out.print(x + " "); System.out.println(); } public static void main(String args[]) { // Calling overloaded fun() with different parameter fun(1, 2, 3); //OK fun(true, false, false); //OK fun(); // Error: Ambiguous! }} In above program, the overloading of fun( ) is perfectly correct. However, this program will not compile because of the following call: fun(); // Error: Ambiguous! According to (JLS 15.2.2), there are 3 phases used in overload resolution: First phase performs overload resolution without permitting boxing or unboxing conversion, Second phase performs overload resolution while allowing boxing and unboxing and Third phase allows overloading to be combined with variable arity methods, boxing, and unboxing. If no applicable method is found during these phases, then ambiguity occurs.The call above could be translated into a call to fun(int ...) or fun(boolean ...). Both are equally valid and do not be resolved after all three phases of overload resolution because both the data types are different. Thus, the call is inherently ambiguous. Another example of ambiguity:The following overloaded versions of fun( )are inherently ambiguous: static void fun(int ... a) { // method body } static void fun(int n, int ... a) { //method body } Here, although the parameter lists of fun( ) differ, there is no way for the compiler to resolve the following call: fun(1) This call may resolve to fun(int ... a) or fun(int n, int ... a) method, thus creating ambiguity. To solve these ambiguity errors like above, we will need to forego overloading and simply use two different method names. This article is contributed by Gaurav Miglani. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. Java-Overloading Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n03 Sep, 2018" }, { "code": null, "e": 96, "s": 52, "text": "Prerequisite – Varargs , Method Overloading" }, { "code": null, "e": 126, "s": 96, "text": "Method Overloading in Varargs" }, { "code": null, "e": 383, "s": 126, "text": "Overloading allows different methods to have same name, but different signatures where signature can differ by number of input parameters or type of input parameters or both. We can overload a method that takes a variable-length argument by following ways:" }, { "code": null, "e": 1752, "s": 383, "text": "Case 1 – Methods with only Varargs parameters: In this case, Java uses the type difference to determine which overloaded method to call. If one method signature is strictly more specific than the other, then Java chooses it without an error.//Java program to illustrate //method overloading in varargspublic class varargsDemo{ public static void main(String[] args) { fun(); } //varargs method with float datatype static void fun(float... x) { System.out.println(\"float varargs\"); } //varargs method with int datatype static void fun(int... x) { System.out.println(\"int varargs\"); } //varargs method with double datatype static void fun(double... x) { System.out.println(\"double varargs\"); }}Output:int varargs\nThis output is due to the fact that int is more specific than double. As specified in the JLS section 15.12.2.5, If more than one member method is both accessible and applicable to a method invocation, it is necessary to choose one to provide the descriptor for the run-time method dispatch. The Java programming language uses the rule that the most specific method is chosen according to type promotion. The following rules define the direct supertype relation among the primitive types in this case:double > floatfloat > longlong > intint > charint > shortshort > byte" }, { "code": "//Java program to illustrate //method overloading in varargspublic class varargsDemo{ public static void main(String[] args) { fun(); } //varargs method with float datatype static void fun(float... x) { System.out.println(\"float varargs\"); } //varargs method with int datatype static void fun(int... x) { System.out.println(\"int varargs\"); } //varargs method with double datatype static void fun(double... x) { System.out.println(\"double varargs\"); }}", "e": 2291, "s": 1752, "text": null }, { "code": null, "e": 2299, "s": 2291, "text": "Output:" }, { "code": null, "e": 2312, "s": 2299, "text": "int varargs\n" }, { "code": null, "e": 2814, "s": 2312, "text": "This output is due to the fact that int is more specific than double. As specified in the JLS section 15.12.2.5, If more than one member method is both accessible and applicable to a method invocation, it is necessary to choose one to provide the descriptor for the run-time method dispatch. The Java programming language uses the rule that the most specific method is chosen according to type promotion. The following rules define the direct supertype relation among the primitive types in this case:" }, { "code": null, "e": 2829, "s": 2814, "text": "double > float" }, { "code": null, "e": 2842, "s": 2829, "text": "float > long" }, { "code": null, "e": 2853, "s": 2842, "text": "long > int" }, { "code": null, "e": 2864, "s": 2853, "text": "int > char" }, { "code": null, "e": 2876, "s": 2864, "text": "int > short" }, { "code": null, "e": 2889, "s": 2876, "text": "short > byte" }, { "code": null, "e": 4759, "s": 2889, "text": "Case 2 – Methods with Varargs alongwith other parameters In this case, Java uses both the number of arguments and the type of the arguments to determine which method to call.Below is the java program that overloads fun( ) method three times:// Java program to demonstrate Varargs // and overloading.class Test { // A method that takes varargs(here integers). static void fun(int ... a) { System.out.print(\"fun(int ...): \" + \"Number of args: \" + a.length + \" Contents: \"); // using for each loop to display contents of a for(int x : a) System.out.print(x + \" \"); System.out.println(); } // A method that takes varargs(here booleans). static void fun(boolean ... a) { System.out.print(\"fun(boolean ...) \" + \"Number of args: \" + a.length + \" Contents: \"); // using for each loop to display contents of a for(boolean x : a) System.out.print(x + \" \"); System.out.println(); } // A method takes string as a argument followed by varargs(here integers). static void fun(String msg, int ... a) { System.out.print(\"fun(String, int ...): \" + msg + a.length + \" Contents: \"); // using for each loop to display contents of a for(int x : a) System.out.print(x + \" \"); System.out.println(); } public static void main(String args[]) { // Calling overloaded fun() with different parameter fun(1, 2, 3); fun(\"Testing: \", 10, 20); fun(true, false, false); }}Output:fun(int ...): Number of args: 3 Contents: 1 2 3 \nfun(String, int ...): Testing: 2 Contents: 10 20 \nfun(boolean ...) Number of args: 3 Contents: true false false \n" }, { "code": null, "e": 4827, "s": 4759, "text": "Below is the java program that overloads fun( ) method three times:" }, { "code": "// Java program to demonstrate Varargs // and overloading.class Test { // A method that takes varargs(here integers). static void fun(int ... a) { System.out.print(\"fun(int ...): \" + \"Number of args: \" + a.length + \" Contents: \"); // using for each loop to display contents of a for(int x : a) System.out.print(x + \" \"); System.out.println(); } // A method that takes varargs(here booleans). static void fun(boolean ... a) { System.out.print(\"fun(boolean ...) \" + \"Number of args: \" + a.length + \" Contents: \"); // using for each loop to display contents of a for(boolean x : a) System.out.print(x + \" \"); System.out.println(); } // A method takes string as a argument followed by varargs(here integers). static void fun(String msg, int ... a) { System.out.print(\"fun(String, int ...): \" + msg + a.length + \" Contents: \"); // using for each loop to display contents of a for(int x : a) System.out.print(x + \" \"); System.out.println(); } public static void main(String args[]) { // Calling overloaded fun() with different parameter fun(1, 2, 3); fun(\"Testing: \", 10, 20); fun(true, false, false); }}", "e": 6287, "s": 4827, "text": null }, { "code": null, "e": 6295, "s": 6287, "text": "Output:" }, { "code": null, "e": 6458, "s": 6295, "text": "fun(int ...): Number of args: 3 Contents: 1 2 3 \nfun(String, int ...): Testing: 2 Contents: 10 20 \nfun(boolean ...) Number of args: 3 Contents: true false false \n" }, { "code": null, "e": 6480, "s": 6458, "text": "Varargs and Ambiguity" }, { "code": null, "e": 6747, "s": 6480, "text": "Sometimes unexpected errors can result when overloading a method that takes a variable length argument. These errors involve ambiguity because both the methods are valid candidates for invocation. The compiler cannot decide onto which method to bind the method call." }, { "code": "// Java program to illustrate Varargs and ambiguityclass Test { // A method that takes varargs(here integers). static void fun(int ... a) { System.out.print(\"fun(int ...): \" + \"Number of args: \" + a.length + \" Contents: \"); // using for each loop to display contents of a for(int x : a) System.out.print(x + \" \"); System.out.println(); } // A method that takes varargs(here booleans). static void fun(boolean ... a) { System.out.print(\"fun(boolean ...) \" + \"Number of args: \" + a.length + \" Contents: \"); // using for each loop to display contents of a for(boolean x : a) System.out.print(x + \" \"); System.out.println(); } public static void main(String args[]) { // Calling overloaded fun() with different parameter fun(1, 2, 3); //OK fun(true, false, false); //OK fun(); // Error: Ambiguous! }}", "e": 7797, "s": 6747, "text": null }, { "code": null, "e": 7933, "s": 7797, "text": "In above program, the overloading of fun( ) is perfectly correct. However, this program will not compile because of the following call:" }, { "code": null, "e": 7962, "s": 7933, "text": "fun(); // Error: Ambiguous!\n" }, { "code": null, "e": 8641, "s": 7962, "text": "According to (JLS 15.2.2), there are 3 phases used in overload resolution: First phase performs overload resolution without permitting boxing or unboxing conversion, Second phase performs overload resolution while allowing boxing and unboxing and Third phase allows overloading to be combined with variable arity methods, boxing, and unboxing. If no applicable method is found during these phases, then ambiguity occurs.The call above could be translated into a call to fun(int ...) or fun(boolean ...). Both are equally valid and do not be resolved after all three phases of overload resolution because both the data types are different. Thus, the call is inherently ambiguous." }, { "code": null, "e": 8739, "s": 8641, "text": "Another example of ambiguity:The following overloaded versions of fun( )are inherently ambiguous:" }, { "code": null, "e": 8839, "s": 8739, "text": "static void fun(int ... a) { // method body }\nstatic void fun(int n, int ... a) { //method body }\n" }, { "code": null, "e": 8956, "s": 8839, "text": "Here, although the parameter lists of fun( ) differ, there is no way for the compiler to resolve the following call:" }, { "code": null, "e": 8964, "s": 8956, "text": "fun(1)\n" }, { "code": null, "e": 9184, "s": 8964, "text": "This call may resolve to fun(int ... a) or fun(int n, int ... a) method, thus creating ambiguity. To solve these ambiguity errors like above, we will need to forego overloading and simply use two different method names." }, { "code": null, "e": 9486, "s": 9184, "text": "This article is contributed by Gaurav Miglani. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks." }, { "code": null, "e": 9611, "s": 9486, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 9628, "s": 9611, "text": "Java-Overloading" }, { "code": null, "e": 9633, "s": 9628, "text": "Java" }, { "code": null, "e": 9638, "s": 9633, "text": "Java" } ]
Python Program for Maximum size square sub-matrix with all 1s
19 Apr, 2020 Given a binary matrix, find out the maximum size square sub-matrix with all 1s. For example, consider the below binary matrix. Python3 def print_max_sub_matrix(grid): row_len = len(grid) col_len = len(grid[0]) cache = [[0 for k in range(col_len)] for l in range(row_len)] for i in range(0, row_len): for j in range(0, col_len): if (grid[i][j] == 1): # if row(i) or column(j) is 0, set to 1 or if i == 0 or j == 0: cache[i][j] = min(grid[i][j], 1) else: cache[i][j] = min(cache[i][j-1], cache[i-1][j],cache[i-1][j-1]) + 1 else: cache[i][j] = 0 max_in_cache = cache[0][0] max_i = 0 max_j = 0 for i in range(row_len): for j in range(col_len): if max_in_cache < cache[i][j]: max_in_cache = cache[i][j] max_i = i max_j = j for i in range(max_i, max_i - max_in_cache, - 1): for j in range(max_j, max_j - max_in_cache, - 1): print (grid[i][j], end = " ") print("") # Driver Program grid = [ [1, 1, 1, 1, 1], [1, 1, 1, 1, 0], [1, 1, 0, 1, 0], [0, 1, 1, 1, 0], [1, 1, 0, 1, 1], [0, 0, 0, 0, 0]] print("Maximum sub-matrix:") print_max_sub_matrix(grid) Maximum size sub-matrix is: 1 1 1 1 Please refer complete article on Maximum size square sub-matrix with all 1s for more details! chasezimmy 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": "\n19 Apr, 2020" }, { "code": null, "e": 108, "s": 28, "text": "Given a binary matrix, find out the maximum size square sub-matrix with all 1s." }, { "code": null, "e": 155, "s": 108, "text": "For example, consider the below binary matrix." }, { "code": null, "e": 163, "s": 155, "text": "Python3" }, { "code": "def print_max_sub_matrix(grid): row_len = len(grid) col_len = len(grid[0]) cache = [[0 for k in range(col_len)] for l in range(row_len)] for i in range(0, row_len): for j in range(0, col_len): if (grid[i][j] == 1): # if row(i) or column(j) is 0, set to 1 or if i == 0 or j == 0: cache[i][j] = min(grid[i][j], 1) else: cache[i][j] = min(cache[i][j-1], cache[i-1][j],cache[i-1][j-1]) + 1 else: cache[i][j] = 0 max_in_cache = cache[0][0] max_i = 0 max_j = 0 for i in range(row_len): for j in range(col_len): if max_in_cache < cache[i][j]: max_in_cache = cache[i][j] max_i = i max_j = j for i in range(max_i, max_i - max_in_cache, - 1): for j in range(max_j, max_j - max_in_cache, - 1): print (grid[i][j], end = \" \") print(\"\") # Driver Program grid = [ [1, 1, 1, 1, 1], [1, 1, 1, 1, 0], [1, 1, 0, 1, 0], [0, 1, 1, 1, 0], [1, 1, 0, 1, 1], [0, 0, 0, 0, 0]] print(\"Maximum sub-matrix:\") print_max_sub_matrix(grid)", "e": 1383, "s": 163, "text": null }, { "code": null, "e": 1422, "s": 1383, "text": "Maximum size sub-matrix is: \n1 1 \n1 1\n" }, { "code": null, "e": 1516, "s": 1422, "text": "Please refer complete article on Maximum size square sub-matrix with all 1s for more details!" }, { "code": null, "e": 1527, "s": 1516, "text": "chasezimmy" }, { "code": null, "e": 1543, "s": 1527, "text": "Python Programs" } ]
PHP program to find the Standard Deviation of an array
05 Apr, 2018 Given an array of elements. We need to find the Standard Deviation of the elements of the array in PHP. Examples: Input : array(2, 3, 5, 6, 7) Output : 1.5620499351813 Input : array(1, 2, 3, 4, 5) Output : 1 The following problem can be solved using the PHP inbuilt functions. The inbuilt functions used to solve the above problem are as such: array_sum(): The function returns the sum of all the elements of an array.count(): This function gives the number of elements currently present in the given array.sqrt(): The function returns the square root of the given number. array_sum(): The function returns the sum of all the elements of an array. count(): This function gives the number of elements currently present in the given array. sqrt(): The function returns the square root of the given number. To calculate the standard deviation, we have to first calculate the variance. The variance can be calculated as the sum of squares of differences between all numbers and means. Finally to get the standard deviation we will use the formula, √(variance/no_of_elements). Below is the implementation in PHP to calculate the standard deviation: <?php // function to calculate the standard deviation // of array elements function Stand_Deviation($arr) { $num_of_elements = count($arr); $variance = 0.0; // calculating mean using array_sum() method $average = array_sum($arr)/$num_of_elements; foreach($arr as $i) { // sum of squares of differences between // all numbers and means. $variance += pow(($i - $average), 2); } return (float)sqrt($variance/$num_of_elements); } // Input array $arr = array(2, 3, 5, 6, 7); print_r(Stand_Deviation($arr)); ?> Output: 1.8547236990991 PHP-array PHP Technical Scripter Web Technologies PHP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n05 Apr, 2018" }, { "code": null, "e": 132, "s": 28, "text": "Given an array of elements. We need to find the Standard Deviation of the elements of the array in PHP." }, { "code": null, "e": 142, "s": 132, "text": "Examples:" }, { "code": null, "e": 238, "s": 142, "text": "Input : array(2, 3, 5, 6, 7)\nOutput : 1.5620499351813\n\nInput : array(1, 2, 3, 4, 5)\nOutput : 1\n" }, { "code": null, "e": 374, "s": 238, "text": "The following problem can be solved using the PHP inbuilt functions. The inbuilt functions used to solve the above problem are as such:" }, { "code": null, "e": 603, "s": 374, "text": "array_sum(): The function returns the sum of all the elements of an array.count(): This function gives the number of elements currently present in the given array.sqrt(): The function returns the square root of the given number." }, { "code": null, "e": 678, "s": 603, "text": "array_sum(): The function returns the sum of all the elements of an array." }, { "code": null, "e": 768, "s": 678, "text": "count(): This function gives the number of elements currently present in the given array." }, { "code": null, "e": 834, "s": 768, "text": "sqrt(): The function returns the square root of the given number." }, { "code": null, "e": 1102, "s": 834, "text": "To calculate the standard deviation, we have to first calculate the variance. The variance can be calculated as the sum of squares of differences between all numbers and means. Finally to get the standard deviation we will use the formula, √(variance/no_of_elements)." }, { "code": null, "e": 1174, "s": 1102, "text": "Below is the implementation in PHP to calculate the standard deviation:" }, { "code": "<?php // function to calculate the standard deviation // of array elements function Stand_Deviation($arr) { $num_of_elements = count($arr); $variance = 0.0; // calculating mean using array_sum() method $average = array_sum($arr)/$num_of_elements; foreach($arr as $i) { // sum of squares of differences between // all numbers and means. $variance += pow(($i - $average), 2); } return (float)sqrt($variance/$num_of_elements); } // Input array $arr = array(2, 3, 5, 6, 7); print_r(Stand_Deviation($arr)); ?>", "e": 1876, "s": 1174, "text": null }, { "code": null, "e": 1884, "s": 1876, "text": "Output:" }, { "code": null, "e": 1900, "s": 1884, "text": "1.8547236990991" }, { "code": null, "e": 1910, "s": 1900, "text": "PHP-array" }, { "code": null, "e": 1914, "s": 1910, "text": "PHP" }, { "code": null, "e": 1933, "s": 1914, "text": "Technical Scripter" }, { "code": null, "e": 1950, "s": 1933, "text": "Web Technologies" }, { "code": null, "e": 1954, "s": 1950, "text": "PHP" } ]
Sort the PySpark DataFrame columns by Ascending or Descending order
06 Jun, 2021 In this article, we are going to sort the dataframe columns in the pyspark. For this, we are using sort() and orderBy() functions in ascending order and descending order sorting. Let’s create a sample dataframe. Python3 # importing moduleimport pyspark # importing sparksession from # pyspark.sql modulefrom pyspark.sql import SparkSession # creating sparksession and giving an app namespark = SparkSession.builder.appName('sparkdf').getOrCreate() # list of employee datadata = [["1", "sravan", "company 1"], ["2", "ojaswi", "company 1"], ["3", "rohith", "company 2"], ["4", "sridevi", "company 1"], ["1", "sravan", "company 1"], ["4", "sridevi", "company 1"]] # specify column namescolumns = ['Employee_ID', 'Employee NAME', 'Company'] # creating a dataframe from the lists of datadataframe = spark.createDataFrame(data, columns) # display data in the dataframedataframe.show() Output: +-----------+-------------+---------+ |Employee_ID|Employee NAME| Company| +-----------+-------------+---------+ | 1| sravan|company 1| | 2| ojaswi|company 1| | 3| rohith|company 2| | 4| sridevi|company 1| | 1| sravan|company 1| | 4| sridevi|company 1| +-----------+-------------+---------+ The sort function is used to sort the data frame column. Syntax: dataframe.sort([‘column name’], ascending=True).show() Example 1: Arrange in ascending Using Sort() with one column Sort the data based on Employee Name in increasing order Python3 # sort the dataframe based on # employee name column in ascending orderdataframe.sort(['Employee NAME'], ascending = True).show() Output: +-----------+-------------+---------+ |Employee_ID|Employee NAME| Company| +-----------+-------------+---------+ | 1| sravan|company 1| | 1| sravan|company 1| | 2| ojaswi|company 1| | 3| rohith|company 2| | 4| sridevi|company 1| | 4| sridevi|company 1| +-----------+-------------+---------+ Sort the data based on Employee name in decreasing order: Syntax: dataframe.sort([‘column name’], ascending = False).show() Code: Python3 # sort the dataframe based on # employee name column in descending orderdataframe.sort(['Employee NAME'], ascending = False).show() Output: +-----------+-------------+---------+ |Employee_ID|Employee NAME| Company| +-----------+-------------+---------+ | 4| sridevi|company 1| | 4| sridevi|company 1| | 1| sravan|company 1| | 1| sravan|company 1| | 3| rohith|company 2| | 2| ojaswi|company 1| +-----------+-------------+---------+ Example 2: Using Sort() with multiple columns We are going to sort the dataframe based on employee id and employee name in ascending order. Python3 # sort the dataframe based on employee ID# and employee Name columns in ascending orderdataframe.sort(['Employee_ID','Employee NAME'], ascending = True).show() Output: +-----------+-------------+---------+ |Employee_ID|Employee NAME| Company| +-----------+-------------+---------+ | 1| sravan|company 1| | 1| sravan|company 1| | 2| ojaswi|company 1| | 3| rohith|company 2| | 4| sridevi|company 1| | 4| sridevi|company 1| +-----------+-------------+---------+ We are going to sort the dataframe based on employee ID, company, and employee name in descending order Python3 # sort the dataframe based on employee ID ,# company and employee Name columns in descending orderdataframe.sort(['Employee_ID','Employee NAME', 'Company'], ascending = False).show() Output: +-----------+-------------+---------+ |Employee_ID|Employee NAME| Company| +-----------+-------------+---------+ | 4| sridevi|company 1| | 4| sridevi|company 1| | 3| rohith|company 2| | 2| ojaswi|company 1| | 1| sravan|company 1| | 1| sravan|company 1| +-----------+-------------+---------+ Example 3: Sort by ASC methods. ASC method of the Column function, it returns a sort expression based on the ascending order of the given column name. Python3 dataframe.sort(dataframe.Employee_ID.asc()).show() Output: +-----------+-------------+---------+ |Employee_ID|Employee NAME| Company| +-----------+-------------+---------+ | 1| sravan|company 1| | 1| sravan|company 1| | 2| ojaswi|company 1| | 3| rohith|company 2| | 4| sridevi|company 1| | 4| sridevi|company 1| +-----------+-------------+---------+ Example 4: Sort by DESC methods. DESC method of the Column function, it returns a sort expression based on the descending order of the given column name. Python3 dataframe.sort(dataframe.Employee_ID.desc()).show() Output: +-----------+-------------+---------+ |Employee_ID|Employee NAME| Company| +-----------+-------------+---------+ | 4| sridevi|company 1| | 4| sridevi|company 1| | 3| rohith|company 2| | 2| ojaswi|company 1| | 1| sravan|company 1| | 1| sravan|company 1| +-----------+-------------+---------+ The orderBy() function sorts by one or more columns. By default, it sorts by ascending order. Syntax: orderBy(*cols, ascending=True) Parameters: cols→ Columns by which sorting is needed to be performed. ascending→ Boolean value to say that sorting is to be done in ascending order Example 1: ascending for one column Python program to sort the dataframe based on Employee ID in ascending order Python3 # sort the dataframe based on employee I# columns in descending orderdataframe.orderBy(['Employee_ID'], ascending=False).show() Output: +-----------+-------------+---------+ |Employee_ID|Employee NAME| Company| +-----------+-------------+---------+ | 4| sridevi|company 1| | 4| sridevi|company 1| | 3| rohith|company 2| | 2| ojaswi|company 1| | 1| sravan|company 1| | 1| sravan|company 1| +-----------+-------------+---------+ Python program to sort the dataframe based on Employee ID in descending order Python3 # sort the dataframe based on# Employee ID in descending orderdataframe.orderBy(['Employee_ID'], ascending = False).show() Output: +-----------+-------------+---------+ |Employee_ID|Employee NAME| Company| +-----------+-------------+---------+ | 4| sridevi|company 1| | 4| sridevi|company 1| | 3| rohith|company 2| | 2| ojaswi|company 1| | 1| sravan|company 1| | 1| sravan|company 1| +-----------+-------------+---------+ Example 2: Ascending multiple columns Sort the dataframe based on employee ID and employee Name columns in descending order using orderBy. Python3 # sort the dataframe based on employee ID # and employee Name columns in descending orderdataframe.orderBy(['Employee ID','Employee NAME'], ascending = False).show() Output: +-----------+-------------+---------+ |Employee_ID|Employee NAME| Company| +-----------+-------------+---------+ | 4| sridevi|company 1| | 4| sridevi|company 1| | 3| rohith|company 2| | 2| ojaswi|company 1| | 1| sravan|company 1| | 1| sravan|company 1| +-----------+-------------+---------+ Sort the dataframe based on employee ID and employee Name columns in ascending order Python3 # sort the dataframe based on employee ID # and employee Name columns in ascending orderdataframe.orderBy(['Employee_ID','Employee NAME'], ascending =True).show() Output: +-----------+-------------+---------+ |Employee_ID|Employee NAME| Company| +-----------+-------------+---------+ | 1| sravan|company 1| | 1| sravan|company 1| | 2| ojaswi|company 1| | 3| rohith|company 2| | 4| sridevi|company 1| | 4| sridevi|company 1| +-----------+-------------+---------+ Picked Python-Pyspark Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n06 Jun, 2021" }, { "code": null, "e": 207, "s": 28, "text": "In this article, we are going to sort the dataframe columns in the pyspark. For this, we are using sort() and orderBy() functions in ascending order and descending order sorting." }, { "code": null, "e": 240, "s": 207, "text": "Let’s create a sample dataframe." }, { "code": null, "e": 248, "s": 240, "text": "Python3" }, { "code": "# importing moduleimport pyspark # importing sparksession from # pyspark.sql modulefrom pyspark.sql import SparkSession # creating sparksession and giving an app namespark = SparkSession.builder.appName('sparkdf').getOrCreate() # list of employee datadata = [[\"1\", \"sravan\", \"company 1\"], [\"2\", \"ojaswi\", \"company 1\"], [\"3\", \"rohith\", \"company 2\"], [\"4\", \"sridevi\", \"company 1\"], [\"1\", \"sravan\", \"company 1\"], [\"4\", \"sridevi\", \"company 1\"]] # specify column namescolumns = ['Employee_ID', 'Employee NAME', 'Company'] # creating a dataframe from the lists of datadataframe = spark.createDataFrame(data, columns) # display data in the dataframedataframe.show()", "e": 949, "s": 248, "text": null }, { "code": null, "e": 957, "s": 949, "text": "Output:" }, { "code": null, "e": 1337, "s": 957, "text": "+-----------+-------------+---------+\n|Employee_ID|Employee NAME| Company|\n+-----------+-------------+---------+\n| 1| sravan|company 1|\n| 2| ojaswi|company 1|\n| 3| rohith|company 2|\n| 4| sridevi|company 1|\n| 1| sravan|company 1|\n| 4| sridevi|company 1|\n+-----------+-------------+---------+" }, { "code": null, "e": 1394, "s": 1337, "text": "The sort function is used to sort the data frame column." }, { "code": null, "e": 1457, "s": 1394, "text": "Syntax: dataframe.sort([‘column name’], ascending=True).show()" }, { "code": null, "e": 1518, "s": 1457, "text": "Example 1: Arrange in ascending Using Sort() with one column" }, { "code": null, "e": 1575, "s": 1518, "text": "Sort the data based on Employee Name in increasing order" }, { "code": null, "e": 1583, "s": 1575, "text": "Python3" }, { "code": "# sort the dataframe based on # employee name column in ascending orderdataframe.sort(['Employee NAME'], ascending = True).show()", "e": 1727, "s": 1583, "text": null }, { "code": null, "e": 1735, "s": 1727, "text": "Output:" }, { "code": null, "e": 2115, "s": 1735, "text": "+-----------+-------------+---------+\n|Employee_ID|Employee NAME| Company|\n+-----------+-------------+---------+\n| 1| sravan|company 1|\n| 1| sravan|company 1|\n| 2| ojaswi|company 1|\n| 3| rohith|company 2|\n| 4| sridevi|company 1|\n| 4| sridevi|company 1|\n+-----------+-------------+---------+" }, { "code": null, "e": 2173, "s": 2115, "text": "Sort the data based on Employee name in decreasing order:" }, { "code": null, "e": 2239, "s": 2173, "text": "Syntax: dataframe.sort([‘column name’], ascending = False).show()" }, { "code": null, "e": 2245, "s": 2239, "text": "Code:" }, { "code": null, "e": 2253, "s": 2245, "text": "Python3" }, { "code": "# sort the dataframe based on # employee name column in descending orderdataframe.sort(['Employee NAME'], ascending = False).show()", "e": 2399, "s": 2253, "text": null }, { "code": null, "e": 2407, "s": 2399, "text": "Output:" }, { "code": null, "e": 2787, "s": 2407, "text": "+-----------+-------------+---------+\n|Employee_ID|Employee NAME| Company|\n+-----------+-------------+---------+\n| 4| sridevi|company 1|\n| 4| sridevi|company 1|\n| 1| sravan|company 1|\n| 1| sravan|company 1|\n| 3| rohith|company 2|\n| 2| ojaswi|company 1|\n+-----------+-------------+---------+" }, { "code": null, "e": 2833, "s": 2787, "text": "Example 2: Using Sort() with multiple columns" }, { "code": null, "e": 2927, "s": 2833, "text": "We are going to sort the dataframe based on employee id and employee name in ascending order." }, { "code": null, "e": 2935, "s": 2927, "text": "Python3" }, { "code": "# sort the dataframe based on employee ID# and employee Name columns in ascending orderdataframe.sort(['Employee_ID','Employee NAME'], ascending = True).show()", "e": 3109, "s": 2935, "text": null }, { "code": null, "e": 3117, "s": 3109, "text": "Output:" }, { "code": null, "e": 3497, "s": 3117, "text": "+-----------+-------------+---------+\n|Employee_ID|Employee NAME| Company|\n+-----------+-------------+---------+\n| 1| sravan|company 1|\n| 1| sravan|company 1|\n| 2| ojaswi|company 1|\n| 3| rohith|company 2|\n| 4| sridevi|company 1|\n| 4| sridevi|company 1|\n+-----------+-------------+---------+" }, { "code": null, "e": 3601, "s": 3497, "text": "We are going to sort the dataframe based on employee ID, company, and employee name in descending order" }, { "code": null, "e": 3609, "s": 3601, "text": "Python3" }, { "code": "# sort the dataframe based on employee ID ,# company and employee Name columns in descending orderdataframe.sort(['Employee_ID','Employee NAME', 'Company'], ascending = False).show()", "e": 3807, "s": 3609, "text": null }, { "code": null, "e": 3815, "s": 3807, "text": "Output:" }, { "code": null, "e": 4195, "s": 3815, "text": "+-----------+-------------+---------+\n|Employee_ID|Employee NAME| Company|\n+-----------+-------------+---------+\n| 4| sridevi|company 1|\n| 4| sridevi|company 1|\n| 3| rohith|company 2|\n| 2| ojaswi|company 1|\n| 1| sravan|company 1|\n| 1| sravan|company 1|\n+-----------+-------------+---------+" }, { "code": null, "e": 4227, "s": 4195, "text": "Example 3: Sort by ASC methods." }, { "code": null, "e": 4346, "s": 4227, "text": "ASC method of the Column function, it returns a sort expression based on the ascending order of the given column name." }, { "code": null, "e": 4354, "s": 4346, "text": "Python3" }, { "code": "dataframe.sort(dataframe.Employee_ID.asc()).show()", "e": 4405, "s": 4354, "text": null }, { "code": null, "e": 4413, "s": 4405, "text": "Output:" }, { "code": null, "e": 4793, "s": 4413, "text": "+-----------+-------------+---------+\n|Employee_ID|Employee NAME| Company|\n+-----------+-------------+---------+\n| 1| sravan|company 1|\n| 1| sravan|company 1|\n| 2| ojaswi|company 1|\n| 3| rohith|company 2|\n| 4| sridevi|company 1|\n| 4| sridevi|company 1|\n+-----------+-------------+---------+" }, { "code": null, "e": 4826, "s": 4793, "text": "Example 4: Sort by DESC methods." }, { "code": null, "e": 4947, "s": 4826, "text": "DESC method of the Column function, it returns a sort expression based on the descending order of the given column name." }, { "code": null, "e": 4955, "s": 4947, "text": "Python3" }, { "code": "dataframe.sort(dataframe.Employee_ID.desc()).show()", "e": 5007, "s": 4955, "text": null }, { "code": null, "e": 5015, "s": 5007, "text": "Output:" }, { "code": null, "e": 5395, "s": 5015, "text": "+-----------+-------------+---------+\n|Employee_ID|Employee NAME| Company|\n+-----------+-------------+---------+\n| 4| sridevi|company 1|\n| 4| sridevi|company 1|\n| 3| rohith|company 2|\n| 2| ojaswi|company 1|\n| 1| sravan|company 1|\n| 1| sravan|company 1|\n+-----------+-------------+---------+" }, { "code": null, "e": 5489, "s": 5395, "text": "The orderBy() function sorts by one or more columns. By default, it sorts by ascending order." }, { "code": null, "e": 5528, "s": 5489, "text": "Syntax: orderBy(*cols, ascending=True)" }, { "code": null, "e": 5540, "s": 5528, "text": "Parameters:" }, { "code": null, "e": 5598, "s": 5540, "text": "cols→ Columns by which sorting is needed to be performed." }, { "code": null, "e": 5676, "s": 5598, "text": "ascending→ Boolean value to say that sorting is to be done in ascending order" }, { "code": null, "e": 5712, "s": 5676, "text": "Example 1: ascending for one column" }, { "code": null, "e": 5789, "s": 5712, "text": "Python program to sort the dataframe based on Employee ID in ascending order" }, { "code": null, "e": 5797, "s": 5789, "text": "Python3" }, { "code": "# sort the dataframe based on employee I# columns in descending orderdataframe.orderBy(['Employee_ID'], ascending=False).show()", "e": 5942, "s": 5797, "text": null }, { "code": null, "e": 5950, "s": 5942, "text": "Output:" }, { "code": null, "e": 6330, "s": 5950, "text": "+-----------+-------------+---------+\n|Employee_ID|Employee NAME| Company|\n+-----------+-------------+---------+\n| 4| sridevi|company 1|\n| 4| sridevi|company 1|\n| 3| rohith|company 2|\n| 2| ojaswi|company 1|\n| 1| sravan|company 1|\n| 1| sravan|company 1|\n+-----------+-------------+---------+" }, { "code": null, "e": 6409, "s": 6330, "text": "Python program to sort the dataframe based on Employee ID in descending order" }, { "code": null, "e": 6417, "s": 6409, "text": "Python3" }, { "code": "# sort the dataframe based on# Employee ID in descending orderdataframe.orderBy(['Employee_ID'], ascending = False).show()", "e": 6557, "s": 6417, "text": null }, { "code": null, "e": 6565, "s": 6557, "text": "Output:" }, { "code": null, "e": 6945, "s": 6565, "text": "+-----------+-------------+---------+\n|Employee_ID|Employee NAME| Company|\n+-----------+-------------+---------+\n| 4| sridevi|company 1|\n| 4| sridevi|company 1|\n| 3| rohith|company 2|\n| 2| ojaswi|company 1|\n| 1| sravan|company 1|\n| 1| sravan|company 1|\n+-----------+-------------+---------+" }, { "code": null, "e": 6983, "s": 6945, "text": "Example 2: Ascending multiple columns" }, { "code": null, "e": 7084, "s": 6983, "text": "Sort the dataframe based on employee ID and employee Name columns in descending order using orderBy." }, { "code": null, "e": 7092, "s": 7084, "text": "Python3" }, { "code": "# sort the dataframe based on employee ID # and employee Name columns in descending orderdataframe.orderBy(['Employee ID','Employee NAME'], ascending = False).show()", "e": 7275, "s": 7092, "text": null }, { "code": null, "e": 7283, "s": 7275, "text": "Output:" }, { "code": null, "e": 7663, "s": 7283, "text": "+-----------+-------------+---------+\n|Employee_ID|Employee NAME| Company|\n+-----------+-------------+---------+\n| 4| sridevi|company 1|\n| 4| sridevi|company 1|\n| 3| rohith|company 2|\n| 2| ojaswi|company 1|\n| 1| sravan|company 1|\n| 1| sravan|company 1|\n+-----------+-------------+---------+" }, { "code": null, "e": 7748, "s": 7663, "text": "Sort the dataframe based on employee ID and employee Name columns in ascending order" }, { "code": null, "e": 7756, "s": 7748, "text": "Python3" }, { "code": "# sort the dataframe based on employee ID # and employee Name columns in ascending orderdataframe.orderBy(['Employee_ID','Employee NAME'], ascending =True).show()", "e": 7936, "s": 7756, "text": null }, { "code": null, "e": 7944, "s": 7936, "text": "Output:" }, { "code": null, "e": 8324, "s": 7944, "text": "+-----------+-------------+---------+\n|Employee_ID|Employee NAME| Company|\n+-----------+-------------+---------+\n| 1| sravan|company 1|\n| 1| sravan|company 1|\n| 2| ojaswi|company 1|\n| 3| rohith|company 2|\n| 4| sridevi|company 1|\n| 4| sridevi|company 1|\n+-----------+-------------+---------+" }, { "code": null, "e": 8331, "s": 8324, "text": "Picked" }, { "code": null, "e": 8346, "s": 8331, "text": "Python-Pyspark" }, { "code": null, "e": 8353, "s": 8346, "text": "Python" } ]
Sort an Array of Strings according to the number of Vowels in them
11 Jun, 2021 Given an array arr[] of N strings, the task is to sort these strings according to the numbers of vowels in them. Examples: Input: arr[] = { “geeks”, “for”, “coding” } Output: for, coding, geeks for -> o = 1 vowel coding -> o, i = 2 vowels geeks -> e, e = 2 vowels Input: arr[] = { “lmno”, “pqrst”, “aeiou”, “xyz” } Output: pqrst, xyz, lmno, aeiou Approach: The idea is to store each element with its number of vowels in a vector pair and then sort all the elements of the vector according to the number of vowels stored. Finally, print the strings in order. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ implementation of the approach #include <bits/stdc++.h>using namespace std; // Function to check the Vowelbool isVowel(char ch){ ch = toupper(ch); return (ch == 'A' || ch == 'E' || ch == 'I' || ch == 'O' || ch == 'U');} // Returns count of vowels in strint countVowels(string str){ int count = 0; for (int i = 0; i < str.length(); i++) if (isVowel(str[i])) // Check for vowel ++count; return count;} // Function to sort the array according to// the number of the vowelsvoid sortArr(string arr[], int n){ // Vector to store the number of vowels // with respective elements vector<pair<int, string> > vp; // Inserting number of vowels // with respective strings // in the vector pair for (int i = 0; i < n; i++) { vp.push_back( make_pair( countVowels( arr[i]), arr[i])); } // Sort the vector, this will sort the pair // according to the number of vowels sort(vp.begin(), vp.end()); // Print the sorted vector content for (int i = 0; i < vp.size(); i++) cout << vp[i].second << " ";} // Driver codeint main(){ string arr[] = { "lmno", "pqrst", "aeiou", "xyz" }; int n = sizeof(arr) / sizeof(arr[0]); sortArr(arr, n); return 0;} // Java implementation of the approachimport java.util.*;import java.lang.*;import java.io.*; class GFG{ static class pair{ int first; String second; pair(int first,String second) { this.first = first; this.second = second; }} // Function to check the Vowelstatic boolean isVowel(char ch){ ch = Character.toUpperCase(ch); return (ch == 'A' || ch == 'E' || ch == 'I' || ch == 'O' || ch == 'U');} // Returns count of vowels in strstatic int countVowels(String str){ int count = 0; for(int i = 0; i < str.length(); i++) // Check for vowel if (isVowel(str.charAt(i))) ++count; return count;} // Function to sort the array according to// the number of the vowelsstatic void sortArr(String arr[], int n){ // Vector to store the number of vowels // with respective elements ArrayList<pair> vp = new ArrayList<>(); // Inserting number of vowels // with respective strings // in the vector pair for(int i = 0; i < n; i++) { vp.add(new pair(countVowels(arr[i]), arr[i])); } // Sort the vector, this will sort the pair // according to the number of vowels Collections.sort(vp, (a, b) -> a.first - b.first); // Print the sorted vector content for(int i = 0; i < vp.size(); i++) System.out.print(vp.get(i).second + " ");} // Driver codepublic static void main(String[] args){ String arr[] = { "lmno", "pqrst", "aeiou", "xyz" }; int n = arr.length; sortArr(arr, n);}} // This code is contributed by offbeat # Python3 implementation of the approach # Function to check the Voweldef isVowel(ch) : ch = ch.upper(); return (ch == 'A' or ch == 'E'or ch == 'I' or ch == 'O'or ch == 'U'); # Returns count of vowels in strdef countVowels(string) : count = 0; for i in range(len(string)) : # Check for vowel if (isVowel(string[i])) : count += 1; return count; # Function to sort the array according to# the number of the vowelsdef sortArr(arr, n) : # Vector to store the number of vowels # with respective elements vp = []; # Inserting number of vowels # with respective strings # in the vector pair for i in range(n) : vp.append((countVowels(arr[i]),arr[i])); # Sort the vector, this will sort the pair # according to the number of vowels vp.sort() # Print the sorted vector content for i in range(len(vp)) : print(vp[i][1], end= " "); # Driver codeif __name__ == "__main__" : arr = [ "lmno", "pqrst","aeiou", "xyz" ]; n = len(arr); sortArr(arr, n); # This code is contributed by AnkitRai01 // C# implementation of the approachusing System;using System.Collections.Generic;class GFG{ // Function to check the Vowel static bool isVowel(char ch) { ch = char.ToUpper(ch); return (ch == 'A' || ch == 'E' || ch == 'I' || ch == 'O' || ch == 'U'); } // Returns count of vowels in str static int countVowels(string str) { int count = 0; for (int i = 0; i < str.Length; i++) if (isVowel(str[i])) // Check for vowel ++count; return count; } // Function to sort the array according to // the number of the vowels static void sortArr(string[] arr, int n) { // Vector to store the number of vowels // with respective elements List<Tuple<int, string>> vp = new List<Tuple<int, string>>(); // Inserting number of vowels // with respective strings // in the vector pair for (int i = 0; i < n; i++) { vp.Add(new Tuple<int, string>(countVowels(arr[i]), arr[i])); } // Sort the vector, this will sort the pair // according to the number of vowels vp.Sort(); // Print the sorted vector content for (int i = 0; i < vp.Count; i++) Console.Write(vp[i].Item2 + " "); } // Driver code static void Main() { string[] arr = { "lmno", "pqrst", "aeiou", "xyz" }; int n = arr.Length; sortArr(arr, n); }} // This code is contributed by divyesh072019 <script> // JavaScript implementation of the approach // Function to check the Vowel function isVowel(ch) { ch = ch.toUpperCase(); return (ch == 'A' || ch == 'E' || ch == 'I' || ch == 'O' || ch == 'U'); } // Returns count of vowels in str function countVowels(str) { let count = 0; for (let i = 0; i < str.length; i++) if (isVowel(str[i])) // Check for vowel ++count; return count; } // Function to sort the array according to // the number of the vowels function sortArr(arr, n) { // Vector to store the number of vowels // with respective elements let vp = []; // Inserting number of vowels // with respective strings // in the vector pair for (let i = 0; i < n; i++) { vp.push([countVowels(arr[i]), arr[i]]); } // Sort the vector, this will sort the pair // according to the number of vowels vp.sort(); // Print the sorted vector content for (let i = 0; i < vp.length; i++) document.write(vp[i][1] + " "); } let arr = [ "lmno", "pqrst", "aeiou", "xyz" ]; let n = arr.length; sortArr(arr, n); </script> pqrst xyz lmno aeiou Time Complexity: O(N*log N) ankthon offbeat divyesh072019 suresh07 vowel-consonant School Programming Sorting Strings Strings Sorting Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Constructors in Java Exceptions in Java Python Exception Handling Python Try Except Ternary Operator in Python Merge Sort Bubble Sort Algorithm QuickSort Insertion Sort Selection Sort Algorithm
[ { "code": null, "e": 28, "s": 0, "text": "\n11 Jun, 2021" }, { "code": null, "e": 141, "s": 28, "text": "Given an array arr[] of N strings, the task is to sort these strings according to the numbers of vowels in them." }, { "code": null, "e": 152, "s": 141, "text": "Examples: " }, { "code": null, "e": 293, "s": 152, "text": "Input: arr[] = { “geeks”, “for”, “coding” } Output: for, coding, geeks for -> o = 1 vowel coding -> o, i = 2 vowels geeks -> e, e = 2 vowels" }, { "code": null, "e": 378, "s": 293, "text": "Input: arr[] = { “lmno”, “pqrst”, “aeiou”, “xyz” } Output: pqrst, xyz, lmno, aeiou " }, { "code": null, "e": 589, "s": 378, "text": "Approach: The idea is to store each element with its number of vowels in a vector pair and then sort all the elements of the vector according to the number of vowels stored. Finally, print the strings in order." }, { "code": null, "e": 642, "s": 589, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 646, "s": 642, "text": "C++" }, { "code": null, "e": 651, "s": 646, "text": "Java" }, { "code": null, "e": 659, "s": 651, "text": "Python3" }, { "code": null, "e": 662, "s": 659, "text": "C#" }, { "code": null, "e": 673, "s": 662, "text": "Javascript" }, { "code": "// C++ implementation of the approach #include <bits/stdc++.h>using namespace std; // Function to check the Vowelbool isVowel(char ch){ ch = toupper(ch); return (ch == 'A' || ch == 'E' || ch == 'I' || ch == 'O' || ch == 'U');} // Returns count of vowels in strint countVowels(string str){ int count = 0; for (int i = 0; i < str.length(); i++) if (isVowel(str[i])) // Check for vowel ++count; return count;} // Function to sort the array according to// the number of the vowelsvoid sortArr(string arr[], int n){ // Vector to store the number of vowels // with respective elements vector<pair<int, string> > vp; // Inserting number of vowels // with respective strings // in the vector pair for (int i = 0; i < n; i++) { vp.push_back( make_pair( countVowels( arr[i]), arr[i])); } // Sort the vector, this will sort the pair // according to the number of vowels sort(vp.begin(), vp.end()); // Print the sorted vector content for (int i = 0; i < vp.size(); i++) cout << vp[i].second << \" \";} // Driver codeint main(){ string arr[] = { \"lmno\", \"pqrst\", \"aeiou\", \"xyz\" }; int n = sizeof(arr) / sizeof(arr[0]); sortArr(arr, n); return 0;}", "e": 2011, "s": 673, "text": null }, { "code": "// Java implementation of the approachimport java.util.*;import java.lang.*;import java.io.*; class GFG{ static class pair{ int first; String second; pair(int first,String second) { this.first = first; this.second = second; }} // Function to check the Vowelstatic boolean isVowel(char ch){ ch = Character.toUpperCase(ch); return (ch == 'A' || ch == 'E' || ch == 'I' || ch == 'O' || ch == 'U');} // Returns count of vowels in strstatic int countVowels(String str){ int count = 0; for(int i = 0; i < str.length(); i++) // Check for vowel if (isVowel(str.charAt(i))) ++count; return count;} // Function to sort the array according to// the number of the vowelsstatic void sortArr(String arr[], int n){ // Vector to store the number of vowels // with respective elements ArrayList<pair> vp = new ArrayList<>(); // Inserting number of vowels // with respective strings // in the vector pair for(int i = 0; i < n; i++) { vp.add(new pair(countVowels(arr[i]), arr[i])); } // Sort the vector, this will sort the pair // according to the number of vowels Collections.sort(vp, (a, b) -> a.first - b.first); // Print the sorted vector content for(int i = 0; i < vp.size(); i++) System.out.print(vp.get(i).second + \" \");} // Driver codepublic static void main(String[] args){ String arr[] = { \"lmno\", \"pqrst\", \"aeiou\", \"xyz\" }; int n = arr.length; sortArr(arr, n);}} // This code is contributed by offbeat", "e": 3655, "s": 2011, "text": null }, { "code": "# Python3 implementation of the approach # Function to check the Voweldef isVowel(ch) : ch = ch.upper(); return (ch == 'A' or ch == 'E'or ch == 'I' or ch == 'O'or ch == 'U'); # Returns count of vowels in strdef countVowels(string) : count = 0; for i in range(len(string)) : # Check for vowel if (isVowel(string[i])) : count += 1; return count; # Function to sort the array according to# the number of the vowelsdef sortArr(arr, n) : # Vector to store the number of vowels # with respective elements vp = []; # Inserting number of vowels # with respective strings # in the vector pair for i in range(n) : vp.append((countVowels(arr[i]),arr[i])); # Sort the vector, this will sort the pair # according to the number of vowels vp.sort() # Print the sorted vector content for i in range(len(vp)) : print(vp[i][1], end= \" \"); # Driver codeif __name__ == \"__main__\" : arr = [ \"lmno\", \"pqrst\",\"aeiou\", \"xyz\" ]; n = len(arr); sortArr(arr, n); # This code is contributed by AnkitRai01", "e": 4779, "s": 3655, "text": null }, { "code": "// C# implementation of the approachusing System;using System.Collections.Generic;class GFG{ // Function to check the Vowel static bool isVowel(char ch) { ch = char.ToUpper(ch); return (ch == 'A' || ch == 'E' || ch == 'I' || ch == 'O' || ch == 'U'); } // Returns count of vowels in str static int countVowels(string str) { int count = 0; for (int i = 0; i < str.Length; i++) if (isVowel(str[i])) // Check for vowel ++count; return count; } // Function to sort the array according to // the number of the vowels static void sortArr(string[] arr, int n) { // Vector to store the number of vowels // with respective elements List<Tuple<int, string>> vp = new List<Tuple<int, string>>(); // Inserting number of vowels // with respective strings // in the vector pair for (int i = 0; i < n; i++) { vp.Add(new Tuple<int, string>(countVowels(arr[i]), arr[i])); } // Sort the vector, this will sort the pair // according to the number of vowels vp.Sort(); // Print the sorted vector content for (int i = 0; i < vp.Count; i++) Console.Write(vp[i].Item2 + \" \"); } // Driver code static void Main() { string[] arr = { \"lmno\", \"pqrst\", \"aeiou\", \"xyz\" }; int n = arr.Length; sortArr(arr, n); }} // This code is contributed by divyesh072019", "e": 6338, "s": 4779, "text": null }, { "code": "<script> // JavaScript implementation of the approach // Function to check the Vowel function isVowel(ch) { ch = ch.toUpperCase(); return (ch == 'A' || ch == 'E' || ch == 'I' || ch == 'O' || ch == 'U'); } // Returns count of vowels in str function countVowels(str) { let count = 0; for (let i = 0; i < str.length; i++) if (isVowel(str[i])) // Check for vowel ++count; return count; } // Function to sort the array according to // the number of the vowels function sortArr(arr, n) { // Vector to store the number of vowels // with respective elements let vp = []; // Inserting number of vowels // with respective strings // in the vector pair for (let i = 0; i < n; i++) { vp.push([countVowels(arr[i]), arr[i]]); } // Sort the vector, this will sort the pair // according to the number of vowels vp.sort(); // Print the sorted vector content for (let i = 0; i < vp.length; i++) document.write(vp[i][1] + \" \"); } let arr = [ \"lmno\", \"pqrst\", \"aeiou\", \"xyz\" ]; let n = arr.length; sortArr(arr, n); </script>", "e": 7663, "s": 6338, "text": null }, { "code": null, "e": 7684, "s": 7663, "text": "pqrst xyz lmno aeiou" }, { "code": null, "e": 7715, "s": 7686, "text": "Time Complexity: O(N*log N) " }, { "code": null, "e": 7723, "s": 7715, "text": "ankthon" }, { "code": null, "e": 7731, "s": 7723, "text": "offbeat" }, { "code": null, "e": 7745, "s": 7731, "text": "divyesh072019" }, { "code": null, "e": 7754, "s": 7745, "text": "suresh07" }, { "code": null, "e": 7770, "s": 7754, "text": "vowel-consonant" }, { "code": null, "e": 7789, "s": 7770, "text": "School Programming" }, { "code": null, "e": 7797, "s": 7789, "text": "Sorting" }, { "code": null, "e": 7805, "s": 7797, "text": "Strings" }, { "code": null, "e": 7813, "s": 7805, "text": "Strings" }, { "code": null, "e": 7821, "s": 7813, "text": "Sorting" }, { "code": null, "e": 7919, "s": 7821, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 7940, "s": 7919, "text": "Constructors in Java" }, { "code": null, "e": 7959, "s": 7940, "text": "Exceptions in Java" }, { "code": null, "e": 7985, "s": 7959, "text": "Python Exception Handling" }, { "code": null, "e": 8003, "s": 7985, "text": "Python Try Except" }, { "code": null, "e": 8030, "s": 8003, "text": "Ternary Operator in Python" }, { "code": null, "e": 8041, "s": 8030, "text": "Merge Sort" }, { "code": null, "e": 8063, "s": 8041, "text": "Bubble Sort Algorithm" }, { "code": null, "e": 8073, "s": 8063, "text": "QuickSort" }, { "code": null, "e": 8088, "s": 8073, "text": "Insertion Sort" } ]
C# – Break statement
10 Feb, 2022 In C#, the break statement is used to terminate a loop(for, if, while, etc.) or a switch statement on a certain condition. And after terminating the controls will pass to the statements that present after the break statement, if available. If the break statement exists in the nested loop, then it will terminate only those loops which contain the break statements. Syntax: break; Flow Chart: Now we will see the usage of break statement: Simple LoopNested LoopInfinite Loop Switch-Case statement Simple Loop Nested Loop Infinite Loop Switch-Case statement 1. Simple Loop: Here we will discuss the use of break statements in simple for loop. As shown in the below example the for loop is programmed to execute from 0 to 20 but the output of this example is “0 1 2 3 4 5 6”. Because here we break the loop when the value of x is equal to 7. If we do not use a break statement, then this loop prints 0....20 numbers. C# // C# program to illustrate the use of// break statement in loopusing System; class GFG{ static public void Main (){ // Here, the break statement // terminates the loop when x = 7 for(int x = 0; x <= 20; x++) { if (x == 7) { break; } Console.WriteLine(x); }}} Output: 0 1 2 3 4 5 6 2. Nested Loop: We can also use the break statements in the nested loops. If you use a break statement in the innermost loop, then control will come out only from the innermost loop. Let us discuss the use of break statement in the nested loops with the help of an example: C# // C# program to illustrate the use of// break statement in nested loopusing System; class GFG{ static public void Main (){ // Outer Loop for(int x = 0; x < 4; x++) { // Inner Loop for(int y = 1; y < 4; y++) { if (y > 2) { break; } Console.Write("#"); } Console.Write("\n"); }}} Output: ## ## ## ## In the above example, the inner loop is programmed to execute for 4 iterations, but when the value of y is greater than 2 the inner loop stops executing because we use a break statement to restrict the number of iteration of the inner loop to 2. However, the outer loop remains unaffected. 3. Infinite Loops: We can also use the break statement in the infinite loop to terminate the execution of the infinite loop. Let us discuss the use of break statement in the infinite loops with the help of an example: C# // C# program to illustrate// infinite loopusing System; class GFG{ static public void Main (){ int x = 1; // Creating infinite loop // using while loop while (true) { // This statement will be printed // infinite times Console.WriteLine("Hey GeeksforGeeks"); x++; }}} In the above example, the loop condition based on which the loop terminates is always true. So, the loop will execute an infinite number of times, or we can say never terminate. So, here we use the break statement to terminate the loop when the value of x is equal to 7 C# // C# program to illustrate the use of// break statement in the infinite loopusing System; class GFG{ static public void Main (){ int x = 1; while (true) { if (x == 7) break; Console.WriteLine("Hey GeeksforGeeks"); x++; }}} Output: Hey GeeksforGeeks Hey GeeksforGeeks Hey GeeksforGeeks Hey GeeksforGeeks Hey GeeksforGeeks Hey GeeksforGeeks 4. Switch-case Statement: As we know that the switch statement has a drawback, i.e. when the matching value is found it will execute all the statements until the end of the switch block. To avoid such type of problem we use break statement in every case. So that the break statement terminates the execution of the switch statement for nonmatching statements. As shown in the below example: C# // C# program to illustrate the use of// break statement in switch-case statementusing System; class GFG{ static public void Main (){ // Enter the value Console.Write("Select option(1, 2, 3): "); string str = Console.ReadLine(); int x = Int32.Parse(str); // Using break statement in the switch-case // statements switch(x) { case 1: Console.WriteLine("You select group A"); break; case 2: Console.WriteLine("You select group B"); break; case 3: Console.WriteLine("You select group C"); break; default: Console.WriteLine("Sorry, Not a valid selection!"); break; }}} Output: Select option(1, 2, 3): 2 You select group B abhishek0719kadiyan simranarora5sos C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Introduction to .NET Framework C# | Delegates C# | Multiple inheritance using interfaces Differences Between .NET Core and .NET Framework C# | Data Types C# | String.IndexOf( ) Method | Set - 1 Extension Method in C# C# | Replace() Method C# | Arrays C# | List Class
[ { "code": null, "e": 28, "s": 0, "text": "\n10 Feb, 2022" }, { "code": null, "e": 395, "s": 28, "text": "In C#, the break statement is used to terminate a loop(for, if, while, etc.) or a switch statement on a certain condition. And after terminating the controls will pass to the statements that present after the break statement, if available. If the break statement exists in the nested loop, then it will terminate only those loops which contain the break statements. " }, { "code": null, "e": 403, "s": 395, "text": "Syntax:" }, { "code": null, "e": 410, "s": 403, "text": "break;" }, { "code": null, "e": 422, "s": 410, "text": "Flow Chart:" }, { "code": null, "e": 468, "s": 422, "text": "Now we will see the usage of break statement:" }, { "code": null, "e": 526, "s": 468, "text": "Simple LoopNested LoopInfinite Loop Switch-Case statement" }, { "code": null, "e": 538, "s": 526, "text": "Simple Loop" }, { "code": null, "e": 550, "s": 538, "text": "Nested Loop" }, { "code": null, "e": 565, "s": 550, "text": "Infinite Loop " }, { "code": null, "e": 587, "s": 565, "text": "Switch-Case statement" }, { "code": null, "e": 603, "s": 587, "text": "1. Simple Loop:" }, { "code": null, "e": 947, "s": 603, "text": "Here we will discuss the use of break statements in simple for loop. As shown in the below example the for loop is programmed to execute from 0 to 20 but the output of this example is “0 1 2 3 4 5 6”. Because here we break the loop when the value of x is equal to 7. If we do not use a break statement, then this loop prints 0....20 numbers. " }, { "code": null, "e": 950, "s": 947, "text": "C#" }, { "code": "// C# program to illustrate the use of// break statement in loopusing System; class GFG{ static public void Main (){ // Here, the break statement // terminates the loop when x = 7 for(int x = 0; x <= 20; x++) { if (x == 7) { break; } Console.WriteLine(x); }}}", "e": 1273, "s": 950, "text": null }, { "code": null, "e": 1281, "s": 1273, "text": "Output:" }, { "code": null, "e": 1295, "s": 1281, "text": "0\n1\n2\n3\n4\n5\n6" }, { "code": null, "e": 1311, "s": 1295, "text": "2. Nested Loop:" }, { "code": null, "e": 1570, "s": 1311, "text": "We can also use the break statements in the nested loops. If you use a break statement in the innermost loop, then control will come out only from the innermost loop. Let us discuss the use of break statement in the nested loops with the help of an example:" }, { "code": null, "e": 1573, "s": 1570, "text": "C#" }, { "code": "// C# program to illustrate the use of// break statement in nested loopusing System; class GFG{ static public void Main (){ // Outer Loop for(int x = 0; x < 4; x++) { // Inner Loop for(int y = 1; y < 4; y++) { if (y > 2) { break; } Console.Write(\"#\"); } Console.Write(\"\\n\"); }}}", "e": 1968, "s": 1573, "text": null }, { "code": null, "e": 1976, "s": 1968, "text": "Output:" }, { "code": null, "e": 1988, "s": 1976, "text": "##\n##\n##\n##" }, { "code": null, "e": 2278, "s": 1988, "text": "In the above example, the inner loop is programmed to execute for 4 iterations, but when the value of y is greater than 2 the inner loop stops executing because we use a break statement to restrict the number of iteration of the inner loop to 2. However, the outer loop remains unaffected." }, { "code": null, "e": 2297, "s": 2278, "text": "3. Infinite Loops:" }, { "code": null, "e": 2496, "s": 2297, "text": "We can also use the break statement in the infinite loop to terminate the execution of the infinite loop. Let us discuss the use of break statement in the infinite loops with the help of an example:" }, { "code": null, "e": 2499, "s": 2496, "text": "C#" }, { "code": "// C# program to illustrate// infinite loopusing System; class GFG{ static public void Main (){ int x = 1; // Creating infinite loop // using while loop while (true) { // This statement will be printed // infinite times Console.WriteLine(\"Hey GeeksforGeeks\"); x++; }}}", "e": 2825, "s": 2499, "text": null }, { "code": null, "e": 3096, "s": 2825, "text": " In the above example, the loop condition based on which the loop terminates is always true. So, the loop will execute an infinite number of times, or we can say never terminate. So, here we use the break statement to terminate the loop when the value of x is equal to 7" }, { "code": null, "e": 3099, "s": 3096, "text": "C#" }, { "code": "// C# program to illustrate the use of// break statement in the infinite loopusing System; class GFG{ static public void Main (){ int x = 1; while (true) { if (x == 7) break; Console.WriteLine(\"Hey GeeksforGeeks\"); x++; }}}", "e": 3389, "s": 3099, "text": null }, { "code": null, "e": 3397, "s": 3389, "text": "Output:" }, { "code": null, "e": 3505, "s": 3397, "text": "Hey GeeksforGeeks\nHey GeeksforGeeks\nHey GeeksforGeeks\nHey GeeksforGeeks\nHey GeeksforGeeks\nHey GeeksforGeeks" }, { "code": null, "e": 3532, "s": 3505, "text": "4. Switch-case Statement: " }, { "code": null, "e": 3897, "s": 3532, "text": "As we know that the switch statement has a drawback, i.e. when the matching value is found it will execute all the statements until the end of the switch block. To avoid such type of problem we use break statement in every case. So that the break statement terminates the execution of the switch statement for nonmatching statements. As shown in the below example:" }, { "code": null, "e": 3900, "s": 3897, "text": "C#" }, { "code": "// C# program to illustrate the use of// break statement in switch-case statementusing System; class GFG{ static public void Main (){ // Enter the value Console.Write(\"Select option(1, 2, 3): \"); string str = Console.ReadLine(); int x = Int32.Parse(str); // Using break statement in the switch-case // statements switch(x) { case 1: Console.WriteLine(\"You select group A\"); break; case 2: Console.WriteLine(\"You select group B\"); break; case 3: Console.WriteLine(\"You select group C\"); break; default: Console.WriteLine(\"Sorry, Not a valid selection!\"); break; }}}", "e": 4623, "s": 3900, "text": null }, { "code": null, "e": 4631, "s": 4623, "text": "Output:" }, { "code": null, "e": 4676, "s": 4631, "text": "Select option(1, 2, 3): 2\nYou select group B" }, { "code": null, "e": 4696, "s": 4676, "text": "abhishek0719kadiyan" }, { "code": null, "e": 4712, "s": 4696, "text": "simranarora5sos" }, { "code": null, "e": 4715, "s": 4712, "text": "C#" }, { "code": null, "e": 4813, "s": 4715, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4844, "s": 4813, "text": "Introduction to .NET Framework" }, { "code": null, "e": 4859, "s": 4844, "text": "C# | Delegates" }, { "code": null, "e": 4902, "s": 4859, "text": "C# | Multiple inheritance using interfaces" }, { "code": null, "e": 4951, "s": 4902, "text": "Differences Between .NET Core and .NET Framework" }, { "code": null, "e": 4967, "s": 4951, "text": "C# | Data Types" }, { "code": null, "e": 5007, "s": 4967, "text": "C# | String.IndexOf( ) Method | Set - 1" }, { "code": null, "e": 5030, "s": 5007, "text": "Extension Method in C#" }, { "code": null, "e": 5052, "s": 5030, "text": "C# | Replace() Method" }, { "code": null, "e": 5064, "s": 5052, "text": "C# | Arrays" } ]
Zero value in Golang
09 Aug, 2019 In Go language, whenever we allocate memory for a variable with the help of declaration or by using new and if the variable is not initialized explicitly, then the value of such types of variables are automatically initialized with their zero value. The initialization of the zero value is done recursively. So, every element of the array of the structs has its fields zero if they are not specified with any value. Following are the zero values for different types of variables: Example 1: // Go program to illustrate the concept of zero valuepackage main import "fmt" // Main Methodfunc main() { // Creating variables // of different types var q1 int var q2 float64 var q3 bool var q4 string var q5 []int var q6 *int var q7 map[int]string // Displaying the zero value // of the above variables fmt.Println("Zero value for integer types: ", q1) fmt.Println("Zero value for float64 types: ", q2) fmt.Println("Zero value for boolean types: ", q3) fmt.Println("Zero value for string types: ", q4) fmt.Println("Zero value for slice types: ", q5) fmt.Println("Zero value for pointer types: ", q6) fmt.Println("Zero value for map types: ", q7)} Output: Zero value for integer types: 0 Zero value for float64 types: 0 Zero value for boolean types: false Zero value for string types: Zero value for slice types: [] Zero value for pointer types: <nil> Zero value for map types: map[] Example 2: // Go program to check the variable// contains zero value or notpackage main import "fmt" func main() { // Creating variables of different types var q1 int = 2 var q2 float64 var q3 bool var q4 string // Slice var q5 []int // Pointer var q6 *int // Map var q7 map[int]string // Checking if the given variables // contain their zero value or not if q1 == 0 { fmt.Println("True") } else { fmt.Println("False") } if q2 == 0 { fmt.Println("True") } else { fmt.Println("False") } if q3 == false { fmt.Println("True") } else { fmt.Println("False") } if q4 == "" { fmt.Println("True") } else { fmt.Println("False") } if q5 == nil { fmt.Println("True") } else { fmt.Println("False") } if q6 == nil { fmt.Println("True") } else { fmt.Println("False") } if q7 == nil { fmt.Println("True") } else { fmt.Println("False") } } Output: False True True True True True True Golang Go Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n09 Aug, 2019" }, { "code": null, "e": 508, "s": 28, "text": "In Go language, whenever we allocate memory for a variable with the help of declaration or by using new and if the variable is not initialized explicitly, then the value of such types of variables are automatically initialized with their zero value. The initialization of the zero value is done recursively. So, every element of the array of the structs has its fields zero if they are not specified with any value. Following are the zero values for different types of variables:" }, { "code": null, "e": 519, "s": 508, "text": "Example 1:" }, { "code": "// Go program to illustrate the concept of zero valuepackage main import \"fmt\" // Main Methodfunc main() { // Creating variables // of different types var q1 int var q2 float64 var q3 bool var q4 string var q5 []int var q6 *int var q7 map[int]string // Displaying the zero value // of the above variables fmt.Println(\"Zero value for integer types: \", q1) fmt.Println(\"Zero value for float64 types: \", q2) fmt.Println(\"Zero value for boolean types: \", q3) fmt.Println(\"Zero value for string types: \", q4) fmt.Println(\"Zero value for slice types: \", q5) fmt.Println(\"Zero value for pointer types: \", q6) fmt.Println(\"Zero value for map types: \", q7)}", "e": 1228, "s": 519, "text": null }, { "code": null, "e": 1236, "s": 1228, "text": "Output:" }, { "code": null, "e": 1473, "s": 1236, "text": "Zero value for integer types: 0\nZero value for float64 types: 0\nZero value for boolean types: false\nZero value for string types: \nZero value for slice types: []\nZero value for pointer types: <nil>\nZero value for map types: map[]\n" }, { "code": null, "e": 1484, "s": 1473, "text": "Example 2:" }, { "code": "// Go program to check the variable// contains zero value or notpackage main import \"fmt\" func main() { // Creating variables of different types var q1 int = 2 var q2 float64 var q3 bool var q4 string // Slice var q5 []int // Pointer var q6 *int // Map var q7 map[int]string // Checking if the given variables // contain their zero value or not if q1 == 0 { fmt.Println(\"True\") } else { fmt.Println(\"False\") } if q2 == 0 { fmt.Println(\"True\") } else { fmt.Println(\"False\") } if q3 == false { fmt.Println(\"True\") } else { fmt.Println(\"False\") } if q4 == \"\" { fmt.Println(\"True\") } else { fmt.Println(\"False\") } if q5 == nil { fmt.Println(\"True\") } else { fmt.Println(\"False\") } if q6 == nil { fmt.Println(\"True\") } else { fmt.Println(\"False\") } if q7 == nil { fmt.Println(\"True\") } else { fmt.Println(\"False\") } }", "e": 2670, "s": 1484, "text": null }, { "code": null, "e": 2678, "s": 2670, "text": "Output:" }, { "code": null, "e": 2715, "s": 2678, "text": "False\nTrue\nTrue\nTrue\nTrue\nTrue\nTrue\n" }, { "code": null, "e": 2722, "s": 2715, "text": "Golang" }, { "code": null, "e": 2734, "s": 2722, "text": "Go Language" } ]
How to remove array rows that contain only 0 using NumPy?
20 Aug, 2021 Numpy library provides a function called numpy.all() that returns True when all elements of n-d array passed to the first parameter are True else it returns False. Thus, to determine the entire row containing 0’s can be removed by specifying axis=1. It will traverse each row and will check for the condition given in first parameter. Example: data=[[1,2,3] [0,0,0] [9,8,7]] After removing row with all zeroes: data=[[1,2,3] [9,8,7]] Example 1: Approach Followed: Take a numpy n-d array. Remove rows that contain only zeroes using numpy.all() function. Print the n-d array. Python3 import numpy as np# take datadata = np.array([[1, 2, 3], [0, 0, 0], [4, 5, 6], [0, 0, 0], [7, 8, 9], [0, 0, 0]])# print original data having rows with all zeroesprint("Original Dataset")print(data) # remove rows having all zeroesdata = data[~np.all(data == 0, axis=1)] # data after removing rows having all zeroesprint("After removing rows")print(data) Output: Example 2: Approach Followed: Take 20 random numbers between 0-10, using numpy.random.choice() method. Align them in rows and columns, using reshape() method. Explicitly mark some rows as completely 0. Remove rows having all zeroes. Print dataset. Python3 import numpy as np# take random data # random.choice(x,y) will pick y elements from range (0,(x-1))data = np.random.choice(10, 20) # specify the dimensions of data i.e (rows,columns)data = data.reshape(5, 4) # print original data having rows with all zeroesprint("Original Dataset")print(data) # make some rows entirely zerodata[1, :] = 0 # making 2nd row entirely 0data[4, :] = 0 # making last row entirely 0 # after making 2nd and 5th row as 0print("After making some rows as entirely 0")print(data)data = data[~np.all(data == 0, axis=1)] # data after removing rows having all zeroesprint("After removing rows")print(data) Output: clintra Picked Python numpy-arrayManipulation Python-numpy Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? 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": "\n20 Aug, 2021" }, { "code": null, "e": 364, "s": 28, "text": "Numpy library provides a function called numpy.all() that returns True when all elements of n-d array passed to the first parameter are True else it returns False. Thus, to determine the entire row containing 0’s can be removed by specifying axis=1. It will traverse each row and will check for the condition given in first parameter. " }, { "code": null, "e": 373, "s": 364, "text": "Example:" }, { "code": null, "e": 481, "s": 373, "text": "data=[[1,2,3]\n [0,0,0]\n [9,8,7]]\nAfter removing row with all zeroes:\ndata=[[1,2,3]\n [9,8,7]]" }, { "code": null, "e": 492, "s": 481, "text": "Example 1:" }, { "code": null, "e": 512, "s": 492, "text": "Approach Followed: " }, { "code": null, "e": 536, "s": 512, "text": "Take a numpy n-d array." }, { "code": null, "e": 601, "s": 536, "text": "Remove rows that contain only zeroes using numpy.all() function." }, { "code": null, "e": 622, "s": 601, "text": "Print the n-d array." }, { "code": null, "e": 630, "s": 622, "text": "Python3" }, { "code": "import numpy as np# take datadata = np.array([[1, 2, 3], [0, 0, 0], [4, 5, 6], [0, 0, 0], [7, 8, 9], [0, 0, 0]])# print original data having rows with all zeroesprint(\"Original Dataset\")print(data) # remove rows having all zeroesdata = data[~np.all(data == 0, axis=1)] # data after removing rows having all zeroesprint(\"After removing rows\")print(data)", "e": 999, "s": 630, "text": null }, { "code": null, "e": 1007, "s": 999, "text": "Output:" }, { "code": null, "e": 1018, "s": 1007, "text": "Example 2:" }, { "code": null, "e": 1037, "s": 1018, "text": "Approach Followed:" }, { "code": null, "e": 1110, "s": 1037, "text": "Take 20 random numbers between 0-10, using numpy.random.choice() method." }, { "code": null, "e": 1166, "s": 1110, "text": "Align them in rows and columns, using reshape() method." }, { "code": null, "e": 1209, "s": 1166, "text": "Explicitly mark some rows as completely 0." }, { "code": null, "e": 1240, "s": 1209, "text": "Remove rows having all zeroes." }, { "code": null, "e": 1255, "s": 1240, "text": "Print dataset." }, { "code": null, "e": 1263, "s": 1255, "text": "Python3" }, { "code": "import numpy as np# take random data # random.choice(x,y) will pick y elements from range (0,(x-1))data = np.random.choice(10, 20) # specify the dimensions of data i.e (rows,columns)data = data.reshape(5, 4) # print original data having rows with all zeroesprint(\"Original Dataset\")print(data) # make some rows entirely zerodata[1, :] = 0 # making 2nd row entirely 0data[4, :] = 0 # making last row entirely 0 # after making 2nd and 5th row as 0print(\"After making some rows as entirely 0\")print(data)data = data[~np.all(data == 0, axis=1)] # data after removing rows having all zeroesprint(\"After removing rows\")print(data)", "e": 1890, "s": 1263, "text": null }, { "code": null, "e": 1898, "s": 1890, "text": "Output:" }, { "code": null, "e": 1906, "s": 1898, "text": "clintra" }, { "code": null, "e": 1913, "s": 1906, "text": "Picked" }, { "code": null, "e": 1944, "s": 1913, "text": "Python numpy-arrayManipulation" }, { "code": null, "e": 1957, "s": 1944, "text": "Python-numpy" }, { "code": null, "e": 1964, "s": 1957, "text": "Python" }, { "code": null, "e": 2062, "s": 1964, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2094, "s": 2062, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2121, "s": 2094, "text": "Python Classes and Objects" }, { "code": null, "e": 2142, "s": 2121, "text": "Python OOPs Concepts" }, { "code": null, "e": 2165, "s": 2142, "text": "Introduction To PYTHON" }, { "code": null, "e": 2196, "s": 2165, "text": "Python | os.path.join() method" }, { "code": null, "e": 2252, "s": 2196, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 2294, "s": 2252, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 2336, "s": 2294, "text": "Check if element exists in list in Python" }, { "code": null, "e": 2375, "s": 2336, "text": "Python | Get unique values from a list" } ]
Sliding Window Maximum : Set 2
08 Apr, 2022 Set 1: Sliding Window Maximum (Maximum of all subarrays of size k).Given an array arr of size N and an integer K, the task is to find the maximum for each and every contiguous subarray of size K. Examples: Input: arr[] = {1, 2, 3, 1, 4, 5, 2, 3, 6}, K = 3 Output: 3 3 4 5 5 5 6 All contiguous subarrays of size k are {1, 2, 3} => 3 {2, 3, 1} => 3 {3, 1, 4} => 4 {1, 4, 5} => 5 {4, 5, 2} => 5 {5, 2, 3} => 5 {2, 3, 6} => 6 Input: arr[] = {8, 5, 10, 7, 9, 4, 15, 12, 90, 13}, K = 4 Output: 10 10 10 15 15 90 90 Approach: To solve this in lesser space complexity we can use two pointer technique. The first variable pointer iterates through the subarray and finds the maximum element of a given size K The second variable pointer marks the ending index of the first variable pointer i.e., (i + K – 1)th index. When the first variable pointer reaches the index of the second variable pointer, the maximum of that subarray has been computed and will be printed. The process is repeated until the second variable pointer reaches the last array index (i.e array_size – 1). Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ program to find the maximum for each// and every contiguous subarray of size K #include <bits/stdc++.h>using namespace std; // Function to find the maximum for each// and every contiguous subarray of size kvoid printKMax(int a[], int n, int k){ // If k = 1, print all elements if (k == 1) { for (int i = 0; i < n; i += 1) cout << a[i] << " "; return; } // Using p and q as variable pointers // where p iterates through the subarray // and q marks end of the subarray. int p = 0, q = k - 1, t = p, max = a[k - 1]; // Iterating through subarray. while (q <= n - 1) { // Finding max // from the subarray. if (a[p] > max) max = a[p]; p += 1; // Printing max of subarray // and shifting pointers // to next index. if (q == p && p != n) { cout << max << " "; q++; p = ++t; if (q < n) max = a[q]; } }} // Driver Codeint main(){ int a[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; int n = sizeof(a) / sizeof(a[0]); int K = 3; printKMax(a, n, K); return 0;} // Java program to find the maximum for each// and every contiguous subarray of size Kimport java.util.*; class GFG{ // Function to find the maximum for each// and every contiguous subarray of size kstatic void printKMax(int a[], int n, int k){ // If k = 1, print all elements if (k == 1) { for (int i = 0; i < n; i += 1) System.out.print(a[i]+ " "); return; } // Using p and q as variable pointers // where p iterates through the subarray // and q marks end of the subarray. int p = 0, q = k - 1, t = p, max = a[k - 1]; // Iterating through subarray. while (q <= n - 1) { // Finding max // from the subarray. if (a[p] > max) max = a[p]; p += 1; // Printing max of subarray // and shifting pointers // to next index. if (q == p && p != n) { System.out.print(max+ " "); q++; p = ++t; if (q < n) max = a[q]; } }} // Driver Codepublic static void main(String[] args){ int a[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; int n = a.length; int K = 3; printKMax(a, n, K);}} // This code is contributed by 29AjayKumar # Python3 program to find the maximum for each# and every contiguous subarray of size K # Function to find the maximum for each# and every contiguous subarray of size kdef printKMax(a, n, k): # If k = 1, print all elements if (k == 1): for i in range(n): print(a[i], end=" "); return; # Using p and q as variable pointers # where p iterates through the subarray # and q marks end of the subarray. p = 0; q = k - 1; t = p; max = a[k - 1]; # Iterating through subarray. while (q <= n - 1): # Finding max # from the subarray. if (a[p] > max): max = a[p]; p += 1; # Printing max of subarray # and shifting pointers # to next index. if (q == p and p != n): print(max, end=" "); q += 1; p = t + 1; t = p; if (q < n): max = a[q]; # Driver Codeif __name__ == '__main__': a = [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; n = len(a); K = 3; printKMax(a, n, K); # This code is contributed by Princi Singh // C# program to find the maximum for each// and every contiguous subarray of size Kusing System; class GFG{ // Function to find the maximum for each// and every contiguous subarray of size kstatic void printKMax(int []a, int n, int k){ // If k = 1, print all elements if (k == 1) { for (int i = 0; i < n; i += 1) Console.Write(a[i]+ " "); return; } // Using p and q as variable pointers // where p iterates through the subarray // and q marks end of the subarray. int p = 0, q = k - 1, t = p, max = a[k - 1]; // Iterating through subarray. while (q <= n - 1) { // Finding max // from the subarray. if (a[p] > max) max = a[p]; p += 1; // Printing max of subarray // and shifting pointers // to next index. if (q == p && p != n) { Console.Write(max+ " "); q++; p = ++t; if (q < n) max = a[q]; } }} // Driver Codepublic static void Main(String[] args){ int []a = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; int n = a.Length; int K = 3; printKMax(a, n, K);}} // This code is contributed by Rajput-Ji <script>// Javascript program to find the maximum for each// and every contiguous subarray of size K // Function to find the maximum for each// and every contiguous subarray of size kfunction printKMax(a, n, k){ // If k = 1, print all elements if (k == 1) { for (let i = 0; i < n; i += 1) document.write(a[i] + " "); return; } // Using p and q as variable pointers // where p iterates through the subarray // and q marks end of the subarray. let p = 0, q = k - 1, t = p, max = a[k - 1]; // Iterating through subarray. while (q <= n - 1) { // Finding max // from the subarray. if (a[p] > max) max = a[p]; p += 1; // Printing max of subarray // and shifting pointers // to next index. if (q == p && p != n) { document.write(max + " "); q++; p = ++t; if (q < n) max = a[q]; } }} // Driver Code let a = [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ];let n = a.lengthlet K = 3; printKMax(a, n, K);</script> 3 4 5 6 7 8 9 10 Time Complexity: O(N*k) Auxiliary Space Complexity: O(1) Approach 2: Using Dynamic Programming: Firstly, divide the entire array into blocks of k elements such that each block contains k elements of the array(not always for the last block). Maintain two dp arrays namely, left and right. left[i] is the maximum of all elements that are to the left of current element(including current element) in the current block(block in which current element is present). Similarly, right[i] is the maximum of all elements that are to the right of current element(including current element) in the current block(block in which current element is present). Finally, when calculating the maximum element in any subarray of length k, we calculate the maximum of right[l] and left[r]where l = starting index of current sub array, r = ending index of current sub array Below is the implementation of above approach, C++ Java Python3 C# Javascript // C++ program to find the maximum for each// and every contiguous subarray of size K #include <bits/stdc++.h>using namespace std; // Function to find the maximum for each// and every contiguous subarray of size kvoid printKMax(int a[], int n, int k){ // If k = 1, print all elements if (k == 1) { for (int i = 0; i < n; i += 1) cout << a[i] << " "; return; } //left[i] stores the maximum value to left of i in the current block //right[i] stores the maximum value to the right of i in the current block int left[n],right[n]; for(int i=0;i<n;i++){ //if the element is starting element of that block if(i%k == 0) left[i] = a[i]; else left[i] = max(left[i-1],a[i]); //if the element is ending element of that block if((n-i)%k == 0 || i==0) right[n-1-i] = a[n-1-i]; else right[n-1-i] = max(right[n-i],a[n-1-i]); } for(int i=0,j=k-1; j<n; i++,j++) cout << max(left[j],right[i]) << ' ';} // Driver Codeint main(){ int a[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; int n = sizeof(a) / sizeof(a[0]); int K = 3; printKMax(a, n, K); return 0;} // Java program to find the maximum for each// and every contiguous subarray of size Kimport java.util.*; class GFG{ // Function to find the maximum for each // and every contiguous subarray of size k static void printKMax(int a[], int n, int k) { // If k = 1, print all elements if (k == 1) { for (int i = 0; i < n; i += 1) System.out.print(a[i] + " "); return; } // left[i] stores the maximum value to left of i in the current block // right[i] stores the maximum value to the right of i in the current block int left[] = new int[n]; int right[] = new int[n]; for (int i = 0; i < n; i++) { // if the element is starting element of that block if (i % k == 0) left[i] = a[i]; else left[i] = Math.max(left[i - 1], a[i]); // if the element is ending element of that block if ((n - i) % k == 0 || i == 0) right[n - 1 - i] = a[n - 1 - i]; else right[n - 1 - i] = Math.max(right[n - i], a[n - 1 - i]); } for (int i = 0, j = k - 1; j < n; i++, j++) System.out.print(Math.max(left[j], right[i]) + " "); } // Driver Code public static void main(String[] args) { int a[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; int n = a.length; int K = 3; printKMax(a, n, K); }} // This code is contributed by gauravrajput1 # Python3 program to find the maximum for each# and every contiguous subarray of size K# Function to find the maximum for each# and every contiguous subarray of size kdef printKMax(a, n, k): # If k = 1, print all elements if (k == 1): for i in range(n): print(a[i],end = " ") return # left[i] stores the maximum value to left of i in the current block # right[i] stores the maximum value to the right of i in the current block left = [ 0 for i in range(n)] right = [ 0 for i in range(n)] for i in range(n): # if the element is starting element of that block if (i % k == 0): left[i] = a[i] else: left[i] = max(left[i - 1], a[i]) # if the element is ending element of that block if ((n - i) % k == 0 or i == 0): right[n - 1 - i] = a[n - 1 - i] else: right[n - 1 - i] = max(right[n - i], a[n - 1 - i]) i = 0 j = k - 1 while j < n: print(max(left[j], right[i]),end = " ") i += 1 j += 1 # Driver Codea = [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]n = len(a)K = 3 printKMax(a, n, K) # This code is contributed by shinjanpatra // C# program to find the maximum for each// and every contiguous subarray of size Kusing System; class GFG{ // Function to find the maximum for each // and every contiguous subarray of size k static void printKMax(int []a, int n, int k) { // If k = 1, print all elements if (k == 1) { for (int i = 0; i < n; i += 1) Console.Write(a[i] + " "); return; } // left[i] stores the maximum value to left of i in the current block // right[i] stores the maximum value to the right of i in the current block int []left = new int[n]; int []right = new int[n]; for (int i = 0; i < n; i++) { // if the element is starting element of that block if (i % k == 0) left[i] = a[i]; else left[i] = Math.Max(left[i - 1], a[i]); // if the element is ending element of that block if ((n - i) % k == 0 || i == 0) right[n - 1 - i] = a[n - 1 - i]; else right[n - 1 - i] = Math.Max(right[n - i], a[n - 1 - i]); } for (int i = 0, j = k - 1; j < n; i++, j++) Console.Write(Math.Max(left[j], right[i]) + " "); } // Driver Code public static void Main(String[] args) { int []a = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; int n = a.Length; int K = 3; printKMax(a, n, K); }} // This code is contributed by shivanisinghss2110 <script> // JavaScript program to find the maximum for each// and every contiguous subarray of size K// Function to find the maximum for each// and every contiguous subarray of size kfunction printKMax(a, n, k) { // If k = 1, print all elements if (k == 1) { for (var i = 0; i < n; i += 1) document.write(a[i] + " "); return; } // left[i] stores the maximum value to left of i in the current block // right[i] stores the maximum value to the right of i in the current block var left = [n]; var right = [n]; for (var i = 0; i < n; i++) { // if the element is starting element of that block if (i % k == 0) left[i] = a[i]; else left[i] = Math.max(left[i - 1], a[i]); // if the element is ending element of that block if ((n - i) % k == 0 || i == 0) right[n - 1 - i] = a[n - 1 - i]; else right[n - 1 - i] = Math.max(right[n - i], a[n - 1 - i]); } for (var i = 0, j = k - 1; j < n; i++, j++) document.write(Math.max(left[j], right[i]) + " "); } // Driver Code var a = [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]; var n = a.length; var K = 3; printKMax(a, n, K); // This code is contributed by shivanisinghss2110 </script> 3 4 5 6 7 8 9 10 Time Complexity : O(n)Auxiliary Space : O(n) 29AjayKumar Rajput-Ji princi singh sirmihirmsd07 _saurabh_jaiswal ritwiksri3 GauravRajput1 shivanisinghss2110 adnanirshad158 shinjanpatra Amazon Directi Flipkart SAP Labs sliding-window two-pointer-algorithm Zoho Arrays Zoho Flipkart Amazon Directi SAP Labs sliding-window two-pointer-algorithm Arrays Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Multidimensional Arrays in Java Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum) Introduction to Arrays K'th Smallest/Largest Element in Unsorted Array | Set 1 Subset Sum Problem | DP-25 Introduction to Data Structures Python | Using 2D arrays/lists the right way Find Second largest element in an array Search an element in a sorted and rotated array Find the Missing Number
[ { "code": null, "e": 54, "s": 26, "text": "\n08 Apr, 2022" }, { "code": null, "e": 250, "s": 54, "text": "Set 1: Sliding Window Maximum (Maximum of all subarrays of size k).Given an array arr of size N and an integer K, the task is to find the maximum for each and every contiguous subarray of size K." }, { "code": null, "e": 261, "s": 250, "text": "Examples: " }, { "code": null, "e": 477, "s": 261, "text": "Input: arr[] = {1, 2, 3, 1, 4, 5, 2, 3, 6}, K = 3 Output: 3 3 4 5 5 5 6 All contiguous subarrays of size k are {1, 2, 3} => 3 {2, 3, 1} => 3 {3, 1, 4} => 4 {1, 4, 5} => 5 {4, 5, 2} => 5 {5, 2, 3} => 5 {2, 3, 6} => 6" }, { "code": null, "e": 566, "s": 477, "text": "Input: arr[] = {8, 5, 10, 7, 9, 4, 15, 12, 90, 13}, K = 4 Output: 10 10 10 15 15 90 90 " }, { "code": null, "e": 653, "s": 566, "text": "Approach: To solve this in lesser space complexity we can use two pointer technique. " }, { "code": null, "e": 758, "s": 653, "text": "The first variable pointer iterates through the subarray and finds the maximum element of a given size K" }, { "code": null, "e": 866, "s": 758, "text": "The second variable pointer marks the ending index of the first variable pointer i.e., (i + K – 1)th index." }, { "code": null, "e": 1016, "s": 866, "text": "When the first variable pointer reaches the index of the second variable pointer, the maximum of that subarray has been computed and will be printed." }, { "code": null, "e": 1125, "s": 1016, "text": "The process is repeated until the second variable pointer reaches the last array index (i.e array_size – 1)." }, { "code": null, "e": 1177, "s": 1125, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 1181, "s": 1177, "text": "C++" }, { "code": null, "e": 1186, "s": 1181, "text": "Java" }, { "code": null, "e": 1194, "s": 1186, "text": "Python3" }, { "code": null, "e": 1197, "s": 1194, "text": "C#" }, { "code": null, "e": 1208, "s": 1197, "text": "Javascript" }, { "code": "// C++ program to find the maximum for each// and every contiguous subarray of size K #include <bits/stdc++.h>using namespace std; // Function to find the maximum for each// and every contiguous subarray of size kvoid printKMax(int a[], int n, int k){ // If k = 1, print all elements if (k == 1) { for (int i = 0; i < n; i += 1) cout << a[i] << \" \"; return; } // Using p and q as variable pointers // where p iterates through the subarray // and q marks end of the subarray. int p = 0, q = k - 1, t = p, max = a[k - 1]; // Iterating through subarray. while (q <= n - 1) { // Finding max // from the subarray. if (a[p] > max) max = a[p]; p += 1; // Printing max of subarray // and shifting pointers // to next index. if (q == p && p != n) { cout << max << \" \"; q++; p = ++t; if (q < n) max = a[q]; } }} // Driver Codeint main(){ int a[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; int n = sizeof(a) / sizeof(a[0]); int K = 3; printKMax(a, n, K); return 0;}", "e": 2404, "s": 1208, "text": null }, { "code": "// Java program to find the maximum for each// and every contiguous subarray of size Kimport java.util.*; class GFG{ // Function to find the maximum for each// and every contiguous subarray of size kstatic void printKMax(int a[], int n, int k){ // If k = 1, print all elements if (k == 1) { for (int i = 0; i < n; i += 1) System.out.print(a[i]+ \" \"); return; } // Using p and q as variable pointers // where p iterates through the subarray // and q marks end of the subarray. int p = 0, q = k - 1, t = p, max = a[k - 1]; // Iterating through subarray. while (q <= n - 1) { // Finding max // from the subarray. if (a[p] > max) max = a[p]; p += 1; // Printing max of subarray // and shifting pointers // to next index. if (q == p && p != n) { System.out.print(max+ \" \"); q++; p = ++t; if (q < n) max = a[q]; } }} // Driver Codepublic static void main(String[] args){ int a[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; int n = a.length; int K = 3; printKMax(a, n, K);}} // This code is contributed by 29AjayKumar", "e": 3660, "s": 2404, "text": null }, { "code": "# Python3 program to find the maximum for each# and every contiguous subarray of size K # Function to find the maximum for each# and every contiguous subarray of size kdef printKMax(a, n, k): # If k = 1, print all elements if (k == 1): for i in range(n): print(a[i], end=\" \"); return; # Using p and q as variable pointers # where p iterates through the subarray # and q marks end of the subarray. p = 0; q = k - 1; t = p; max = a[k - 1]; # Iterating through subarray. while (q <= n - 1): # Finding max # from the subarray. if (a[p] > max): max = a[p]; p += 1; # Printing max of subarray # and shifting pointers # to next index. if (q == p and p != n): print(max, end=\" \"); q += 1; p = t + 1; t = p; if (q < n): max = a[q]; # Driver Codeif __name__ == '__main__': a = [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; n = len(a); K = 3; printKMax(a, n, K); # This code is contributed by Princi Singh", "e": 4769, "s": 3660, "text": null }, { "code": "// C# program to find the maximum for each// and every contiguous subarray of size Kusing System; class GFG{ // Function to find the maximum for each// and every contiguous subarray of size kstatic void printKMax(int []a, int n, int k){ // If k = 1, print all elements if (k == 1) { for (int i = 0; i < n; i += 1) Console.Write(a[i]+ \" \"); return; } // Using p and q as variable pointers // where p iterates through the subarray // and q marks end of the subarray. int p = 0, q = k - 1, t = p, max = a[k - 1]; // Iterating through subarray. while (q <= n - 1) { // Finding max // from the subarray. if (a[p] > max) max = a[p]; p += 1; // Printing max of subarray // and shifting pointers // to next index. if (q == p && p != n) { Console.Write(max+ \" \"); q++; p = ++t; if (q < n) max = a[q]; } }} // Driver Codepublic static void Main(String[] args){ int []a = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; int n = a.Length; int K = 3; printKMax(a, n, K);}} // This code is contributed by Rajput-Ji", "e": 6019, "s": 4769, "text": null }, { "code": "<script>// Javascript program to find the maximum for each// and every contiguous subarray of size K // Function to find the maximum for each// and every contiguous subarray of size kfunction printKMax(a, n, k){ // If k = 1, print all elements if (k == 1) { for (let i = 0; i < n; i += 1) document.write(a[i] + \" \"); return; } // Using p and q as variable pointers // where p iterates through the subarray // and q marks end of the subarray. let p = 0, q = k - 1, t = p, max = a[k - 1]; // Iterating through subarray. while (q <= n - 1) { // Finding max // from the subarray. if (a[p] > max) max = a[p]; p += 1; // Printing max of subarray // and shifting pointers // to next index. if (q == p && p != n) { document.write(max + \" \"); q++; p = ++t; if (q < n) max = a[q]; } }} // Driver Code let a = [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ];let n = a.lengthlet K = 3; printKMax(a, n, K);</script>", "e": 7113, "s": 6019, "text": null }, { "code": null, "e": 7131, "s": 7113, "text": "3 4 5 6 7 8 9 10 " }, { "code": null, "e": 7189, "s": 7131, "text": "Time Complexity: O(N*k) Auxiliary Space Complexity: O(1) " }, { "code": null, "e": 7228, "s": 7189, "text": "Approach 2: Using Dynamic Programming:" }, { "code": null, "e": 7373, "s": 7228, "text": "Firstly, divide the entire array into blocks of k elements such that each block contains k elements of the array(not always for the last block)." }, { "code": null, "e": 7420, "s": 7373, "text": "Maintain two dp arrays namely, left and right." }, { "code": null, "e": 7591, "s": 7420, "text": "left[i] is the maximum of all elements that are to the left of current element(including current element) in the current block(block in which current element is present)." }, { "code": null, "e": 7775, "s": 7591, "text": "Similarly, right[i] is the maximum of all elements that are to the right of current element(including current element) in the current block(block in which current element is present)." }, { "code": null, "e": 7983, "s": 7775, "text": "Finally, when calculating the maximum element in any subarray of length k, we calculate the maximum of right[l] and left[r]where l = starting index of current sub array, r = ending index of current sub array" }, { "code": null, "e": 8030, "s": 7983, "text": "Below is the implementation of above approach," }, { "code": null, "e": 8034, "s": 8030, "text": "C++" }, { "code": null, "e": 8039, "s": 8034, "text": "Java" }, { "code": null, "e": 8047, "s": 8039, "text": "Python3" }, { "code": null, "e": 8050, "s": 8047, "text": "C#" }, { "code": null, "e": 8061, "s": 8050, "text": "Javascript" }, { "code": "// C++ program to find the maximum for each// and every contiguous subarray of size K #include <bits/stdc++.h>using namespace std; // Function to find the maximum for each// and every contiguous subarray of size kvoid printKMax(int a[], int n, int k){ // If k = 1, print all elements if (k == 1) { for (int i = 0; i < n; i += 1) cout << a[i] << \" \"; return; } //left[i] stores the maximum value to left of i in the current block //right[i] stores the maximum value to the right of i in the current block int left[n],right[n]; for(int i=0;i<n;i++){ //if the element is starting element of that block if(i%k == 0) left[i] = a[i]; else left[i] = max(left[i-1],a[i]); //if the element is ending element of that block if((n-i)%k == 0 || i==0) right[n-1-i] = a[n-1-i]; else right[n-1-i] = max(right[n-i],a[n-1-i]); } for(int i=0,j=k-1; j<n; i++,j++) cout << max(left[j],right[i]) << ' ';} // Driver Codeint main(){ int a[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; int n = sizeof(a) / sizeof(a[0]); int K = 3; printKMax(a, n, K); return 0;}", "e": 9265, "s": 8061, "text": null }, { "code": "// Java program to find the maximum for each// and every contiguous subarray of size Kimport java.util.*; class GFG{ // Function to find the maximum for each // and every contiguous subarray of size k static void printKMax(int a[], int n, int k) { // If k = 1, print all elements if (k == 1) { for (int i = 0; i < n; i += 1) System.out.print(a[i] + \" \"); return; } // left[i] stores the maximum value to left of i in the current block // right[i] stores the maximum value to the right of i in the current block int left[] = new int[n]; int right[] = new int[n]; for (int i = 0; i < n; i++) { // if the element is starting element of that block if (i % k == 0) left[i] = a[i]; else left[i] = Math.max(left[i - 1], a[i]); // if the element is ending element of that block if ((n - i) % k == 0 || i == 0) right[n - 1 - i] = a[n - 1 - i]; else right[n - 1 - i] = Math.max(right[n - i], a[n - 1 - i]); } for (int i = 0, j = k - 1; j < n; i++, j++) System.out.print(Math.max(left[j], right[i]) + \" \"); } // Driver Code public static void main(String[] args) { int a[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; int n = a.length; int K = 3; printKMax(a, n, K); }} // This code is contributed by gauravrajput1", "e": 10605, "s": 9265, "text": null }, { "code": "# Python3 program to find the maximum for each# and every contiguous subarray of size K# Function to find the maximum for each# and every contiguous subarray of size kdef printKMax(a, n, k): # If k = 1, print all elements if (k == 1): for i in range(n): print(a[i],end = \" \") return # left[i] stores the maximum value to left of i in the current block # right[i] stores the maximum value to the right of i in the current block left = [ 0 for i in range(n)] right = [ 0 for i in range(n)] for i in range(n): # if the element is starting element of that block if (i % k == 0): left[i] = a[i] else: left[i] = max(left[i - 1], a[i]) # if the element is ending element of that block if ((n - i) % k == 0 or i == 0): right[n - 1 - i] = a[n - 1 - i] else: right[n - 1 - i] = max(right[n - i], a[n - 1 - i]) i = 0 j = k - 1 while j < n: print(max(left[j], right[i]),end = \" \") i += 1 j += 1 # Driver Codea = [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]n = len(a)K = 3 printKMax(a, n, K) # This code is contributed by shinjanpatra", "e": 11785, "s": 10605, "text": null }, { "code": "// C# program to find the maximum for each// and every contiguous subarray of size Kusing System; class GFG{ // Function to find the maximum for each // and every contiguous subarray of size k static void printKMax(int []a, int n, int k) { // If k = 1, print all elements if (k == 1) { for (int i = 0; i < n; i += 1) Console.Write(a[i] + \" \"); return; } // left[i] stores the maximum value to left of i in the current block // right[i] stores the maximum value to the right of i in the current block int []left = new int[n]; int []right = new int[n]; for (int i = 0; i < n; i++) { // if the element is starting element of that block if (i % k == 0) left[i] = a[i]; else left[i] = Math.Max(left[i - 1], a[i]); // if the element is ending element of that block if ((n - i) % k == 0 || i == 0) right[n - 1 - i] = a[n - 1 - i]; else right[n - 1 - i] = Math.Max(right[n - i], a[n - 1 - i]); } for (int i = 0, j = k - 1; j < n; i++, j++) Console.Write(Math.Max(left[j], right[i]) + \" \"); } // Driver Code public static void Main(String[] args) { int []a = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; int n = a.Length; int K = 3; printKMax(a, n, K); }} // This code is contributed by shivanisinghss2110", "e": 13116, "s": 11785, "text": null }, { "code": "<script> // JavaScript program to find the maximum for each// and every contiguous subarray of size K// Function to find the maximum for each// and every contiguous subarray of size kfunction printKMax(a, n, k) { // If k = 1, print all elements if (k == 1) { for (var i = 0; i < n; i += 1) document.write(a[i] + \" \"); return; } // left[i] stores the maximum value to left of i in the current block // right[i] stores the maximum value to the right of i in the current block var left = [n]; var right = [n]; for (var i = 0; i < n; i++) { // if the element is starting element of that block if (i % k == 0) left[i] = a[i]; else left[i] = Math.max(left[i - 1], a[i]); // if the element is ending element of that block if ((n - i) % k == 0 || i == 0) right[n - 1 - i] = a[n - 1 - i]; else right[n - 1 - i] = Math.max(right[n - i], a[n - 1 - i]); } for (var i = 0, j = k - 1; j < n; i++, j++) document.write(Math.max(left[j], right[i]) + \" \"); } // Driver Code var a = [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]; var n = a.length; var K = 3; printKMax(a, n, K); // This code is contributed by shivanisinghss2110 </script>", "e": 14360, "s": 13116, "text": null }, { "code": null, "e": 14378, "s": 14360, "text": "3 4 5 6 7 8 9 10 " }, { "code": null, "e": 14426, "s": 14378, "text": "Time Complexity : O(n)Auxiliary Space : O(n)" }, { "code": null, "e": 14438, "s": 14426, "text": "29AjayKumar" }, { "code": null, "e": 14448, "s": 14438, "text": "Rajput-Ji" }, { "code": null, "e": 14461, "s": 14448, "text": "princi singh" }, { "code": null, "e": 14475, "s": 14461, "text": "sirmihirmsd07" }, { "code": null, "e": 14492, "s": 14475, "text": "_saurabh_jaiswal" }, { "code": null, "e": 14503, "s": 14492, "text": "ritwiksri3" }, { "code": null, "e": 14517, "s": 14503, "text": "GauravRajput1" }, { "code": null, "e": 14536, "s": 14517, "text": "shivanisinghss2110" }, { "code": null, "e": 14551, "s": 14536, "text": "adnanirshad158" }, { "code": null, "e": 14564, "s": 14551, "text": "shinjanpatra" }, { "code": null, "e": 14571, "s": 14564, "text": "Amazon" }, { "code": null, "e": 14579, "s": 14571, "text": "Directi" }, { "code": null, "e": 14588, "s": 14579, "text": "Flipkart" }, { "code": null, "e": 14597, "s": 14588, "text": "SAP Labs" }, { "code": null, "e": 14612, "s": 14597, "text": "sliding-window" }, { "code": null, "e": 14634, "s": 14612, "text": "two-pointer-algorithm" }, { "code": null, "e": 14639, "s": 14634, "text": "Zoho" }, { "code": null, "e": 14646, "s": 14639, "text": "Arrays" }, { "code": null, "e": 14651, "s": 14646, "text": "Zoho" }, { "code": null, "e": 14660, "s": 14651, "text": "Flipkart" }, { "code": null, "e": 14667, "s": 14660, "text": "Amazon" }, { "code": null, "e": 14675, "s": 14667, "text": "Directi" }, { "code": null, "e": 14684, "s": 14675, "text": "SAP Labs" }, { "code": null, "e": 14699, "s": 14684, "text": "sliding-window" }, { "code": null, "e": 14721, "s": 14699, "text": "two-pointer-algorithm" }, { "code": null, "e": 14728, "s": 14721, "text": "Arrays" }, { "code": null, "e": 14826, "s": 14728, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 14858, "s": 14826, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 14943, "s": 14858, "text": "Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)" }, { "code": null, "e": 14966, "s": 14943, "text": "Introduction to Arrays" }, { "code": null, "e": 15022, "s": 14966, "text": "K'th Smallest/Largest Element in Unsorted Array | Set 1" }, { "code": null, "e": 15049, "s": 15022, "text": "Subset Sum Problem | DP-25" }, { "code": null, "e": 15081, "s": 15049, "text": "Introduction to Data Structures" }, { "code": null, "e": 15126, "s": 15081, "text": "Python | Using 2D arrays/lists the right way" }, { "code": null, "e": 15166, "s": 15126, "text": "Find Second largest element in an array" }, { "code": null, "e": 15214, "s": 15166, "text": "Search an element in a sorted and rotated array" } ]
Remove unique key from MySQL table?
To remove the unique key from MySQL, use the DROP command. The syntax is as follows − ALTER TABLE yourTableName DROP INDEX yourKeyName; To understand the above syntax, let us create a table with the unique key. The query to create a table is as follows − mysql> create table DropIndexDemo −> ( −> BookId int unique key, −> BookName varchar(200) −> ); Query OK, 0 rows affected (0.88 sec) Now you can check what is the key name with the help of show command. This unique key will get deleted. The query is as follows − mysql> show index from DropIndexDemo; The following is the output − +-----------+------------+----------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+---------+ | Table | Non_unique | Key_name | Seq_in_index | Column_name | Collation | Cardinality | Sub_part | Packed | Null | Index_type | Comment | Index_comment | Visible | +-----------+------------+----------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+---------+ | dropindex | 0 | BookId | 1 | BookId | A | 0 | NULL | NULL | YES | BTREE | | | YES | +-----------+------------+----------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+---------+ 1 row in set (0.17 sec) Look at the above sample output, your key name is ‘BookId’. Now here is the query to remove unique key − mysql> alter table DropIndex drop index BookId ; Query OK, 0 rows affected (0.33 sec) Records: 0 Duplicates: 0 Warnings: 0 We have removed the unique key from MySQL table DropIndex. The BookId column had unique key before. Now display the table structure with the help of desc command. This won’t display Unique Key since we have deleted it − mysql> desc DropIndex; The following is the output − +----------+--------------+------+-----+---------+-------+ | Field | Type | Null | Key | Default | Extra | +----------+--------------+------+-----+---------+-------+ | BookId | int(11) | YES | | NULL | | | BookName | varchar(200) | YES | | NULL | | +----------+--------------+------+-----+---------+-------+ 2 rows in set (0.00 sec) Look at the above sample output there is no unique key in column BookId.
[ { "code": null, "e": 1273, "s": 1187, "text": "To remove the unique key from MySQL, use the DROP command. The syntax is as follows −" }, { "code": null, "e": 1323, "s": 1273, "text": "ALTER TABLE yourTableName DROP INDEX yourKeyName;" }, { "code": null, "e": 1442, "s": 1323, "text": "To understand the above syntax, let us create a table with the unique key. The query to create a table is as follows −" }, { "code": null, "e": 1587, "s": 1442, "text": "mysql> create table DropIndexDemo\n −> (\n −> BookId int unique key,\n −> BookName varchar(200)\n −> );\nQuery OK, 0 rows affected (0.88 sec)" }, { "code": null, "e": 1717, "s": 1587, "text": "Now you can check what is the key name with the help of show command. This unique key will get deleted. The query is as follows −" }, { "code": null, "e": 1755, "s": 1717, "text": "mysql> show index from DropIndexDemo;" }, { "code": null, "e": 1785, "s": 1755, "text": "The following is the output −" }, { "code": null, "e": 2654, "s": 1785, "text": "+-----------+------------+----------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+---------+\n| Table | Non_unique | Key_name | Seq_in_index | Column_name | Collation | Cardinality | Sub_part | Packed | Null | Index_type | Comment | Index_comment | Visible |\n+-----------+------------+----------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+---------+\n| dropindex | 0 | BookId | 1 | BookId | A | 0 | NULL | NULL | YES | BTREE | | | YES |\n+-----------+------------+----------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+---------+\n1 row in set (0.17 sec)" }, { "code": null, "e": 2759, "s": 2654, "text": "Look at the above sample output, your key name is ‘BookId’. Now here is the query to remove unique key −" }, { "code": null, "e": 2882, "s": 2759, "text": "mysql> alter table DropIndex drop index BookId ;\nQuery OK, 0 rows affected (0.33 sec)\nRecords: 0 Duplicates: 0 Warnings: 0" }, { "code": null, "e": 2982, "s": 2882, "text": "We have removed the unique key from MySQL table DropIndex. The BookId column had unique key before." }, { "code": null, "e": 3102, "s": 2982, "text": "Now display the table structure with the help of desc command. This won’t display Unique Key since we have deleted it −" }, { "code": null, "e": 3125, "s": 3102, "text": "mysql> desc DropIndex;" }, { "code": null, "e": 3155, "s": 3125, "text": "The following is the output −" }, { "code": null, "e": 3534, "s": 3155, "text": "+----------+--------------+------+-----+---------+-------+\n| Field | Type | Null | Key | Default | Extra |\n+----------+--------------+------+-----+---------+-------+\n| BookId | int(11) | YES | | NULL | |\n| BookName | varchar(200) | YES | | NULL | |\n+----------+--------------+------+-----+---------+-------+\n2 rows in set (0.00 sec)" }, { "code": null, "e": 3607, "s": 3534, "text": "Look at the above sample output there is no unique key in column BookId." } ]
numpy.squeeze() in Python
28 Nov, 2018 numpy.squeeze() function is used when we want to remove single-dimensional entries from the shape of an array. Syntax : numpy.squeeze(arr, axis=None ) Parameters :arr : [array_like] Input array.axis : [None or int or tuple of ints, optional] Selects a subset of the single-dimensional entries in the shape. If an axis is selected with shape entry greater than one, an error is raised. Return :squeezed [ndarray] The input array, but with all or a subset of the dimensions of length 1 removed. This is always a itself or a view into arr. Code #1 : # Python program explaining# numpy.squeeze function import numpy as geek in_arr = geek.array([[[2, 2, 2], [2, 2, 2]]]) print ("Input array : ", in_arr) print("Shape of input array : ", in_arr.shape) out_arr = geek.squeeze(in_arr) print ("output squeezed array : ", out_arr)print("Shape of output array : ", out_arr.shape) Output : Input array : [[[2 2 2] [2 2 2]]] Shape of input array : (1, 2, 3) output squeezed array : [[2 2 2] [2 2 2]] Shape of output array : (2, 3) Code #2 : # Python program explaining# numpy.squeeze functionimport numpy as geekin_arr = geek.arange(9).reshape(1, 3, 3) print ("Input array : ", in_arr) out_arr = geek.squeeze(in_arr, axis = 0) print ("output array : ", out_arr) print("The shapes of Input and Output array : ") print(in_arr.shape, out_arr.shape) Output : Input array : [[[0 1 2] [3 4 5] [6 7 8]]] output array : [[0 1 2] [3 4 5] [6 7 8]] The shapes of Input and Output array : (1, 3, 3) (3, 3) Note : ValueError : If axis is not None, and an axis being squeezed is not of length 1. Code #3 : # Python program explaining# numpy.squeeze function# when value error occursimport numpy as geek in_arr = geek.arange(9).reshape(1, 3, 3) print ("Input array : ", in_arr) out_arr = geek.squeeze(in_arr, axis = 1) print ("output array : ", out_arr) print("The shapes of Input and Output array : ") print(in_arr.shape, out_arr.shape) Output : ValueError Traceback (most recent call last) in () 5 6 print ("Input array : ", in_arr) ----> 7 out_arr = geek.squeeze(in_arr, axis=1) 8 print ("output array : ", out_arr) 9 print("The shapes of Input and Output array : ") ~\Anaconda3\lib\site-packages\numpy\core\fromnumeric.py in squeeze(a, axis) 1196 try: 1197 # First try to use the new axis= parameter -> 1198 return squeeze(axis=axis) 1199 except TypeError: 1200 # For backwards compatibility ValueError: cannot select an axis to squeeze out which has size not equal to one Python numpy-arrayManipulation Python-numpy 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 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 Introduction To PYTHON Python OOPs Concepts Convert integer to string in Python
[ { "code": null, "e": 28, "s": 0, "text": "\n28 Nov, 2018" }, { "code": null, "e": 139, "s": 28, "text": "numpy.squeeze() function is used when we want to remove single-dimensional entries from the shape of an array." }, { "code": null, "e": 179, "s": 139, "text": "Syntax : numpy.squeeze(arr, axis=None )" }, { "code": null, "e": 413, "s": 179, "text": "Parameters :arr : [array_like] Input array.axis : [None or int or tuple of ints, optional] Selects a subset of the single-dimensional entries in the shape. If an axis is selected with shape entry greater than one, an error is raised." }, { "code": null, "e": 565, "s": 413, "text": "Return :squeezed [ndarray] The input array, but with all or a subset of the dimensions of length 1 removed. This is always a itself or a view into arr." }, { "code": null, "e": 575, "s": 565, "text": "Code #1 :" }, { "code": "# Python program explaining# numpy.squeeze function import numpy as geek in_arr = geek.array([[[2, 2, 2], [2, 2, 2]]]) print (\"Input array : \", in_arr) print(\"Shape of input array : \", in_arr.shape) out_arr = geek.squeeze(in_arr) print (\"output squeezed array : \", out_arr)print(\"Shape of output array : \", out_arr.shape) ", "e": 907, "s": 575, "text": null }, { "code": null, "e": 916, "s": 907, "text": "Output :" }, { "code": null, "e": 1064, "s": 916, "text": "Input array : [[[2 2 2]\n [2 2 2]]]\nShape of input array : (1, 2, 3)\noutput squeezed array : [[2 2 2]\n [2 2 2]]\nShape of output array : (2, 3)\n" }, { "code": null, "e": 1075, "s": 1064, "text": " Code #2 :" }, { "code": "# Python program explaining# numpy.squeeze functionimport numpy as geekin_arr = geek.arange(9).reshape(1, 3, 3) print (\"Input array : \", in_arr) out_arr = geek.squeeze(in_arr, axis = 0) print (\"output array : \", out_arr) print(\"The shapes of Input and Output array : \") print(in_arr.shape, out_arr.shape)", "e": 1388, "s": 1075, "text": null }, { "code": null, "e": 1397, "s": 1388, "text": "Output :" }, { "code": null, "e": 1546, "s": 1397, "text": "Input array : [[[0 1 2]\n [3 4 5]\n [6 7 8]]]\noutput array : [[0 1 2]\n [3 4 5]\n [6 7 8]]\nThe shapes of Input and Output array : \n(1, 3, 3) (3, 3)\n" }, { "code": null, "e": 1553, "s": 1546, "text": "Note :" }, { "code": null, "e": 1634, "s": 1553, "text": "ValueError :\nIf axis is not None, and an axis being squeezed is not of length 1." }, { "code": null, "e": 1645, "s": 1634, "text": " Code #3 :" }, { "code": "# Python program explaining# numpy.squeeze function# when value error occursimport numpy as geek in_arr = geek.arange(9).reshape(1, 3, 3) print (\"Input array : \", in_arr) out_arr = geek.squeeze(in_arr, axis = 1) print (\"output array : \", out_arr) print(\"The shapes of Input and Output array : \") print(in_arr.shape, out_arr.shape)", "e": 1985, "s": 1645, "text": null }, { "code": null, "e": 1994, "s": 1985, "text": "Output :" }, { "code": null, "e": 2628, "s": 1994, "text": "ValueError Traceback (most recent call last)\n in ()\n 5 \n 6 print (\"Input array : \", in_arr)\n----> 7 out_arr = geek.squeeze(in_arr, axis=1)\n 8 print (\"output array : \", out_arr)\n 9 print(\"The shapes of Input and Output array : \")\n\n~\\Anaconda3\\lib\\site-packages\\numpy\\core\\fromnumeric.py in squeeze(a, axis)\n 1196 try:\n 1197 # First try to use the new axis= parameter\n-> 1198 return squeeze(axis=axis)\n 1199 except TypeError:\n 1200 # For backwards compatibility\n\nValueError: cannot select an axis to squeeze out which has size not equal to one\n" }, { "code": null, "e": 2659, "s": 2628, "text": "Python numpy-arrayManipulation" }, { "code": null, "e": 2672, "s": 2659, "text": "Python-numpy" }, { "code": null, "e": 2679, "s": 2672, "text": "Python" }, { "code": null, "e": 2777, "s": 2679, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2795, "s": 2777, "text": "Python Dictionary" }, { "code": null, "e": 2837, "s": 2795, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 2872, "s": 2837, "text": "Read a file line by line in Python" }, { "code": null, "e": 2898, "s": 2872, "text": "Python String | replace()" }, { "code": null, "e": 2930, "s": 2898, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2959, "s": 2930, "text": "*args and **kwargs in Python" }, { "code": null, "e": 2986, "s": 2959, "text": "Python Classes and Objects" }, { "code": null, "e": 3009, "s": 2986, "text": "Introduction To PYTHON" }, { "code": null, "e": 3030, "s": 3009, "text": "Python OOPs Concepts" } ]
Efficient Program to Compute Sum of Series 1/1! + 1/2! + 1/3! + 1/4! + .. + 1/n!
15 Jun, 2022 Given a positive integer n, write a function to compute the sum of the series 1/1! + 1/2! + .. + 1/n!A Simple Solution is to initialize the sum as 0, then run a loop and call the factorial function inside the loop. Following is the implementation of a simple solution. C++ Java Python3 C# PHP Javascript // A simple C++ program to compute sum of series 1/1! + 1/2! + .. + 1/n!#include <iostream>using namespace std; // Utility function to findint factorial(int n){ int res = 1; for (int i=2; i<=n; i++) res *= i; return res;} // A Simple Function to return value of 1/1! + 1/2! + .. + 1/n!double sum(int n){ double sum = 0; for (int i = 1; i <= n; i++) sum += 1.0/factorial(i); return sum;} // Driver program to test above functionsint main(){ int n = 5; cout << sum(n); return 0;} // A simple Java program to compute// sum of series 1/1! + 1/2! + .. + 1/n!import java.io.*; class GFG { // Utility function to find static int factorial(int n) { int res = 1; for (int i = 2; i <= n; i++) res *= i; return res; } // A Simple Function to return value // of 1/1! + 1/2! + .. + 1/n! static double sum(int n) { double sum = 0; for (int i = 1; i <= n; i++) sum += 1.0/factorial(i); return sum; } // Driver program public static void main (String[] args) { int n = 5; System.out.println(sum(n)); }} // This code is contributed by Ajit. # Python3 program to compute sum of series# 1/1! + 1/2! + .. + 1/n! # Function to find factorial of a numberdef factorial(n): res = 1 for i in range(2, n + 1): res *= i return res # A Simple Function to return value# of 1/1! + 1/2! + .. + 1/n!def sum(n): s = 0.0 for i in range(1, n + 1): s += 1.0 / factorial(i) print(s) # Driver program to test above functionsn = 5sum(n) # This code is contributed by Danish Raza // A simple C# program to compute sum// of series 1/1! + 1/2! + .. + 1/n!using System; class GFG { // Utility function to find static int factorial(int n) { int res = 1; for (int i = 2; i <= n; i++) res *= i; return res; } // A Simple Function to return value // of 1/1! + 1/2! + .. + 1/n! static double sum(int n) { double sum = 0; for (int i = 1; i <= n; i++) sum += 1.0/factorial(i); return sum; } // Driver program public static void Main () { int n = 5; Console.WriteLine(sum(n)); }} // This code is contributed by Sam007. <?php// A simple PHP program to compute// sum of series 1/1! + 1/2! + .. + 1/n! // Utility function to findfunction factorial($n){ $res = 1; for ($i = 2; $i <= $n; $i++) $res *= $i; return $res;} // A Simple Function to return// value of 1/1! + 1/2! + .. + 1/n!function sum($n){ $sum = 0; for ($i = 1; $i <= $n; $i++) $sum += 1.0 / factorial($i); return $sum;} // Driver Code$n = 5;echo(sum($n)); // This code is contributed by Ajit.?> <script> //Javascript program to compute// sum of series 1/1! + 1/2! + .. + 1/n! // Utility function to findfunction factorial(n){ let res = 1; for (let i = 2; i <= n; i++) res *= i; return res;} // A Simple Function to return// value of 1/1! + 1/2! + .. + 1/n!function sum(n){ let sum = 0; for (let i = 1; i <= n; i++) sum += 1.0 / factorial(i); return sum;} // Driver Code let n = 5;document.write(sum(n).toFixed(5)); // This code is contributed by sravan kumar </script> Output: 1.71667 Time complexity: O(n * n) Auxiliary Space: O(1)An Efficient Solution can find the sum in O(n) time. The idea is to calculate factorial in the same loop as the sum. Following is the implementation of this idea. C++ Java Python3 C# PHP Javascript // A simple C++ program to compute sum of series 1/1! + 1/2! + .. + 1/n!#include <iostream>using namespace std; // An Efficient Function to return value of 1/1! + 1/2! + .. + 1/n!double sum(int n){ double sum = 0; int fact = 1; for (int i = 1; i <= n; i++) { fact *= i; // Update factorial sum += 1.0/fact; // Update series sum } return sum;} // Driver program to test above functionsint main(){ int n = 5; cout << sum(n); return 0;} // A simple Java program to compute// sum of series 1/1! + 1/2! + .. + 1/n!import java.io.*; class GFG { // An Efficient Function to return // value of 1/1! + 1/2! + .. + 1/n! static double sum(int n) { double sum = 0; int fact = 1; for (int i = 1; i <= n; i++) { // Update factorial fact *= i; // Update series sum sum += 1.0/fact; } return sum; } // Driver program public static void main (String[] args) { int n = 5; System.out.println(sum(n)); }} // This code is contributed by Ajit. # Python3 program to compute sum of series# 1/1! + 1/2! + .. + 1/n! # Function to return value of# 1/1! + 1/2! + .. + 1/n!def sum(n): sum = 0 fact = 1 for i in range(1, n + 1): # Update factorial fact *= i # Update series sum sum += 1.0/fact print(sum) # Driver program to test above functionsn = 5sum(n) # This code is contributed by Danish Raza // A simple C# program to compute sum// of series 1/1! + 1/2! + .. + 1/n!using System; class GFG { // An Efficient Function to return // value of 1/1! + 1/2! + .. + 1/n! static double sum(int n) { double sum = 0; int fact = 1; for (int i = 1; i <= n; i++) { // Update factorial fact *= i; // Update series sum sum += 1.0 / fact; } return sum; } // Driver program public static void Main () { int n = 5; Console.WriteLine(sum(n)); }} // This code is contributed by Sam007. <?php// A simple PHP program to// compute sum of series// 1/1! + 1/2! + .. + 1/n! // An Efficient Function to// return value of 1/1! +// 1/2! + .. + 1/n!function sum($n){ $sum = 0; $fact = 1; for ($i = 1; $i <= $n; $i++) { // Update factorial $fact *= $i; // Update series sum $sum += 1.0 / $fact; } return $sum;} // Driver Code$n = 5;echo sum($n); // This code is contributed by vt_m.?> <script> // A simple Javascript program to compute sum // of series 1/1! + 1/2! + .. + 1/n! // An Efficient Function to return // value of 1/1! + 1/2! + .. + 1/n! function sum(n) { let sum = 0; let fact = 1; for (let i = 1; i <= n; i++) { // Update factorial fact *= i; // Update series sum sum += 1.0 / fact; } return sum.toFixed(5); } let n = 5; document.write(sum(n)); </script> Output: 1.71667 Time complexity: O(n) since using a single loop Auxiliary Space: O(1)This article is contributed by Rahul Gupta. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. Sam007 jit_t vt_m sravankumar8128 divyeshrabadiya07 surindertarika1234 polymatir3j factorial Mathematical Mathematical factorial Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Operators in C / C++ Find minimum number of coins that make a given value Minimum number of jumps to reach end Algorithm to solve Rubik's Cube The Knight's tour problem | Backtracking-1 Modulo 10^9+7 (1000000007) Modulo Operator (%) in C/C++ with Examples Program for factorial of a number Program to print prime numbers from 1 to N. Program to find sum of elements in a given array
[ { "code": null, "e": 52, "s": 24, "text": "\n15 Jun, 2022" }, { "code": null, "e": 323, "s": 52, "text": "Given a positive integer n, write a function to compute the sum of the series 1/1! + 1/2! + .. + 1/n!A Simple Solution is to initialize the sum as 0, then run a loop and call the factorial function inside the loop. Following is the implementation of a simple solution. " }, { "code": null, "e": 327, "s": 323, "text": "C++" }, { "code": null, "e": 332, "s": 327, "text": "Java" }, { "code": null, "e": 340, "s": 332, "text": "Python3" }, { "code": null, "e": 343, "s": 340, "text": "C#" }, { "code": null, "e": 347, "s": 343, "text": "PHP" }, { "code": null, "e": 358, "s": 347, "text": "Javascript" }, { "code": "// A simple C++ program to compute sum of series 1/1! + 1/2! + .. + 1/n!#include <iostream>using namespace std; // Utility function to findint factorial(int n){ int res = 1; for (int i=2; i<=n; i++) res *= i; return res;} // A Simple Function to return value of 1/1! + 1/2! + .. + 1/n!double sum(int n){ double sum = 0; for (int i = 1; i <= n; i++) sum += 1.0/factorial(i); return sum;} // Driver program to test above functionsint main(){ int n = 5; cout << sum(n); return 0;}", "e": 877, "s": 358, "text": null }, { "code": "// A simple Java program to compute// sum of series 1/1! + 1/2! + .. + 1/n!import java.io.*; class GFG { // Utility function to find static int factorial(int n) { int res = 1; for (int i = 2; i <= n; i++) res *= i; return res; } // A Simple Function to return value // of 1/1! + 1/2! + .. + 1/n! static double sum(int n) { double sum = 0; for (int i = 1; i <= n; i++) sum += 1.0/factorial(i); return sum; } // Driver program public static void main (String[] args) { int n = 5; System.out.println(sum(n)); }} // This code is contributed by Ajit.", "e": 1547, "s": 877, "text": null }, { "code": "# Python3 program to compute sum of series# 1/1! + 1/2! + .. + 1/n! # Function to find factorial of a numberdef factorial(n): res = 1 for i in range(2, n + 1): res *= i return res # A Simple Function to return value# of 1/1! + 1/2! + .. + 1/n!def sum(n): s = 0.0 for i in range(1, n + 1): s += 1.0 / factorial(i) print(s) # Driver program to test above functionsn = 5sum(n) # This code is contributed by Danish Raza", "e": 2012, "s": 1547, "text": null }, { "code": "// A simple C# program to compute sum// of series 1/1! + 1/2! + .. + 1/n!using System; class GFG { // Utility function to find static int factorial(int n) { int res = 1; for (int i = 2; i <= n; i++) res *= i; return res; } // A Simple Function to return value // of 1/1! + 1/2! + .. + 1/n! static double sum(int n) { double sum = 0; for (int i = 1; i <= n; i++) sum += 1.0/factorial(i); return sum; } // Driver program public static void Main () { int n = 5; Console.WriteLine(sum(n)); }} // This code is contributed by Sam007.", "e": 2703, "s": 2012, "text": null }, { "code": "<?php// A simple PHP program to compute// sum of series 1/1! + 1/2! + .. + 1/n! // Utility function to findfunction factorial($n){ $res = 1; for ($i = 2; $i <= $n; $i++) $res *= $i; return $res;} // A Simple Function to return// value of 1/1! + 1/2! + .. + 1/n!function sum($n){ $sum = 0; for ($i = 1; $i <= $n; $i++) $sum += 1.0 / factorial($i); return $sum;} // Driver Code$n = 5;echo(sum($n)); // This code is contributed by Ajit.?>", "e": 3171, "s": 2703, "text": null }, { "code": "<script> //Javascript program to compute// sum of series 1/1! + 1/2! + .. + 1/n! // Utility function to findfunction factorial(n){ let res = 1; for (let i = 2; i <= n; i++) res *= i; return res;} // A Simple Function to return// value of 1/1! + 1/2! + .. + 1/n!function sum(n){ let sum = 0; for (let i = 1; i <= n; i++) sum += 1.0 / factorial(i); return sum;} // Driver Code let n = 5;document.write(sum(n).toFixed(5)); // This code is contributed by sravan kumar </script>", "e": 3678, "s": 3171, "text": null }, { "code": null, "e": 3687, "s": 3678, "text": "Output: " }, { "code": null, "e": 3695, "s": 3687, "text": "1.71667" }, { "code": null, "e": 3721, "s": 3695, "text": "Time complexity: O(n * n)" }, { "code": null, "e": 3907, "s": 3721, "text": "Auxiliary Space: O(1)An Efficient Solution can find the sum in O(n) time. The idea is to calculate factorial in the same loop as the sum. Following is the implementation of this idea. " }, { "code": null, "e": 3911, "s": 3907, "text": "C++" }, { "code": null, "e": 3916, "s": 3911, "text": "Java" }, { "code": null, "e": 3924, "s": 3916, "text": "Python3" }, { "code": null, "e": 3927, "s": 3924, "text": "C#" }, { "code": null, "e": 3931, "s": 3927, "text": "PHP" }, { "code": null, "e": 3942, "s": 3931, "text": "Javascript" }, { "code": "// A simple C++ program to compute sum of series 1/1! + 1/2! + .. + 1/n!#include <iostream>using namespace std; // An Efficient Function to return value of 1/1! + 1/2! + .. + 1/n!double sum(int n){ double sum = 0; int fact = 1; for (int i = 1; i <= n; i++) { fact *= i; // Update factorial sum += 1.0/fact; // Update series sum } return sum;} // Driver program to test above functionsint main(){ int n = 5; cout << sum(n); return 0;}", "e": 4425, "s": 3942, "text": null }, { "code": "// A simple Java program to compute// sum of series 1/1! + 1/2! + .. + 1/n!import java.io.*; class GFG { // An Efficient Function to return // value of 1/1! + 1/2! + .. + 1/n! static double sum(int n) { double sum = 0; int fact = 1; for (int i = 1; i <= n; i++) { // Update factorial fact *= i; // Update series sum sum += 1.0/fact; } return sum; } // Driver program public static void main (String[] args) { int n = 5; System.out.println(sum(n)); }} // This code is contributed by Ajit.", "e": 5059, "s": 4425, "text": null }, { "code": "# Python3 program to compute sum of series# 1/1! + 1/2! + .. + 1/n! # Function to return value of# 1/1! + 1/2! + .. + 1/n!def sum(n): sum = 0 fact = 1 for i in range(1, n + 1): # Update factorial fact *= i # Update series sum sum += 1.0/fact print(sum) # Driver program to test above functionsn = 5sum(n) # This code is contributed by Danish Raza", "e": 5450, "s": 5059, "text": null }, { "code": "// A simple C# program to compute sum// of series 1/1! + 1/2! + .. + 1/n!using System; class GFG { // An Efficient Function to return // value of 1/1! + 1/2! + .. + 1/n! static double sum(int n) { double sum = 0; int fact = 1; for (int i = 1; i <= n; i++) { // Update factorial fact *= i; // Update series sum sum += 1.0 / fact; } return sum; } // Driver program public static void Main () { int n = 5; Console.WriteLine(sum(n)); }} // This code is contributed by Sam007.", "e": 6099, "s": 5450, "text": null }, { "code": "<?php// A simple PHP program to// compute sum of series// 1/1! + 1/2! + .. + 1/n! // An Efficient Function to// return value of 1/1! +// 1/2! + .. + 1/n!function sum($n){ $sum = 0; $fact = 1; for ($i = 1; $i <= $n; $i++) { // Update factorial $fact *= $i; // Update series sum $sum += 1.0 / $fact; } return $sum;} // Driver Code$n = 5;echo sum($n); // This code is contributed by vt_m.?>", "e": 6545, "s": 6099, "text": null }, { "code": "<script> // A simple Javascript program to compute sum // of series 1/1! + 1/2! + .. + 1/n! // An Efficient Function to return // value of 1/1! + 1/2! + .. + 1/n! function sum(n) { let sum = 0; let fact = 1; for (let i = 1; i <= n; i++) { // Update factorial fact *= i; // Update series sum sum += 1.0 / fact; } return sum.toFixed(5); } let n = 5; document.write(sum(n)); </script>", "e": 7105, "s": 6545, "text": null }, { "code": null, "e": 7114, "s": 7105, "text": "Output: " }, { "code": null, "e": 7122, "s": 7114, "text": "1.71667" }, { "code": null, "e": 7170, "s": 7122, "text": "Time complexity: O(n) since using a single loop" }, { "code": null, "e": 7361, "s": 7170, "text": "Auxiliary Space: O(1)This article is contributed by Rahul Gupta. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 7368, "s": 7361, "text": "Sam007" }, { "code": null, "e": 7374, "s": 7368, "text": "jit_t" }, { "code": null, "e": 7379, "s": 7374, "text": "vt_m" }, { "code": null, "e": 7395, "s": 7379, "text": "sravankumar8128" }, { "code": null, "e": 7413, "s": 7395, "text": "divyeshrabadiya07" }, { "code": null, "e": 7432, "s": 7413, "text": "surindertarika1234" }, { "code": null, "e": 7444, "s": 7432, "text": "polymatir3j" }, { "code": null, "e": 7454, "s": 7444, "text": "factorial" }, { "code": null, "e": 7467, "s": 7454, "text": "Mathematical" }, { "code": null, "e": 7480, "s": 7467, "text": "Mathematical" }, { "code": null, "e": 7490, "s": 7480, "text": "factorial" }, { "code": null, "e": 7588, "s": 7490, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 7609, "s": 7588, "text": "Operators in C / C++" }, { "code": null, "e": 7662, "s": 7609, "text": "Find minimum number of coins that make a given value" }, { "code": null, "e": 7699, "s": 7662, "text": "Minimum number of jumps to reach end" }, { "code": null, "e": 7731, "s": 7699, "text": "Algorithm to solve Rubik's Cube" }, { "code": null, "e": 7774, "s": 7731, "text": "The Knight's tour problem | Backtracking-1" }, { "code": null, "e": 7801, "s": 7774, "text": "Modulo 10^9+7 (1000000007)" }, { "code": null, "e": 7844, "s": 7801, "text": "Modulo Operator (%) in C/C++ with Examples" }, { "code": null, "e": 7878, "s": 7844, "text": "Program for factorial of a number" }, { "code": null, "e": 7922, "s": 7878, "text": "Program to print prime numbers from 1 to N." } ]
Python Program to Count trailing zeroes in factorial of a number
14 Jun, 2022 Given an integer n, write a function that returns count of trailing zeroes in n!. Examples : Input: n = 5 Output: 1 Factorial of 5 is 120 which has one trailing 0. Input: n = 20 Output: 4 Factorial of 20 is 2432902008176640000 which has 4 trailing zeroes. Input: n = 100 Output: 24 Trailing 0s in n! = Count of 5s in prime factors of n! = floor(n/5) + floor(n/25) + floor(n/125) + .... Python3 # Python3 program to# count trailing 0s# in n ! # Function to return# trailing 0s in# factorial of ndef findTrailingZeros(n): # Initialize result count = 0 # Keep dividing n by # powers of 5 and # update Count i = 5 while (n / i>= 1): count += int(n / i) i *= 5 return int(count) # Driver programn = 100print("Count of trailing 0s "+ "in 100 ! is", findTrailingZeros(n)) # This code is contributed by Smitha Dinesh Semwal Count of trailing 0s in 100 ! is 24 Time Complexity: O(log5n) Auxiliary Space: O(1) Please refer complete article on Count trailing zeroes in factorial of a number for more details! chandramauliguptach Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n14 Jun, 2022" }, { "code": null, "e": 148, "s": 54, "text": "Given an integer n, write a function that returns count of trailing zeroes in n!. Examples :" }, { "code": null, "e": 340, "s": 148, "text": "Input: n = 5\nOutput: 1 \nFactorial of 5 is 120 which has one trailing 0.\n\nInput: n = 20\nOutput: 4\nFactorial of 20 is 2432902008176640000 which has\n4 trailing zeroes.\n\nInput: n = 100\nOutput: 24" }, { "code": null, "e": 462, "s": 340, "text": "Trailing 0s in n! = Count of 5s in prime factors of n!\n = floor(n/5) + floor(n/25) + floor(n/125) + ...." }, { "code": null, "e": 470, "s": 462, "text": "Python3" }, { "code": "# Python3 program to# count trailing 0s# in n ! # Function to return# trailing 0s in# factorial of ndef findTrailingZeros(n): # Initialize result count = 0 # Keep dividing n by # powers of 5 and # update Count i = 5 while (n / i>= 1): count += int(n / i) i *= 5 return int(count) # Driver programn = 100print(\"Count of trailing 0s \"+ \"in 100 ! is\", findTrailingZeros(n)) # This code is contributed by Smitha Dinesh Semwal", "e": 940, "s": 470, "text": null }, { "code": null, "e": 976, "s": 940, "text": "Count of trailing 0s in 100 ! is 24" }, { "code": null, "e": 1003, "s": 976, "text": "Time Complexity: O(log5n)" }, { "code": null, "e": 1025, "s": 1003, "text": "Auxiliary Space: O(1)" }, { "code": null, "e": 1123, "s": 1025, "text": "Please refer complete article on Count trailing zeroes in factorial of a number for more details!" }, { "code": null, "e": 1143, "s": 1123, "text": "chandramauliguptach" }, { "code": null, "e": 1159, "s": 1143, "text": "Python Programs" } ]
How to Install and Configure Apache Subversion(SVN) In Linux?
06 Oct, 2021 Apache Subversion (SVN), is a version control system like Git. it is distributed under an open-source license. SVN was created by CollabNet Inc. but now it is developed as a project of the Apache Software Foundation. Apache Subversion(SVN) can be easily downloaded and installed with the use of the command-line. Following steps provide a step-by-step procedure to install Apache SVN: Step 1: First, we need to Install the subversion, apache2 and libapache2-svn/libapache2-mod-svn packages.For this open terminal and type the following command and press Enter: $ sudo apt install subversion apache2 libapache2-mod-svn Step 2: Now create a SVN directory, at the root of file system. Type the following command and press Enter: $ sudo mkdir /svn Step 3: Now, change the owner’s permission of the directory to the webserver user, www-data by default. $ sudo chown www-data:www-data /svn Step 4: Now change to superuser by typing this command and then type password $ sudo su now switch to www-data user $ su -s /bin/bash www-data Step 5: Create a new SVN repository to store files. $ svnadmin create /svn/repo Step 6: Now we’ll have to create credentials for User: $ htpasswd -cmb /svn/passwd admin password here “admin” is username and “password” is password Step 7: Now exit from www-data and install Vim editor. Type the following command to install Vim editor: $ sudo apt-get install vim Step 8: Open and edit SVN configuration file in sudo mode with the use of following command: $ sudo vim /etc/apache2/mods-enabled/dav_svn.conf Now, paste the following code in that file: <Location /repo> DAV svn SVNPath /svn/repo AuthUserFile /svn/passwd Require valid-user AuthType basic AuthName "Subversion"</Location> Now save the file and exit the Vim Editor by using the command :wq Step 9: Now restart Apache Subversion and you are done with the installation process. Type the following command and press Enter: $ sudo /etc/init.d/apache2 restart how-to-install Technical Scripter 2019 How To Installation Guide Linux-Unix Technical Scripter Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Set Git Username and Password in GitBash? How to Install and Use NVM on Windows? How to Install Jupyter Notebook on MacOS? How to Permanently Disable Swap in Linux? How to Import JSON Data into SQL Server? Installation of Node.js on Linux Installation of Node.js on Windows How to Install and Use NVM on Windows? How to Install Jupyter Notebook on MacOS? How to Add External JAR File to an IntelliJ IDEA Project?
[ { "code": null, "e": 28, "s": 0, "text": "\n06 Oct, 2021" }, { "code": null, "e": 245, "s": 28, "text": "Apache Subversion (SVN), is a version control system like Git. it is distributed under an open-source license. SVN was created by CollabNet Inc. but now it is developed as a project of the Apache Software Foundation." }, { "code": null, "e": 413, "s": 245, "text": "Apache Subversion(SVN) can be easily downloaded and installed with the use of the command-line. Following steps provide a step-by-step procedure to install Apache SVN:" }, { "code": null, "e": 589, "s": 413, "text": "Step 1: First, we need to Install the subversion, apache2 and libapache2-svn/libapache2-mod-svn packages.For this open terminal and type the following command and press Enter:" }, { "code": null, "e": 646, "s": 589, "text": "$ sudo apt install subversion apache2 libapache2-mod-svn" }, { "code": null, "e": 755, "s": 646, "text": " Step 2: Now create a SVN directory, at the root of file system. Type the following command and press Enter:" }, { "code": null, "e": 773, "s": 755, "text": "$ sudo mkdir /svn" }, { "code": null, "e": 878, "s": 773, "text": " Step 3: Now, change the owner’s permission of the directory to the webserver user, www-data by default." }, { "code": null, "e": 914, "s": 878, "text": "$ sudo chown www-data:www-data /svn" }, { "code": null, "e": 993, "s": 914, "text": " Step 4: Now change to superuser by typing this command and then type password" }, { "code": null, "e": 1003, "s": 993, "text": "$ sudo su" }, { "code": null, "e": 1031, "s": 1003, "text": "now switch to www-data user" }, { "code": null, "e": 1058, "s": 1031, "text": "$ su -s /bin/bash www-data" }, { "code": null, "e": 1110, "s": 1058, "text": "Step 5: Create a new SVN repository to store files." }, { "code": null, "e": 1138, "s": 1110, "text": "$ svnadmin create /svn/repo" }, { "code": null, "e": 1193, "s": 1138, "text": "Step 6: Now we’ll have to create credentials for User:" }, { "code": null, "e": 1236, "s": 1193, "text": "$ htpasswd -cmb /svn/passwd admin password" }, { "code": null, "e": 1393, "s": 1236, "text": "here “admin” is username and “password” is password Step 7: Now exit from www-data and install Vim editor. Type the following command to install Vim editor:" }, { "code": null, "e": 1420, "s": 1393, "text": "$ sudo apt-get install vim" }, { "code": null, "e": 1514, "s": 1420, "text": " Step 8: Open and edit SVN configuration file in sudo mode with the use of following command:" }, { "code": null, "e": 1564, "s": 1514, "text": "$ sudo vim /etc/apache2/mods-enabled/dav_svn.conf" }, { "code": null, "e": 1608, "s": 1564, "text": "Now, paste the following code in that file:" }, { "code": "<Location /repo> DAV svn SVNPath /svn/repo AuthUserFile /svn/passwd Require valid-user AuthType basic AuthName \"Subversion\"</Location>", "e": 1791, "s": 1608, "text": null }, { "code": null, "e": 1988, "s": 1791, "text": "Now save the file and exit the Vim Editor by using the command :wq Step 9: Now restart Apache Subversion and you are done with the installation process. Type the following command and press Enter:" }, { "code": null, "e": 2023, "s": 1988, "text": "$ sudo /etc/init.d/apache2 restart" }, { "code": null, "e": 2038, "s": 2023, "text": "how-to-install" }, { "code": null, "e": 2062, "s": 2038, "text": "Technical Scripter 2019" }, { "code": null, "e": 2069, "s": 2062, "text": "How To" }, { "code": null, "e": 2088, "s": 2069, "text": "Installation Guide" }, { "code": null, "e": 2099, "s": 2088, "text": "Linux-Unix" }, { "code": null, "e": 2118, "s": 2099, "text": "Technical Scripter" }, { "code": null, "e": 2216, "s": 2118, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2265, "s": 2216, "text": "How to Set Git Username and Password in GitBash?" }, { "code": null, "e": 2304, "s": 2265, "text": "How to Install and Use NVM on Windows?" }, { "code": null, "e": 2346, "s": 2304, "text": "How to Install Jupyter Notebook on MacOS?" }, { "code": null, "e": 2388, "s": 2346, "text": "How to Permanently Disable Swap in Linux?" }, { "code": null, "e": 2429, "s": 2388, "text": "How to Import JSON Data into SQL Server?" }, { "code": null, "e": 2462, "s": 2429, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 2497, "s": 2462, "text": "Installation of Node.js on Windows" }, { "code": null, "e": 2536, "s": 2497, "text": "How to Install and Use NVM on Windows?" }, { "code": null, "e": 2578, "s": 2536, "text": "How to Install Jupyter Notebook on MacOS?" } ]
Laravel - Routing
In Laravel, all requests are mapped with the help of routes. Basic routing routes the request to the associated controllers. This chapter discusses routing in Laravel. Routing in Laravel includes the following categories − Basic Routing Route parameters Named Routes All the application routes are registered within the app/routes.php file. This file tells Laravel for the URIs it should respond to and the associated controller will give it a particular call. The sample route for the welcome page can be seen as shown in the screenshot given below − Route::get ('/', function () { return view('welcome');}); Observe the following example to understand more about Routing − app/Http/routes.php <?php Route::get('/', function () { return view('welcome'); }); resources/view/welcome.blade.php <!DOCTYPE html> <html> <head> <title>Laravel</title> <link href = "https://fonts.googleapis.com/css?family=Lato:100" rel = "stylesheet" type = "text/css"> <style> html, body { height: 100%; } body { margin: 0; padding: 0; width: 100%; display: table; font-weight: 100; font-family: 'Lato'; } .container { text-align: center; display: table-cell; vertical-align: middle; } .content { text-align: center; display: inline-block; } .title { font-size: 96px; } </style> </head> <body> <div class = "container"> <div class = "content"> <div class = "title">Laravel 5.1</div> </div> </div> </body> </html> The routing mechanism is shown in the image given below − Let us now understand the steps involved in routing mechanism in detail − Step 1 − Initially, we should execute the root URL of the application. Step 2 − Now, the executed URL should match with the appropriate method in the route.php file. In the present case, it should match the method and the root (‘/’) URL. This will execute the related function. Step 3 − The function calls the template file resources/views/welcome.blade.php. Next, the function calls the view() function with argument ‘welcome’ without using the blade.php. This will produce the HTML output as shown in the image below − Sometimes in the web application, you may need to capture the parameters passed with the URL. For this, you should modify the code in routes.php file. You can capture the parameters in routes.php file in two ways as discussed here − These parameters are those which should be mandatorily captured for routing the web application. For example, it is important to capture the user’s identification number from the URL. This can be possible by defining route parameters as shown below − Route::get('ID/{id}',function($id) { echo 'ID: '.$id; }); Sometimes developers can produce parameters as optional and it is possible with the inclusion of ? after the parameter name in URL. It is important to keep the default value mentioned as a parameter name. Look at the following example that shows how to define an optional parameter − Route::get('user/{name?}', function ($name = 'TutorialsPoint') { return $name;}); The example above checks if the value matches to TutorialsPoint and accordingly routes to the defined URL. Named routes allow a convenient way of creating routes. The chaining of routes can be specified using name method onto the route definition. The following code shows an example for creating named routes with controller − Route::get('user/profile', 'UserController@showProfile')->name('profile'); The user controller will call for the function showProfile with parameter as profile. The parameters use name method onto the route definition.
[ { "code": null, "e": 2774, "s": 2606, "text": "In Laravel, all requests are mapped with the help of routes. Basic routing routes the request to the associated controllers. This chapter discusses routing in Laravel." }, { "code": null, "e": 2829, "s": 2774, "text": "Routing in Laravel includes the following categories −" }, { "code": null, "e": 2843, "s": 2829, "text": "Basic Routing" }, { "code": null, "e": 2860, "s": 2843, "text": "Route parameters" }, { "code": null, "e": 2873, "s": 2860, "text": "Named Routes" }, { "code": null, "e": 3158, "s": 2873, "text": "All the application routes are registered within the app/routes.php file. This file tells Laravel for the URIs it should respond to and the associated controller will give it a particular call. The sample route for the welcome page can be seen as shown in the screenshot given below −" }, { "code": null, "e": 3219, "s": 3158, "text": "Route::get ('/', function () {\n return view('welcome');});" }, { "code": null, "e": 3284, "s": 3219, "text": "Observe the following example to understand more about Routing −" }, { "code": null, "e": 3304, "s": 3284, "text": "app/Http/routes.php" }, { "code": null, "e": 3371, "s": 3304, "text": "<?php\nRoute::get('/', function () {\n return view('welcome');\n});" }, { "code": null, "e": 3404, "s": 3371, "text": "resources/view/welcome.blade.php" }, { "code": null, "e": 4362, "s": 3404, "text": "<!DOCTYPE html>\n<html>\n <head>\n <title>Laravel</title>\n <link href = \"https://fonts.googleapis.com/css?family=Lato:100\" rel = \"stylesheet\" \n type = \"text/css\">\n \n <style>\n html, body {\n height: 100%;\n }\n body {\n margin: 0;\n padding: 0;\n width: 100%;\n display: table;\n font-weight: 100;\n font-family: 'Lato';\n }\n .container {\n text-align: center;\n display: table-cell;\n vertical-align: middle;\n }\n .content {\n text-align: center;\n display: inline-block;\n }\n .title {\n font-size: 96px;\n }\n </style>\n </head>\n \n <body>\n <div class = \"container\">\n \n <div class = \"content\">\n <div class = \"title\">Laravel 5.1</div>\n </div>\n\t\t\t\n </div>\n </body>\n</html>" }, { "code": null, "e": 4420, "s": 4362, "text": "The routing mechanism is shown in the image given below −" }, { "code": null, "e": 4494, "s": 4420, "text": "Let us now understand the steps involved in routing mechanism in detail −" }, { "code": null, "e": 4565, "s": 4494, "text": "Step 1 − Initially, we should execute the root URL of the application." }, { "code": null, "e": 4772, "s": 4565, "text": "Step 2 − Now, the executed URL should match with the appropriate method in the route.php file. In the present case, it should match the method and the root (‘/’) URL. This will execute the related function." }, { "code": null, "e": 4951, "s": 4772, "text": "Step 3 − The function calls the template file resources/views/welcome.blade.php. Next, the function calls the view() function with argument ‘welcome’ without using the blade.php." }, { "code": null, "e": 5015, "s": 4951, "text": "This will produce the HTML output as shown in the image below −" }, { "code": null, "e": 5166, "s": 5015, "text": "Sometimes in the web application, you may need to capture the parameters passed with the URL. For this, you should modify the code in routes.php file." }, { "code": null, "e": 5248, "s": 5166, "text": "You can capture the parameters in routes.php file in two ways as discussed here −" }, { "code": null, "e": 5499, "s": 5248, "text": "These parameters are those which should be mandatorily captured for routing the web application. For example, it is important to capture the user’s identification number from the URL. This can be possible by defining route parameters as shown below −" }, { "code": null, "e": 5560, "s": 5499, "text": "Route::get('ID/{id}',function($id) {\n echo 'ID: '.$id;\n});" }, { "code": null, "e": 5844, "s": 5560, "text": "Sometimes developers can produce parameters as optional and it is possible with the inclusion of ? after the parameter name in URL. It is important to keep the default value mentioned as a parameter name. Look at the following example that shows how to define an optional parameter −" }, { "code": null, "e": 5927, "s": 5844, "text": "Route::get('user/{name?}', function ($name = 'TutorialsPoint') { return $name;});\n" }, { "code": null, "e": 6034, "s": 5927, "text": "The example above checks if the value matches to TutorialsPoint and accordingly routes to the defined URL." }, { "code": null, "e": 6255, "s": 6034, "text": "Named routes allow a convenient way of creating routes. The chaining of routes can be specified using name method onto the route definition. The following code shows an example for creating named routes with controller −" }, { "code": null, "e": 6331, "s": 6255, "text": "Route::get('user/profile', 'UserController@showProfile')->name('profile');\n" } ]
Java Program to Traverse Through ArrayList in Reverse Direction
22 Dec, 2020 ArrayList is a part of collection framework and is present in java.util package. It provides us with dynamic arrays in Java just as Vector in C++. Though, it may be slower than standard arrays but can be helpful in programs where lots of manipulation in the array is needed. The task is to insert an element in ArrayList and then Reverse it or say reverse the direction. Example : Input : 1, 2, 3, 4, 5, 6 Output : 6, 5, 4, 3, 2, 1 Input : 10, 22, 34, 3, 2, 6 Output : 6, 2, 3, 34, 22, 10 Input : 11, 22, 34, 42, 51 , 63 Output : 63, 51, 42, 34, 22, 11 There are several methods by which we can Iterate and print List in reverse direction listed below. Method 1: (Using ListIterator) 1. Declare an ArrayList // size of n ArrayList<Integer> List = new ArrayList<Integer>(n); 2. By using the add function we push the element into the ArrayList. 3. After reaching the last element of ArrayList traverse by using iterator. hasPrevious() method returns true if an element is present at the back of the current element, traverse until hasPrevious( ) return false. 4. While traversing print the current element of ArrayList. Java // Traverse through ArrayList in // reverse direction using List // Iterator in Java import java.util.ListIterator;import java.io.*;import java.util.ArrayList; class GFG { public static void main(String[] args) { // create an instance of arraylist ArrayList<Integer> List = new ArrayList<Integer>(); // add elements List.add(10); List.add(9); List.add(8); List.add(7); List.add(6); // create a listiterator on list ListIterator<Integer> List_Iterator = List.listIterator(List.size()); System.out.println("Reversed : "); // print ArrayList in reverse direction using // listiterator while (List_Iterator.hasPrevious()) { System.out.println(List_Iterator.previous()); } }} Reversed : 6 7 8 9 10 Method 2: (Using Stream) The Stream API is used to process collections of objects. A stream is a sequence of objects that supports various methods that can be pipelined to produce the desired result. Get Stream using List.stream(). Collect elements of this stream to a LinkedList using Stream.collect(). Iterate through the LinkedList in reverse sequential order using LinkedList.descendingIterator() method. Perform the print operation on each element of the ArrayList using forEachRemaining(). We can provide the method reference System.out::println Iterator to the forEachRemaining(). Java // Traverse through ArrayList in// reverse direction Using// stream in Java import java.lang.*;import java.util.stream.*;import java.util.*;import java.io.*; class GFG { public static void main(String[] args) { // create a list List<Integer> Arlist = Arrays.asList(5, 2, 4, 8); System.out.println("Reversed : "); // create a stream // collect the elements after these operations // create a descending iterator on the stream // loop through the descending iterator // print the element Arlist.stream() .collect( Collectors.toCollection(LinkedList::new)) .descendingIterator() .forEachRemaining(System.out::println); }} Reversed : 8 4 2 5 Method 3: (Using For Loop) We know that List is an ordered collection, and we can access the element of the list just by its index, so Define an ArrayList and iterate from last using a for loop till the first element and print each element. Java // Traverse through ArrayList in// reverse direction using For// Loop in Javaimport java.util.*;import java.io.*; class GFG { public static void main(String[] args) { // create a list List<Integer> Arlist = Arrays.asList(5, 4, 8, 2); System.out.println("Reversed :"); // Printing in reverse for (int i = Arlist.size() - 1; i >= 0; i--) { System.out.println(Arlist.get(i)); } }} Reversed : 2 8 4 5 Method 4: (Using Apache Common’s ReverseListIterator) This method provides ReverseListIterator that we can use to iterate List in reverse order. As we use the ReverseListIterator then next() will return the last element from the array list, Then as we call the next element then next bracket will return the previous element of the current element, and has next will check whether our ArrayList contains an element or not. Java // Traverse through ArrayList in reverse direction using// ReverseListIterator in Java import org.apache.commons.collections.iterators.ReverseListIterator; import java.util.Arrays;import java.util.List; class Main { public static void main(String[] args) { // create a list List<Integer> list = Arrays.asList(1, 5, 8, 7); // create a reverse listiterator ReverseListIterator it = new ReverseListIterator(list); System.out.println("Reversed : "); // print the elements while (it.hasNext()) { System.out.println(it.next()); } }} Output Reversed : 7 8 5 1 Time Complexity: O(n) Java-ArrayList Picked Technical Scripter 2020 Java Java Programs Technical Scripter Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n22 Dec, 2020" }, { "code": null, "e": 399, "s": 28, "text": "ArrayList is a part of collection framework and is present in java.util package. It provides us with dynamic arrays in Java just as Vector in C++. Though, it may be slower than standard arrays but can be helpful in programs where lots of manipulation in the array is needed. The task is to insert an element in ArrayList and then Reverse it or say reverse the direction." }, { "code": null, "e": 409, "s": 399, "text": "Example :" }, { "code": null, "e": 592, "s": 409, "text": "Input : 1, 2, 3, 4, 5, 6 \nOutput : 6, 5, 4, 3, 2, 1 \n\nInput : 10, 22, 34, 3, 2, 6\nOutput : 6, 2, 3, 34, 22, 10 \n\nInput : 11, 22, 34, 42, 51 , 63\nOutput : 63, 51, 42, 34, 22, 11" }, { "code": null, "e": 692, "s": 592, "text": "There are several methods by which we can Iterate and print List in reverse direction listed below." }, { "code": null, "e": 723, "s": 692, "text": "Method 1: (Using ListIterator)" }, { "code": null, "e": 747, "s": 723, "text": "1. Declare an ArrayList" }, { "code": null, "e": 814, "s": 747, "text": "// size of n\nArrayList<Integer> List = new ArrayList<Integer>(n);" }, { "code": null, "e": 888, "s": 814, "text": "2. By using the add function we push the element into the ArrayList. " }, { "code": null, "e": 1103, "s": 888, "text": "3. After reaching the last element of ArrayList traverse by using iterator. hasPrevious() method returns true if an element is present at the back of the current element, traverse until hasPrevious( ) return false." }, { "code": null, "e": 1163, "s": 1103, "text": "4. While traversing print the current element of ArrayList." }, { "code": null, "e": 1168, "s": 1163, "text": "Java" }, { "code": "// Traverse through ArrayList in // reverse direction using List // Iterator in Java import java.util.ListIterator;import java.io.*;import java.util.ArrayList; class GFG { public static void main(String[] args) { // create an instance of arraylist ArrayList<Integer> List = new ArrayList<Integer>(); // add elements List.add(10); List.add(9); List.add(8); List.add(7); List.add(6); // create a listiterator on list ListIterator<Integer> List_Iterator = List.listIterator(List.size()); System.out.println(\"Reversed : \"); // print ArrayList in reverse direction using // listiterator while (List_Iterator.hasPrevious()) { System.out.println(List_Iterator.previous()); } }}", "e": 1985, "s": 1168, "text": null }, { "code": null, "e": 2008, "s": 1985, "text": "Reversed : \n6\n7\n8\n9\n10" }, { "code": null, "e": 2034, "s": 2008, "text": "Method 2: (Using Stream) " }, { "code": null, "e": 2209, "s": 2034, "text": "The Stream API is used to process collections of objects. A stream is a sequence of objects that supports various methods that can be pipelined to produce the desired result." }, { "code": null, "e": 2241, "s": 2209, "text": "Get Stream using List.stream()." }, { "code": null, "e": 2313, "s": 2241, "text": "Collect elements of this stream to a LinkedList using Stream.collect()." }, { "code": null, "e": 2418, "s": 2313, "text": "Iterate through the LinkedList in reverse sequential order using LinkedList.descendingIterator() method." }, { "code": null, "e": 2597, "s": 2418, "text": "Perform the print operation on each element of the ArrayList using forEachRemaining(). We can provide the method reference System.out::println Iterator to the forEachRemaining()." }, { "code": null, "e": 2602, "s": 2597, "text": "Java" }, { "code": "// Traverse through ArrayList in// reverse direction Using// stream in Java import java.lang.*;import java.util.stream.*;import java.util.*;import java.io.*; class GFG { public static void main(String[] args) { // create a list List<Integer> Arlist = Arrays.asList(5, 2, 4, 8); System.out.println(\"Reversed : \"); // create a stream // collect the elements after these operations // create a descending iterator on the stream // loop through the descending iterator // print the element Arlist.stream() .collect( Collectors.toCollection(LinkedList::new)) .descendingIterator() .forEachRemaining(System.out::println); }}", "e": 3345, "s": 2602, "text": null }, { "code": null, "e": 3365, "s": 3345, "text": "Reversed : \n8\n4\n2\n5" }, { "code": null, "e": 3607, "s": 3365, "text": "Method 3: (Using For Loop) We know that List is an ordered collection, and we can access the element of the list just by its index, so Define an ArrayList and iterate from last using a for loop till the first element and print each element. " }, { "code": null, "e": 3612, "s": 3607, "text": "Java" }, { "code": "// Traverse through ArrayList in// reverse direction using For// Loop in Javaimport java.util.*;import java.io.*; class GFG { public static void main(String[] args) { // create a list List<Integer> Arlist = Arrays.asList(5, 4, 8, 2); System.out.println(\"Reversed :\"); // Printing in reverse for (int i = Arlist.size() - 1; i >= 0; i--) { System.out.println(Arlist.get(i)); } }}", "e": 4059, "s": 3612, "text": null }, { "code": null, "e": 4078, "s": 4059, "text": "Reversed :\n2\n8\n4\n5" }, { "code": null, "e": 4132, "s": 4078, "text": "Method 4: (Using Apache Common’s ReverseListIterator)" }, { "code": null, "e": 4501, "s": 4132, "text": "This method provides ReverseListIterator that we can use to iterate List in reverse order. As we use the ReverseListIterator then next() will return the last element from the array list, Then as we call the next element then next bracket will return the previous element of the current element, and has next will check whether our ArrayList contains an element or not." }, { "code": null, "e": 4506, "s": 4501, "text": "Java" }, { "code": "// Traverse through ArrayList in reverse direction using// ReverseListIterator in Java import org.apache.commons.collections.iterators.ReverseListIterator; import java.util.Arrays;import java.util.List; class Main { public static void main(String[] args) { // create a list List<Integer> list = Arrays.asList(1, 5, 8, 7); // create a reverse listiterator ReverseListIterator it = new ReverseListIterator(list); System.out.println(\"Reversed : \"); // print the elements while (it.hasNext()) { System.out.println(it.next()); } }}", "e": 5129, "s": 4506, "text": null }, { "code": null, "e": 5137, "s": 5129, "text": "Output " }, { "code": null, "e": 5156, "s": 5137, "text": "Reversed :\n7\n8\n5\n1" }, { "code": null, "e": 5178, "s": 5156, "text": "Time Complexity: O(n)" }, { "code": null, "e": 5193, "s": 5178, "text": "Java-ArrayList" }, { "code": null, "e": 5200, "s": 5193, "text": "Picked" }, { "code": null, "e": 5224, "s": 5200, "text": "Technical Scripter 2020" }, { "code": null, "e": 5229, "s": 5224, "text": "Java" }, { "code": null, "e": 5243, "s": 5229, "text": "Java Programs" }, { "code": null, "e": 5262, "s": 5243, "text": "Technical Scripter" }, { "code": null, "e": 5267, "s": 5262, "text": "Java" } ]
HTML Calculator
06 Jul, 2022 HTML calculator is used to perform the basic mathematical operations like Addition, subtraction, multiplication, and division. To design the basic calculator, we will use HTML, CSS, and JavaScript. HTML is used to design the basic structure of the calculator. CSS styles are used to apply styles on the calculator and JavaScript is used to add the calculation functionality. Complete Code: <html> <head> <script> //function that display value function dis(val) { document.getElementById("result").value+=val } //function that evaluates the digit and return result function solve() { let x = document.getElementById("result").value let y = eval(x) document.getElementById("result").value = y } //function that clear the display function clr() { document.getElementById("result").value = "" } </script> <!-- for styling --> <style> .title{ margin-bottom: 10px; text-align:center; width: 210px; color:green; border: solid black 2px; } input[type="button"] { background-color:green; color: black; border: solid black 2px; width:100% } input[type="text"] { background-color:white; border: solid black 2px; width:100% } </style> </head> <!-- create table --> <body> <div class = title >GeeksforGeeks Calculator</div> <table border="1"> <tr> <td colspan="3"><input type="text" id="result"/></td> <!-- clr() function will call clr to clear all value --> <td><input type="button" value="c" onclick="clr()"/> </td> </tr> <tr> <!-- create button and assign value to each button --> <!-- dis("1") will call function dis to display value --> <td><input type="button" value="1" onclick="dis('1')"/> </td> <td><input type="button" value="2" onclick="dis('2')"/> </td> <td><input type="button" value="3" onclick="dis('3')"/> </td> <td><input type="button" value="/" onclick="dis('/')"/> </td> </tr> <tr> <td><input type="button" value="4" onclick="dis('4')"/> </td> <td><input type="button" value="5" onclick="dis('5')"/> </td> <td><input type="button" value="6" onclick="dis('6')"/> </td> <td><input type="button" value="-" onclick="dis('-')"/> </td> </tr> <tr> <td><input type="button" value="7" onclick="dis('7')"/> </td> <td><input type="button" value="8" onclick="dis('8')"/> </td> <td><input type="button" value="9" onclick="dis('9')"/> </td> <td><input type="button" value="+" onclick="dis('+')"/> </td> </tr> <tr> <td><input type="button" value="." onclick="dis('.')"/> </td> <td><input type="button" value="0" onclick="dis('0')"/> </td> <!-- solve function call function solve to evaluate value --> <td><input type="button" value="=" onclick="solve()"/> </td> <td><input type="button" value="*" onclick="dis('*')"/> </td> </tr> </table> </body></html> Output:At first-After entering some data-And finally result will be like- AnmolAgarwal CSS-Questions HTML-Questions JavaScript-Questions CSS HTML JavaScript Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to update Node.js and NPM to next version ? Top 10 Projects For Beginners To Practice HTML and CSS Skills How to insert spaces/tabs in text using HTML/CSS? How to create footer to stay at the bottom of a Web page? CSS to put icon inside an input element in a form How to update Node.js and NPM to next version ? Top 10 Projects For Beginners To Practice HTML and CSS Skills How to insert spaces/tabs in text using HTML/CSS? REST API (Introduction) Hide or show elements in HTML using display property
[ { "code": null, "e": 52, "s": 24, "text": "\n06 Jul, 2022" }, { "code": null, "e": 179, "s": 52, "text": "HTML calculator is used to perform the basic mathematical operations like Addition, subtraction, multiplication, and division." }, { "code": null, "e": 488, "s": 240, "text": "To design the basic calculator, we will use HTML, CSS, and JavaScript. HTML is used to design the basic structure of the calculator. CSS styles are used to apply styles on the calculator and JavaScript is used to add the calculation functionality." }, { "code": null, "e": 503, "s": 488, "text": "Complete Code:" }, { "code": "<html> <head> <script> //function that display value function dis(val) { document.getElementById(\"result\").value+=val } //function that evaluates the digit and return result function solve() { let x = document.getElementById(\"result\").value let y = eval(x) document.getElementById(\"result\").value = y } //function that clear the display function clr() { document.getElementById(\"result\").value = \"\" } </script> <!-- for styling --> <style> .title{ margin-bottom: 10px; text-align:center; width: 210px; color:green; border: solid black 2px; } input[type=\"button\"] { background-color:green; color: black; border: solid black 2px; width:100% } input[type=\"text\"] { background-color:white; border: solid black 2px; width:100% } </style> </head> <!-- create table --> <body> <div class = title >GeeksforGeeks Calculator</div> <table border=\"1\"> <tr> <td colspan=\"3\"><input type=\"text\" id=\"result\"/></td> <!-- clr() function will call clr to clear all value --> <td><input type=\"button\" value=\"c\" onclick=\"clr()\"/> </td> </tr> <tr> <!-- create button and assign value to each button --> <!-- dis(\"1\") will call function dis to display value --> <td><input type=\"button\" value=\"1\" onclick=\"dis('1')\"/> </td> <td><input type=\"button\" value=\"2\" onclick=\"dis('2')\"/> </td> <td><input type=\"button\" value=\"3\" onclick=\"dis('3')\"/> </td> <td><input type=\"button\" value=\"/\" onclick=\"dis('/')\"/> </td> </tr> <tr> <td><input type=\"button\" value=\"4\" onclick=\"dis('4')\"/> </td> <td><input type=\"button\" value=\"5\" onclick=\"dis('5')\"/> </td> <td><input type=\"button\" value=\"6\" onclick=\"dis('6')\"/> </td> <td><input type=\"button\" value=\"-\" onclick=\"dis('-')\"/> </td> </tr> <tr> <td><input type=\"button\" value=\"7\" onclick=\"dis('7')\"/> </td> <td><input type=\"button\" value=\"8\" onclick=\"dis('8')\"/> </td> <td><input type=\"button\" value=\"9\" onclick=\"dis('9')\"/> </td> <td><input type=\"button\" value=\"+\" onclick=\"dis('+')\"/> </td> </tr> <tr> <td><input type=\"button\" value=\".\" onclick=\"dis('.')\"/> </td> <td><input type=\"button\" value=\"0\" onclick=\"dis('0')\"/> </td> <!-- solve function call function solve to evaluate value --> <td><input type=\"button\" value=\"=\" onclick=\"solve()\"/> </td> <td><input type=\"button\" value=\"*\" onclick=\"dis('*')\"/> </td> </tr> </table> </body></html> ", "e": 3475, "s": 503, "text": null }, { "code": null, "e": 3549, "s": 3475, "text": "Output:At first-After entering some data-And finally result will be like-" }, { "code": null, "e": 3562, "s": 3549, "text": "AnmolAgarwal" }, { "code": null, "e": 3576, "s": 3562, "text": "CSS-Questions" }, { "code": null, "e": 3591, "s": 3576, "text": "HTML-Questions" }, { "code": null, "e": 3612, "s": 3591, "text": "JavaScript-Questions" }, { "code": null, "e": 3616, "s": 3612, "text": "CSS" }, { "code": null, "e": 3621, "s": 3616, "text": "HTML" }, { "code": null, "e": 3632, "s": 3621, "text": "JavaScript" }, { "code": null, "e": 3649, "s": 3632, "text": "Web Technologies" }, { "code": null, "e": 3654, "s": 3649, "text": "HTML" }, { "code": null, "e": 3752, "s": 3654, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3800, "s": 3752, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 3862, "s": 3800, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 3912, "s": 3862, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 3970, "s": 3912, "text": "How to create footer to stay at the bottom of a Web page?" }, { "code": null, "e": 4020, "s": 3970, "text": "CSS to put icon inside an input element in a form" }, { "code": null, "e": 4068, "s": 4020, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 4130, "s": 4068, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 4180, "s": 4130, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 4204, "s": 4180, "text": "REST API (Introduction)" } ]
How to trim a file extension from string using JavaScript ?
29 May, 2019 Given a fileName in string format and the task is to trim the file extension from the string using JavaScript. replace() method: This method searches a string for a defined value or a regular expression, and returns a new string with the replaced defined value.Syntax:string.replace(searchVal, newvalue)Parameters:searchVal: It is required parameter. It specifies the value or regular expression, that is going to replace by the new value.newvalue: It is required parameter. It specifies the value to be replaced with the search value.Return value: It returns a new string where the defines value(s) has been replaced by the new value. Syntax: string.replace(searchVal, newvalue) Parameters: searchVal: It is required parameter. It specifies the value or regular expression, that is going to replace by the new value. newvalue: It is required parameter. It specifies the value to be replaced with the search value. Return value: It returns a new string where the defines value(s) has been replaced by the new value. split() method: This method is used to split a string into an array of substrings and returns the new array.Syntax:string.split(separator, limit)Parameters:separator: It is optional parameter. It specifies the character, or the regular expression, to use for splitting the string. If not used, the whole string will be returned (an array with only one item).limit: It is optional parameter. It specifies the integer that specifies the number of split items beyond the split limit will be excluded from the array.Return value: It returns a new Array, having the splitted items. Syntax: string.split(separator, limit) Parameters: separator: It is optional parameter. It specifies the character, or the regular expression, to use for splitting the string. If not used, the whole string will be returned (an array with only one item). limit: It is optional parameter. It specifies the integer that specifies the number of split items beyond the split limit will be excluded from the array. Return value: It returns a new Array, having the splitted items. JavaScript String slice() method: This method gets parts of a string and returns the extracted parts in a new string. Start and end parameters are used to specify the part of the string to extract. The first character starts from position 0, the second has position 1, and so on.Syntax:string.slice(start, end) Parameters:start: It is required parameter. It specifies the position from where to start the extraction. First character start from position 0.end: It is optional parameter. It specifies the position (excluding it) where to stop the extraction. If not used, slice() selects all characters from the start-position to the end.Return value: It returns a string, representing the extracted part of the string. Syntax: string.slice(start, end) Parameters: start: It is required parameter. It specifies the position from where to start the extraction. First character start from position 0. end: It is optional parameter. It specifies the position (excluding it) where to stop the extraction. If not used, slice() selects all characters from the start-position to the end. Return value: It returns a string, representing the extracted part of the string. JavaScript Array join() Method: This method adds the elements of an array into a string, and returns the string. The elements will be separated by a passed separator. The default separator is comma (, ).Syntax:array.join(separator) Parameters: This method accepts single parameter separator which is optional. It specifies the separator to be used. If not used, the elements are separated with a commaReturn value: It returns a string, denoting the array values, separated by the defined separator. Syntax: array.join(separator) Parameters: This method accepts single parameter separator which is optional. It specifies the separator to be used. If not used, the elements are separated with a comma Return value: It returns a string, denoting the array values, separated by the defined separator. Example 1: This example gets the file Name by using split(), slice() and join() methods. <!DOCTYPE HTML> <html> <head> <title> Trim a file extension from a string using JavaScript </title> </head> <body style = "text-align:center;"> <h1 style = "color:green;" > GeeksForGeeks </h1> <p id = "GFG_UP" style = "font-size: 15px; font-weight: bold;"> </p> <button onclick = "gfg_Run()"> click here </button> <p id = "GFG_DOWN" style = "color:green; font-size: 20px; font-weight: bold;"> </p> <script> var el_up = document.getElementById("GFG_UP"); var el_down = document.getElementById("GFG_DOWN"); var fName = "fileName.jpg"; el_up.innerHTML = "String = '"+fName + "'"; function gfg_Run() { el_down.innerHTML = fName.split('.').slice(0, -1).join('.'); } </script> </body> </html> Output: Before clicking on the button: After clicking on the button: Example 2: This example gets the file Name by using RegExp along with replace() method. <!DOCTYPE HTML> <html> <head> <title> Trim a file extension from a string using JavaScript </title> </head> <body style = "text-align:center;"> <h1 style = "color:green;" > GeeksForGeeks </h1> <p id = "GFG_UP" style = "font-size: 15px; font-weight: bold;"> </p> <button onclick = "gfg_Run()"> click here </button> <p id = "GFG_DOWN" style = "color:green; font-size: 20px; font-weight: bold;"> </p> <script> var el_up = document.getElementById("GFG_UP"); var el_down = document.getElementById("GFG_DOWN"); var fName = "fileName.jpg"; el_up.innerHTML = "String = '" + fName + "'"; function gfg_Run() { el_down.innerHTML =fName.replace(/\.[^/.]+$/, "") } </script> </body> </html> Output: Before clicking on the button: After clicking 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.
[ { "code": null, "e": 28, "s": 0, "text": "\n29 May, 2019" }, { "code": null, "e": 139, "s": 28, "text": "Given a fileName in string format and the task is to trim the file extension from the string using JavaScript." }, { "code": null, "e": 664, "s": 139, "text": "replace() method: This method searches a string for a defined value or a regular expression, and returns a new string with the replaced defined value.Syntax:string.replace(searchVal, newvalue)Parameters:searchVal: It is required parameter. It specifies the value or regular expression, that is going to replace by the new value.newvalue: It is required parameter. It specifies the value to be replaced with the search value.Return value: It returns a new string where the defines value(s) has been replaced by the new value." }, { "code": null, "e": 672, "s": 664, "text": "Syntax:" }, { "code": null, "e": 708, "s": 672, "text": "string.replace(searchVal, newvalue)" }, { "code": null, "e": 720, "s": 708, "text": "Parameters:" }, { "code": null, "e": 846, "s": 720, "text": "searchVal: It is required parameter. It specifies the value or regular expression, that is going to replace by the new value." }, { "code": null, "e": 943, "s": 846, "text": "newvalue: It is required parameter. It specifies the value to be replaced with the search value." }, { "code": null, "e": 1044, "s": 943, "text": "Return value: It returns a new string where the defines value(s) has been replaced by the new value." }, { "code": null, "e": 1621, "s": 1044, "text": "split() method: This method is used to split a string into an array of substrings and returns the new array.Syntax:string.split(separator, limit)Parameters:separator: It is optional parameter. It specifies the character, or the regular expression, to use for splitting the string. If not used, the whole string will be returned (an array with only one item).limit: It is optional parameter. It specifies the integer that specifies the number of split items beyond the split limit will be excluded from the array.Return value: It returns a new Array, having the splitted items." }, { "code": null, "e": 1629, "s": 1621, "text": "Syntax:" }, { "code": null, "e": 1660, "s": 1629, "text": "string.split(separator, limit)" }, { "code": null, "e": 1672, "s": 1660, "text": "Parameters:" }, { "code": null, "e": 1875, "s": 1672, "text": "separator: It is optional parameter. It specifies the character, or the regular expression, to use for splitting the string. If not used, the whole string will be returned (an array with only one item)." }, { "code": null, "e": 2030, "s": 1875, "text": "limit: It is optional parameter. It specifies the integer that specifies the number of split items beyond the split limit will be excluded from the array." }, { "code": null, "e": 2095, "s": 2030, "text": "Return value: It returns a new Array, having the splitted items." }, { "code": null, "e": 2813, "s": 2095, "text": "JavaScript String slice() method: This method gets parts of a string and returns the extracted parts in a new string. Start and end parameters are used to specify the part of the string to extract. The first character starts from position 0, the second has position 1, and so on.Syntax:string.slice(start, end)\nParameters:start: It is required parameter. It specifies the position from where to start the extraction. First character start from position 0.end: It is optional parameter. It specifies the position (excluding it) where to stop the extraction. If not used, slice() selects all characters from the start-position to the end.Return value: It returns a string, representing the extracted part of the string." }, { "code": null, "e": 2821, "s": 2813, "text": "Syntax:" }, { "code": null, "e": 2847, "s": 2821, "text": "string.slice(start, end)\n" }, { "code": null, "e": 2859, "s": 2847, "text": "Parameters:" }, { "code": null, "e": 2993, "s": 2859, "text": "start: It is required parameter. It specifies the position from where to start the extraction. First character start from position 0." }, { "code": null, "e": 3175, "s": 2993, "text": "end: It is optional parameter. It specifies the position (excluding it) where to stop the extraction. If not used, slice() selects all characters from the start-position to the end." }, { "code": null, "e": 3257, "s": 3175, "text": "Return value: It returns a string, representing the extracted part of the string." }, { "code": null, "e": 3756, "s": 3257, "text": "JavaScript Array join() Method: This method adds the elements of an array into a string, and returns the string. The elements will be separated by a passed separator. The default separator is comma (, ).Syntax:array.join(separator)\nParameters: This method accepts single parameter separator which is optional. It specifies the separator to be used. If not used, the elements are separated with a commaReturn value: It returns a string, denoting the array values, separated by the defined separator." }, { "code": null, "e": 3764, "s": 3756, "text": "Syntax:" }, { "code": null, "e": 3787, "s": 3764, "text": "array.join(separator)\n" }, { "code": null, "e": 3957, "s": 3787, "text": "Parameters: This method accepts single parameter separator which is optional. It specifies the separator to be used. If not used, the elements are separated with a comma" }, { "code": null, "e": 4055, "s": 3957, "text": "Return value: It returns a string, denoting the array values, separated by the defined separator." }, { "code": null, "e": 4144, "s": 4055, "text": "Example 1: This example gets the file Name by using split(), slice() and join() methods." }, { "code": "<!DOCTYPE HTML> <html> <head> <title> Trim a file extension from a string using JavaScript </title> </head> <body style = \"text-align:center;\"> <h1 style = \"color:green;\" > GeeksForGeeks </h1> <p id = \"GFG_UP\" style = \"font-size: 15px; font-weight: bold;\"> </p> <button onclick = \"gfg_Run()\"> click here </button> <p id = \"GFG_DOWN\" style = \"color:green; font-size: 20px; font-weight: bold;\"> </p> <script> var el_up = document.getElementById(\"GFG_UP\"); var el_down = document.getElementById(\"GFG_DOWN\"); var fName = \"fileName.jpg\"; el_up.innerHTML = \"String = '\"+fName + \"'\"; function gfg_Run() { el_down.innerHTML = fName.split('.').slice(0, -1).join('.'); } </script> </body> </html> ", "e": 5168, "s": 4144, "text": null }, { "code": null, "e": 5176, "s": 5168, "text": "Output:" }, { "code": null, "e": 5207, "s": 5176, "text": "Before clicking on the button:" }, { "code": null, "e": 5237, "s": 5207, "text": "After clicking on the button:" }, { "code": null, "e": 5325, "s": 5237, "text": "Example 2: This example gets the file Name by using RegExp along with replace() method." }, { "code": "<!DOCTYPE HTML> <html> <head> <title> Trim a file extension from a string using JavaScript </title> </head> <body style = \"text-align:center;\"> <h1 style = \"color:green;\" > GeeksForGeeks </h1> <p id = \"GFG_UP\" style = \"font-size: 15px; font-weight: bold;\"> </p> <button onclick = \"gfg_Run()\"> click here </button> <p id = \"GFG_DOWN\" style = \"color:green; font-size: 20px; font-weight: bold;\"> </p> <script> var el_up = document.getElementById(\"GFG_UP\"); var el_down = document.getElementById(\"GFG_DOWN\"); var fName = \"fileName.jpg\"; el_up.innerHTML = \"String = '\" + fName + \"'\"; function gfg_Run() { el_down.innerHTML =fName.replace(/\\.[^/.]+$/, \"\") } </script> </body> </html> ", "e": 6338, "s": 5325, "text": null }, { "code": null, "e": 6346, "s": 6338, "text": "Output:" }, { "code": null, "e": 6377, "s": 6346, "text": "Before clicking on the button:" }, { "code": null, "e": 6407, "s": 6377, "text": "After clicking on the button:" }, { "code": null, "e": 6418, "s": 6407, "text": "JavaScript" }, { "code": null, "e": 6435, "s": 6418, "text": "Web Technologies" }, { "code": null, "e": 6462, "s": 6435, "text": "Web technologies Questions" } ]
Encoder in Digital Logic
25 Nov, 2019 An Encoder is a combinational circuit that performs the reverse operation of Decoder.It has maximum of 2^n input lines and ‘n’ output lines, hence it encodes the information from 2^n inputs into an n-bit code. It will produce a binary code equivalent to the input, which is active High. Therefore, the encoder encodes 2^n input lines with ‘n’ bits. The 4 to 2 Encoder consists of four inputs Y3, Y2, Y1 & Y0 and two outputs A1 & A0. At any time, only one of these 4 inputs can be ‘1’ in order to get the respective binary code at the output. The figure below shows the logic symbol of 4 to 2 encoder : The Truth table of 4 to 2 encoder is as follows : Logical expression for A1 and A0 : A1 = Y3 + Y2 A0 = Y3 + Y1 The above two Boolean functions A1 and A0 can be implemented using two input OR gates : The 8 to 3 Encoder or octal to Binary encoder consists of 8 inputs : Y7 to Y0 and 3 outputs : A2, A1 & A0. Each input line corresponds to each octal digit and three outputs generate corresponding binary code. The figure below shows the logic symbol of octal to binary encoder: The truth table for 8 to 3 encoder is as follows : Logical expression for A2, A1 and A0 : A2 = Y7 + Y6 + Y5 + Y4 A1 = Y7 + Y6 + Y3 + Y2 A0 = Y7 + Y5 + Y3 + Y1 The above two Boolean functions A2, A1 and A0 can be implemented using four input OR gates : The decimal to binary encoder usually consists of 10 input lines and 4 output lines. Each input line corresponds to the each decimal digit and 4 outputs correspond to the BCD code. This encoder accepts the decoded decimal data as an input and encodes it to the BCD output which is available on the output lines. The figure below shows the logic symbol of decimal to BCD encoder : The truth table for decimal to BCD encoder is as follows: Logical expression for A3, A2, A1 and A0 : A3 = Y9 + Y8 A2 = Y7 + Y6 + Y5 +Y4 A1 = Y7 + Y6 + Y3 +Y2 A0 = Y9 + Y7 +Y5 +Y3 + Y1 The above two Boolean functions can be implemented using OR gates : A 4 to 2 priority encoder has 4 inputs : Y3, Y2, Y1 & Y0 and 2 outputs : A1 & A0. Here, the input, Y3 has the highest priority, whereas the input, Y0 has the lowest priority. In this case, even if more than one input is ‘1’ at the same time, the output will be the (binary) code corresponding to the input, which is having higher priority. The truth table for priority encoder is as follows : The above two Boolean functions can be implemented as : Drawbacks of Normal Encoders – There is an ambiguity, when all outputs of encoder are equal to zero.If more than one input is active High, then the encoder produces an output, which may not be the correct code. There is an ambiguity, when all outputs of encoder are equal to zero. If more than one input is active High, then the encoder produces an output, which may not be the correct code. So, to overcome these difficulties, we should assign priorities to each input of encoder. Then, the output of encoder will be the ( code corresponding to the active High inputs, which has higher priority. Uses of Encoders – Encoders are very common electronic circuits used in all digital systems.Encoders are used to translate the decimal values to the binary in order to perform the binary functions such as addition, subtraction, multiplication, etc.Other applications especially for Priority Encoders may include detecting interrupts in microprocessor applications. Encoders are very common electronic circuits used in all digital systems. Encoders are used to translate the decimal values to the binary in order to perform the binary functions such as addition, subtraction, multiplication, etc. Other applications especially for Priority Encoders may include detecting interrupts in microprocessor applications. GATE CS Corner Questions Practicing the following questions will help you test your knowledge. All questions have been asked in GATE in previous years or in GATE Mock Tests. It is highly recommended that you practice them. GATE CS 2013, Question 65GATE CS 2014 (Set 3), Question 65 GATE CS 2013, Question 65 GATE CS 2014 (Set 3), Question 65 References –Encoder – WikipediaPriority encoder – Wikipedia This article is contributed by Harshita Pandey. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. Digital Electronics & Logic Design GATE CS Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. IEEE Standard 754 Floating Point Numbers Difference between RAM and ROM Introduction to memory and memory units Analog to Digital Conversion Difference between Half adder and full adder Layers of OSI Model ACID Properties in DBMS TCP/IP Model Types of Operating Systems Normal Forms in DBMS
[ { "code": null, "e": 54, "s": 26, "text": "\n25 Nov, 2019" }, { "code": null, "e": 403, "s": 54, "text": "An Encoder is a combinational circuit that performs the reverse operation of Decoder.It has maximum of 2^n input lines and ‘n’ output lines, hence it encodes the information from 2^n inputs into an n-bit code. It will produce a binary code equivalent to the input, which is active High. Therefore, the encoder encodes 2^n input lines with ‘n’ bits." }, { "code": null, "e": 656, "s": 403, "text": "The 4 to 2 Encoder consists of four inputs Y3, Y2, Y1 & Y0 and two outputs A1 & A0. At any time, only one of these 4 inputs can be ‘1’ in order to get the respective binary code at the output. The figure below shows the logic symbol of 4 to 2 encoder :" }, { "code": null, "e": 706, "s": 656, "text": "The Truth table of 4 to 2 encoder is as follows :" }, { "code": null, "e": 741, "s": 706, "text": "Logical expression for A1 and A0 :" }, { "code": null, "e": 768, "s": 741, "text": "A1 = Y3 + Y2\nA0 = Y3 + Y1\n" }, { "code": null, "e": 856, "s": 768, "text": "The above two Boolean functions A1 and A0 can be implemented using two input OR gates :" }, { "code": null, "e": 1065, "s": 856, "text": "The 8 to 3 Encoder or octal to Binary encoder consists of 8 inputs : Y7 to Y0 and 3 outputs : A2, A1 & A0. Each input line corresponds to each octal digit and three outputs generate corresponding binary code." }, { "code": null, "e": 1133, "s": 1065, "text": "The figure below shows the logic symbol of octal to binary encoder:" }, { "code": null, "e": 1184, "s": 1133, "text": "The truth table for 8 to 3 encoder is as follows :" }, { "code": null, "e": 1223, "s": 1184, "text": "Logical expression for A2, A1 and A0 :" }, { "code": null, "e": 1293, "s": 1223, "text": "A2 = Y7 + Y6 + Y5 + Y4\nA1 = Y7 + Y6 + Y3 + Y2\nA0 = Y7 + Y5 + Y3 + Y1\n" }, { "code": null, "e": 1386, "s": 1293, "text": "The above two Boolean functions A2, A1 and A0 can be implemented using four input OR gates :" }, { "code": null, "e": 1766, "s": 1386, "text": "The decimal to binary encoder usually consists of 10 input lines and 4 output lines. Each input line corresponds to the each decimal digit and 4 outputs correspond to the BCD code. This encoder accepts the decoded decimal data as an input and encodes it to the BCD output which is available on the output lines. The figure below shows the logic symbol of decimal to BCD encoder :" }, { "code": null, "e": 1824, "s": 1766, "text": "The truth table for decimal to BCD encoder is as follows:" }, { "code": null, "e": 1867, "s": 1824, "text": "Logical expression for A3, A2, A1 and A0 :" }, { "code": null, "e": 1955, "s": 1867, "text": " A3 = Y9 + Y8\n A2 = Y7 + Y6 + Y5 +Y4\n A1 = Y7 + Y6 + Y3 +Y2\n A0 = Y9 + Y7 +Y5 +Y3 + Y1\n" }, { "code": null, "e": 2023, "s": 1955, "text": "The above two Boolean functions can be implemented using OR gates :" }, { "code": null, "e": 2363, "s": 2023, "text": "A 4 to 2 priority encoder has 4 inputs : Y3, Y2, Y1 & Y0 and 2 outputs : A1 & A0. Here, the input, Y3 has the highest priority, whereas the input, Y0 has the lowest priority. In this case, even if more than one input is ‘1’ at the same time, the output will be the (binary) code corresponding to the input, which is having higher priority." }, { "code": null, "e": 2416, "s": 2363, "text": "The truth table for priority encoder is as follows :" }, { "code": null, "e": 2472, "s": 2416, "text": "The above two Boolean functions can be implemented as :" }, { "code": null, "e": 2503, "s": 2472, "text": "Drawbacks of Normal Encoders –" }, { "code": null, "e": 2683, "s": 2503, "text": "There is an ambiguity, when all outputs of encoder are equal to zero.If more than one input is active High, then the encoder produces an output, which may not be the correct code." }, { "code": null, "e": 2753, "s": 2683, "text": "There is an ambiguity, when all outputs of encoder are equal to zero." }, { "code": null, "e": 2864, "s": 2753, "text": "If more than one input is active High, then the encoder produces an output, which may not be the correct code." }, { "code": null, "e": 3069, "s": 2864, "text": "So, to overcome these difficulties, we should assign priorities to each input of encoder. Then, the output of encoder will be the ( code corresponding to the active High inputs, which has higher priority." }, { "code": null, "e": 3088, "s": 3069, "text": "Uses of Encoders –" }, { "code": null, "e": 3434, "s": 3088, "text": "Encoders are very common electronic circuits used in all digital systems.Encoders are used to translate the decimal values to the binary in order to perform the binary functions such as addition, subtraction, multiplication, etc.Other applications especially for Priority Encoders may include detecting interrupts in microprocessor applications." }, { "code": null, "e": 3508, "s": 3434, "text": "Encoders are very common electronic circuits used in all digital systems." }, { "code": null, "e": 3665, "s": 3508, "text": "Encoders are used to translate the decimal values to the binary in order to perform the binary functions such as addition, subtraction, multiplication, etc." }, { "code": null, "e": 3782, "s": 3665, "text": "Other applications especially for Priority Encoders may include detecting interrupts in microprocessor applications." }, { "code": null, "e": 3807, "s": 3782, "text": "GATE CS Corner Questions" }, { "code": null, "e": 4005, "s": 3807, "text": "Practicing the following questions will help you test your knowledge. All questions have been asked in GATE in previous years or in GATE Mock Tests. It is highly recommended that you practice them." }, { "code": null, "e": 4064, "s": 4005, "text": "GATE CS 2013, Question 65GATE CS 2014 (Set 3), Question 65" }, { "code": null, "e": 4090, "s": 4064, "text": "GATE CS 2013, Question 65" }, { "code": null, "e": 4124, "s": 4090, "text": "GATE CS 2014 (Set 3), Question 65" }, { "code": null, "e": 4184, "s": 4124, "text": "References –Encoder – WikipediaPriority encoder – Wikipedia" }, { "code": null, "e": 4487, "s": 4184, "text": "This article is contributed by Harshita Pandey. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks." }, { "code": null, "e": 4612, "s": 4487, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 4647, "s": 4612, "text": "Digital Electronics & Logic Design" }, { "code": null, "e": 4655, "s": 4647, "text": "GATE CS" }, { "code": null, "e": 4753, "s": 4655, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4794, "s": 4753, "text": "IEEE Standard 754 Floating Point Numbers" }, { "code": null, "e": 4825, "s": 4794, "text": "Difference between RAM and ROM" }, { "code": null, "e": 4865, "s": 4825, "text": "Introduction to memory and memory units" }, { "code": null, "e": 4894, "s": 4865, "text": "Analog to Digital Conversion" }, { "code": null, "e": 4939, "s": 4894, "text": "Difference between Half adder and full adder" }, { "code": null, "e": 4959, "s": 4939, "text": "Layers of OSI Model" }, { "code": null, "e": 4983, "s": 4959, "text": "ACID Properties in DBMS" }, { "code": null, "e": 4996, "s": 4983, "text": "TCP/IP Model" }, { "code": null, "e": 5023, "s": 4996, "text": "Types of Operating Systems" } ]
Electron - Debugging
We have two processes that run our application – the main process and the renderer process. Since the renderer process is the one being executed in our browser window, we can use the Chrome Devtools to debug it. To open DevTools, use the shortcut "Ctrl+Shift+I" or the <F12> key. You can check out how to use devtools here. When you open the DevTools, your app will look like as shown in the following screenshot − The DevTools in an Electron browser window can only debug JavaScript that is executed in that window (i.e., the web pages). To debug JavaScript that is executed in the main process you will need to use an external debugger and launch Electron with the --debug or the --debug-brk switch. Electron will listen for the V8 debugger protocol messages on the specified port; an external debugger will need to connect on this port. The default port is 5858. Run your app using the following − $ electron --debug = 5858 ./main.js Now you will need a debugger that supports the V8 debugger protocol. You can use VSCode or node-inspector for this purpose. For example, let us follow these steps and set up VSCode for this purpose. Follow these steps to set it up − Download and install VSCode. Open your Electron project in VSCode. Add a file .vscode/launch.json with the following configuration − { "version": "1.0.0", "configurations": [ { "name": "Debug Main Process", "type": "node", "request": "launch", "cwd": "${workspaceRoot}", "runtimeExecutable": "${workspaceRoot}/node_modules/.bin/electron", "program": "${workspaceRoot}/main.js" } ] } Note − For Windows, use "${workspaceRoot}/node_modules/.bin/electron.cmd" for runtimeExecutable. Set some breakpoints in main.js, and start debugging in the Debug View. When you hit the breakpoints, the screen will look something like this − The VSCode debugger is very powerful and will help you rectify errors quickly. You also have other options like node-inspector for debugging electron apps. 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": 2157, "s": 2065, "text": "We have two processes that run our application – the main process and the renderer process." }, { "code": null, "e": 2389, "s": 2157, "text": "Since the renderer process is the one being executed in our browser window, we can use the Chrome Devtools to debug it. To open DevTools, use the shortcut \"Ctrl+Shift+I\" or the <F12> key. You can check out how to use devtools here." }, { "code": null, "e": 2480, "s": 2389, "text": "When you open the DevTools, your app will look like as shown in the following screenshot −" }, { "code": null, "e": 2767, "s": 2480, "text": "The DevTools in an Electron browser window can only debug JavaScript that is executed in that window (i.e., the web pages). To debug JavaScript that is executed in the main process you will need to use an external debugger and launch Electron with the --debug or the --debug-brk switch." }, { "code": null, "e": 2931, "s": 2767, "text": "Electron will listen for the V8 debugger protocol messages on the specified port; an external debugger will need to connect on this port. The default port is 5858." }, { "code": null, "e": 2966, "s": 2931, "text": "Run your app using the following −" }, { "code": null, "e": 3003, "s": 2966, "text": "$ electron --debug = 5858 ./main.js\n" }, { "code": null, "e": 3236, "s": 3003, "text": "Now you will need a debugger that supports the V8 debugger protocol. You can use VSCode or node-inspector for this purpose. For example, let us follow these steps and set up VSCode for this purpose. Follow these steps to set it up −" }, { "code": null, "e": 3303, "s": 3236, "text": "Download and install VSCode. Open your Electron project in VSCode." }, { "code": null, "e": 3369, "s": 3303, "text": "Add a file .vscode/launch.json with the following configuration −" }, { "code": null, "e": 3694, "s": 3369, "text": "{\n \"version\": \"1.0.0\",\n \"configurations\": [\n {\n \"name\": \"Debug Main Process\",\n \"type\": \"node\",\n \"request\": \"launch\",\n \"cwd\": \"${workspaceRoot}\",\n \"runtimeExecutable\": \"${workspaceRoot}/node_modules/.bin/electron\",\n \"program\": \"${workspaceRoot}/main.js\"\n }\n ]\n}" }, { "code": null, "e": 3791, "s": 3694, "text": "Note − For Windows, use \"${workspaceRoot}/node_modules/.bin/electron.cmd\" for runtimeExecutable." }, { "code": null, "e": 3936, "s": 3791, "text": "Set some breakpoints in main.js, and start debugging in the Debug View. When you hit the breakpoints, the screen will look something like this −" }, { "code": null, "e": 4092, "s": 3936, "text": "The VSCode debugger is very powerful and will help you rectify errors quickly. You also have other options like node-inspector for debugging electron apps." }, { "code": null, "e": 4129, "s": 4092, "text": "\n 251 Lectures \n 35.5 hours \n" }, { "code": null, "e": 4146, "s": 4129, "text": " Gowthami Swarna" }, { "code": null, "e": 4177, "s": 4146, "text": "\n 9 Lectures \n 41 mins\n" }, { "code": null, "e": 4190, "s": 4177, "text": " Ashraf Said" }, { "code": null, "e": 4221, "s": 4190, "text": "\n 8 Lectures \n 32 mins\n" }, { "code": null, "e": 4234, "s": 4221, "text": " Ashraf Said" }, { "code": null, "e": 4267, "s": 4234, "text": "\n 25 Lectures \n 1 hours \n" }, { "code": null, "e": 4280, "s": 4267, "text": " Ashraf Said" }, { "code": null, "e": 4313, "s": 4280, "text": "\n 17 Lectures \n 1 hours \n" }, { "code": null, "e": 4326, "s": 4313, "text": " Ashraf Said" }, { "code": null, "e": 4357, "s": 4326, "text": "\n 8 Lectures \n 25 mins\n" }, { "code": null, "e": 4370, "s": 4357, "text": " Ashraf Said" }, { "code": null, "e": 4377, "s": 4370, "text": " Print" }, { "code": null, "e": 4388, "s": 4377, "text": " Add Notes" } ]
What is an anonymous function in JavaScript?
A function expression is similar to and has the same syntax as a function declaration One can define "named" function expressions (where the name of the expression might be used in the call stack for example) or "anonymous" function expressions. An example of an anonymous function expression (the name is not used) − var myFunction = function() { // Function code } This function can be invoked using the variable name referring to it − myFunction() In conclusion, an anonymous function is a function that is not stored but is associated with a variable. Anonymous functions can accept inputs and return outputs, just as standard functions
[ { "code": null, "e": 1308, "s": 1062, "text": "A function expression is similar to and has the same syntax as a function\ndeclaration One can define \"named\" function expressions (where the name of the expression might be used in the call stack for example) or \"anonymous\" function expressions." }, { "code": null, "e": 1380, "s": 1308, "text": "An example of an anonymous function expression (the name is not used) −" }, { "code": null, "e": 1432, "s": 1380, "text": "var myFunction = function() {\n // Function code\n}" }, { "code": null, "e": 1503, "s": 1432, "text": "This function can be invoked using the variable name referring to it −" }, { "code": null, "e": 1516, "s": 1503, "text": "myFunction()" }, { "code": null, "e": 1706, "s": 1516, "text": "In conclusion, an anonymous function is a function that is not stored but is associated with a variable. Anonymous functions can accept inputs and return outputs, just as standard functions" } ]
Sort the Matrix Diagonally in C++
Suppose we have N x M matrix, we have to sort this diagonally in increasing order from top-left to the bottom right. So if the matrix is like − The output matrix will be − To solve this, we will follow these steps − Define a method called solve(), this will take si, sj and matrix mat Define a method called solve(), this will take si, sj and matrix mat n := number of rows and m := number of columns n := number of rows and m := number of columns make an array called temp make an array called temp i:= si and j := sj, and index := 0 i:= si and j := sj, and index := 0 while i < n and j < minsert m[i, j] into temp, then increase i and j by 1 while i < n and j < m insert m[i, j] into temp, then increase i and j by 1 insert m[i, j] into temp, then increase i and j by 1 sort temp array sort temp array set index := 0, i := si and j := sj set index := 0, i := si and j := sj while i < n and j < mmat[i, j] := temp[index]increase i, j and index by 1 while i < n and j < m mat[i, j] := temp[index] mat[i, j] := temp[index] increase i, j and index by 1 increase i, j and index by 1 from the main method, do the following − from the main method, do the following − n := number of rows and m := number of columns n := number of rows and m := number of columns for i in range 0 to n – 1solve(i, 0, mat) for i in range 0 to n – 1 solve(i, 0, mat) solve(i, 0, mat) for j in range 1 to m – 1solve(0, j, mat) for j in range 1 to m – 1 solve(0, j, mat) solve(0, j, mat) return mat return mat Let us see the following implementation to get a better understanding − Live Demo #include <bits/stdc++.h> using namespace std; void print_vector(vector<vector<auto> > v){ cout << "["; for(int i = 0; i<v.size(); i++){ cout << "["; for(int j = 0; j <v[i].size(); j++){ cout << v[i][j] << ", "; } cout << "],"; } cout << "]"<<endl; } class Solution { public: void solve(int si, int sj, vector < vector <int> > &mat){ int n = mat.size(); int m = mat[0].size(); vector <int> temp; int i = si; int j = sj; int idx = 0; while(i < n && j < m){ temp.push_back(mat[i][j]); i++; j++; } sort(temp.begin(), temp.end()); idx = 0; i = si; j = sj; while(i < n && j < m){ mat[i][j] = temp[idx]; i++; j++; idx++; } } vector<vector<int>> diagonalSort(vector<vector<int>>& mat) { int n = mat.size(); int m = mat[0].size(); for(int i = 0; i <n; i++){ solve(i, 0, mat); } for(int j = 1; j < m; j++){ solve(0, j, mat); } return mat; } }; main(){ vector<vector<int>> v = {{3,3,1,1},{2,2,1,2},{1,1,1,2}}; Solution ob; print_vector(ob.diagonalSort(v)); } [[3,3,1,1],[2,2,1,2],[1,1,1,2]] [[1,1,1,1],[1,2,2,2],[1,2,3,3]]
[ { "code": null, "e": 1206, "s": 1062, "text": "Suppose we have N x M matrix, we have to sort this diagonally in increasing order from top-left to the bottom right. So if the matrix is like −" }, { "code": null, "e": 1234, "s": 1206, "text": "The output matrix will be −" }, { "code": null, "e": 1278, "s": 1234, "text": "To solve this, we will follow these steps −" }, { "code": null, "e": 1347, "s": 1278, "text": "Define a method called solve(), this will take si, sj and matrix mat" }, { "code": null, "e": 1416, "s": 1347, "text": "Define a method called solve(), this will take si, sj and matrix mat" }, { "code": null, "e": 1463, "s": 1416, "text": "n := number of rows and m := number of columns" }, { "code": null, "e": 1510, "s": 1463, "text": "n := number of rows and m := number of columns" }, { "code": null, "e": 1536, "s": 1510, "text": "make an array called temp" }, { "code": null, "e": 1562, "s": 1536, "text": "make an array called temp" }, { "code": null, "e": 1597, "s": 1562, "text": "i:= si and j := sj, and index := 0" }, { "code": null, "e": 1632, "s": 1597, "text": "i:= si and j := sj, and index := 0" }, { "code": null, "e": 1706, "s": 1632, "text": "while i < n and j < minsert m[i, j] into temp, then increase i and j by 1" }, { "code": null, "e": 1728, "s": 1706, "text": "while i < n and j < m" }, { "code": null, "e": 1781, "s": 1728, "text": "insert m[i, j] into temp, then increase i and j by 1" }, { "code": null, "e": 1834, "s": 1781, "text": "insert m[i, j] into temp, then increase i and j by 1" }, { "code": null, "e": 1850, "s": 1834, "text": "sort temp array" }, { "code": null, "e": 1866, "s": 1850, "text": "sort temp array" }, { "code": null, "e": 1902, "s": 1866, "text": "set index := 0, i := si and j := sj" }, { "code": null, "e": 1938, "s": 1902, "text": "set index := 0, i := si and j := sj" }, { "code": null, "e": 2012, "s": 1938, "text": "while i < n and j < mmat[i, j] := temp[index]increase i, j and index by 1" }, { "code": null, "e": 2034, "s": 2012, "text": "while i < n and j < m" }, { "code": null, "e": 2059, "s": 2034, "text": "mat[i, j] := temp[index]" }, { "code": null, "e": 2084, "s": 2059, "text": "mat[i, j] := temp[index]" }, { "code": null, "e": 2113, "s": 2084, "text": "increase i, j and index by 1" }, { "code": null, "e": 2142, "s": 2113, "text": "increase i, j and index by 1" }, { "code": null, "e": 2183, "s": 2142, "text": "from the main method, do the following −" }, { "code": null, "e": 2224, "s": 2183, "text": "from the main method, do the following −" }, { "code": null, "e": 2271, "s": 2224, "text": "n := number of rows and m := number of columns" }, { "code": null, "e": 2318, "s": 2271, "text": "n := number of rows and m := number of columns" }, { "code": null, "e": 2360, "s": 2318, "text": "for i in range 0 to n – 1solve(i, 0, mat)" }, { "code": null, "e": 2386, "s": 2360, "text": "for i in range 0 to n – 1" }, { "code": null, "e": 2403, "s": 2386, "text": "solve(i, 0, mat)" }, { "code": null, "e": 2420, "s": 2403, "text": "solve(i, 0, mat)" }, { "code": null, "e": 2462, "s": 2420, "text": "for j in range 1 to m – 1solve(0, j, mat)" }, { "code": null, "e": 2488, "s": 2462, "text": "for j in range 1 to m – 1" }, { "code": null, "e": 2505, "s": 2488, "text": "solve(0, j, mat)" }, { "code": null, "e": 2522, "s": 2505, "text": "solve(0, j, mat)" }, { "code": null, "e": 2533, "s": 2522, "text": "return mat" }, { "code": null, "e": 2544, "s": 2533, "text": "return mat" }, { "code": null, "e": 2616, "s": 2544, "text": "Let us see the following implementation to get a better understanding −" }, { "code": null, "e": 2627, "s": 2616, "text": " Live Demo" }, { "code": null, "e": 3848, "s": 2627, "text": "#include <bits/stdc++.h>\nusing namespace std;\nvoid print_vector(vector<vector<auto> > v){\n cout << \"[\";\n for(int i = 0; i<v.size(); i++){\n cout << \"[\";\n for(int j = 0; j <v[i].size(); j++){\n cout << v[i][j] << \", \";\n }\n cout << \"],\";\n }\n cout << \"]\"<<endl;\n}\nclass Solution {\npublic:\n void solve(int si, int sj, vector < vector <int> > &mat){\n int n = mat.size();\n int m = mat[0].size();\n vector <int> temp;\n int i = si;\n int j = sj;\n int idx = 0;\n while(i < n && j < m){\n temp.push_back(mat[i][j]);\n i++;\n j++;\n }\n sort(temp.begin(), temp.end());\n idx = 0;\n i = si;\n j = sj;\n while(i < n && j < m){\n mat[i][j] = temp[idx];\n i++;\n j++;\n idx++;\n }\n }\n vector<vector<int>> diagonalSort(vector<vector<int>>& mat) {\n int n = mat.size();\n int m = mat[0].size();\n for(int i = 0; i <n; i++){\n solve(i, 0, mat);\n }\n for(int j = 1; j < m; j++){\n solve(0, j, mat);\n }\n return mat;\n }\n};\nmain(){\n vector<vector<int>> v = {{3,3,1,1},{2,2,1,2},{1,1,1,2}};\n Solution ob;\n print_vector(ob.diagonalSort(v));\n}" }, { "code": null, "e": 3880, "s": 3848, "text": "[[3,3,1,1],[2,2,1,2],[1,1,1,2]]" }, { "code": null, "e": 3912, "s": 3880, "text": "[[1,1,1,1],[1,2,2,2],[1,2,3,3]]" } ]
Electron - Quick Guide
Electron enables you to create desktop applications with pure JavaScript by providing a runtime with rich native (operating system) APIs. This does not mean Electron is a JavaScript binding to graphical user interface (GUI) libraries. Instead, Electron uses web pages as its GUI, so you can also see it as a minimal Chromium browser, controlled by JavaScript. So all the electron apps are technically web pages running in a browser that can leverage your OS APIs. Github developed Electron for creating the text editor Atom. They were both open sourced in 2014. Electron is used by many companies like Microsoft, Github, Slack, etc. Electron has been used to create a number of apps. Following are a few notable apps − Slack desktop Wordpress desktop app Visual Studio Code Caret Markdown Editor Nylas Email App GitKraken git client To get started with developing using the Electron, you need to have Node and npm(node package manager) installed. If you do not already have these, head over to Node setup to install node on your local system. Confirm that node and npm are installed by running the following commands in your terminal. node --version npm --version The above command will generate the following output − v6.9.1 3.10.8 Whenever we create a project using npm, we need to provide a package.json file, which has all the details about our project. npm makes it easy for us to set up this file. Let us set up our development project. Fire up your terminal/cmd, create a new folder named hello-world and open that folder using the cd command. Fire up your terminal/cmd, create a new folder named hello-world and open that folder using the cd command. Now to create the package.json file using npm, use the following command. Now to create the package.json file using npm, use the following command. npm init It will ask you for the following information − It will ask you for the following information − Just keep pressing Enter, and enter your name at the “author name” field. Create a new folder and open it using the cd command. Now run the following command to install Electron globally. $ npm install -g electron-prebuilt Once it executes, you can check if Electron is installed the right way by running the following command − $ electron --version You should get the output − v1.4.13 Now that we have set up Electron, let us move on to creating our first app using it. Electron takes a main file defined in your package.json file and executes it. This main file creates application windows which contain rendered web pages and interaction with the native GUI (graphical user interface) of your Operating System. As you start an application using Electron, a main process is created. This main process is responsible for interacting with the native GUI of the Operating System. It creates the GUI of your application. Just starting the main process does not give the users of your application any application window. These are created by the main process in the main file by using the BrowserWindow module. Each browser window then runs its own renderer process. The renderer process takes an HTML file which references the usual CSS files, JavaScript files, images, etc. and renders it in the window. The main process can access the native GUI through modules available directly in Electron. The desktop application can access all Node modules like the file system module for handling files, request to make HTTP calls, etc. The main process creates web pages by creating the BrowserWindow instances. Each BrowserWindow instance runs the web page in its own renderer process. When a BrowserWindow instance is destroyed, the corresponding renderer process is also terminated. The main process manages all web pages and their corresponding renderer processes. Each renderer process is isolated and only cares about the web page running in it. We have created a package.json file for our project. Now we will create our first desktop app using Electron. Create a new file called main.js. Enter the following code in it − 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) Create another file, this time an HTML file called index.html. Enter the following code in it. <!DOCTYPE html> <html> <head> <meta charset = "UTF-8"> <title>Hello World!</title> </head> <body> <h1>Hello World!</h1> We are using node <script>document.write(process.versions.node)</script>, Chrome <script>document.write(process.versions.chrome)</script>, and Electron <script>document.write(process.versions.electron)</script>. </body> </html> Run this app using the following command − $ electron ./main.js A new window will open up. It will look like the following − We created a main file and an HTML file. The main file uses two modules – app and BrowserWindow. The app module is used to control your application’s event lifecycle while the BrowserWindow module is used to create and control browser windows. We defined a createWindow function, where we are creating a new BrowserWindow and attaching a URL to this BrowserWindow. This is the HTML file that is rendered and shown to us when we run the app. We have used a native Electron object process in our html file. This object is extended from the Node.js process object and includes all of t=its functionalities while adding many more. The User Interface of Electron apps is built using HTML, CSS and JS. So we can leverage all the available tools for front-end web development here as well. You can use the tools such as Angular, Backbone, React, Bootstrap, and Foundation, to build the apps. You can use Bower to manage these front-end dependencies. Install bower using − $ npm install -g bower Now you can get all the available JS and CSS frameworks, libraries, plugins, etc. using bower. For example, to get the latest stable version of bootstrap, enter the following command − $ bower install bootstrap This will download bootstrap in bower_components. Now you can reference this library in your HTML. Let us create a simple page using these libraries. Let us now install jquery using the npm command − $ npm install --save jquery Further, this will be required in our view.js file. We already have a main.js setup as follows − 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) Open your index.html file and enter the following code in it − <!DOCTYPE html> <html> <head> <meta charset = "UTF-8"> <title>Hello World!</title> <link rel = "stylesheet" href = "./bower_components/bootstrap/dist/css/bootstrap.min.css" /> </head> <body> <div class = "container"> <h1>This page is using Bootstrap and jQuery!</h1> <h3 id = "click-counter"></h3> <button class = "btn btn-success" id = "countbtn">Click here</button> <script src = "./view.js" ></script> </div> </body> </html> Create view.js and enter the click counter logic in it − let $ = require('jquery') // jQuery now loaded and assigned to $ let count = 0 $('#click-counter').text(count.toString()) $('#countbtn').on('click', () => { count ++ $('#click-counter').text(count) }) Run the app using the following command − $ electron ./main.js The above command will generate the output as in the following screenshot − You can build your native app just like you build websites. If you do not want users to be restricted to an exact window size, you can leverage the responsive design and allow users to use your app in a flexible manner. File handling is a very important part of building a desktop application. Almost all desktop apps interact with files. We will create a form in our app that will take as input, a Name and an Email address. This form will be saved to a file and a list will be created that will show this as output. Set up your main process using the following code in the main.js file − 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 open the index.html file and enter the following code in it − <!DOCTYPE html> <html> <head> <meta charset = "UTF-8"> <title>File System</title> <link rel = "stylesheet" href = "./bower_components/bootstrap/dist/css/bootstrap.min.css" /> <style type = "text/css"> #contact-list { height: 150px; overflow-y: auto; } </style> </head> <body> <div class = "container"> <h1>Enter Names and Email addresses of your contacts</h1> <div class = "form-group"> <label for = "Name">Name</label> <input type = "text" name = "Name" value = "" id = "Name" placeholder = "Name" class = "form-control" required> </div> <div class = "form-group"> <label for = "Email">Email</label> <input type = "email" name = "Email" value = "" id = "Email" placeholder = "Email" class = "form-control" required> </div> <div class = "form-group"> <button class = "btn btn-primary" id = "add-to-list">Add to list!</button> </div> <div id = "contact-list"> <table class = "table-striped" id = "contact-table"> <tr> <th class = "col-xs-2">S. No.</th> <th class = "col-xs-4">Name</th> <th class = "col-xs-6">Email</th> </tr> </table> </div> <script src = "./view.js" ></script> </div> </body> </html> Now we need to handle the addition event. We will do this in our view.js file. We will create a function loadAndDisplayContacts() that will initially load contacts from the file. After creating the loadAndDisplayContacts() function, we will create a click handler on our add to list button. This will add the entry to both the file and the table. In your view.js file, enter the following code − let $ = require('jquery') let fs = require('fs') let filename = 'contacts' let sno = 0 $('#add-to-list').on('click', () => { let name = $('#Name').val() let email = $('#Email').val() fs.appendFile('contacts', name + ',' + email + '\n') addEntry(name, email) }) function addEntry(name, email) { if(name && email) { sno++ let updateString = '<tr><td>'+ sno + '</td><td>'+ name +'</td><td>' + email +'</td></tr>' $('#contact-table').append(updateString) } } function loadAndDisplayContacts() { //Check if file exists if(fs.existsSync(filename)) { let data = fs.readFileSync(filename, 'utf8').split('\n') data.forEach((contact, index) => { let [ name, email ] = contact.split(',') addEntry(name, email) }) } else { console.log("File Doesn\'t Exist. Creating new file.") fs.writeFile(filename, '', (err) => { if(err) console.log(err) }) } } loadAndDisplayContacts() Now run the application, using the following command − $ electron ./main.js Once you add some contacts to it, the application will look like − For more fs module API calls, please refer to Node File System tutorial. Now we can handle files using Electron. We will look at how to call the save and open dialog boxes(native) for files in the dialogs chapter. We used a node module, fs, in the previous chapter. We will now look at some other node modules that we can use with Electron. Using the OS module, we can get a lot of information about the system our application is running on. Following are a few methods that help while the app is being created. These methods help us customize the apps according to the OS that they are running on. os.userInfo([options]) The os.userInfo() method returns information about the currently effective user. This information can be used to personalize the application for the user even without explicitly asking for information. os.platform() The os.platform() method returns a string identifying the operating system platform. This can be used to customize the app according to the user OS. os.homedir() The os.homedir() method returns the home directory of the current user as a string. Generally, configs of all users reside in the home directory of the user. So this can be used for the same purpose for our app. os.arch() The os.arch() method returns a string identifying the operating system CPU architecture. This can be used when running on exotic architectures to adapt your application for that system. os.EOL A string constant defining the operating system-specific end-ofline marker. This should be used whenever ending lines in files on the host OS. Using the same main.js file and the following HTML file, we can print these properties on the screen − <html> <head> <title>OS Module</title> </head> <body> <script> let os = require('os') document.write('User Info: ' + JSON.stringify(os.userInfo()) + '<br>' + 'Platform: ' + os.platform() + '<br>' + 'User home directory: ' + os.homedir() + '<br>' + 'OS Architecture: ' + os.arch() + '<br>') </script> </body> </html> Now run the app using the following command − $ electron ./main.js The above command will generate the following output − User Info: {"uid":1000,"gid":1000,"username":"ayushgp","homedir":"/home/ayushgp", "shell":"/usr/bin/zsh"} Platform: linux User home directory: /home/ayushgp OS Architecture: x64 The net module is used for network related work in the app. We can create both servers and socket connections using this module. Generally, the use of wrapper module from npm is recommended over the use of the net module for networking related tasks. The following tables lists down the most useful methods from the module − net.createServer([options][, connectionListener]) Creates a new TCP server. The connectionListener argument is automatically set as a listener for the 'connection' event. net.createConnection(options[, connectionListener]) A factory method, which returns a new 'net.Socket' and connects to the supplied address and port. net.Server.listen(port[, host][, backlog][, callback]) Begin accepting connections on the specified port and host. If the host is omitted, the server will accept connections directed to any IPv4 address. net.Server.close([callback]) Finally closed when all connections are ended and the server emits a 'close' event. net.Socket.connect(port[, host][, connectListener]) Opens the connection for a given socket. If port and host are given, then the socket will be opened as a TCP socket. The net module comes with a few other methods too. To get a more comprehensive list, see this. Now, let us create an electron app that uses the net module to create connections to the server. We will need to create a new file, server.js − var net = require('net'); var server = net.createServer(function(connection) { console.log('Client Connected'); connection.on('end', function() { console.log('client disconnected'); }); connection.write('Hello World!\r\n'); connection.pipe(connection); }); server.listen(8080, function() { console.log('Server running on http://localhost:8080'); }); Using the same main.js file, replace the HTML file with the following − <html> <head> <title>net Module</title> </head> <body> <script> var net = require('net'); var client = net.connect({port: 8080}, function() { console.log('Connection established!'); }); client.on('data', function(data) { document.write(data.toString()); client.end(); }); client.on('end', function() { console.log('Disconnected :('); }); </script> </body> </html> Run the server using the following command − $ node server.js Run the application using the following command − $ electron ./main.js The above command will generate the following output − Observe that we connect to the server automatically and automatically get disconnected too. We also have a few other node modules that we can be used directly on the front-end using Electron. The usage of these modules depends on the scenario you use them in. Electron provides us with 2 IPC (Inter Process Communication) modules called ipcMain and ipcRenderer. The ipcMain module is used to communicate asynchronously from the main process to renderer processes. When used in the main process, the module handles asynchronous and synchronous messages sent from a renderer process (web page). The messages sent from a renderer will be emitted to this module. The ipcRenderer module is used to communicate asynchronously from a renderer process to the main process. It provides a few methods so you can send synchronous and asynchronous messages from the renderer process (web page) to the main process. You can also receive replies from the main process. We will create a main process and a renderer process that will send each other messages using the above modules. Create a new file called main_process.js with the following contents − const {app, BrowserWindow} = require('electron') const url = require('url') const path = require('path') const {ipcMain} = require('electron') 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 })) } // Event handler for asynchronous incoming messages ipcMain.on('asynchronous-message', (event, arg) => { console.log(arg) // Event emitter for sending asynchronous messages event.sender.send('asynchronous-reply', 'async pong') }) // Event handler for synchronous incoming messages ipcMain.on('synchronous-message', (event, arg) => { console.log(arg) // Synchronous event emmision event.returnValue = 'sync pong' }) app.on('ready', createWindow) Now create a new index.html file and add the following code in it. <!DOCTYPE html> <html> <head> <meta charset = "UTF-8"> <title>Hello World!</title> </head> <body> <script> const {ipcRenderer} = require('electron') // Synchronous message emmiter and handler console.log(ipcRenderer.sendSync('synchronous-message', 'sync ping')) // Async message handler ipcRenderer.on('asynchronous-reply', (event, arg) => { console.log(arg) }) // Async message sender ipcRenderer.send('asynchronous-message', 'async ping') </script> </body> </html> Run the app using the following command − $ electron ./main_process.js The above command will generate the following output − // On your app console Sync Pong Async Pong // On your terminal where you ran the app Sync Ping Async Ping It is recommended not to perform computation of heavy/ blocking tasks on the renderer process. Always use IPC to delegate these tasks to the main process. This helps in maintaining the pace of your application. It is very important for any app to be a user-friendly one. As a result you should not create dialog boxes using alert() calls. Electron provides a pretty good interface to accomplish the task of creating dialog boxes. Let us have a look at it. Electron provides a dialog module that we can use for displaying native system dialogs for opening and saving files, alerting, etc. Let us directly jump into an example and create an app to display simple textfiles. Create a new main.js file and enter the following code in it − const {app, BrowserWindow} = require('electron') const url = require('url') const path = require('path') const {ipcMain} = require('electron') 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 })) } ipcMain.on('openFile', (event, path) => { const {dialog} = require('electron') const fs = require('fs') dialog.showOpenDialog(function (fileNames) { // fileNames is an array that contains all the selected if(fileNames === undefined) { console.log("No file selected"); } else { readFile(fileNames[0]); } }); function readFile(filepath) { fs.readFile(filepath, 'utf-8', (err, data) => { if(err){ alert("An error ocurred reading the file :" + err.message) return } // handle the file content event.sender.send('fileData', data) }) } }) app.on('ready', createWindow) This code will pop open the open dialog box whenever our main process recieves a 'openFile' message from a renderer process. This message will redirect the file content back to the renderer process. Now, we will have to print the content. Now, create a new index.html file with the following content − <!DOCTYPE html> <html> <head> <meta charset = "UTF-8"> <title>File read using system dialogs</title> </head> <body> <script type = "text/javascript"> const {ipcRenderer} = require('electron') ipcRenderer.send('openFile', () => { console.log("Event sent."); }) ipcRenderer.on('fileData', (event, data) => { document.write(data) }) </script> </body> </html> Now whenever we run our app, a native open dialog box will pop up as shown in the following screenshot − Once we select a file to display, its contents will be displayed on the app window − This was just one of the four dialogs that Electron provides. They all have similar usage though. Once you learn how to do it using showOpenDialog, then you can use any of the other dialogs. The dialogs having the same functionality are − showSaveDialog([browserWindow, ]options[, callback]) showMessageDialog([browserWindow, ]options[, callback]) showErrorDialog(title, content) The desktop apps come with two types of menus – the application menu(on the top bar) and a context menu(right-click menu). We will learn how to create both of these in this chapter. We will be using two modules – the Menu and the MenuItem modules. Note that the Menu and the MenuItem modules are only available in the main process. For using these modules in the renderer process, you need the remote module. We will come across this when we create a context menu. Now, let us create a new main.js file for the main process − const {app, BrowserWindow, Menu, MenuItem} = 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 })) } const template = [ { label: 'Edit', submenu: [ { role: 'undo' }, { role: 'redo' }, { type: 'separator' }, { role: 'cut' }, { role: 'copy' }, { role: 'paste' } ] }, { label: 'View', submenu: [ { role: 'reload' }, { role: 'toggledevtools' }, { type: 'separator' }, { role: 'resetzoom' }, { role: 'zoomin' }, { role: 'zoomout' }, { type: 'separator' }, { role: 'togglefullscreen' } ] }, { role: 'window', submenu: [ { role: 'minimize' }, { role: 'close' } ] }, { role: 'help', submenu: [ { label: 'Learn More' } ] } ] const menu = Menu.buildFromTemplate(template) Menu.setApplicationMenu(menu) app.on('ready', createWindow) We are building a menu from a template here. This means that we provide the menu as a JSON to the function and it will take care of the rest. Now we have to set this menu as the Application menu. Now create an empty HTML file called index.html and run this application using − $ electron ./main.js On the normal position of application menus, you will see a menu based on the above template. We created this menu from the main process. Let us now create a context menu for our app. We will do this in our HTML file − <!DOCTYPE html> <html> <head> <meta charset = "UTF-8"> <title>Menus</title> </head> <body> <script type = "text/javascript"> const {remote} = require('electron') const {Menu, MenuItem} = remote const menu = new Menu() // Build menu one item at a time, unlike menu.append(new MenuItem ({ label: 'MenuItem1', click() { console.log('item 1 clicked') } })) menu.append(new MenuItem({type: 'separator'})) menu.append(new MenuItem({label: 'MenuItem2', type: 'checkbox', checked: true})) menu.append(new MenuItem ({ label: 'MenuItem3', click() { console.log('item 3 clicked') } })) // Prevent default action of right click in chromium. Replace with our menu. window.addEventListener('contextmenu', (e) => { e.preventDefault() menu.popup(remote.getCurrentWindow()) }, false) </script> </body> </html> We imported the Menu and MenuItem modules using the remote module; then, we created a menu and appended our menuitems to it one by one. Further, we prevented the default action of right-click in chromium and replaced it with our menu. The creation of menus in Electron is a very simple task. Now you can attach your event handlers to these items and handle the events according to your needs. System tray is a menu outside of your application window. On MacOS and Ubuntu, it is located on the top right corner of your screen. On Windows it is on the bottom right corner. We can create menus for our application in system trays using Electron. Create a new main.js file and add the following code to it. Have a png file ready to use for the system tray icon. 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) After having set up a basic browser window, we will create a new index.html file with the following content − <!DOCTYPE html> <html> <head> <meta charset = "UTF-8"> <title>Menus</title> </head> <body> <script type = "text/javascript"> const {remote} = require('electron') const {Tray, Menu} = remote const path = require('path') let trayIcon = new Tray(path.join('','/home/ayushgp/Desktop/images.png')) const trayMenuTemplate = [ { label: 'Empty Application', enabled: false }, { label: 'Settings', click: function () { console.log("Clicked on settings") } }, { label: 'Help', click: function () { console.log("Clicked on Help") } } ] let trayMenu = Menu.buildFromTemplate(trayMenuTemplate) trayIcon.setContextMenu(trayMenu) </script> </body> </html> We created the tray using the Tray submodule. We then created a menu using a template and further attached the menu to our tray object. Run the application using the following command − $ electron ./main.js When you run the above command, check your system tray for the icon you used. I used a smiley face for my application. The above command will generate the following output − Electron provides native notifications API only for MacOS. So we are not going to use that, instead we'll be using a npm module called node-notifier. It allows us to notify users on Windows, MacOS and Linux. Install the node-notifier module in your app folder using the following command in that folder − $ npm install --save node-notifier Let us now create an app that has a button which will generate a notification every time we click on this button. Create a new main.js file and enter the following code in it − 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) Let us now create our webpage and script that will trigger the notification. Create a new index.html file with the following code − <!DOCTYPE html> <html> <head> <meta charset = "UTF-8"> <title>Menus</title> </head> <body> <button type = "button" id = "notify" name = "button"> Click here to trigger a notification!</button> <script type = "text/javascript"> const notifier = require('node-notifier') const path = require('path'); document.getElementById('notify').onclick = (event) => { notifier.notify ({ title: 'My awesome title', message: 'Hello from electron, Mr. User!', icon: path.join('','/home/ayushgp/Desktop/images.png'), // Absolute path (doesn't work on balloons) sound: true, // Only Notification Center or Windows Toasters wait: true // Wait with callback, until user action is taken against notification }, function (err, response) { // Response is response from notification }); notifier.on('click', function (notifierObject, options) { console.log("You clicked on the notification") }); notifier.on('timeout', function (notifierObject, options) { console.log("Notification timed out!") }); } </script> </body> </html> The notify method allows us to pass it an objectwith information like the title, message, thumbnail, etc. which help us customize the notification. We can also set some event listeners on the notification. Now, run the app using the following command − $ electron ./main.js When you click on the button that we created, you will see a native notification from your operating system as shown in the following screenshot − We have also handled the events wherein, the user clicks the notification or the notification times out. These methods help us make the app more interactive if its running in the background. 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. Audio and video capturing are important characteristics if you are building apps for screen sharing, voice memos, etc. They are also useful if you require an application to capture the profile picture. We will be using the getUserMedia HTML5 API for capturing audio and video streams with Electron. Let us first set up our main process in the main.js file as follows − const {app, BrowserWindow} = require('electron') const url = require('url') const path = require('path') let win // Set the path where recordings will be saved app.setPath("userData", __dirname + "/saved_recordings") 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 be capturing this content. Create a file called index.html with the following content − <!DOCTYPE html> <html> <head> <meta charset = "UTF-8"> <title>Audio and Video</title> </head> <body> <video autoplay></video> <script type = "text/javascript"> function errorCallback(e) { console.log('Error', e) } navigator.getUserMedia({video: true, audio: true}, (localMediaStream) => { var video = document.querySelector('video') video.src = window.URL.createObjectURL(localMediaStream) video.onloadedmetadata = (e) => { // Ready to go. Do some stuff. }; }, errorCallback) </script> </body> </html> The above program will generate the following output − You now have the stream from both your webcam and your microphone. You can send this stream over the network or save this in a format you like. Have a look at the MDN Documentation for capturing images to get the images from your webcam and store them. This was done using the HTML5 getUserMedia API. You can also capture the user desktop using the desktopCapturer module that comes with Electron. Let us now see an example of how to get the screen stream. Use the same main.js file as above and edit the index.html file to have the following content − desktopCapturer.getSources({types: ['window', 'screen']}, (error, sources) => { if (error) throw error for (let i = 0; i < sources.length; ++i) { if (sources[i].name === 'Your Window Name here!') { navigator.webkitGetUserMedia({ audio: false, video: { mandatory: { chromeMediaSource: 'desktop', chromeMediaSourceId: sources[i].id, minWidth: 1280, maxWidth: 1280, minHeight: 720, maxHeight: 720 } } }, handleStream, handleError) return } } }) function handleStream (stream) { document.querySelector('video').src = URL.createObjectURL(stream) } function handleError (e) { console.log(e) } We have used the desktopCapturer module to get the information about each open window. Now you can capture the events of a specific application or of the entire screen depending on the name you pass to the above if statement. This will stream only that which is happening on that screen to your app. You can refer to this StackOverflow question to understand the usage in detail. We typically have memorized certain shortcuts for all the apps that we use on our PC daily. To make your applications feel intuitive and easily accessible to the user, you must allow the user to use shortcuts. We will use the globalShortcut module to define shortcuts in our app. Note that Accelerators are Strings that can contain multiple modifiers and key codes, combined by the + character. These accelerators are used to define keyboard shortcuts throughout our application. Let us consider an example and create a shortcut. For this, we will follow the dialog boxes example where we used the open dialog box for opening files. We will register a CommandOrControl+O shortcut to bring up the dialog box. Our main.js code will remain the same as before. So create a new main.js file and enter the following code in it − const {app, BrowserWindow} = require('electron') const url = require('url') const path = require('path') const {ipcMain} = require('electron') 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 })) } ipcMain.on('openFile', (event, path) => { const {dialog} = require('electron') const fs = require('fs') dialog.showOpenDialog(function (fileNames) { // fileNames is an array that contains all the selected if(fileNames === undefined) console.log("No file selected") else readFile(fileNames[0]) }) function readFile(filepath){ fs.readFile(filepath, 'utf-8', (err, data) => { if(err){ alert("An error ocurred reading the file :" + err.message) return } // handle the file content event.sender.send('fileData', data) }) } }) app.on('ready', createWindow) This code will pop open the open dialog box whenever our main process receives a 'openFile' message from a renderer process. Earlier this dialog box popped up whenever the app was run. Let us now limit it to open only when we press CommandOrControl+O. Now create a new index.html file with the following content − <!DOCTYPE html> <html> <head> <meta charset = "UTF-8"> <title>File read using system dialogs</title> </head> <body> <p>Press CTRL/CMD + O to open a file. </p> <script type = "text/javascript"> const {ipcRenderer, remote} = require('electron') const {globalShortcut} = remote globalShortcut.register('CommandOrControl+O', () => { ipcRenderer.send('openFile', () => { console.log("Event sent."); }) ipcRenderer.on('fileData', (event, data) => { document.write(data) }) }) </script> </body> </html> We registered a new shortcut and passed a callback that will be executed whenever we press this shortcut. We can deregister shortcuts as and when we do not require them. Now once the app is opened, we will get the message to open the file using the shortcut we just defined. These shortcuts can be made customizable by allowing the user to choose his own shortcuts for defined actions. Environment Variables control application configuration and behavior without changing code. Certain Electron behaviors are controlled by environment variables because they are initialized earlier than the command line flags and the app’s code. There are two kinds of environment variables encoded in electron – Production variables and Development variables. The following environment variables are intended for use at runtime in packaged Electron applications. GOOGLE_API_KEY Electron includes a hardcoded API key for making requests to Google’s geocoding webservice. Because this API key is included in every version of Electron, it often exceeds its usage quota. To work around this, you can supply your own Google API key in the environment. Place the following code in your main process file, before opening any browser windows that will make geocoding requests − process.env.GOOGLE_API_KEY = 'YOUR_KEY_HERE' ELECTRON_RUN_AS_NODE Starts the process as a normal Node.js process. ELECTRON_FORCE_WINDOW_MENU_BAR (Linux Only) Do not use the global menu bar on Linux. The following environment variables are intended primarily for development and debugging purposes. ELECTRON_ENABLE_LOGGING Prints Chrome’s internal logging to the console. ELECTRON_ENABLE_STACK_DUMPING Prints the stack trace to the console when Electron crashes. ELECTRON_DEFAULT_ERROR_MODE Shows the Windows’s crash dialog when Electron crashes. To set any of these environment variables as true, set it in your console. For example, if you want to enable logging, then use the following commands − > set ELECTRON_ENABLE_LOGGING=true $ export ELECTRON_ENABLE_LOGGING=true Note that you will need to set these environment variables every time you restart your computer. If you want to avoid doing so, add these lines to your .bashrc files. We have two processes that run our application – the main process and the renderer process. Since the renderer process is the one being executed in our browser window, we can use the Chrome Devtools to debug it. To open DevTools, use the shortcut "Ctrl+Shift+I" or the <F12> key. You can check out how to use devtools here. When you open the DevTools, your app will look like as shown in the following screenshot − The DevTools in an Electron browser window can only debug JavaScript that is executed in that window (i.e., the web pages). To debug JavaScript that is executed in the main process you will need to use an external debugger and launch Electron with the --debug or the --debug-brk switch. Electron will listen for the V8 debugger protocol messages on the specified port; an external debugger will need to connect on this port. The default port is 5858. Run your app using the following − $ electron --debug = 5858 ./main.js Now you will need a debugger that supports the V8 debugger protocol. You can use VSCode or node-inspector for this purpose. For example, let us follow these steps and set up VSCode for this purpose. Follow these steps to set it up − Download and install VSCode. Open your Electron project in VSCode. Add a file .vscode/launch.json with the following configuration − { "version": "1.0.0", "configurations": [ { "name": "Debug Main Process", "type": "node", "request": "launch", "cwd": "${workspaceRoot}", "runtimeExecutable": "${workspaceRoot}/node_modules/.bin/electron", "program": "${workspaceRoot}/main.js" } ] } Note − For Windows, use "${workspaceRoot}/node_modules/.bin/electron.cmd" for runtimeExecutable. Set some breakpoints in main.js, and start debugging in the Debug View. When you hit the breakpoints, the screen will look something like this − The VSCode debugger is very powerful and will help you rectify errors quickly. You also have other options like node-inspector for debugging electron apps. Packaging and distributing apps is an integral part of the development process of a desktop application. Since Electron is a cross-platform desktop application development framework, packaging and distribution of apps for all the platforms should also be a seamless experience. The electron community has created a project, electron-packager that takes care of the same for us. It allows us to package and distribute our Electron app with OS-specific bundles (.app, .exe etc) via JS or CLI. Electron Packager runs on the following host platforms − Windows (32/64 bit) OS X Linux (x86/x86_64) It generates executables/bundles for the following target platforms − Windows (also known as win32, for both 32/64 bit) OS X (also known as darwin) / Mac App Store (also known as mas) Linux (for x86, x86_64, and armv7l architectures) Install the electron packager using − # for use in npm scripts $ npm install electron-packager --save-dev # for use from cli $ npm install electron-packager -g In this section, we will see how to run the packager from the command line. The basic form of the command is − electron-packager <sourcedir> <appname> --platform=<platform> --arch=<arch> [optional flags...] This will − Find or download the correct release of Electron. Find or download the correct release of Electron. Use that version of Electron to create a app in <output-folder>/<appname>-<platform>-<arch>. Use that version of Electron to create a app in <output-folder>/<appname>-<platform>-<arch>. --platform and --arch can be omitted, in two cases. If you specify --all instead, bundles for all valid combinations of target platforms/architectures will be created. Otherwise, a single bundle for the host platform/architecture will be created. We have used the following resources to learn more about Electron. We have referred to these while creating this tutorial. The most important resource is the Electron documentation. The Documentation has extensive coverage of almost all features and quirks of the framework. They are alone enough to make your way through building an app. There are also some very good Electron examples presented in the electron-sample-apps respository. Desktop apps with web languages Rapid cross platform desktop app development using JavaScript and Electron Building a desktop application with Electron Build a Music Player with React & Electron Creating Your First Desktop App With HTML, JS and Electron Create Cross-Platform Desktop Node Apps with Electron 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": 2203, "s": 2065, "text": "Electron enables you to create desktop applications with pure JavaScript by providing a runtime with rich native (operating system) APIs." }, { "code": null, "e": 2529, "s": 2203, "text": "This does not mean Electron is a JavaScript binding to graphical user interface (GUI) libraries. Instead, Electron uses web pages as its GUI, so you can also see it as a minimal Chromium browser, controlled by JavaScript. So all the electron apps are technically web pages running in a browser that can leverage your OS APIs." }, { "code": null, "e": 2698, "s": 2529, "text": "Github developed Electron for creating the text editor Atom. They were both open sourced in 2014. Electron is used by many companies like Microsoft, Github, Slack, etc." }, { "code": null, "e": 2784, "s": 2698, "text": "Electron has been used to create a number of apps. Following are a few notable apps −" }, { "code": null, "e": 2798, "s": 2784, "text": "Slack desktop" }, { "code": null, "e": 2820, "s": 2798, "text": "Wordpress desktop app" }, { "code": null, "e": 2839, "s": 2820, "text": "Visual Studio Code" }, { "code": null, "e": 2861, "s": 2839, "text": "Caret Markdown Editor" }, { "code": null, "e": 2877, "s": 2861, "text": "Nylas Email App" }, { "code": null, "e": 2898, "s": 2877, "text": "GitKraken git client" }, { "code": null, "e": 3200, "s": 2898, "text": "To get started with developing using the Electron, you need to have Node and npm(node package manager) installed. If you do not already have these, head over to Node setup to install node on your local system. Confirm that node and npm are installed by running the following commands in your terminal." }, { "code": null, "e": 3230, "s": 3200, "text": "node --version\nnpm --version\n" }, { "code": null, "e": 3285, "s": 3230, "text": "The above command will generate the following output −" }, { "code": null, "e": 3300, "s": 3285, "text": "v6.9.1\n3.10.8\n" }, { "code": null, "e": 3510, "s": 3300, "text": "Whenever we create a project using npm, we need to provide a package.json file, which has all the details about our project. npm makes it easy for us to set up this file. Let us set up our development project." }, { "code": null, "e": 3618, "s": 3510, "text": "Fire up your terminal/cmd, create a new folder named hello-world and open that folder using the cd command." }, { "code": null, "e": 3726, "s": 3618, "text": "Fire up your terminal/cmd, create a new folder named hello-world and open that folder using the cd command." }, { "code": null, "e": 3800, "s": 3726, "text": "Now to create the package.json file using npm, use the following command." }, { "code": null, "e": 3874, "s": 3800, "text": "Now to create the package.json file using npm, use the following command." }, { "code": null, "e": 3884, "s": 3874, "text": "npm init\n" }, { "code": null, "e": 3932, "s": 3884, "text": "It will ask you for the following information −" }, { "code": null, "e": 3980, "s": 3932, "text": "It will ask you for the following information −" }, { "code": null, "e": 4054, "s": 3980, "text": "Just keep pressing Enter, and enter your name at the “author name” field." }, { "code": null, "e": 4168, "s": 4054, "text": "Create a new folder and open it using the cd command. Now run the following command to install Electron globally." }, { "code": null, "e": 4204, "s": 4168, "text": "$ npm install -g electron-prebuilt\n" }, { "code": null, "e": 4310, "s": 4204, "text": "Once it executes, you can check if Electron is installed the right way by running the following command −" }, { "code": null, "e": 4332, "s": 4310, "text": "$ electron --version\n" }, { "code": null, "e": 4360, "s": 4332, "text": "You should get the output −" }, { "code": null, "e": 4369, "s": 4360, "text": "v1.4.13\n" }, { "code": null, "e": 4454, "s": 4369, "text": "Now that we have set up Electron, let us move on to creating our first app using it." }, { "code": null, "e": 4697, "s": 4454, "text": "Electron takes a main file defined in your package.json file and executes it. This main file creates application windows which contain rendered web pages and interaction with the native GUI (graphical user interface) of your Operating System." }, { "code": null, "e": 4902, "s": 4697, "text": "As you start an application using Electron, a main process is created. This main process is responsible for interacting with the native GUI of the Operating System. It creates the GUI of your application." }, { "code": null, "e": 5286, "s": 4902, "text": "Just starting the main process does not give the users of your application any application window. These are created by the main process in the main file by using the BrowserWindow module. Each browser window then runs its own renderer process. The renderer process takes an HTML file which references the usual CSS files, JavaScript files, images, etc. and renders it in the window." }, { "code": null, "e": 5510, "s": 5286, "text": "The main process can access the native GUI through modules available directly in Electron. The desktop application can access all Node modules like the file system module for handling files, request to make HTTP calls, etc." }, { "code": null, "e": 5760, "s": 5510, "text": "The main process creates web pages by creating the BrowserWindow instances. Each BrowserWindow instance runs the web page in its own renderer process. When a BrowserWindow instance is destroyed, the corresponding renderer process is also terminated." }, { "code": null, "e": 5926, "s": 5760, "text": "The main process manages all web pages and their corresponding renderer processes. Each renderer process is isolated and only cares about the web page running in it." }, { "code": null, "e": 6036, "s": 5926, "text": "We have created a package.json file for our project. Now we will create our first desktop app using Electron." }, { "code": null, "e": 6103, "s": 6036, "text": "Create a new file called main.js. Enter the following code in it −" }, { "code": null, "e": 6480, "s": 6103, "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": 6575, "s": 6480, "text": "Create another file, this time an HTML file called index.html. Enter the following code in it." }, { "code": null, "e": 6975, "s": 6575, "text": "<!DOCTYPE html>\n<html>\n <head>\n <meta charset = \"UTF-8\">\n <title>Hello World!</title>\n </head>\n \n <body>\n <h1>Hello World!</h1>\n We are using node <script>document.write(process.versions.node)</script>,\n Chrome <script>document.write(process.versions.chrome)</script>,\n and Electron <script>document.write(process.versions.electron)</script>.\n </body>\n</html>" }, { "code": null, "e": 7018, "s": 6975, "text": "Run this app using the following command −" }, { "code": null, "e": 7040, "s": 7018, "text": "$ electron ./main.js\n" }, { "code": null, "e": 7101, "s": 7040, "text": "A new window will open up. It will look like the following −" }, { "code": null, "e": 7345, "s": 7101, "text": "We created a main file and an HTML file. The main file uses two modules – app and BrowserWindow. The app module is used to control your application’s event lifecycle while the BrowserWindow module is used to create and control browser windows." }, { "code": null, "e": 7542, "s": 7345, "text": "We defined a createWindow function, where we are creating a new BrowserWindow and attaching a URL to this BrowserWindow. This is the HTML file that is rendered and shown to us when we run the app." }, { "code": null, "e": 7728, "s": 7542, "text": "We have used a native Electron object process in our html file. This object is extended from the Node.js process object and includes all of t=its functionalities while adding many more." }, { "code": null, "e": 7986, "s": 7728, "text": "The User Interface of Electron apps is built using HTML, CSS and JS. So we can leverage all the available tools for front-end web development here as well. You can use the tools such as Angular, Backbone, React, Bootstrap, and Foundation, to build the apps." }, { "code": null, "e": 8066, "s": 7986, "text": "You can use Bower to manage these front-end dependencies. Install bower using −" }, { "code": null, "e": 8090, "s": 8066, "text": "$ npm install -g bower\n" }, { "code": null, "e": 8275, "s": 8090, "text": "Now you can get all the available JS and CSS frameworks, libraries, plugins, etc. using bower. For example, to get the latest stable version of bootstrap, enter the following command −" }, { "code": null, "e": 8302, "s": 8275, "text": "$ bower install bootstrap\n" }, { "code": null, "e": 8452, "s": 8302, "text": "This will download bootstrap in bower_components. Now you can reference this library in your HTML. Let us create a simple page using these libraries." }, { "code": null, "e": 8502, "s": 8452, "text": "Let us now install jquery using the npm command −" }, { "code": null, "e": 8531, "s": 8502, "text": "$ npm install --save jquery\n" }, { "code": null, "e": 8628, "s": 8531, "text": "Further, this will be required in our view.js file. We already have a main.js setup as follows −" }, { "code": null, "e": 8989, "s": 8628, "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": 9052, "s": 8989, "text": "Open your index.html file and enter the following code in it −" }, { "code": null, "e": 9572, "s": 9052, "text": "<!DOCTYPE html>\n<html>\n <head>\n <meta charset = \"UTF-8\">\n <title>Hello World!</title>\n <link rel = \"stylesheet\" \n href = \"./bower_components/bootstrap/dist/css/bootstrap.min.css\" />\n </head>\n \n <body>\n <div class = \"container\">\n <h1>This page is using Bootstrap and jQuery!</h1>\n <h3 id = \"click-counter\"></h3>\n <button class = \"btn btn-success\" id = \"countbtn\">Click here</button>\n <script src = \"./view.js\" ></script>\n </div>\n </body>\n</html>" }, { "code": null, "e": 9629, "s": 9572, "text": "Create view.js and enter the click counter logic in it −" }, { "code": null, "e": 9839, "s": 9629, "text": "let $ = require('jquery') // jQuery now loaded and assigned to $\nlet count = 0\n$('#click-counter').text(count.toString())\n$('#countbtn').on('click', () => {\n count ++ \n $('#click-counter').text(count)\n}) " }, { "code": null, "e": 9881, "s": 9839, "text": "Run the app using the following command −" }, { "code": null, "e": 9903, "s": 9881, "text": "$ electron ./main.js\n" }, { "code": null, "e": 9979, "s": 9903, "text": "The above command will generate the output as in the following screenshot −" }, { "code": null, "e": 10199, "s": 9979, "text": "You can build your native app just like you build websites. If you do not want users to be restricted to an exact window size, you can leverage the responsive design and allow users to use your app in a flexible manner." }, { "code": null, "e": 10318, "s": 10199, "text": "File handling is a very important part of building a desktop application. Almost all desktop apps interact with files." }, { "code": null, "e": 10497, "s": 10318, "text": "We will create a form in our app that will take as input, a Name and an Email address. This form will be saved to a file and a list will be created that will show this as output." }, { "code": null, "e": 10569, "s": 10497, "text": "Set up your main process using the following code in the main.js file −" }, { "code": null, "e": 10930, "s": 10569, "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": 10996, "s": 10930, "text": "Now open the index.html file and enter the following code in it −" }, { "code": null, "e": 12544, "s": 10996, "text": "<!DOCTYPE html>\n<html>\n <head>\n <meta charset = \"UTF-8\">\n <title>File System</title>\n <link rel = \"stylesheet\" \n href = \"./bower_components/bootstrap/dist/css/bootstrap.min.css\" />\n \n <style type = \"text/css\">\n #contact-list {\n height: 150px;\n overflow-y: auto;\n }\n </style>\n </head>\n \n <body>\n <div class = \"container\">\n <h1>Enter Names and Email addresses of your contacts</h1>\n <div class = \"form-group\">\n <label for = \"Name\">Name</label>\n <input type = \"text\" name = \"Name\" value = \"\" id = \"Name\" \n placeholder = \"Name\" class = \"form-control\" required>\n </div>\n \n <div class = \"form-group\">\n <label for = \"Email\">Email</label>\n <input type = \"email\" name = \"Email\" value = \"\" id = \"Email\" \n placeholder = \"Email\" class = \"form-control\" required>\n </div>\n \n <div class = \"form-group\">\n <button class = \"btn btn-primary\" id = \"add-to-list\">Add to list!</button>\n </div>\n \n <div id = \"contact-list\">\n <table class = \"table-striped\" id = \"contact-table\">\n <tr>\n <th class = \"col-xs-2\">S. No.</th>\n <th class = \"col-xs-4\">Name</th>\n <th class = \"col-xs-6\">Email</th>\n </tr>\n </table>\n </div>\n \n <script src = \"./view.js\" ></script>\n </div>\n </body>\n</html>" }, { "code": null, "e": 12623, "s": 12544, "text": "Now we need to handle the addition event. We will do this in our view.js file." }, { "code": null, "e": 12891, "s": 12623, "text": "We will create a function loadAndDisplayContacts() that will initially load contacts from the file. After creating the loadAndDisplayContacts() function, we will create a click handler on our add to list button. This will add the entry to both the file and the table." }, { "code": null, "e": 12940, "s": 12891, "text": "In your view.js file, enter the following code −" }, { "code": null, "e": 13957, "s": 12940, "text": "let $ = require('jquery')\nlet fs = require('fs')\nlet filename = 'contacts'\nlet sno = 0\n\n$('#add-to-list').on('click', () => {\n let name = $('#Name').val()\n let email = $('#Email').val()\n\n fs.appendFile('contacts', name + ',' + email + '\\n')\n\n addEntry(name, email)\n})\n\nfunction addEntry(name, email) {\n if(name && email) {\n sno++\n let updateString = '<tr><td>'+ sno + '</td><td>'+ name +'</td><td>' \n + email +'</td></tr>'\n $('#contact-table').append(updateString)\n }\n}\n\nfunction loadAndDisplayContacts() { \n \n //Check if file exists\n if(fs.existsSync(filename)) {\n let data = fs.readFileSync(filename, 'utf8').split('\\n')\n \n data.forEach((contact, index) => {\n let [ name, email ] = contact.split(',')\n addEntry(name, email)\n })\n \n } else {\n console.log(\"File Doesn\\'t Exist. Creating new file.\")\n fs.writeFile(filename, '', (err) => {\n if(err)\n console.log(err)\n })\n }\n}\n\nloadAndDisplayContacts()" }, { "code": null, "e": 14012, "s": 13957, "text": "Now run the application, using the following command −" }, { "code": null, "e": 14034, "s": 14012, "text": "$ electron ./main.js\n" }, { "code": null, "e": 14101, "s": 14034, "text": "Once you add some contacts to it, the application will look like −" }, { "code": null, "e": 14174, "s": 14101, "text": "For more fs module API calls, please refer to Node File System tutorial." }, { "code": null, "e": 14315, "s": 14174, "text": "Now we can handle files using Electron. We will look at how to call the save and open dialog boxes(native) for files in the dialogs chapter." }, { "code": null, "e": 14442, "s": 14315, "text": "We used a node module, fs, in the previous chapter. We will now look at some other node modules that we can use with Electron." }, { "code": null, "e": 14700, "s": 14442, "text": "Using the OS module, we can get a lot of information about the system our application is running on. Following are a few methods that help while the app is being created. These methods help us customize the apps according to the OS that they are running on." }, { "code": null, "e": 14723, "s": 14700, "text": "os.userInfo([options])" }, { "code": null, "e": 14925, "s": 14723, "text": "The os.userInfo() method returns information about the currently effective user. This information can be used to personalize the application for the user even without explicitly asking for information." }, { "code": null, "e": 14939, "s": 14925, "text": "os.platform()" }, { "code": null, "e": 15088, "s": 14939, "text": "The os.platform() method returns a string identifying the operating system platform. This can be used to customize the app according to the user OS." }, { "code": null, "e": 15101, "s": 15088, "text": "os.homedir()" }, { "code": null, "e": 15313, "s": 15101, "text": "The os.homedir() method returns the home directory of the current user as a string. Generally, configs of all users reside in the home directory of the user. So this can be used for the same purpose for our app." }, { "code": null, "e": 15323, "s": 15313, "text": "os.arch()" }, { "code": null, "e": 15509, "s": 15323, "text": "The os.arch() method returns a string identifying the operating system CPU architecture. This can be used when running on exotic architectures to adapt your application for that system." }, { "code": null, "e": 15516, "s": 15509, "text": "os.EOL" }, { "code": null, "e": 15659, "s": 15516, "text": "A string constant defining the operating system-specific end-ofline marker. This should be used whenever ending lines in files on the host OS." }, { "code": null, "e": 15762, "s": 15659, "text": "Using the same main.js file and the following HTML file, we can print these properties on the screen −" }, { "code": null, "e": 16170, "s": 15762, "text": "<html>\n <head>\n <title>OS Module</title>\n </head>\n \n <body>\n <script>\n let os = require('os')\n document.write('User Info: ' + JSON.stringify(os.userInfo()) + '<br>' + \n 'Platform: ' + os.platform() + '<br>' + \n 'User home directory: ' + os.homedir() + '<br>' + \n 'OS Architecture: ' + os.arch() + '<br>')\n </script>\n </body>\n</html>" }, { "code": null, "e": 16216, "s": 16170, "text": "Now run the app using the following command −" }, { "code": null, "e": 16238, "s": 16216, "text": "$ electron ./main.js\n" }, { "code": null, "e": 16293, "s": 16238, "text": "The above command will generate the following output −" }, { "code": null, "e": 16475, "s": 16293, "text": "User Info: {\"uid\":1000,\"gid\":1000,\"username\":\"ayushgp\",\"homedir\":\"/home/ayushgp\",\n \"shell\":\"/usr/bin/zsh\"}\nPlatform: linux\nUser home directory: /home/ayushgp\nOS Architecture: x64\n" }, { "code": null, "e": 16726, "s": 16475, "text": "The net module is used for network related work in the app. We can create both servers and socket connections using this module. Generally, the use of wrapper module from npm is recommended over the use of the net module for networking related tasks." }, { "code": null, "e": 16800, "s": 16726, "text": "The following tables lists down the most useful methods from the module −" }, { "code": null, "e": 16850, "s": 16800, "text": "net.createServer([options][, connectionListener])" }, { "code": null, "e": 16971, "s": 16850, "text": "Creates a new TCP server. The connectionListener argument is automatically set as a listener for the 'connection' event." }, { "code": null, "e": 17023, "s": 16971, "text": "net.createConnection(options[, connectionListener])" }, { "code": null, "e": 17121, "s": 17023, "text": "A factory method, which returns a new 'net.Socket' and connects to the supplied address and port." }, { "code": null, "e": 17176, "s": 17121, "text": "net.Server.listen(port[, host][, backlog][, callback])" }, { "code": null, "e": 17325, "s": 17176, "text": "Begin accepting connections on the specified port and host. If the host is omitted, the server will accept connections directed to any IPv4 address." }, { "code": null, "e": 17354, "s": 17325, "text": "net.Server.close([callback])" }, { "code": null, "e": 17438, "s": 17354, "text": "Finally closed when all connections are ended and the server emits a 'close' event." }, { "code": null, "e": 17490, "s": 17438, "text": "net.Socket.connect(port[, host][, connectListener])" }, { "code": null, "e": 17607, "s": 17490, "text": "Opens the connection for a given socket. If port and host are given, then the socket will be opened as a TCP socket." }, { "code": null, "e": 17702, "s": 17607, "text": "The net module comes with a few other methods too. To get a more comprehensive list, see this." }, { "code": null, "e": 17846, "s": 17702, "text": "Now, let us create an electron app that uses the net module to create connections to the server. We will need to create a new file, server.js −" }, { "code": null, "e": 18231, "s": 17846, "text": "var net = require('net');\nvar server = net.createServer(function(connection) { \n console.log('Client Connected');\n \n connection.on('end', function() {\n console.log('client disconnected');\n });\n \n connection.write('Hello World!\\r\\n');\n connection.pipe(connection);\n});\n\nserver.listen(8080, function() { \n console.log('Server running on http://localhost:8080');\n});" }, { "code": null, "e": 18303, "s": 18231, "text": "Using the same main.js file, replace the HTML file with the following −" }, { "code": null, "e": 18835, "s": 18303, "text": "<html>\n <head>\n <title>net Module</title>\n </head>\n \n <body>\n <script>\n var net = require('net');\n var client = net.connect({port: 8080}, function() {\n console.log('Connection established!'); \n });\n \n client.on('data', function(data) {\n document.write(data.toString());\n client.end();\n });\n \n client.on('end', function() { \n console.log('Disconnected :(');\n });\n </script>\n </body>\n</html>" }, { "code": null, "e": 18880, "s": 18835, "text": "Run the server using the following command −" }, { "code": null, "e": 18898, "s": 18880, "text": "$ node server.js\n" }, { "code": null, "e": 18948, "s": 18898, "text": "Run the application using the following command −" }, { "code": null, "e": 18970, "s": 18948, "text": "$ electron ./main.js\n" }, { "code": null, "e": 19025, "s": 18970, "text": "The above command will generate the following output −" }, { "code": null, "e": 19117, "s": 19025, "text": "Observe that we connect to the server automatically and automatically get disconnected too." }, { "code": null, "e": 19285, "s": 19117, "text": "We also have a few other node modules that we can be used directly on the front-end using Electron. The usage of these modules depends on the scenario you use them in." }, { "code": null, "e": 19387, "s": 19285, "text": "Electron provides us with 2 IPC (Inter Process Communication) modules called ipcMain and ipcRenderer." }, { "code": null, "e": 19684, "s": 19387, "text": "The ipcMain module is used to communicate asynchronously from the main process to renderer processes. When used in the main process, the module handles asynchronous and synchronous messages sent from a renderer process (web page). The messages sent from a renderer will be emitted to this module." }, { "code": null, "e": 19980, "s": 19684, "text": "The ipcRenderer module is used to communicate asynchronously from a renderer process to the main process. It provides a few methods so you can send synchronous and asynchronous messages from the renderer process (web page) to the main process. You can also receive replies from the main process." }, { "code": null, "e": 20093, "s": 19980, "text": "We will create a main process and a renderer process that will send each other messages using the above modules." }, { "code": null, "e": 20164, "s": 20093, "text": "Create a new file called main_process.js with the following contents −" }, { "code": null, "e": 21001, "s": 20164, "text": "const {app, BrowserWindow} = require('electron')\nconst url = require('url')\nconst path = require('path')\nconst {ipcMain} = require('electron')\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\n// Event handler for asynchronous incoming messages\nipcMain.on('asynchronous-message', (event, arg) => {\n console.log(arg)\n\n // Event emitter for sending asynchronous messages\n event.sender.send('asynchronous-reply', 'async pong')\n})\n\n// Event handler for synchronous incoming messages\nipcMain.on('synchronous-message', (event, arg) => {\n console.log(arg) \n\n // Synchronous event emmision\n event.returnValue = 'sync pong'\n})\n\napp.on('ready', createWindow)" }, { "code": null, "e": 21068, "s": 21001, "text": "Now create a new index.html file and add the following code in it." }, { "code": null, "e": 21663, "s": 21068, "text": "<!DOCTYPE html>\n<html>\n <head>\n <meta charset = \"UTF-8\">\n <title>Hello World!</title>\n </head>\n \n <body>\n <script>\n const {ipcRenderer} = require('electron')\n\n // Synchronous message emmiter and handler\n console.log(ipcRenderer.sendSync('synchronous-message', 'sync ping')) \n\n // Async message handler\n ipcRenderer.on('asynchronous-reply', (event, arg) => {\n console.log(arg)\n })\n\n // Async message sender\n ipcRenderer.send('asynchronous-message', 'async ping')\n </script>\n </body>\n</html>" }, { "code": null, "e": 21705, "s": 21663, "text": "Run the app using the following command −" }, { "code": null, "e": 21735, "s": 21705, "text": "$ electron ./main_process.js\n" }, { "code": null, "e": 21790, "s": 21735, "text": "The above command will generate the following output −" }, { "code": null, "e": 21899, "s": 21790, "text": "// On your app console\nSync Pong\nAsync Pong\n\n// On your terminal where you ran the app\nSync Ping\nAsync Ping\n" }, { "code": null, "e": 22110, "s": 21899, "text": "It is recommended not to perform computation of heavy/ blocking tasks on the renderer process. Always use IPC to delegate these tasks to the main process. This helps in maintaining the pace of your application." }, { "code": null, "e": 22355, "s": 22110, "text": "It is very important for any app to be a user-friendly one. As a result you should not create dialog boxes using alert() calls. Electron provides a pretty good interface to accomplish the task of creating dialog boxes. Let us have a look at it." }, { "code": null, "e": 22487, "s": 22355, "text": "Electron provides a dialog module that we can use for displaying native system dialogs for opening and saving files, alerting, etc." }, { "code": null, "e": 22571, "s": 22487, "text": "Let us directly jump into an example and create an app to display simple textfiles." }, { "code": null, "e": 22634, "s": 22571, "text": "Create a new main.js file and enter the following code in it −" }, { "code": null, "e": 23774, "s": 22634, "text": "const {app, BrowserWindow} = require('electron') \nconst url = require('url') \nconst path = require('path') \nconst {ipcMain} = require('electron') \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\nipcMain.on('openFile', (event, path) => { \n const {dialog} = require('electron') \n const fs = require('fs') \n dialog.showOpenDialog(function (fileNames) { \n \n // fileNames is an array that contains all the selected \n if(fileNames === undefined) { \n console.log(\"No file selected\"); \n \n } else { \n readFile(fileNames[0]); \n } \n });\n \n function readFile(filepath) { \n fs.readFile(filepath, 'utf-8', (err, data) => { \n \n if(err){ \n alert(\"An error ocurred reading the file :\" + err.message) \n return \n } \n \n // handle the file content \n event.sender.send('fileData', data) \n }) \n } \n}) \napp.on('ready', createWindow)" }, { "code": null, "e": 24013, "s": 23774, "text": "This code will pop open the open dialog box whenever our main process recieves a 'openFile' message from a renderer process. This message will redirect the file content back to the renderer process. Now, we will have to print the content." }, { "code": null, "e": 24076, "s": 24013, "text": "Now, create a new index.html file with the following content −" }, { "code": null, "e": 24568, "s": 24076, "text": "<!DOCTYPE html> \n<html> \n <head> \n <meta charset = \"UTF-8\"> \n <title>File read using system dialogs</title> \n </head> \n \n <body> \n <script type = \"text/javascript\"> \n const {ipcRenderer} = require('electron') \n ipcRenderer.send('openFile', () => { \n console.log(\"Event sent.\"); \n }) \n \n ipcRenderer.on('fileData', (event, data) => { \n document.write(data) \n }) \n </script> \n </body> \n</html>" }, { "code": null, "e": 24673, "s": 24568, "text": "Now whenever we run our app, a native open dialog box will pop up as shown in the following screenshot −" }, { "code": null, "e": 24758, "s": 24673, "text": "Once we select a file to display, its contents will be displayed on the app window −" }, { "code": null, "e": 24949, "s": 24758, "text": "This was just one of the four dialogs that Electron provides. They all have similar usage though. Once you learn how to do it using showOpenDialog, then you can use any of the other dialogs." }, { "code": null, "e": 24997, "s": 24949, "text": "The dialogs having the same functionality are −" }, { "code": null, "e": 25050, "s": 24997, "text": "showSaveDialog([browserWindow, ]options[, callback])" }, { "code": null, "e": 25106, "s": 25050, "text": "showMessageDialog([browserWindow, ]options[, callback])" }, { "code": null, "e": 25138, "s": 25106, "text": "showErrorDialog(title, content)" }, { "code": null, "e": 25320, "s": 25138, "text": "The desktop apps come with two types of menus – the application menu(on the top bar) and a context menu(right-click menu). We will learn how to create both of these in this chapter." }, { "code": null, "e": 25603, "s": 25320, "text": "We will be using two modules – the Menu and the MenuItem modules. Note that the Menu and the MenuItem modules are only available in the main process. For using these modules in the renderer process, you need the remote module. We will come across this when we create a context menu." }, { "code": null, "e": 25664, "s": 25603, "text": "Now, let us create a new main.js file for the main process −" }, { "code": null, "e": 27251, "s": 25664, "text": "const {app, BrowserWindow, Menu, MenuItem} = 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\nconst template = [\n {\n label: 'Edit',\n submenu: [\n {\n role: 'undo'\n },\n {\n role: 'redo'\n },\n {\n type: 'separator'\n },\n {\n role: 'cut'\n },\n {\n role: 'copy'\n },\n {\n role: 'paste'\n }\n ]\n },\n \n {\n label: 'View',\n submenu: [\n {\n role: 'reload'\n },\n {\n role: 'toggledevtools'\n },\n {\n type: 'separator'\n },\n {\n role: 'resetzoom'\n },\n {\n role: 'zoomin'\n },\n {\n role: 'zoomout'\n },\n {\n type: 'separator'\n },\n {\n role: 'togglefullscreen'\n }\n ]\n },\n \n {\n role: 'window',\n submenu: [\n {\n role: 'minimize'\n },\n {\n role: 'close'\n }\n ]\n },\n \n {\n role: 'help',\n submenu: [\n {\n label: 'Learn More'\n }\n ]\n }\n]\n\nconst menu = Menu.buildFromTemplate(template)\nMenu.setApplicationMenu(menu)\napp.on('ready', createWindow)" }, { "code": null, "e": 27447, "s": 27251, "text": "We are building a menu from a template here. This means that we provide the menu as a JSON to the function and it will take care of the rest. Now we have to set this menu as the Application menu." }, { "code": null, "e": 27528, "s": 27447, "text": "Now create an empty HTML file called index.html and run this application using −" }, { "code": null, "e": 27550, "s": 27528, "text": "$ electron ./main.js\n" }, { "code": null, "e": 27644, "s": 27550, "text": "On the normal position of application menus, you will see a menu based on the above template." }, { "code": null, "e": 27769, "s": 27644, "text": "We created this menu from the main process. Let us now create a context menu for our app. We will do this in our HTML file −" }, { "code": null, "e": 28859, "s": 27769, "text": "<!DOCTYPE html>\n<html>\n <head>\n <meta charset = \"UTF-8\">\n <title>Menus</title>\n </head>\n \n <body>\n <script type = \"text/javascript\">\n const {remote} = require('electron')\n const {Menu, MenuItem} = remote\n\n const menu = new Menu()\n\n // Build menu one item at a time, unlike\n menu.append(new MenuItem ({\n label: 'MenuItem1',\n click() { \n console.log('item 1 clicked')\n }\n }))\n \n menu.append(new MenuItem({type: 'separator'}))\n menu.append(new MenuItem({label: 'MenuItem2', type: 'checkbox', checked: true}))\n menu.append(new MenuItem ({\n label: 'MenuItem3',\n click() {\n console.log('item 3 clicked')\n }\n }))\n\n // Prevent default action of right click in chromium. Replace with our menu.\n window.addEventListener('contextmenu', (e) => {\n e.preventDefault()\n menu.popup(remote.getCurrentWindow())\n }, false)\n </script>\n </body>\n</html>" }, { "code": null, "e": 29094, "s": 28859, "text": "We imported the Menu and MenuItem modules using the remote module; then, we created a menu and appended our menuitems to it one by one. Further, we prevented the default action of right-click in chromium and replaced it with our menu." }, { "code": null, "e": 29252, "s": 29094, "text": "The creation of menus in Electron is a very simple task. Now you can attach your event handlers to these items and handle the events according to your needs." }, { "code": null, "e": 29502, "s": 29252, "text": "System tray is a menu outside of your application window. On MacOS and Ubuntu, it is located on the top right corner of your screen. On Windows it is on the bottom right corner. We can create menus for our application in system trays using Electron." }, { "code": null, "e": 29617, "s": 29502, "text": "Create a new main.js file and add the following code to it. Have a png file ready to use for the system tray icon." }, { "code": null, "e": 29978, "s": 29617, "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": 30088, "s": 29978, "text": "After having set up a basic browser window, we will create a new index.html file with the following content −" }, { "code": null, "e": 31103, "s": 30088, "text": "<!DOCTYPE html>\n<html>\n <head>\n <meta charset = \"UTF-8\">\n <title>Menus</title>\n </head>\n <body>\n <script type = \"text/javascript\">\n const {remote} = require('electron')\n const {Tray, Menu} = remote\n const path = require('path')\n\n let trayIcon = new Tray(path.join('','/home/ayushgp/Desktop/images.png'))\n\n const trayMenuTemplate = [\n {\n label: 'Empty Application',\n enabled: false\n },\n \n {\n label: 'Settings',\n click: function () {\n console.log(\"Clicked on settings\")\n }\n },\n \n {\n label: 'Help',\n click: function () {\n console.log(\"Clicked on Help\")\n }\n }\n ]\n \n let trayMenu = Menu.buildFromTemplate(trayMenuTemplate)\n trayIcon.setContextMenu(trayMenu)\n </script>\n </body>\n</html>" }, { "code": null, "e": 31239, "s": 31103, "text": "We created the tray using the Tray submodule. We then created a menu using a template and further attached the menu to our tray object." }, { "code": null, "e": 31289, "s": 31239, "text": "Run the application using the following command −" }, { "code": null, "e": 31311, "s": 31289, "text": "$ electron ./main.js\n" }, { "code": null, "e": 31485, "s": 31311, "text": "When you run the above command, check your system tray for the icon you used. I used a smiley face for my application. The above command will generate the following output −" }, { "code": null, "e": 31693, "s": 31485, "text": "Electron provides native notifications API only for MacOS. So we are not going to use that, instead we'll be using a npm module called node-notifier. It allows us to notify users on Windows, MacOS and Linux." }, { "code": null, "e": 31790, "s": 31693, "text": "Install the node-notifier module in your app folder using the following command in that folder −" }, { "code": null, "e": 31826, "s": 31790, "text": "$ npm install --save node-notifier\n" }, { "code": null, "e": 31940, "s": 31826, "text": "Let us now create an app that has a button which will generate a notification every time we click on this button." }, { "code": null, "e": 32003, "s": 31940, "text": "Create a new main.js file and enter the following code in it −" }, { "code": null, "e": 32364, "s": 32003, "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": 32496, "s": 32364, "text": "Let us now create our webpage and script that will trigger the notification. Create a new index.html file with the following code −" }, { "code": null, "e": 33860, "s": 32496, "text": "<!DOCTYPE html>\n<html>\n <head>\n <meta charset = \"UTF-8\">\n <title>Menus</title>\n </head>\n \n <body>\n <button type = \"button\" id = \"notify\" name = \"button\">\n Click here to trigger a notification!</button>\n <script type = \"text/javascript\">\n const notifier = require('node-notifier')\n const path = require('path');\n \n document.getElementById('notify').onclick = (event) => {\n notifier.notify ({\n title: 'My awesome title',\n message: 'Hello from electron, Mr. User!',\n icon: path.join('','/home/ayushgp/Desktop/images.png'), // Absolute path \n (doesn't work on balloons)\n sound: true, // Only Notification Center or Windows Toasters\n wait: true // Wait with callback, until user action is taken \n against notification\n \n }, function (err, response) {\n // Response is response from notification\n });\n\n notifier.on('click', function (notifierObject, options) {\n console.log(\"You clicked on the notification\")\n });\n\n notifier.on('timeout', function (notifierObject, options) {\n console.log(\"Notification timed out!\")\n });\n }\n </script>\n </body>\n</html>" }, { "code": null, "e": 34066, "s": 33860, "text": "The notify method allows us to pass it an objectwith information like the title, message, thumbnail, etc. which help us customize the notification. We can also set some event listeners on the notification." }, { "code": null, "e": 34113, "s": 34066, "text": "Now, run the app using the following command −" }, { "code": null, "e": 34135, "s": 34113, "text": "$ electron ./main.js\n" }, { "code": null, "e": 34282, "s": 34135, "text": "When you click on the button that we created, you will see a native notification from your operating system as shown in the following screenshot −" }, { "code": null, "e": 34473, "s": 34282, "text": "We have also handled the events wherein, the user clicks the notification or the notification times out. These methods help us make the app more interactive if its running in the background." }, { "code": null, "e": 34697, "s": 34473, "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": 34984, "s": 34697, "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": 35209, "s": 34984, "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": 35570, "s": 35209, "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": 35745, "s": 35570, "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": 36848, "s": 35745, "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": 36890, "s": 36848, "text": "Run the app using the following command −" }, { "code": null, "e": 36912, "s": 36890, "text": "$ electron ./main.js\n" }, { "code": null, "e": 36967, "s": 36912, "text": "The above command will generate the following output −" }, { "code": null, "e": 37218, "s": 36967, "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": 37422, "s": 37218, "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": 37624, "s": 37422, "text": "Audio and video capturing are important characteristics if you are building apps for screen sharing, voice memos, etc. They are also useful if you require an application to capture the profile picture." }, { "code": null, "e": 37791, "s": 37624, "text": "We will be using the getUserMedia HTML5 API for capturing audio and video streams with Electron. Let us first set up our main process in the main.js file as follows −" }, { "code": null, "e": 38256, "s": 37791, "text": "const {app, BrowserWindow} = require('electron')\nconst url = require('url')\nconst path = require('path')\n\nlet win\n\n// Set the path where recordings will be saved\napp.setPath(\"userData\", __dirname + \"/saved_recordings\")\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": 38424, "s": 38256, "text": "Now that we have set up our main process, let us create the HTML file that will be capturing this content. Create a file called index.html with the following content −" }, { "code": null, "e": 39084, "s": 38424, "text": "<!DOCTYPE html>\n<html>\n <head>\n <meta charset = \"UTF-8\">\n <title>Audio and Video</title>\n </head>\n \n <body>\n <video autoplay></video>\n <script type = \"text/javascript\">\n function errorCallback(e) {\n console.log('Error', e)\n }\n\n navigator.getUserMedia({video: true, audio: true}, (localMediaStream) => {\n var video = document.querySelector('video')\n video.src = window.URL.createObjectURL(localMediaStream)\n video.onloadedmetadata = (e) => {\n // Ready to go. Do some stuff.\n };\n }, errorCallback)\n </script>\n </body>\n</html>" }, { "code": null, "e": 39139, "s": 39084, "text": "The above program will generate the following output −" }, { "code": null, "e": 39283, "s": 39139, "text": "You now have the stream from both your webcam and your microphone. You can send this stream over the network or save this in a format you like." }, { "code": null, "e": 39596, "s": 39283, "text": "Have a look at the MDN Documentation for capturing images to get the images from your webcam and store them. This was done using the HTML5 getUserMedia API. You can also capture the user desktop using the desktopCapturer module that comes with Electron. Let us now see an example of how to get the screen stream." }, { "code": null, "e": 39692, "s": 39596, "text": "Use the same main.js file as above and edit the index.html file to have the following content −" }, { "code": null, "e": 40509, "s": 39692, "text": "desktopCapturer.getSources({types: ['window', 'screen']}, (error, sources) => {\n if (error) throw error\n for (let i = 0; i < sources.length; ++i) {\n if (sources[i].name === 'Your Window Name here!') {\n navigator.webkitGetUserMedia({\n audio: false,\n video: {\n mandatory: {\n chromeMediaSource: 'desktop',\n chromeMediaSourceId: sources[i].id,\n minWidth: 1280,\n maxWidth: 1280,\n minHeight: 720,\n maxHeight: 720\n }\n }\n }, handleStream, handleError)\n return\n }\n }\n})\n\nfunction handleStream (stream) {\n document.querySelector('video').src = URL.createObjectURL(stream)\n}\n\nfunction handleError (e) {\n console.log(e)\n}" }, { "code": null, "e": 40809, "s": 40509, "text": "We have used the desktopCapturer module to get the information about each open window. Now you can capture the events of a specific application or of the entire screen depending on the name you pass to the above if statement. This will stream only that which is happening on that screen to your app." }, { "code": null, "e": 40889, "s": 40809, "text": "You can refer to this StackOverflow question to understand the usage in detail." }, { "code": null, "e": 41099, "s": 40889, "text": "We typically have memorized certain shortcuts for all the apps that we use on our PC daily. To make your applications feel intuitive and easily accessible to the user, you must allow the user to use shortcuts." }, { "code": null, "e": 41369, "s": 41099, "text": "We will use the globalShortcut module to define shortcuts in our app. Note that Accelerators are Strings that can contain multiple modifiers and key codes, combined by the + character. These accelerators are used to define keyboard shortcuts throughout our application." }, { "code": null, "e": 41597, "s": 41369, "text": "Let us consider an example and create a shortcut. For this, we will follow the dialog boxes example where we used the open dialog box for opening files. We will register a CommandOrControl+O shortcut to bring up the dialog box." }, { "code": null, "e": 41712, "s": 41597, "text": "Our main.js code will remain the same as before. So create a new main.js file and enter the following code in it −" }, { "code": null, "e": 42780, "s": 41712, "text": "const {app, BrowserWindow} = require('electron')\nconst url = require('url')\nconst path = require('path')\nconst {ipcMain} = require('electron')\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\nipcMain.on('openFile', (event, path) => {\n const {dialog} = require('electron')\n const fs = require('fs')\n dialog.showOpenDialog(function (fileNames) {\n \n // fileNames is an array that contains all the selected\n if(fileNames === undefined)\n console.log(\"No file selected\")\n else\n readFile(fileNames[0])\n })\n\n function readFile(filepath){\n fs.readFile(filepath, 'utf-8', (err, data) => {\n if(err){\n alert(\"An error ocurred reading the file :\" + err.message)\n return\n }\n \n // handle the file content\n event.sender.send('fileData', data)\n })\n }\n})\n\napp.on('ready', createWindow)" }, { "code": null, "e": 43032, "s": 42780, "text": "This code will pop open the open dialog box whenever our main process receives a 'openFile' message from a renderer process. Earlier this dialog box popped up whenever the app was run. Let us now limit it to open only when we press CommandOrControl+O." }, { "code": null, "e": 43094, "s": 43032, "text": "Now create a new index.html file with the following content −" }, { "code": null, "e": 43763, "s": 43094, "text": "<!DOCTYPE html>\n<html>\n <head>\n <meta charset = \"UTF-8\">\n <title>File read using system dialogs</title>\n </head>\n \n <body>\n <p>Press CTRL/CMD + O to open a file. </p>\n <script type = \"text/javascript\">\n const {ipcRenderer, remote} = require('electron')\n const {globalShortcut} = remote\n globalShortcut.register('CommandOrControl+O', () => {\n ipcRenderer.send('openFile', () => {\n console.log(\"Event sent.\");\n })\n \n ipcRenderer.on('fileData', (event, data) => {\n document.write(data)\n })\n })\n </script>\n </body>\n</html>" }, { "code": null, "e": 43933, "s": 43763, "text": "We registered a new shortcut and passed a callback that will be executed whenever we press this shortcut. We can deregister shortcuts as and when we do not require them." }, { "code": null, "e": 44038, "s": 43933, "text": "Now once the app is opened, we will get the message to open the file using the shortcut we just defined." }, { "code": null, "e": 44149, "s": 44038, "text": "These shortcuts can be made customizable by allowing the user to choose his own shortcuts for defined actions." }, { "code": null, "e": 44393, "s": 44149, "text": "Environment Variables control application configuration and behavior without changing code. Certain Electron behaviors are controlled by environment variables because they are initialized earlier than the command line flags and the app’s code." }, { "code": null, "e": 44508, "s": 44393, "text": "There are two kinds of environment variables encoded in electron – Production variables and Development variables." }, { "code": null, "e": 44611, "s": 44508, "text": "The following environment variables are intended for use at runtime in packaged Electron applications." }, { "code": null, "e": 44626, "s": 44611, "text": "GOOGLE_API_KEY" }, { "code": null, "e": 44815, "s": 44626, "text": "Electron includes a hardcoded API key for making requests to Google’s geocoding webservice. Because this API key is included in every version of Electron, it often exceeds its usage quota." }, { "code": null, "e": 45018, "s": 44815, "text": "To work around this, you can supply your own Google API key in the environment. Place the following code in your main process file, before opening any browser windows that will make geocoding requests −" }, { "code": null, "e": 45064, "s": 45018, "text": "process.env.GOOGLE_API_KEY = 'YOUR_KEY_HERE'\n" }, { "code": null, "e": 45085, "s": 45064, "text": "ELECTRON_RUN_AS_NODE" }, { "code": null, "e": 45133, "s": 45085, "text": "Starts the process as a normal Node.js process." }, { "code": null, "e": 45177, "s": 45133, "text": "ELECTRON_FORCE_WINDOW_MENU_BAR (Linux Only)" }, { "code": null, "e": 45218, "s": 45177, "text": "Do not use the global menu bar on Linux." }, { "code": null, "e": 45317, "s": 45218, "text": "The following environment variables are intended primarily for development and debugging purposes." }, { "code": null, "e": 45341, "s": 45317, "text": "ELECTRON_ENABLE_LOGGING" }, { "code": null, "e": 45390, "s": 45341, "text": "Prints Chrome’s internal logging to the console." }, { "code": null, "e": 45420, "s": 45390, "text": "ELECTRON_ENABLE_STACK_DUMPING" }, { "code": null, "e": 45481, "s": 45420, "text": "Prints the stack trace to the console when Electron crashes." }, { "code": null, "e": 45509, "s": 45481, "text": "ELECTRON_DEFAULT_ERROR_MODE" }, { "code": null, "e": 45565, "s": 45509, "text": "Shows the Windows’s crash dialog when Electron crashes." }, { "code": null, "e": 45718, "s": 45565, "text": "To set any of these environment variables as true, set it in your console. For example, if you want to enable logging, then use the following commands −" }, { "code": null, "e": 45754, "s": 45718, "text": "> set ELECTRON_ENABLE_LOGGING=true\n" }, { "code": null, "e": 45793, "s": 45754, "text": "$ export ELECTRON_ENABLE_LOGGING=true\n" }, { "code": null, "e": 45960, "s": 45793, "text": "Note that you will need to set these environment variables every time you restart your computer. If you want to avoid doing so, add these lines to your .bashrc files." }, { "code": null, "e": 46052, "s": 45960, "text": "We have two processes that run our application – the main process and the renderer process." }, { "code": null, "e": 46284, "s": 46052, "text": "Since the renderer process is the one being executed in our browser window, we can use the Chrome Devtools to debug it. To open DevTools, use the shortcut \"Ctrl+Shift+I\" or the <F12> key. You can check out how to use devtools here." }, { "code": null, "e": 46375, "s": 46284, "text": "When you open the DevTools, your app will look like as shown in the following screenshot −" }, { "code": null, "e": 46662, "s": 46375, "text": "The DevTools in an Electron browser window can only debug JavaScript that is executed in that window (i.e., the web pages). To debug JavaScript that is executed in the main process you will need to use an external debugger and launch Electron with the --debug or the --debug-brk switch." }, { "code": null, "e": 46826, "s": 46662, "text": "Electron will listen for the V8 debugger protocol messages on the specified port; an external debugger will need to connect on this port. The default port is 5858." }, { "code": null, "e": 46861, "s": 46826, "text": "Run your app using the following −" }, { "code": null, "e": 46898, "s": 46861, "text": "$ electron --debug = 5858 ./main.js\n" }, { "code": null, "e": 47131, "s": 46898, "text": "Now you will need a debugger that supports the V8 debugger protocol. You can use VSCode or node-inspector for this purpose. For example, let us follow these steps and set up VSCode for this purpose. Follow these steps to set it up −" }, { "code": null, "e": 47198, "s": 47131, "text": "Download and install VSCode. Open your Electron project in VSCode." }, { "code": null, "e": 47264, "s": 47198, "text": "Add a file .vscode/launch.json with the following configuration −" }, { "code": null, "e": 47589, "s": 47264, "text": "{\n \"version\": \"1.0.0\",\n \"configurations\": [\n {\n \"name\": \"Debug Main Process\",\n \"type\": \"node\",\n \"request\": \"launch\",\n \"cwd\": \"${workspaceRoot}\",\n \"runtimeExecutable\": \"${workspaceRoot}/node_modules/.bin/electron\",\n \"program\": \"${workspaceRoot}/main.js\"\n }\n ]\n}" }, { "code": null, "e": 47686, "s": 47589, "text": "Note − For Windows, use \"${workspaceRoot}/node_modules/.bin/electron.cmd\" for runtimeExecutable." }, { "code": null, "e": 47831, "s": 47686, "text": "Set some breakpoints in main.js, and start debugging in the Debug View. When you hit the breakpoints, the screen will look something like this −" }, { "code": null, "e": 47987, "s": 47831, "text": "The VSCode debugger is very powerful and will help you rectify errors quickly. You also have other options like node-inspector for debugging electron apps." }, { "code": null, "e": 48265, "s": 47987, "text": "Packaging and distributing apps is an integral part of the development process of a desktop application. Since Electron is a cross-platform desktop application development framework, packaging and distribution of apps for all the platforms should also be a seamless experience." }, { "code": null, "e": 48478, "s": 48265, "text": "The electron community has created a project, electron-packager that takes care of the same for us. It allows us to package and distribute our Electron app with OS-specific bundles (.app, .exe etc) via JS or CLI." }, { "code": null, "e": 48535, "s": 48478, "text": "Electron Packager runs on the following host platforms −" }, { "code": null, "e": 48555, "s": 48535, "text": "Windows (32/64 bit)" }, { "code": null, "e": 48560, "s": 48555, "text": "OS X" }, { "code": null, "e": 48579, "s": 48560, "text": "Linux (x86/x86_64)" }, { "code": null, "e": 48649, "s": 48579, "text": "It generates executables/bundles for the following target platforms −" }, { "code": null, "e": 48699, "s": 48649, "text": "Windows (also known as win32, for both 32/64 bit)" }, { "code": null, "e": 48763, "s": 48699, "text": "OS X (also known as darwin) / Mac App Store (also known as mas)" }, { "code": null, "e": 48813, "s": 48763, "text": "Linux (for x86, x86_64, and armv7l architectures)" }, { "code": null, "e": 48851, "s": 48813, "text": "Install the electron packager using −" }, { "code": null, "e": 48975, "s": 48851, "text": "# for use in npm scripts\n$ npm install electron-packager --save-dev\n\n# for use from cli\n$ npm install electron-packager -g\n" }, { "code": null, "e": 49086, "s": 48975, "text": "In this section, we will see how to run the packager from the command line. The basic form of the command is −" }, { "code": null, "e": 49183, "s": 49086, "text": "electron-packager <sourcedir> <appname> --platform=<platform> --arch=<arch> [optional flags...]\n" }, { "code": null, "e": 49195, "s": 49183, "text": "This will −" }, { "code": null, "e": 49245, "s": 49195, "text": "Find or download the correct release of Electron." }, { "code": null, "e": 49295, "s": 49245, "text": "Find or download the correct release of Electron." }, { "code": null, "e": 49388, "s": 49295, "text": "Use that version of Electron to create a app in <output-folder>/<appname>-<platform>-<arch>." }, { "code": null, "e": 49481, "s": 49388, "text": "Use that version of Electron to create a app in <output-folder>/<appname>-<platform>-<arch>." }, { "code": null, "e": 49728, "s": 49481, "text": "--platform and --arch can be omitted, in two cases. If you specify --all instead, bundles for all valid combinations of target platforms/architectures will be created. Otherwise, a single bundle for the host platform/architecture will be created." }, { "code": null, "e": 49851, "s": 49728, "text": "We have used the following resources to learn more about Electron. We have referred to these while creating this tutorial." }, { "code": null, "e": 50067, "s": 49851, "text": "The most important resource is the Electron documentation. The Documentation has extensive coverage of almost all features and quirks of the framework. They are alone enough to make your way through building an app." }, { "code": null, "e": 50166, "s": 50067, "text": "There are also some very good Electron examples presented in the electron-sample-apps respository." }, { "code": null, "e": 50198, "s": 50166, "text": "Desktop apps with web languages" }, { "code": null, "e": 50273, "s": 50198, "text": "Rapid cross platform desktop app development using JavaScript and Electron" }, { "code": null, "e": 50318, "s": 50273, "text": "Building a desktop application with Electron" }, { "code": null, "e": 50361, "s": 50318, "text": "Build a Music Player with React & Electron" }, { "code": null, "e": 50420, "s": 50361, "text": "Creating Your First Desktop App With HTML, JS and Electron" }, { "code": null, "e": 50474, "s": 50420, "text": "Create Cross-Platform Desktop Node Apps with Electron" }, { "code": null, "e": 50511, "s": 50474, "text": "\n 251 Lectures \n 35.5 hours \n" }, { "code": null, "e": 50528, "s": 50511, "text": " Gowthami Swarna" }, { "code": null, "e": 50559, "s": 50528, "text": "\n 9 Lectures \n 41 mins\n" }, { "code": null, "e": 50572, "s": 50559, "text": " Ashraf Said" }, { "code": null, "e": 50603, "s": 50572, "text": "\n 8 Lectures \n 32 mins\n" }, { "code": null, "e": 50616, "s": 50603, "text": " Ashraf Said" }, { "code": null, "e": 50649, "s": 50616, "text": "\n 25 Lectures \n 1 hours \n" }, { "code": null, "e": 50662, "s": 50649, "text": " Ashraf Said" }, { "code": null, "e": 50695, "s": 50662, "text": "\n 17 Lectures \n 1 hours \n" }, { "code": null, "e": 50708, "s": 50695, "text": " Ashraf Said" }, { "code": null, "e": 50739, "s": 50708, "text": "\n 8 Lectures \n 25 mins\n" }, { "code": null, "e": 50752, "s": 50739, "text": " Ashraf Said" }, { "code": null, "e": 50759, "s": 50752, "text": " Print" }, { "code": null, "e": 50770, "s": 50759, "text": " Add Notes" } ]
How to insert an item in a list at a given position in C#?
To insert an item in an already created List, use the Insert() method. Firstly, set elements − List <int> list = new List<int>(); list.Add(989); list.Add(345); list.Add(654); list.Add(876); list.Add(234); list.Add(909); Now, let’s say you need to insert an item at 4th position. For that, use the Insert() method − // inserting element at 4th position list.Insert(3, 567); Let us see the complete example − using System; using System.Collections.Generic; namespace Demo { public class Program { public static void Main(string[] args) { List < int > list = new List < int > (); list.Add(989); list.Add(345); list.Add(654); list.Add(876); list.Add(234); list.Add(909); Console.WriteLine("Count: {0}", list.Count); Console.Write("List: "); foreach(int i in list) { Console.Write(i + " "); } // inserting element at 4th position list.Insert(3, 567); Console.Write("\nList after inserting a new element: "); foreach(int i in list) { Console.Write(i + " "); } Console.WriteLine("\nCount: {0}", list.Count); } } }
[ { "code": null, "e": 1133, "s": 1062, "text": "To insert an item in an already created List, use the Insert() method." }, { "code": null, "e": 1157, "s": 1133, "text": "Firstly, set elements −" }, { "code": null, "e": 1282, "s": 1157, "text": "List <int> list = new List<int>();\nlist.Add(989);\nlist.Add(345);\nlist.Add(654);\nlist.Add(876);\nlist.Add(234);\nlist.Add(909);" }, { "code": null, "e": 1377, "s": 1282, "text": "Now, let’s say you need to insert an item at 4th position. For that, use the Insert() method −" }, { "code": null, "e": 1435, "s": 1377, "text": "// inserting element at 4th position\nlist.Insert(3, 567);" }, { "code": null, "e": 1469, "s": 1435, "text": "Let us see the complete example −" }, { "code": null, "e": 2268, "s": 1469, "text": "using System;\nusing System.Collections.Generic;\n\nnamespace Demo {\n public class Program {\n public static void Main(string[] args) {\n List < int > list = new List < int > ();\n\n list.Add(989);\n list.Add(345);\n list.Add(654);\n list.Add(876);\n list.Add(234);\n list.Add(909);\n\n Console.WriteLine(\"Count: {0}\", list.Count);\n\n Console.Write(\"List: \");\n foreach(int i in list) {\n Console.Write(i + \" \");\n }\n // inserting element at 4th position\n list.Insert(3, 567);\n Console.Write(\"\\nList after inserting a new element: \");\n foreach(int i in list) {\n Console.Write(i + \" \");\n }\n Console.WriteLine(\"\\nCount: {0}\", list.Count);\n }\n }\n}" } ]
Python program to calculate Date, Month and Year from Seconds - GeeksforGeeks
15 Mar, 2021 Given the number of seconds, the task is to write a Python program to calculate the date, month, and year in the format MM-DD-YYYY that have been passed from 1 January 1947. Examples: Input: 0 Output: 01-01-1947 Input: 123456789 Output: 11-29-1950 Input: 9876543210 Output: 12-22-2259 Step-by-step Approach: Create a function to get the number of days in a year. Python # function to get number of# days in the year# if leap year then 366# else 365def dayInYear(year): if (year % 4) == 0: if (year % 100) == 0: if (year % 400) == 0: return 366 else: return 365 else: return 366 else: return 365 Create a function to count the years after 1947. Python3 # counting the years after 1947 def getYear(days): year = 1946 while True: year += 1 dcnt = dayInYear(year) if days >= dcnt: days -= dcnt else: break return year, days Create a function to count the number of months. Python3 # counting the number of monthsdef monthCnt(days, year): if days == 0: return 1, 0 else: month_num = 1 months = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] if dayInYear(year) == 366: months[1] = 29 for day in months: if day < days: month_num += 1 days -= day else: break return month_num, days Create a function to get a date using the number of seconds. Python3 # getting date using number of secondsdef getDate(num_sec): # converting seconds into days days_sec = 24*60*60 days = num_sec//days_sec day_started = False # if some seconds are more if days % days_sec != 0: day_started = True # getting year year, days = getYear(days) # getting month month, days = monthCnt(days, year) if day_started or num_sec == 0: days += 1 # preparing date_format date = "" if month < 10: date = date+"0"+str(month) else: date = date+str(month) date = date+"-" if days < 10: date = date+"0"+str(days) else: date = date+str(days) date = date+"-" date = date+str(year) return date Create the driver code and call the required function. Python3 # Driver Code # returns 01-01-1970date_format = getDate(0)print(date_format) # returns 11-29-1973date_format = getDate(123456789)print(date_format) # returns 12-22-2282date_format = getDate(9876543210)print(date_format) Below is the complete program based on the above stepwise approach: Python3 # function to get num of # days in the year# if leap year then 366# else 365def dayInYear(year): if (year % 4) == 0: if (year % 100) == 0: if (year % 400) == 0: return 366 else: return 365 else: return 366 else: return 365 # counting the years after 1947def getYear(days): year = 1946 while True: year += 1 dcnt = dayInYear(year) if days >= dcnt: days -= dcnt else: break return year, days # counting the number of monthsdef monthCnt(days, year): if days == 0: return 1, 0 else: month_num = 1 months = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] if dayInYear(year) == 366: months[1] = 29 for day in months: if day < days: month_num += 1 days -= day else: break return month_num, days # getting date using number of secondsdef getDate(num_sec): # converting seconds into days days_sec = 24*60*60 days = num_sec//days_sec day_started = False # if some seconds are more if days % days_sec != 0: day_started = True # getting year year, days = getYear(days) # getting month month, days = monthCnt(days, year) if day_started or num_sec == 0: days += 1 # preparing date_format date = "" if month < 10: date = date+"0"+str(month) else: date = date+str(month) date = date+"-" if days < 10: date = date+"0"+str(days) else: date = date+str(days) date = date+"-" date = date+str(year) return date # Driver Code # returns 01-01-1970date_format = getDate(0)print(date_format) # returns 11-29-1973date_format = getDate(123456789)print(date_format) # returns 12-22-2282date_format = getDate(9876543210)print(date_format) Output: 01-01-1947 11-29-1950 12-22-2259 Python datetime-program Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to Install PIP on Windows ? How to drop one or multiple columns in Pandas Dataframe How To Convert Python Dictionary To JSON? Check if element exists in list in Python Python | Pandas dataframe.groupby() Defaultdict in Python Python | Get dictionary keys as a list Python | Split string into list of characters Python | Convert a list to dictionary Python program to check whether a number is Prime or not
[ { "code": null, "e": 23901, "s": 23873, "text": "\n15 Mar, 2021" }, { "code": null, "e": 24075, "s": 23901, "text": "Given the number of seconds, the task is to write a Python program to calculate the date, month, and year in the format MM-DD-YYYY that have been passed from 1 January 1947." }, { "code": null, "e": 24085, "s": 24075, "text": "Examples:" }, { "code": null, "e": 24188, "s": 24085, "text": "Input: 0\nOutput: 01-01-1947\n\nInput: 123456789\nOutput: 11-29-1950\n\nInput: 9876543210\nOutput: 12-22-2259" }, { "code": null, "e": 24211, "s": 24188, "text": "Step-by-step Approach:" }, { "code": null, "e": 24266, "s": 24211, "text": "Create a function to get the number of days in a year." }, { "code": null, "e": 24273, "s": 24266, "text": "Python" }, { "code": "# function to get number of# days in the year# if leap year then 366# else 365def dayInYear(year): if (year % 4) == 0: if (year % 100) == 0: if (year % 400) == 0: return 366 else: return 365 else: return 366 else: return 365", "e": 24640, "s": 24273, "text": null }, { "code": null, "e": 24689, "s": 24640, "text": "Create a function to count the years after 1947." }, { "code": null, "e": 24697, "s": 24689, "text": "Python3" }, { "code": "# counting the years after 1947 def getYear(days): year = 1946 while True: year += 1 dcnt = dayInYear(year) if days >= dcnt: days -= dcnt else: break return year, days", "e": 24940, "s": 24697, "text": null }, { "code": null, "e": 24989, "s": 24940, "text": "Create a function to count the number of months." }, { "code": null, "e": 24997, "s": 24989, "text": "Python3" }, { "code": "# counting the number of monthsdef monthCnt(days, year): if days == 0: return 1, 0 else: month_num = 1 months = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] if dayInYear(year) == 366: months[1] = 29 for day in months: if day < days: month_num += 1 days -= day else: break return month_num, days", "e": 25514, "s": 24997, "text": null }, { "code": null, "e": 25575, "s": 25514, "text": "Create a function to get a date using the number of seconds." }, { "code": null, "e": 25583, "s": 25575, "text": "Python3" }, { "code": "# getting date using number of secondsdef getDate(num_sec): # converting seconds into days days_sec = 24*60*60 days = num_sec//days_sec day_started = False # if some seconds are more if days % days_sec != 0: day_started = True # getting year year, days = getYear(days) # getting month month, days = monthCnt(days, year) if day_started or num_sec == 0: days += 1 # preparing date_format date = \"\" if month < 10: date = date+\"0\"+str(month) else: date = date+str(month) date = date+\"-\" if days < 10: date = date+\"0\"+str(days) else: date = date+str(days) date = date+\"-\" date = date+str(year) return date", "e": 26341, "s": 25583, "text": null }, { "code": null, "e": 26396, "s": 26341, "text": "Create the driver code and call the required function." }, { "code": null, "e": 26404, "s": 26396, "text": "Python3" }, { "code": "# Driver Code # returns 01-01-1970date_format = getDate(0)print(date_format) # returns 11-29-1973date_format = getDate(123456789)print(date_format) # returns 12-22-2282date_format = getDate(9876543210)print(date_format)", "e": 26627, "s": 26404, "text": null }, { "code": null, "e": 26695, "s": 26627, "text": "Below is the complete program based on the above stepwise approach:" }, { "code": null, "e": 26703, "s": 26695, "text": "Python3" }, { "code": "# function to get num of # days in the year# if leap year then 366# else 365def dayInYear(year): if (year % 4) == 0: if (year % 100) == 0: if (year % 400) == 0: return 366 else: return 365 else: return 366 else: return 365 # counting the years after 1947def getYear(days): year = 1946 while True: year += 1 dcnt = dayInYear(year) if days >= dcnt: days -= dcnt else: break return year, days # counting the number of monthsdef monthCnt(days, year): if days == 0: return 1, 0 else: month_num = 1 months = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] if dayInYear(year) == 366: months[1] = 29 for day in months: if day < days: month_num += 1 days -= day else: break return month_num, days # getting date using number of secondsdef getDate(num_sec): # converting seconds into days days_sec = 24*60*60 days = num_sec//days_sec day_started = False # if some seconds are more if days % days_sec != 0: day_started = True # getting year year, days = getYear(days) # getting month month, days = monthCnt(days, year) if day_started or num_sec == 0: days += 1 # preparing date_format date = \"\" if month < 10: date = date+\"0\"+str(month) else: date = date+str(month) date = date+\"-\" if days < 10: date = date+\"0\"+str(days) else: date = date+str(days) date = date+\"-\" date = date+str(year) return date # Driver Code # returns 01-01-1970date_format = getDate(0)print(date_format) # returns 11-29-1973date_format = getDate(123456789)print(date_format) # returns 12-22-2282date_format = getDate(9876543210)print(date_format)", "e": 28702, "s": 26703, "text": null }, { "code": null, "e": 28710, "s": 28702, "text": "Output:" }, { "code": null, "e": 28743, "s": 28710, "text": "01-01-1947\n11-29-1950\n12-22-2259" }, { "code": null, "e": 28767, "s": 28743, "text": "Python datetime-program" }, { "code": null, "e": 28774, "s": 28767, "text": "Python" }, { "code": null, "e": 28790, "s": 28774, "text": "Python Programs" }, { "code": null, "e": 28888, "s": 28790, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28897, "s": 28888, "text": "Comments" }, { "code": null, "e": 28910, "s": 28897, "text": "Old Comments" }, { "code": null, "e": 28942, "s": 28910, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 28998, "s": 28942, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 29040, "s": 28998, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 29082, "s": 29040, "text": "Check if element exists in list in Python" }, { "code": null, "e": 29118, "s": 29082, "text": "Python | Pandas dataframe.groupby()" }, { "code": null, "e": 29140, "s": 29118, "text": "Defaultdict in Python" }, { "code": null, "e": 29179, "s": 29140, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 29225, "s": 29179, "text": "Python | Split string into list of characters" }, { "code": null, "e": 29263, "s": 29225, "text": "Python | Convert a list to dictionary" } ]
Python 3 - continue statement
The continue statement in Python returns the control to the beginning of the current loop. When encountered, the loop starts next iteration without executing the remaining statements in the current iteration. The continue statement can be used in both while and for loops. continue #!/usr/bin/python3 for letter in 'Python': # First Example if letter == 'h': continue print ('Current Letter :', letter) var = 10 # Second Example while var > 0: var = var -1 if var == 5: continue print ('Current variable value :', var) print ("Good bye!") When the above code is executed, it produces the following result − Current Letter : P Current Letter : y Current Letter : t Current Letter : o Current Letter : n Current variable value : 9 Current variable value : 8 Current variable value : 7 Current variable value : 6 Current variable value : 4 Current variable value : 3 Current variable value : 2 Current variable value : 1 Current variable value : 0 Good bye! 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": 2549, "s": 2340, "text": "The continue statement in Python returns the control to the beginning of the current loop. When encountered, the loop starts next iteration without executing the remaining statements in the current iteration." }, { "code": null, "e": 2613, "s": 2549, "text": "The continue statement can be used in both while and for loops." }, { "code": null, "e": 2623, "s": 2613, "text": "continue\n" }, { "code": null, "e": 2946, "s": 2623, "text": "#!/usr/bin/python3\n\nfor letter in 'Python': # First Example\n if letter == 'h':\n continue\n print ('Current Letter :', letter)\n\nvar = 10 # Second Example\nwhile var > 0: \n var = var -1\n if var == 5:\n continue\n print ('Current variable value :', var)\nprint (\"Good bye!\")" }, { "code": null, "e": 3014, "s": 2946, "text": "When the above code is executed, it produces the following result −" }, { "code": null, "e": 3363, "s": 3014, "text": "Current Letter : P\nCurrent Letter : y\nCurrent Letter : t\nCurrent Letter : o\nCurrent Letter : n\nCurrent variable value : 9\nCurrent variable value : 8\nCurrent variable value : 7\nCurrent variable value : 6\nCurrent variable value : 4\nCurrent variable value : 3\nCurrent variable value : 2\nCurrent variable value : 1\nCurrent variable value : 0\nGood bye!\n" }, { "code": null, "e": 3400, "s": 3363, "text": "\n 187 Lectures \n 17.5 hours \n" }, { "code": null, "e": 3416, "s": 3400, "text": " Malhar Lathkar" }, { "code": null, "e": 3449, "s": 3416, "text": "\n 55 Lectures \n 8 hours \n" }, { "code": null, "e": 3468, "s": 3449, "text": " Arnab Chakraborty" }, { "code": null, "e": 3503, "s": 3468, "text": "\n 136 Lectures \n 11 hours \n" }, { "code": null, "e": 3525, "s": 3503, "text": " In28Minutes Official" }, { "code": null, "e": 3559, "s": 3525, "text": "\n 75 Lectures \n 13 hours \n" }, { "code": null, "e": 3587, "s": 3559, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 3622, "s": 3587, "text": "\n 70 Lectures \n 8.5 hours \n" }, { "code": null, "e": 3636, "s": 3622, "text": " Lets Kode It" }, { "code": null, "e": 3669, "s": 3636, "text": "\n 63 Lectures \n 6 hours \n" }, { "code": null, "e": 3686, "s": 3669, "text": " Abhilash Nelson" }, { "code": null, "e": 3693, "s": 3686, "text": " Print" }, { "code": null, "e": 3704, "s": 3693, "text": " Add Notes" } ]
Python - Call function from another file - GeeksforGeeks
21 May, 2021 Given a Python file, we need to call a function in it defined in any other Python file. Example: Suppose there is a file test.py which contains the definition of the function displayText(). #test.py>def displayText(): print( “Geeks 4 Geeks!”)We need to call the function displayText() in any other Python file such that wherever we call displayText() function displays text present in it. This can be done using Python modules. Approach: Create a Python file containing the required functions.Create another Python file and import the previous Python file into it.Call the functions defined in the imported file. Create a Python file containing the required functions. Create another Python file and import the previous Python file into it. Call the functions defined in the imported file. The above approach has been used in the below examples:Example 1: A Python file test.py is created and it contains the displayText() function. Python3 # test.py> # functiondef displayText(): print( "Geeks 4 Geeks !") Now another Python file is created which calls the displayText() function defined in test.py. Python3 # importing all the# functions defined in test.pyfrom test import * # calling functionsdisplayText() Output: Geeks 4 Geeks! In the above program, all the functions defined in test.py file is imported then a functions is called.Example 2: A Python file calc.py is created containing addNumbers(), subractNumbers(), multiplyNumbers(), divideNumbers() and modulusNumbers(). Python3 # calc.py> # functionsdef addNumbers(a, b): print("Sum is ", a + b) def subtractNumbers(a, b): print("Difference is ", a-b) def multiplyNumbers(a, b): print("Product is ", a * b) def divideNumbers(a, b): print("Division is ", a / b) def modulusNumbers(a, b): print("Remainder is ", a % b) The functions defined in calc.py is called in another Python file. Python3 # importing limited functions# defined in calc.pyfrom calc import addNumbers, multiplyNumbers # calling functionsaddNumbers(2, 5)multiplyNumbers(5, 4) Output: 7 20 In the above program, all the functions defined in calc.py are not imported. To import all the functions defined in a Python file:Syntax: from file import * To import only required functions defined in a Python file:Syntax: from file import func1, func2, func3 Example 3: The below Python files test.py and calc.py are created having various function definitions. Python3 # test.py> # function defined in test.pydef displayText(): print("\nGeeks 4 Geeks !") Python3 # calc.py> # functions defined in calc.pydef addNumbers(a, b): print("Sum is ", a + b) def subtractNumbers(a, b): print("Difference is ", a-b) def multiplyNumbers(a, b): print("Product is ", a * b) def divideNumbers(a, b): print("Division is ", a / b) def modulusNumbers(a, b): print("Remainder is ", a % b) Both files are imported into an another Python file named file.py. Python3 # file.py> # importing all the functions# defined in calc.pyfrom calc import * # importing required functions# defined in test.pyfrom test import displayText # calling functions defined# in calc.pyaddNumbers(25, 6)subtractNumbers(25, 6)multiplyNumbers(25, 6)divideNumbers(25, 6)modulusNumbers(25, 6) # calling function defined# in test.pydisplayText() Output: Sum is 31 Difference is 19 Product is 150 Division is 4.166666666666667 Remainder is 1 Geeks 4 Geeks! In the above program, functions defined in test.py and calc.py are called in a different file which is file.py. sumitgumber28 python-utility Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Python Dictionary Read a file line by line in Python Enumerate() in Python How to Install PIP on Windows ? Iterate over a list in Python Different ways to create Pandas Dataframe Python String | replace() Python program to convert a list to string Reading and Writing to text files in Python sum() function in Python
[ { "code": null, "e": 23935, "s": 23907, "text": "\n21 May, 2021" }, { "code": null, "e": 24034, "s": 23935, "text": "Given a Python file, we need to call a function in it defined in any other Python file. Example: " }, { "code": null, "e": 24371, "s": 24034, "text": "Suppose there is a file test.py which contains the definition of the function displayText(). #test.py>def displayText(): print( “Geeks 4 Geeks!”)We need to call the function displayText() in any other Python file such that wherever we call displayText() function displays text present in it. This can be done using Python modules. " }, { "code": null, "e": 24382, "s": 24371, "text": "Approach: " }, { "code": null, "e": 24557, "s": 24382, "text": "Create a Python file containing the required functions.Create another Python file and import the previous Python file into it.Call the functions defined in the imported file." }, { "code": null, "e": 24613, "s": 24557, "text": "Create a Python file containing the required functions." }, { "code": null, "e": 24685, "s": 24613, "text": "Create another Python file and import the previous Python file into it." }, { "code": null, "e": 24734, "s": 24685, "text": "Call the functions defined in the imported file." }, { "code": null, "e": 24878, "s": 24734, "text": "The above approach has been used in the below examples:Example 1: A Python file test.py is created and it contains the displayText() function. " }, { "code": null, "e": 24886, "s": 24878, "text": "Python3" }, { "code": "# test.py> # functiondef displayText(): print( \"Geeks 4 Geeks !\")", "e": 24955, "s": 24886, "text": null }, { "code": null, "e": 25050, "s": 24955, "text": "Now another Python file is created which calls the displayText() function defined in test.py. " }, { "code": null, "e": 25058, "s": 25050, "text": "Python3" }, { "code": "# importing all the# functions defined in test.pyfrom test import * # calling functionsdisplayText()", "e": 25161, "s": 25058, "text": null }, { "code": null, "e": 25170, "s": 25161, "text": "Output: " }, { "code": null, "e": 25185, "s": 25170, "text": "Geeks 4 Geeks!" }, { "code": null, "e": 25433, "s": 25185, "text": "In the above program, all the functions defined in test.py file is imported then a functions is called.Example 2: A Python file calc.py is created containing addNumbers(), subractNumbers(), multiplyNumbers(), divideNumbers() and modulusNumbers(). " }, { "code": null, "e": 25441, "s": 25433, "text": "Python3" }, { "code": "# calc.py> # functionsdef addNumbers(a, b): print(\"Sum is \", a + b) def subtractNumbers(a, b): print(\"Difference is \", a-b) def multiplyNumbers(a, b): print(\"Product is \", a * b) def divideNumbers(a, b): print(\"Division is \", a / b) def modulusNumbers(a, b): print(\"Remainder is \", a % b)", "e": 25745, "s": 25441, "text": null }, { "code": null, "e": 25813, "s": 25745, "text": "The functions defined in calc.py is called in another Python file. " }, { "code": null, "e": 25821, "s": 25813, "text": "Python3" }, { "code": "# importing limited functions# defined in calc.pyfrom calc import addNumbers, multiplyNumbers # calling functionsaddNumbers(2, 5)multiplyNumbers(5, 4)", "e": 25973, "s": 25821, "text": null }, { "code": null, "e": 25982, "s": 25973, "text": "Output: " }, { "code": null, "e": 25987, "s": 25982, "text": "7\n20" }, { "code": null, "e": 26127, "s": 25987, "text": "In the above program, all the functions defined in calc.py are not imported. To import all the functions defined in a Python file:Syntax: " }, { "code": null, "e": 26146, "s": 26127, "text": "from file import *" }, { "code": null, "e": 26214, "s": 26146, "text": "To import only required functions defined in a Python file:Syntax: " }, { "code": null, "e": 26251, "s": 26214, "text": "from file import func1, func2, func3" }, { "code": null, "e": 26355, "s": 26251, "text": "Example 3: The below Python files test.py and calc.py are created having various function definitions. " }, { "code": null, "e": 26363, "s": 26355, "text": "Python3" }, { "code": "# test.py> # function defined in test.pydef displayText(): print(\"\\nGeeks 4 Geeks !\")", "e": 26452, "s": 26363, "text": null }, { "code": null, "e": 26460, "s": 26452, "text": "Python3" }, { "code": "# calc.py> # functions defined in calc.pydef addNumbers(a, b): print(\"Sum is \", a + b) def subtractNumbers(a, b): print(\"Difference is \", a-b) def multiplyNumbers(a, b): print(\"Product is \", a * b) def divideNumbers(a, b): print(\"Division is \", a / b) def modulusNumbers(a, b): print(\"Remainder is \", a % b)", "e": 26783, "s": 26460, "text": null }, { "code": null, "e": 26851, "s": 26783, "text": "Both files are imported into an another Python file named file.py. " }, { "code": null, "e": 26859, "s": 26851, "text": "Python3" }, { "code": "# file.py> # importing all the functions# defined in calc.pyfrom calc import * # importing required functions# defined in test.pyfrom test import displayText # calling functions defined# in calc.pyaddNumbers(25, 6)subtractNumbers(25, 6)multiplyNumbers(25, 6)divideNumbers(25, 6)modulusNumbers(25, 6) # calling function defined# in test.pydisplayText()", "e": 27212, "s": 26859, "text": null }, { "code": null, "e": 27221, "s": 27212, "text": "Output: " }, { "code": null, "e": 27329, "s": 27221, "text": "Sum is 31\nDifference is 19\nProduct is 150\nDivision is 4.166666666666667\nRemainder is 1\n\nGeeks 4 Geeks!" }, { "code": null, "e": 27442, "s": 27329, "text": "In the above program, functions defined in test.py and calc.py are called in a different file which is file.py. " }, { "code": null, "e": 27456, "s": 27442, "text": "sumitgumber28" }, { "code": null, "e": 27471, "s": 27456, "text": "python-utility" }, { "code": null, "e": 27478, "s": 27471, "text": "Python" }, { "code": null, "e": 27576, "s": 27478, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27585, "s": 27576, "text": "Comments" }, { "code": null, "e": 27598, "s": 27585, "text": "Old Comments" }, { "code": null, "e": 27616, "s": 27598, "text": "Python Dictionary" }, { "code": null, "e": 27651, "s": 27616, "text": "Read a file line by line in Python" }, { "code": null, "e": 27673, "s": 27651, "text": "Enumerate() in Python" }, { "code": null, "e": 27705, "s": 27673, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27735, "s": 27705, "text": "Iterate over a list in Python" }, { "code": null, "e": 27777, "s": 27735, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 27803, "s": 27777, "text": "Python String | replace()" }, { "code": null, "e": 27846, "s": 27803, "text": "Python program to convert a list to string" }, { "code": null, "e": 27890, "s": 27846, "text": "Reading and Writing to text files in Python" } ]
C# - Unsafe Codes
C# allows using pointer variables in a function of code block when it is marked by the unsafe modifier. The unsafe code or the unmanaged code is a code block that uses a pointer variable. Note − To execute the programs mentioned in this chapter at codingground, please set compilation option in Project >> Compile Options >> Compilation Command to mcs *.cs -out:main.exe -unsafe" A pointer is a variable whose value is the address of another variable i.e., the direct address of the memory location. similar to any variable or constant, you must declare a pointer before you can use it to store any variable address. The general form of a pointer declaration is − type *var-name; Following are valid pointer declarations − int *ip; /* pointer to an integer */ double *dp; /* pointer to a double */ float *fp; /* pointer to a float */ char *ch /* pointer to a character */ The following example illustrates use of pointers in C#, using the unsafe modifier − using System; namespace UnsafeCodeApplication { class Program { static unsafe void Main(string[] args) { int var = 20; int* p = &var; Console.WriteLine("Data is: {0} ", var); Console.WriteLine("Address is: {0}", (int)p); Console.ReadKey(); } } } When the above code wass compiled and executed, it produces the following result − Data is: 20 Address is: 99215364 Instead of declaring an entire method as unsafe, you can also declare a part of the code as unsafe. The example in the following section shows this. You can retrieve the data stored at the located referenced by the pointer variable, using the ToString() method. The following example demonstrates this − using System; namespace UnsafeCodeApplication { class Program { public static void Main() { unsafe { int var = 20; int* p = &var; Console.WriteLine("Data is: {0} " , var); Console.WriteLine("Data is: {0} " , p->ToString()); Console.WriteLine("Address is: {0} " , (int)p); } Console.ReadKey(); } } } When the above code was compiled and executed, it produces the following result − Data is: 20 Data is: 20 Address is: 77128984 You can pass a pointer variable to a method as parameter. The following example illustrates this − using System; namespace UnsafeCodeApplication { class TestPointer { public unsafe void swap(int* p, int *q) { int temp = *p; *p = *q; *q = temp; } public unsafe static void Main() { TestPointer p = new TestPointer(); int var1 = 10; int var2 = 20; int* x = &var1; int* y = &var2; Console.WriteLine("Before Swap: var1:{0}, var2: {1}", var1, var2); p.swap(x, y); Console.WriteLine("After Swap: var1:{0}, var2: {1}", var1, var2); Console.ReadKey(); } } } When the above code is compiled and executed, it produces the following result − Before Swap: var1: 10, var2: 20 After Swap: var1: 20, var2: 10 In C#, an array name and a pointer to a data type same as the array data, are not the same variable type. For example, int *p and int[] p, are not same type. You can increment the pointer variable p because it is not fixed in memory but an array address is fixed in memory, and you can't increment that. Therefore, if you need to access an array data using a pointer variable, as we traditionally do in C, or C++ ( please check: C Pointers), you need to fix the pointer using the fixed keyword. The following example demonstrates this − using System; namespace UnsafeCodeApplication { class TestPointer { public unsafe static void Main() { int[] list = {10, 100, 200}; fixed(int *ptr = list) /* let us have array address in pointer */ for ( int i = 0; i < 3; i++) { Console.WriteLine("Address of list[{0}]={1}",i,(int)(ptr + i)); Console.WriteLine("Value of list[{0}]={1}", i, *(ptr + i)); } Console.ReadKey(); } } } When the above code was compiled and executed, it produces the following result − Address of list[0] = 31627168 Value of list[0] = 10 Address of list[1] = 31627172 Value of list[1] = 100 Address of list[2] = 31627176 Value of list[2] = 200 For compiling unsafe code, you have to specify the /unsafe command-line switch with command-line compiler. For example, to compile a program named prog1.cs containing unsafe code, from command line, give the command − csc /unsafe prog1.cs If you are using Visual Studio IDE then you need to enable use of unsafe code in the project properties. To do this − Open project properties by double clicking the properties node in the Solution Explorer. Open project properties by double clicking the properties node in the Solution Explorer. Click on the Build tab. Click on the Build tab. Select the option "Allow unsafe code". Select the option "Allow unsafe code". 119 Lectures 23.5 hours Raja Biswas 37 Lectures 13 hours Trevoir Williams 16 Lectures 1 hours Peter Jepson 159 Lectures 21.5 hours Ebenezer Ogbu 193 Lectures 17 hours Arnold Higuit 24 Lectures 2.5 hours Eric Frick Print Add Notes Bookmark this page
[ { "code": null, "e": 2458, "s": 2270, "text": "C# allows using pointer variables in a function of code block when it is marked by the unsafe modifier. The unsafe code or the unmanaged code is a code block that uses a pointer variable." }, { "code": null, "e": 2619, "s": 2458, "text": "Note − To execute the programs mentioned in this chapter at codingground, please set compilation option in Project >> Compile Options >> Compilation Command to" }, { "code": null, "e": 2651, "s": 2619, "text": "mcs *.cs -out:main.exe -unsafe\"" }, { "code": null, "e": 2888, "s": 2651, "text": "A pointer is a variable whose value is the address of another variable i.e., the direct address of the memory location. similar to any variable or constant, you must declare a pointer before you can use it to store any variable address." }, { "code": null, "e": 2935, "s": 2888, "text": "The general form of a pointer declaration is −" }, { "code": null, "e": 2952, "s": 2935, "text": "type *var-name;\n" }, { "code": null, "e": 2995, "s": 2952, "text": "Following are valid pointer declarations −" }, { "code": null, "e": 3164, "s": 2995, "text": "int *ip; /* pointer to an integer */\ndouble *dp; /* pointer to a double */\nfloat *fp; /* pointer to a float */\nchar *ch /* pointer to a character */\n" }, { "code": null, "e": 3249, "s": 3164, "text": "The following example illustrates use of pointers in C#, using the unsafe modifier −" }, { "code": null, "e": 3571, "s": 3249, "text": "using System;\n\nnamespace UnsafeCodeApplication {\n class Program {\n static unsafe void Main(string[] args) {\n int var = 20;\n int* p = &var;\n \n Console.WriteLine(\"Data is: {0} \", var);\n Console.WriteLine(\"Address is: {0}\", (int)p);\n Console.ReadKey();\n }\n }\n}" }, { "code": null, "e": 3654, "s": 3571, "text": "When the above code wass compiled and executed, it produces the following result −" }, { "code": null, "e": 3688, "s": 3654, "text": "Data is: 20\nAddress is: 99215364\n" }, { "code": null, "e": 3837, "s": 3688, "text": "Instead of declaring an entire method as unsafe, you can also declare a part of the code as unsafe. The example in the following section shows this." }, { "code": null, "e": 3992, "s": 3837, "text": "You can retrieve the data stored at the located referenced by the pointer variable, using the ToString() method. The following example demonstrates this −" }, { "code": null, "e": 4410, "s": 3992, "text": "using System;\n\nnamespace UnsafeCodeApplication {\n class Program {\n public static void Main() {\n unsafe {\n int var = 20;\n int* p = &var;\n \n Console.WriteLine(\"Data is: {0} \" , var);\n Console.WriteLine(\"Data is: {0} \" , p->ToString());\n Console.WriteLine(\"Address is: {0} \" , (int)p);\n }\n Console.ReadKey();\n }\n }\n}" }, { "code": null, "e": 4492, "s": 4410, "text": "When the above code was compiled and executed, it produces the following result −" }, { "code": null, "e": 4538, "s": 4492, "text": "Data is: 20\nData is: 20\nAddress is: 77128984\n" }, { "code": null, "e": 4637, "s": 4538, "text": "You can pass a pointer variable to a method as parameter. The following example illustrates this −" }, { "code": null, "e": 5238, "s": 4637, "text": "using System;\n\nnamespace UnsafeCodeApplication {\n class TestPointer {\n public unsafe void swap(int* p, int *q) {\n int temp = *p;\n *p = *q;\n *q = temp;\n }\n public unsafe static void Main() {\n TestPointer p = new TestPointer();\n int var1 = 10;\n int var2 = 20;\n int* x = &var1;\n int* y = &var2;\n \n Console.WriteLine(\"Before Swap: var1:{0}, var2: {1}\", var1, var2);\n p.swap(x, y);\n\n Console.WriteLine(\"After Swap: var1:{0}, var2: {1}\", var1, var2);\n Console.ReadKey();\n }\n }\n}" }, { "code": null, "e": 5319, "s": 5238, "text": "When the above code is compiled and executed, it produces the following result −" }, { "code": null, "e": 5383, "s": 5319, "text": "Before Swap: var1: 10, var2: 20\nAfter Swap: var1: 20, var2: 10\n" }, { "code": null, "e": 5687, "s": 5383, "text": "In C#, an array name and a pointer to a data type same as the array data, are not the same variable type. For example, int *p and int[] p, are not same type. You can increment the pointer variable p because it is not fixed in memory but an array address is fixed in memory, and you can't increment that." }, { "code": null, "e": 5878, "s": 5687, "text": "Therefore, if you need to access an array data using a pointer variable, as we traditionally do in C, or C++ ( please check: C Pointers), you need to fix the pointer using the fixed keyword." }, { "code": null, "e": 5920, "s": 5878, "text": "The following example demonstrates this −" }, { "code": null, "e": 6418, "s": 5920, "text": "using System;\n\nnamespace UnsafeCodeApplication {\n class TestPointer {\n public unsafe static void Main() {\n int[] list = {10, 100, 200};\n fixed(int *ptr = list)\n \n /* let us have array address in pointer */\n for ( int i = 0; i < 3; i++) {\n Console.WriteLine(\"Address of list[{0}]={1}\",i,(int)(ptr + i));\n Console.WriteLine(\"Value of list[{0}]={1}\", i, *(ptr + i));\n }\n \n Console.ReadKey();\n }\n }\n}" }, { "code": null, "e": 6500, "s": 6418, "text": "When the above code was compiled and executed, it produces the following result −" }, { "code": null, "e": 6659, "s": 6500, "text": "Address of list[0] = 31627168\nValue of list[0] = 10\nAddress of list[1] = 31627172\nValue of list[1] = 100\nAddress of list[2] = 31627176\nValue of list[2] = 200\n" }, { "code": null, "e": 6766, "s": 6659, "text": "For compiling unsafe code, you have to specify the /unsafe command-line switch with command-line compiler." }, { "code": null, "e": 6877, "s": 6766, "text": "For example, to compile a program named prog1.cs containing unsafe code, from command line, give the command −" }, { "code": null, "e": 6898, "s": 6877, "text": "csc /unsafe prog1.cs" }, { "code": null, "e": 7003, "s": 6898, "text": "If you are using Visual Studio IDE then you need to enable use of unsafe code in the project properties." }, { "code": null, "e": 7016, "s": 7003, "text": "To do this −" }, { "code": null, "e": 7105, "s": 7016, "text": "Open project properties by double clicking the properties node in the Solution Explorer." }, { "code": null, "e": 7194, "s": 7105, "text": "Open project properties by double clicking the properties node in the Solution Explorer." }, { "code": null, "e": 7218, "s": 7194, "text": "Click on the Build tab." }, { "code": null, "e": 7242, "s": 7218, "text": "Click on the Build tab." }, { "code": null, "e": 7281, "s": 7242, "text": "Select the option \"Allow unsafe code\"." }, { "code": null, "e": 7320, "s": 7281, "text": "Select the option \"Allow unsafe code\"." }, { "code": null, "e": 7357, "s": 7320, "text": "\n 119 Lectures \n 23.5 hours \n" }, { "code": null, "e": 7370, "s": 7357, "text": " Raja Biswas" }, { "code": null, "e": 7404, "s": 7370, "text": "\n 37 Lectures \n 13 hours \n" }, { "code": null, "e": 7422, "s": 7404, "text": " Trevoir Williams" }, { "code": null, "e": 7455, "s": 7422, "text": "\n 16 Lectures \n 1 hours \n" }, { "code": null, "e": 7469, "s": 7455, "text": " Peter Jepson" }, { "code": null, "e": 7506, "s": 7469, "text": "\n 159 Lectures \n 21.5 hours \n" }, { "code": null, "e": 7521, "s": 7506, "text": " Ebenezer Ogbu" }, { "code": null, "e": 7556, "s": 7521, "text": "\n 193 Lectures \n 17 hours \n" }, { "code": null, "e": 7571, "s": 7556, "text": " Arnold Higuit" }, { "code": null, "e": 7606, "s": 7571, "text": "\n 24 Lectures \n 2.5 hours \n" }, { "code": null, "e": 7618, "s": 7606, "text": " Eric Frick" }, { "code": null, "e": 7625, "s": 7618, "text": " Print" }, { "code": null, "e": 7636, "s": 7625, "text": " Add Notes" } ]
Solidity - if...else if... statement.
The if...else if... statement is an advanced form of if...else that allows Solidity to make a correct decision out of several conditions. The syntax of an if-else-if statement is as follows − if (expression 1) { Statement(s) to be executed if expression 1 is true } else if (expression 2) { Statement(s) to be executed if expression 2 is true } else if (expression 3) { Statement(s) to be executed if expression 3 is true } else { Statement(s) to be executed if no expression is true } There is nothing special about this code. It is just a series of if statements, where each if is a part of the else clause of the previous statement. Statement(s) are executed based on the true condition, if none of the conditions is true, then the else block is executed. pragma solidity ^0.5.0; contract SolidityTest { uint storedData; // State variable constructor() public { storedData = 10; } function getResult() public view returns(string memory) { uint a = 1; uint b = 2; uint c = 3; uint result if( a > b && a > c) { // if else statement result = a; } else if( b > a && b > c ){ result = b; } else { result = c; } return integerToString(result); } function integerToString(uint _i) internal pure returns (string memory) { if (_i == 0) { return "0"; } uint j = _i; uint len; while (j != 0) { len++; j /= 10; } bytes memory bstr = new bytes(len); uint k = len - 1; while (_i != 0) { bstr[k--] = byte(uint8(48 + _i % 10)); _i /= 10; } return string(bstr);//access local variable } } Run the above program using steps provided in Solidity First Application chapter. 0: string: 3 38 Lectures 4.5 hours Abhilash Nelson 62 Lectures 8.5 hours Frahaan Hussain 31 Lectures 3.5 hours Swapnil Kole Print Add Notes Bookmark this page
[ { "code": null, "e": 2693, "s": 2555, "text": "The if...else if... statement is an advanced form of if...else that allows Solidity to make a correct decision out of several conditions." }, { "code": null, "e": 2747, "s": 2693, "text": "The syntax of an if-else-if statement is as follows −" }, { "code": null, "e": 3054, "s": 2747, "text": "if (expression 1) {\n Statement(s) to be executed if expression 1 is true\n} else if (expression 2) {\n Statement(s) to be executed if expression 2 is true\n} else if (expression 3) {\n Statement(s) to be executed if expression 3 is true\n} else {\n Statement(s) to be executed if no expression is true\n}\n" }, { "code": null, "e": 3327, "s": 3054, "text": "There is nothing special about this code. It is just a series of if statements, where each if is a part of the else clause of the previous statement. Statement(s) are executed based on the true condition, if none of the conditions is true, then the else block is executed." }, { "code": null, "e": 4312, "s": 3327, "text": "pragma solidity ^0.5.0;\n\ncontract SolidityTest {\n uint storedData; // State variable\n constructor() public {\n storedData = 10; \n }\n function getResult() public view returns(string memory) {\n uint a = 1; \n uint b = 2;\n uint c = 3;\n uint result\n \n if( a > b && a > c) { // if else statement\n result = a;\n } else if( b > a && b > c ){\n result = b;\n } else {\n result = c;\n } \n return integerToString(result); \n }\n function integerToString(uint _i) internal pure \n returns (string memory) {\n \n if (_i == 0) {\n return \"0\";\n }\n uint j = _i;\n uint len;\n \n while (j != 0) {\n len++;\n j /= 10;\n }\n bytes memory bstr = new bytes(len);\n uint k = len - 1;\n \n while (_i != 0) {\n bstr[k--] = byte(uint8(48 + _i % 10));\n _i /= 10;\n }\n return string(bstr);//access local variable\n }\n}" }, { "code": null, "e": 4394, "s": 4312, "text": "Run the above program using steps provided in Solidity First Application chapter." }, { "code": null, "e": 4408, "s": 4394, "text": "0: string: 3\n" }, { "code": null, "e": 4443, "s": 4408, "text": "\n 38 Lectures \n 4.5 hours \n" }, { "code": null, "e": 4460, "s": 4443, "text": " Abhilash Nelson" }, { "code": null, "e": 4495, "s": 4460, "text": "\n 62 Lectures \n 8.5 hours \n" }, { "code": null, "e": 4512, "s": 4495, "text": " Frahaan Hussain" }, { "code": null, "e": 4547, "s": 4512, "text": "\n 31 Lectures \n 3.5 hours \n" }, { "code": null, "e": 4561, "s": 4547, "text": " Swapnil Kole" }, { "code": null, "e": 4568, "s": 4561, "text": " Print" }, { "code": null, "e": 4579, "s": 4568, "text": " Add Notes" } ]
Building a Bayesian Logistic Regression with Python and PyMC3 | by Susan Li | Towards Data Science
In this post, we will explore using Bayesian Logistic Regression in order to predict whether or not a customer will subscribe a term deposit after the marketing campaign the bank performed. We want to be able to accomplish: How likely a customer to subscribe a term deposit? Experimenting of variables selection techniques. Explorations of the variables so serves as a good example of Exploratory Data Analysis and how that can guide the model creation and selection process. I am sure you are familiar with the dataset. We built a logistic regression model using standard machine learning methods with this dataset a while ago. And today we are going to apply Bayesian methods to fit a logistic regression model and then interpret the resulting model parameters. Let’s get started! The goal of this dataset is to create a binary classification model that predicts whether or not a customer will subscribe a term deposit after a marketing campaign the bank performed, based on many indicators. The target variable is given as y and takes on a value of 1 if the customer has subscribed and 0 otherwise. This is an imbalanced class problem because there are significantly more customers did not subscribe the term deposit than the ones did. import pandas as pdimport numpy as npimport seaborn as snsimport matplotlib.pyplot as pltimport pymc3 as pmimport arviz as azimport matplotlib.lines as mlinesimport warningswarnings.filterwarnings('ignore')from collections import OrderedDictimport theanoimport theano.tensor as ttimport itertoolsfrom IPython.core.pylabtools import figsizepd.set_option('display.max_columns', 30)from sklearn.metrics import accuracy_score, f1_score, confusion_matrixdf = pd.read_csv('banking.csv') As part of EDA, we will plot a few visualizations. Explore the target variable versus customers’ age using the stripplot function from seaborn: sns.stripplot(x="y", y="age", data=df, jitter=True)plt.show(); Explore the target variable versus euribor3m using the stripplot function from seaborn: sns.stripplot(x="y", y="euribor3m", data=df, jitter=True)plt.show(); Nothing particularly interesting here. The following is my way of making all of the variables numeric. You may have a better way of doing it. We are going to begin with the simplest possible logistic model, using just one independent variable or feature, the duration. outcome = df['y']data = df[['age', 'job', 'marital', 'education', 'default', 'housing', 'loan', 'contact', 'month', 'day_of_week', 'duration', 'campaign', 'pdays', 'previous', 'poutcome', 'euribor3m']]data['outcome'] = outcomedata.corr()['outcome'].sort_values(ascending=False) With the data in the right format, we can start building our first and simplest logistic model with PyMC3: Centering the data can help with the sampling. One of the deterministic variables θ is the output of the logistic function applied to the μ variable. Another deterministic variables bd is the boundary function. pm.math.sigmoid is the Theano function with the same name. We are going to plot the fitted sigmoid curve and the decision boundary: The above plot shows non subscription vs. subscription (y = 0, y = 1). The S-shaped (green) line is the mean value of θ. This line can be interpreted as the probability of a subscription, given that we know that the last time contact duration(the value of the duration). The boundary decision is represented as a (black) vertical line. According to the boundary decision, the values of duration to the left correspond to y = 0 (non subscription), and the values to the right to y = 1 (subscription). We summarize the inferred parameters values for easier analysis of the results and check how well the model did: az.summary(trace_simple, var_names=['α', 'β']) As you can see, the values of α and β are very narrowed defined. This is totally reasonable, given that we are fitting a binary fitted line to a perfectly aligned set of points. Let’s run a posterior predictive check to explore how well our model captures the data. We can let PyMC3 do the hard work of sampling from the posterior for us: ppc = pm.sample_ppc(trace_simple, model=model_simple, samples=500)preds = np.rint(ppc['y_1'].mean(axis=0)).astype('int')print('Accuracy of the simplest model:', accuracy_score(preds, data['outcome']))print('f1 score of the simplest model:', f1_score(preds, data['outcome'])) We plot a heat map to show the correlations between each variables. plt.figure(figsize=(15, 15))corr = data.corr() mask = np.tri(*corr.shape).T sns.heatmap(corr.abs(), mask=mask, annot=True, cmap='viridis'); poutcome & previous have a high correlation, we can simply remove one of them, I decide to remove poutcome. There are not many strong correlations with the outcome variable. The highest positive correlation is 0.41. We assume that the probability of a subscription outcome is a function of age, job, marital, education, default, housing, loan, contact, month, day of week, duration, campaign, pdays, previous and euribor3m. We need to specify a prior and a likelihood in order to draw samples from the posterior. The interpretation formula is as follows: logit = β0 + β1(age) + β2(age)2 + β3(job) + β4(marital) + β5(education) + β6(default) + β7(housing) + β8(loan) + β9(contact) + β10(month) + β11(day_of_week) + β12(duration) + β13(campaign) + β14(campaign) + β15(pdays) + β16(previous) + β17(poutcome) + β18(euribor3m) and y = 1 if outcome is yes and y = 0 otherwise. The log odds can then be converted to a probability of the output: For our problem, we are interested in finding the probability a customer will subscribe a term deposit given all the activities: With the math out of the way we can get back to the data. PyMC3 has a module glm for defining models using a patsy-style formula syntax. This seems really useful, especially for defining models in fewer lines of code. We use PyMC3 to draw samples from the posterior. The sampling algorithm used is NUTS, in which parameters are tuned automatically. We will use all these 18 variables and create the model using the formula defined above. The idea of adding a age2 is borrowed from this tutorial, and It would be interesting to compare models lately as well. We will also scale age by 10, it helps with model convergence. Above I only show part of the trace plot. This trace shows all of the samples drawn for all of the variables. On the left we can see the final approximate posterior distribution for the model parameters. On the right we get the individual sampled values at each step during the sampling. This glm defined model appears to behave in a very similar way, and finds the same parameter values as the conventionally-defined model we have created earlier. I want to be able to answer questions like: To answer this question, we will show how the probability of subscribing a term deposit changes with age for a few different education levels, and we want to study married customers. We will pass in three different linear models: one with education == 1 (illiterate), one with education == 5(basic.9y) and one with education == 8(university.degree). For all three education levels, the probability of subscribing a term deposit decreases with age until approximately at age 40, when the probability begins to increase. Every curve is blurry, this is because we are plotting 100 different curves for each level of education. Each curve is a draw from our posterior distribution. Does education of a person affects his or her subscribing to a term deposit? To do it we will use the concept of odds, and we can estimate the odds ratio of education like this: b = trace['education']plt.hist(np.exp(b), bins=20, normed=True)plt.xlabel("Odds Ratio")plt.show(); We are 95% confident that the odds ratio of education lies within the following interval. lb, ub = np.percentile(b, 2.5), np.percentile(b, 97.5)print("P(%.3f < Odds Ratio < %.3f) = 0.95" % (np.exp(lb), np.exp(ub))) We can interpret something along those lines: “With probability 0.95 the odds ratio is greater than 1.055 and less than 1.108, so the education effect takes place because a person with a higher education level has at least 1.055 higher probability to subscribe to a term deposit than a person with a lower education level, while holding all the other independent variables constant.” We can estimate odds ratio and percentage effect for all the variables. stat_df = pm.summary(trace)stat_df['odds_ratio'] = np.exp(stat_df['mean'])stat_df['percentage_effect'] = 100 * (stat_df['odds_ratio'] - 1)stat_df We can interpret percentage_effect along those lines: “ With a one unit increase in education, the odds of subscribing to a term deposit increases by 8%. Similarly, for a one unit increase in euribor3m, the odds of subscribing to a term deposit decreases by 43%, while holding all the other independent variables constant.” Its hard to show the entire forest plot, I only show part of it, but its enough for us to say that there’s a baseline probability of subscribing a term deposit. Beyond that, age has the biggest effect on subscribing, followed by contact. If you remember, we added an age2 variable which is squared age. Now its the time to ask what effect it has on our model. WAIC is a measure of model fit that can be applied to Bayesian models and that works when the parameter estimation is done using numerical techniques. Read this paper to learn more. We’ll compare three models with increasing polynomial complexity. In our case, we are interested in the WAIC score. Now loop through all the models and calculate the WAIC. PyMC3 includes two convenience functions to help compare WAIC for different models. The first of this functions is compare which computes WAIC from a set of traces and models and returns a DataFrame which is ordered from lowest to highest WAIC. model_trace_dict = dict()for nm in ['k1', 'k2', 'k3']: models_lin[nm].name = nm model_trace_dict.update({models_lin[nm]: traces_lin[nm]})dfwaic = pm.compare(model_trace_dict, ic='WAIC')dfwaic We should prefer the model(s) with lower WAIC. The second convenience function takes the output of compare and produces a summary plot. pm.compareplot(dfwaic); The empty circle represents the values of WAIC and the black error bars associated with them are the values of the standard deviation of WAIC. The value of the lowest WAIC is also indicated with a vertical dashed grey line to ease comparison with other WAIC values. The filled in black dots are the in-sample deviance of each model, which for WAIC is 2 pWAIC from the corresponding WAIC value. For all models except the top-ranked one, we also get a triangle, indicating the value of the difference of WAIC between that model and the top model, and a grey error bar indicating the standard error of the differences between the top-ranked WAIC and WAIC for each model. This confirms that the model that includes square of age is better than the model without. Unlike standard machine learning, Bayesian focused on model interpretability around a prediction. But I’am curious to know what we will get if we calculate the standard machine learning metrics. We are going to calculate the metrics using the mean value of the parameters as a “most likely” estimate. print('Accuracy of the full model: ', accuracy_score(preds, data['outcome']))print('f1 score of the full model: ', f1_score(preds, data['outcome'])) Jupyter notebook can be found on Github. Have a great week! References: docs.pymc.io docs.pymc.io The book: Bayesian Analysis with Python, Second Edition
[ { "code": null, "e": 362, "s": 172, "text": "In this post, we will explore using Bayesian Logistic Regression in order to predict whether or not a customer will subscribe a term deposit after the marketing campaign the bank performed." }, { "code": null, "e": 396, "s": 362, "text": "We want to be able to accomplish:" }, { "code": null, "e": 447, "s": 396, "text": "How likely a customer to subscribe a term deposit?" }, { "code": null, "e": 496, "s": 447, "text": "Experimenting of variables selection techniques." }, { "code": null, "e": 648, "s": 496, "text": "Explorations of the variables so serves as a good example of Exploratory Data Analysis and how that can guide the model creation and selection process." }, { "code": null, "e": 955, "s": 648, "text": "I am sure you are familiar with the dataset. We built a logistic regression model using standard machine learning methods with this dataset a while ago. And today we are going to apply Bayesian methods to fit a logistic regression model and then interpret the resulting model parameters. Let’s get started!" }, { "code": null, "e": 1274, "s": 955, "text": "The goal of this dataset is to create a binary classification model that predicts whether or not a customer will subscribe a term deposit after a marketing campaign the bank performed, based on many indicators. The target variable is given as y and takes on a value of 1 if the customer has subscribed and 0 otherwise." }, { "code": null, "e": 1411, "s": 1274, "text": "This is an imbalanced class problem because there are significantly more customers did not subscribe the term deposit than the ones did." }, { "code": null, "e": 1892, "s": 1411, "text": "import pandas as pdimport numpy as npimport seaborn as snsimport matplotlib.pyplot as pltimport pymc3 as pmimport arviz as azimport matplotlib.lines as mlinesimport warningswarnings.filterwarnings('ignore')from collections import OrderedDictimport theanoimport theano.tensor as ttimport itertoolsfrom IPython.core.pylabtools import figsizepd.set_option('display.max_columns', 30)from sklearn.metrics import accuracy_score, f1_score, confusion_matrixdf = pd.read_csv('banking.csv')" }, { "code": null, "e": 1943, "s": 1892, "text": "As part of EDA, we will plot a few visualizations." }, { "code": null, "e": 2036, "s": 1943, "text": "Explore the target variable versus customers’ age using the stripplot function from seaborn:" }, { "code": null, "e": 2099, "s": 2036, "text": "sns.stripplot(x=\"y\", y=\"age\", data=df, jitter=True)plt.show();" }, { "code": null, "e": 2187, "s": 2099, "text": "Explore the target variable versus euribor3m using the stripplot function from seaborn:" }, { "code": null, "e": 2256, "s": 2187, "text": "sns.stripplot(x=\"y\", y=\"euribor3m\", data=df, jitter=True)plt.show();" }, { "code": null, "e": 2295, "s": 2256, "text": "Nothing particularly interesting here." }, { "code": null, "e": 2398, "s": 2295, "text": "The following is my way of making all of the variables numeric. You may have a better way of doing it." }, { "code": null, "e": 2525, "s": 2398, "text": "We are going to begin with the simplest possible logistic model, using just one independent variable or feature, the duration." }, { "code": null, "e": 2803, "s": 2525, "text": "outcome = df['y']data = df[['age', 'job', 'marital', 'education', 'default', 'housing', 'loan', 'contact', 'month', 'day_of_week', 'duration', 'campaign', 'pdays', 'previous', 'poutcome', 'euribor3m']]data['outcome'] = outcomedata.corr()['outcome'].sort_values(ascending=False)" }, { "code": null, "e": 2910, "s": 2803, "text": "With the data in the right format, we can start building our first and simplest logistic model with PyMC3:" }, { "code": null, "e": 2957, "s": 2910, "text": "Centering the data can help with the sampling." }, { "code": null, "e": 3060, "s": 2957, "text": "One of the deterministic variables θ is the output of the logistic function applied to the μ variable." }, { "code": null, "e": 3121, "s": 3060, "text": "Another deterministic variables bd is the boundary function." }, { "code": null, "e": 3180, "s": 3121, "text": "pm.math.sigmoid is the Theano function with the same name." }, { "code": null, "e": 3253, "s": 3180, "text": "We are going to plot the fitted sigmoid curve and the decision boundary:" }, { "code": null, "e": 3324, "s": 3253, "text": "The above plot shows non subscription vs. subscription (y = 0, y = 1)." }, { "code": null, "e": 3524, "s": 3324, "text": "The S-shaped (green) line is the mean value of θ. This line can be interpreted as the probability of a subscription, given that we know that the last time contact duration(the value of the duration)." }, { "code": null, "e": 3753, "s": 3524, "text": "The boundary decision is represented as a (black) vertical line. According to the boundary decision, the values of duration to the left correspond to y = 0 (non subscription), and the values to the right to y = 1 (subscription)." }, { "code": null, "e": 3866, "s": 3753, "text": "We summarize the inferred parameters values for easier analysis of the results and check how well the model did:" }, { "code": null, "e": 3913, "s": 3866, "text": "az.summary(trace_simple, var_names=['α', 'β'])" }, { "code": null, "e": 4091, "s": 3913, "text": "As you can see, the values of α and β are very narrowed defined. This is totally reasonable, given that we are fitting a binary fitted line to a perfectly aligned set of points." }, { "code": null, "e": 4252, "s": 4091, "text": "Let’s run a posterior predictive check to explore how well our model captures the data. We can let PyMC3 do the hard work of sampling from the posterior for us:" }, { "code": null, "e": 4527, "s": 4252, "text": "ppc = pm.sample_ppc(trace_simple, model=model_simple, samples=500)preds = np.rint(ppc['y_1'].mean(axis=0)).astype('int')print('Accuracy of the simplest model:', accuracy_score(preds, data['outcome']))print('f1 score of the simplest model:', f1_score(preds, data['outcome']))" }, { "code": null, "e": 4595, "s": 4527, "text": "We plot a heat map to show the correlations between each variables." }, { "code": null, "e": 4735, "s": 4595, "text": "plt.figure(figsize=(15, 15))corr = data.corr() mask = np.tri(*corr.shape).T sns.heatmap(corr.abs(), mask=mask, annot=True, cmap='viridis');" }, { "code": null, "e": 4843, "s": 4735, "text": "poutcome & previous have a high correlation, we can simply remove one of them, I decide to remove poutcome." }, { "code": null, "e": 4951, "s": 4843, "text": "There are not many strong correlations with the outcome variable. The highest positive correlation is 0.41." }, { "code": null, "e": 5248, "s": 4951, "text": "We assume that the probability of a subscription outcome is a function of age, job, marital, education, default, housing, loan, contact, month, day of week, duration, campaign, pdays, previous and euribor3m. We need to specify a prior and a likelihood in order to draw samples from the posterior." }, { "code": null, "e": 5290, "s": 5248, "text": "The interpretation formula is as follows:" }, { "code": null, "e": 5606, "s": 5290, "text": "logit = β0 + β1(age) + β2(age)2 + β3(job) + β4(marital) + β5(education) + β6(default) + β7(housing) + β8(loan) + β9(contact) + β10(month) + β11(day_of_week) + β12(duration) + β13(campaign) + β14(campaign) + β15(pdays) + β16(previous) + β17(poutcome) + β18(euribor3m) and y = 1 if outcome is yes and y = 0 otherwise." }, { "code": null, "e": 5673, "s": 5606, "text": "The log odds can then be converted to a probability of the output:" }, { "code": null, "e": 5802, "s": 5673, "text": "For our problem, we are interested in finding the probability a customer will subscribe a term deposit given all the activities:" }, { "code": null, "e": 6020, "s": 5802, "text": "With the math out of the way we can get back to the data. PyMC3 has a module glm for defining models using a patsy-style formula syntax. This seems really useful, especially for defining models in fewer lines of code." }, { "code": null, "e": 6151, "s": 6020, "text": "We use PyMC3 to draw samples from the posterior. The sampling algorithm used is NUTS, in which parameters are tuned automatically." }, { "code": null, "e": 6360, "s": 6151, "text": "We will use all these 18 variables and create the model using the formula defined above. The idea of adding a age2 is borrowed from this tutorial, and It would be interesting to compare models lately as well." }, { "code": null, "e": 6423, "s": 6360, "text": "We will also scale age by 10, it helps with model convergence." }, { "code": null, "e": 6465, "s": 6423, "text": "Above I only show part of the trace plot." }, { "code": null, "e": 6711, "s": 6465, "text": "This trace shows all of the samples drawn for all of the variables. On the left we can see the final approximate posterior distribution for the model parameters. On the right we get the individual sampled values at each step during the sampling." }, { "code": null, "e": 6872, "s": 6711, "text": "This glm defined model appears to behave in a very similar way, and finds the same parameter values as the conventionally-defined model we have created earlier." }, { "code": null, "e": 6916, "s": 6872, "text": "I want to be able to answer questions like:" }, { "code": null, "e": 7099, "s": 6916, "text": "To answer this question, we will show how the probability of subscribing a term deposit changes with age for a few different education levels, and we want to study married customers." }, { "code": null, "e": 7266, "s": 7099, "text": "We will pass in three different linear models: one with education == 1 (illiterate), one with education == 5(basic.9y) and one with education == 8(university.degree)." }, { "code": null, "e": 7435, "s": 7266, "text": "For all three education levels, the probability of subscribing a term deposit decreases with age until approximately at age 40, when the probability begins to increase." }, { "code": null, "e": 7594, "s": 7435, "text": "Every curve is blurry, this is because we are plotting 100 different curves for each level of education. Each curve is a draw from our posterior distribution." }, { "code": null, "e": 7772, "s": 7594, "text": "Does education of a person affects his or her subscribing to a term deposit? To do it we will use the concept of odds, and we can estimate the odds ratio of education like this:" }, { "code": null, "e": 7871, "s": 7772, "text": "b = trace['education']plt.hist(np.exp(b), bins=20, normed=True)plt.xlabel(\"Odds Ratio\")plt.show();" }, { "code": null, "e": 7961, "s": 7871, "text": "We are 95% confident that the odds ratio of education lies within the following interval." }, { "code": null, "e": 8086, "s": 7961, "text": "lb, ub = np.percentile(b, 2.5), np.percentile(b, 97.5)print(\"P(%.3f < Odds Ratio < %.3f) = 0.95\" % (np.exp(lb), np.exp(ub)))" }, { "code": null, "e": 8470, "s": 8086, "text": "We can interpret something along those lines: “With probability 0.95 the odds ratio is greater than 1.055 and less than 1.108, so the education effect takes place because a person with a higher education level has at least 1.055 higher probability to subscribe to a term deposit than a person with a lower education level, while holding all the other independent variables constant.”" }, { "code": null, "e": 8542, "s": 8470, "text": "We can estimate odds ratio and percentage effect for all the variables." }, { "code": null, "e": 8688, "s": 8542, "text": "stat_df = pm.summary(trace)stat_df['odds_ratio'] = np.exp(stat_df['mean'])stat_df['percentage_effect'] = 100 * (stat_df['odds_ratio'] - 1)stat_df" }, { "code": null, "e": 9012, "s": 8688, "text": "We can interpret percentage_effect along those lines: “ With a one unit increase in education, the odds of subscribing to a term deposit increases by 8%. Similarly, for a one unit increase in euribor3m, the odds of subscribing to a term deposit decreases by 43%, while holding all the other independent variables constant.”" }, { "code": null, "e": 9250, "s": 9012, "text": "Its hard to show the entire forest plot, I only show part of it, but its enough for us to say that there’s a baseline probability of subscribing a term deposit. Beyond that, age has the biggest effect on subscribing, followed by contact." }, { "code": null, "e": 9372, "s": 9250, "text": "If you remember, we added an age2 variable which is squared age. Now its the time to ask what effect it has on our model." }, { "code": null, "e": 9554, "s": 9372, "text": "WAIC is a measure of model fit that can be applied to Bayesian models and that works when the parameter estimation is done using numerical techniques. Read this paper to learn more." }, { "code": null, "e": 9670, "s": 9554, "text": "We’ll compare three models with increasing polynomial complexity. In our case, we are interested in the WAIC score." }, { "code": null, "e": 9726, "s": 9670, "text": "Now loop through all the models and calculate the WAIC." }, { "code": null, "e": 9971, "s": 9726, "text": "PyMC3 includes two convenience functions to help compare WAIC for different models. The first of this functions is compare which computes WAIC from a set of traces and models and returns a DataFrame which is ordered from lowest to highest WAIC." }, { "code": null, "e": 10169, "s": 9971, "text": "model_trace_dict = dict()for nm in ['k1', 'k2', 'k3']: models_lin[nm].name = nm model_trace_dict.update({models_lin[nm]: traces_lin[nm]})dfwaic = pm.compare(model_trace_dict, ic='WAIC')dfwaic" }, { "code": null, "e": 10216, "s": 10169, "text": "We should prefer the model(s) with lower WAIC." }, { "code": null, "e": 10305, "s": 10216, "text": "The second convenience function takes the output of compare and produces a summary plot." }, { "code": null, "e": 10329, "s": 10305, "text": "pm.compareplot(dfwaic);" }, { "code": null, "e": 10472, "s": 10329, "text": "The empty circle represents the values of WAIC and the black error bars associated with them are the values of the standard deviation of WAIC." }, { "code": null, "e": 10595, "s": 10472, "text": "The value of the lowest WAIC is also indicated with a vertical dashed grey line to ease comparison with other WAIC values." }, { "code": null, "e": 10723, "s": 10595, "text": "The filled in black dots are the in-sample deviance of each model, which for WAIC is 2 pWAIC from the corresponding WAIC value." }, { "code": null, "e": 10997, "s": 10723, "text": "For all models except the top-ranked one, we also get a triangle, indicating the value of the difference of WAIC between that model and the top model, and a grey error bar indicating the standard error of the differences between the top-ranked WAIC and WAIC for each model." }, { "code": null, "e": 11088, "s": 10997, "text": "This confirms that the model that includes square of age is better than the model without." }, { "code": null, "e": 11283, "s": 11088, "text": "Unlike standard machine learning, Bayesian focused on model interpretability around a prediction. But I’am curious to know what we will get if we calculate the standard machine learning metrics." }, { "code": null, "e": 11389, "s": 11283, "text": "We are going to calculate the metrics using the mean value of the parameters as a “most likely” estimate." }, { "code": null, "e": 11538, "s": 11389, "text": "print('Accuracy of the full model: ', accuracy_score(preds, data['outcome']))print('f1 score of the full model: ', f1_score(preds, data['outcome']))" }, { "code": null, "e": 11598, "s": 11538, "text": "Jupyter notebook can be found on Github. Have a great week!" }, { "code": null, "e": 11610, "s": 11598, "text": "References:" }, { "code": null, "e": 11623, "s": 11610, "text": "docs.pymc.io" }, { "code": null, "e": 11636, "s": 11623, "text": "docs.pymc.io" } ]
How to prevent loops going into infinite mode in Python?
Loops formed with for statement in Python traverse one item at a time in a collection. Hence there is less likelihood of for loop becoming infinite. The while loop however needs to be controlled by making some provision inside the body of the loop to drive the condition mentioned in the beginning to false.This is usually done by keeping count of iterations x=0 while x<5: x=x+1 print (x) Loop repetition can also be controlled by using break to take an early exit from the iterations while True: stmt1 stmt2 if expr==True: break stmt3 ..
[ { "code": null, "e": 1211, "s": 1062, "text": "Loops formed with for statement in Python traverse one item at a time in a collection. Hence there is less likelihood of for loop becoming infinite." }, { "code": null, "e": 1421, "s": 1211, "text": "The while loop however needs to be controlled by making some provision inside the body of the loop to drive the condition mentioned in the beginning to false.This is usually done by keeping count of iterations" }, { "code": null, "e": 1458, "s": 1421, "text": "x=0\nwhile x<5:\n x=x+1\n print (x)" }, { "code": null, "e": 1554, "s": 1458, "text": "Loop repetition can also be controlled by using break to take an early exit from the iterations" }, { "code": null, "e": 1623, "s": 1554, "text": "while True:\n stmt1\n stmt2\n if expr==True: break\n stmt3\n .." } ]
Remove spaces from column names in Pandas - GeeksforGeeks
29 Aug, 2020 Removing spaces from column names in pandas is not very hard we easily remove spaces from column names in pandas using replace() function. We can also replace space with another character. Let’s see the example of both one by one. Example 1: remove the space from column name Python # import pandasimport pandas as pd # create data frameData = {'Employee Name': ['Mukul', 'Rohan', 'Mayank', 'Shubham', 'Aakash'], 'Location': ['Saharanpur', 'Meerut', 'Agra', 'Saharanpur', 'Meerut'], 'Sales Code': ['muk123', 'roh232', 'may989', 'shu564', 'aka343']} df = pd.DataFrame(Data) # print original data frameprint(df) # remove special characterdf.columns = df.columns.str.replace(' ', '') # print file after removing special characterprint("\n\n", df) Output: Example 2: replace space with another character Python # import pandasimport pandas as pd # create data frameData = {'Employee Name': ['Mukul', 'Rohan', 'Mayank', 'Shubham', 'Aakash'], 'Location': ['Saharanpur', 'Meerut', 'Agra', 'Saharanpur', 'Meerut'], 'Sales Code': ['muk123', 'roh232', 'may989', 'shu564', 'aka343']} df = pd.DataFrame(Data) # print original data frameprint(df) # replace space with another characterdf.columns = df.columns.str.replace(' ', '_') # print file after removing special characterprint("\n\n", df) Output: Python-pandas Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Python Dictionary Read a file line by line in Python Enumerate() in Python How to Install PIP on Windows ? Iterate over a list in Python Different ways to create Pandas Dataframe Python String | replace() Reading and Writing to text files in Python sum() function in Python Create a Pandas DataFrame from Lists
[ { "code": null, "e": 24229, "s": 24201, "text": "\n29 Aug, 2020" }, { "code": null, "e": 24460, "s": 24229, "text": "Removing spaces from column names in pandas is not very hard we easily remove spaces from column names in pandas using replace() function. We can also replace space with another character. Let’s see the example of both one by one." }, { "code": null, "e": 24505, "s": 24460, "text": "Example 1: remove the space from column name" }, { "code": null, "e": 24512, "s": 24505, "text": "Python" }, { "code": "# import pandasimport pandas as pd # create data frameData = {'Employee Name': ['Mukul', 'Rohan', 'Mayank', 'Shubham', 'Aakash'], 'Location': ['Saharanpur', 'Meerut', 'Agra', 'Saharanpur', 'Meerut'], 'Sales Code': ['muk123', 'roh232', 'may989', 'shu564', 'aka343']} df = pd.DataFrame(Data) # print original data frameprint(df) # remove special characterdf.columns = df.columns.str.replace(' ', '') # print file after removing special characterprint(\"\\n\\n\", df)", "e": 25080, "s": 24512, "text": null }, { "code": null, "e": 25088, "s": 25080, "text": "Output:" }, { "code": null, "e": 25136, "s": 25088, "text": "Example 2: replace space with another character" }, { "code": null, "e": 25143, "s": 25136, "text": "Python" }, { "code": "# import pandasimport pandas as pd # create data frameData = {'Employee Name': ['Mukul', 'Rohan', 'Mayank', 'Shubham', 'Aakash'], 'Location': ['Saharanpur', 'Meerut', 'Agra', 'Saharanpur', 'Meerut'], 'Sales Code': ['muk123', 'roh232', 'may989', 'shu564', 'aka343']} df = pd.DataFrame(Data) # print original data frameprint(df) # replace space with another characterdf.columns = df.columns.str.replace(' ', '_') # print file after removing special characterprint(\"\\n\\n\", df)", "e": 25724, "s": 25143, "text": null }, { "code": null, "e": 25732, "s": 25724, "text": "Output:" }, { "code": null, "e": 25746, "s": 25732, "text": "Python-pandas" }, { "code": null, "e": 25753, "s": 25746, "text": "Python" }, { "code": null, "e": 25851, "s": 25753, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25860, "s": 25851, "text": "Comments" }, { "code": null, "e": 25873, "s": 25860, "text": "Old Comments" }, { "code": null, "e": 25891, "s": 25873, "text": "Python Dictionary" }, { "code": null, "e": 25926, "s": 25891, "text": "Read a file line by line in Python" }, { "code": null, "e": 25948, "s": 25926, "text": "Enumerate() in Python" }, { "code": null, "e": 25980, "s": 25948, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 26010, "s": 25980, "text": "Iterate over a list in Python" }, { "code": null, "e": 26052, "s": 26010, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 26078, "s": 26052, "text": "Python String | replace()" }, { "code": null, "e": 26122, "s": 26078, "text": "Reading and Writing to text files in Python" }, { "code": null, "e": 26147, "s": 26122, "text": "sum() function in Python" } ]
Julia Programming - Basic Syntax
The simplest first Julia program (and of many other programming languages too) is to print hello world. The script is as follows − If you have added Julia to your path, the same script can be saved in a file say hello.jl and can be run by typing Julia hello.jl at command prompt. Alternatively the same can also be run from Julia REPL by typing include(“hello.jl”). This command will evaluate all valid expressions and return the last output. What can be the simplest definition of a computer program? The simplest one may be that a computer program is a series of instructions to be executed on a variety of data. Here the data can be the name of a person, place, the house number of a person, or even a list of things you have made. In computer programming, when we need to label such information, we give it a name (say A) and call it a variable. In this sense, we can say that a variable is a box containing data. Let us see how we can assign data to a variable. It is quite simple, just type it. For example, student_name = “Ram” roll_no = 15 marks_math = 9.5 Here, the first variable i.e. student_name contains a string, the second variable i.e. roll_no contains a number, and the third variable i.e. marks_math contains a floating-point number. We see, unlike other programming languages such as C++, Python, etc.,in Julia we do not have to specify the type of variables because it can infer the type of object on the right side of the equal sign. Following are some conventions used for variables names − The names of the variables in Julia are case sensitive. So, the variables student_name and Student_name would not be same. The names of the variables in Julia are case sensitive. So, the variables student_name and Student_name would not be same. The names of the variables in Julia should always start with a letter and after that we can use anything like digits, letters, underscores, etc. The names of the variables in Julia should always start with a letter and after that we can use anything like digits, letters, underscores, etc. In Julia, generally lower-case letter is used with multiple words separated by an underscore. In Julia, generally lower-case letter is used with multiple words separated by an underscore. We should use clear, short, and to the point names for variables. We should use clear, short, and to the point names for variables. Some of the valid Julia variable names are student_name, roll_no, speed, current_time. Some of the valid Julia variable names are student_name, roll_no, speed, current_time. Writing comments in Julia is quite same as Python. Based on the usage, comments are of two types − In Julia, the single line comments start with the symbol of # (hashtag) and it lasts till the end of that line. Suppose if your comment exceeds one line then you should put a # symbol on the next line also and can continue the comment. Given below is the code snippet showing single line comment − Example julia> #This is an example to demonstrate the single lined comments. julia> #Print the given name In Julia, the multi-line comment is a piece of text, like single line comment, but it is enclosed in a delimiter #= on the start of the comment and enclosed in a delimiter =# on the end of the comment. Given below is the code snippet showing multi-line comment − Example julia> #= This is an example to demonstrate the multi-line comments that tells us about tutorialspoint.com. At this website you can browse the best resource for Online Education.=# julia> print(www.tutorialspoint.com) 73 Lectures 4 hours Lemuel Ogbunude 24 Lectures 3 hours Mohammad Nauman 29 Lectures 2.5 hours Stone River ELearning Print Add Notes Bookmark this page
[ { "code": null, "e": 2209, "s": 2078, "text": "The simplest first Julia program (and of many other programming languages too) is to print hello world. The script is as follows −" }, { "code": null, "e": 2521, "s": 2209, "text": "If you have added Julia to your path, the same script can be saved in a file say hello.jl and can be run by typing Julia hello.jl at command prompt. Alternatively the same can also be run from Julia REPL by typing include(“hello.jl”). This command will evaluate all valid expressions and return the last output." }, { "code": null, "e": 2693, "s": 2521, "text": "What can be the simplest definition of a computer program? The simplest one may be that a computer program is a series of instructions to be executed on a variety of data." }, { "code": null, "e": 2996, "s": 2693, "text": "Here the data can be the name of a person, place, the house number of a person, or even a list of things you have made. In computer programming, when we need to label such information, we give it a name (say A) and call it a variable. In this sense, we can say that a variable is a box containing data." }, { "code": null, "e": 3092, "s": 2996, "text": "Let us see how we can assign data to a variable. It is quite simple, just type it. For example," }, { "code": null, "e": 3144, "s": 3092, "text": "student_name = “Ram”\nroll_no = 15\nmarks_math = 9.5\n" }, { "code": null, "e": 3534, "s": 3144, "text": "Here, the first variable i.e. student_name contains a string, the second variable i.e. roll_no contains a number, and the third variable i.e. marks_math contains a floating-point number. We see, unlike other programming languages such as C++, Python, etc.,in Julia we do not have to specify the type of variables because it can infer the type of object on the right side of the equal sign." }, { "code": null, "e": 3592, "s": 3534, "text": "Following are some conventions used for variables names −" }, { "code": null, "e": 3715, "s": 3592, "text": "The names of the variables in Julia are case sensitive. So, the variables student_name and Student_name would not be same." }, { "code": null, "e": 3838, "s": 3715, "text": "The names of the variables in Julia are case sensitive. So, the variables student_name and Student_name would not be same." }, { "code": null, "e": 3983, "s": 3838, "text": "The names of the variables in Julia should always start with a letter and after that we can use anything like digits, letters, underscores, etc." }, { "code": null, "e": 4128, "s": 3983, "text": "The names of the variables in Julia should always start with a letter and after that we can use anything like digits, letters, underscores, etc." }, { "code": null, "e": 4222, "s": 4128, "text": "In Julia, generally lower-case letter is used with multiple words separated by an underscore." }, { "code": null, "e": 4316, "s": 4222, "text": "In Julia, generally lower-case letter is used with multiple words separated by an underscore." }, { "code": null, "e": 4382, "s": 4316, "text": "We should use clear, short, and to the point names for variables." }, { "code": null, "e": 4448, "s": 4382, "text": "We should use clear, short, and to the point names for variables." }, { "code": null, "e": 4535, "s": 4448, "text": "Some of the valid Julia variable names are student_name, roll_no, speed, current_time." }, { "code": null, "e": 4622, "s": 4535, "text": "Some of the valid Julia variable names are student_name, roll_no, speed, current_time." }, { "code": null, "e": 4721, "s": 4622, "text": "Writing comments in Julia is quite same as Python. Based on the usage, comments are of two types −" }, { "code": null, "e": 5019, "s": 4721, "text": "In Julia, the single line comments start with the symbol of # (hashtag) and it lasts till the end of that line. Suppose if your comment exceeds one line then you should put a # symbol on the next line also and can continue the comment. Given below is the code snippet showing single line comment −" }, { "code": null, "e": 5027, "s": 5019, "text": "Example" }, { "code": null, "e": 5126, "s": 5027, "text": "julia> #This is an example to demonstrate the single lined comments.\njulia> #Print the given name\n" }, { "code": null, "e": 5389, "s": 5126, "text": "In Julia, the multi-line comment is a piece of text, like single line comment, but it is enclosed in a delimiter #= on the start of the comment and enclosed in a delimiter =# on the end of the comment. Given below is the code snippet showing multi-line comment −" }, { "code": null, "e": 5397, "s": 5389, "text": "Example" }, { "code": null, "e": 5616, "s": 5397, "text": "julia> #= This is an example to demonstrate the multi-line comments that tells us about tutorialspoint.com. At this website you can browse the best resource for Online Education.=#\njulia> print(www.tutorialspoint.com)\n" }, { "code": null, "e": 5649, "s": 5616, "text": "\n 73 Lectures \n 4 hours \n" }, { "code": null, "e": 5666, "s": 5649, "text": " Lemuel Ogbunude" }, { "code": null, "e": 5699, "s": 5666, "text": "\n 24 Lectures \n 3 hours \n" }, { "code": null, "e": 5716, "s": 5699, "text": " Mohammad Nauman" }, { "code": null, "e": 5751, "s": 5716, "text": "\n 29 Lectures \n 2.5 hours \n" }, { "code": null, "e": 5774, "s": 5751, "text": " Stone River ELearning" }, { "code": null, "e": 5781, "s": 5774, "text": " Print" }, { "code": null, "e": 5792, "s": 5781, "text": " Add Notes" } ]
Kruskal’s Minimum Spanning Tree Implementation | by Karan Kharecha | Towards Data Science
Graph is a non linear data structure that has nodes and edges. Minimum Spanning Tree is a set of edges in an undirected weighted graph that connects all the vertices with no cycles and minimum total edge weight. For finding the spanning tree, Kruskal’s algorithm is the simplest one. This content is about implementing the algorithm for undirected weighted graph. First step is to create two classes GraphNode and Edge. class GraphNode { String alias; // it is a label of node Object data; // data that is stored in node GraphNode(String alias, Object data) { this.alias = alias; this.data = data; }}class Edge { GraphNode src; // edge's origin GraphNode dest; // edge's end Integer cost; // cost of the edge Edge(GraphNode src, GraphNode dest, Integer cost) { this.src = src; this.dest = dest; this.cost = cost; }} A class named Graph is created that will have methods and several data structures. For ease, Java’s library guava is used for various Sets operations. HashSet<HashSet<String>> universalNodes = new HashSet<>();HashSet<String> subSet1,subSet2;HashSet<HashSet<String>> kUniversal = new HashSet<>();Integer totalCost;ArrayList<Edge> kruskalEdges = new ArrayList<>(); Following are the methods in class Graph: public void addEdge(GraphNode src,GraphNode dest,Integer cost) { universalNodes.add(Sets.newHashSet(src.alias)); universalNodes.add(Sets.newHashSet(dest.alias)); kruskalEdges.add(new Edge(src, dest, cost));}public ArrayList<Edge> kruskalMST() { totalCost = 0; kUniversal = new HashSet<>(universalNodes); int edgesLimit = kUniversal.size() - 1; ArrayList<Edge> MSTEdges = new ArrayList<>(); kruskalEdges.sort(Comparator.comparing(edge -> edge.cost)); for(Edge edge: kruskalEdges){ if (MSTEdges.size() == edgesLimit) break; if (isAcyclic(edge.src.alias, edge.dest.alias)) { kUniversal.add(Sets.newHashSet(Sets.union(subSet1, subSet2))) kUniversal.remove(subSet1); kUniversal.remove(subSet2); MSTEdges.add(edge); totalCost += edge.cost; } } return MSTEdges;}public boolean isAcyclic(String srcAlias, String destAlias) { subSet1 = new HashSet<>(); subSet2 = new HashSet<>(); HashSet<HashSet<String>> targetSet; targetSet = kUniversal; for (HashSet<String> subSet : targetSet) { if (subSet.contains(srcAlias)) subSet1 = subSet; if (subSet.contains(destAlias)) subSet2 = subSet; if (subSet1 == subSet2) return false; } return true;} Description of all three methods: A) addEdge(GraphNode src, GraphNode dest, Integer cost):This method has 3 arguments that denotes source, destination and cost of the edge. It adds edge to the list named kruskalEdges. Along with this, when edges are being added, the nodes are appended as Set in a Set called universalNodes. Hereby, kruskalEdges contains list of all the edges that a graph has, whereas universalNodes contains all unique node sets. For an instance, universalNodes would look like: universalNodes = { {node1}, {node2}, {node3}........ {node n}}Here, each node is stored as a Set so that it becomes further easy to check whether the spanning tree forms a cycle. B) kruskalMST():Initially, kUniversal set is created that is nothing but a copy of universalNodes, which will be used to find if selected edge forms a cycle if appended to the spanning tree. Variable named edgesLimit is the number of total possible edges. If the graph has n nodes then minimum spanning tree will contain n-1 edges. Next, MSTEdges contains edges that are to be selected in the spanning tree. A loop iterates through kruskalEdges but first it checks whether the spanning tree has n-1 edges. If true, then the loop breaks, else it checks if the current edge forms a cycle, using the method isAcyclic(..). If its acyclic then, kUniversal adds a new set which is the union of two subsets. These subsets are set of edges that are selected previously. For example, consider following iterative steps and changes in kruskalEdges.→ {{node1}, {node2}, {node3}, {node 4}, {node 5}}→ {{node1, node3}, {node2}, {node4}, {node5}}→ {{node1, node3}, {node2}, {node4, node5}}→{{node1, node3, node2}, {node4, node5}} After completion of the loop, a list of edges is returned that is considered as Minimum Spanning Tree. C) isAcyclic(String srcAlias, String destAlias):Firstly, subSet1 and subSet2 are created. Loop iterates through kUniversal and updates aforementioned two sets when src or dest node is found. If they belong in the same set then that edge is responsible for forming a cycle and hence the method will return false, otherwise true. Following lines of code builds a graph mentioned in Fig. 1: // Create object of class GraphGraph testGraph = new Graph();// here second argument is data for node, it is optional and not// required currently for spanning tree. Data can be anything.// String, integer, custom class object, etc.// Create objects of class GraphNodeGraphNode A = new GraphNode("A", "Data for node A");GraphNode B = new GraphNode("B", "Data for node B");GraphNode C = new GraphNode("C", "Data for node C");....GraphNode J = new GraphNode("J", "Data for node J");// Add edges to the testGraph, as per the above image (Fig.1)testGraph.addEdge(A, B, 3);testGraph.addEdge(E, A, 9);testGraph.addEdge(A, D, 6);....testGraph.addEdge(E, F, 8);// Print MSTEdges, the list that has all the edges and lastly, total // cost of minimum spanning treefor (Edge edge: testGraph.kruskalMST()) { System.out.println(edge.src.alias + " - " + edge.dest.alias + " : " + edge.cost);}System.out.println(testGraph.getTotalCost()); Final Result with total cost of 38 units: Link to the entire program: Graph.java
[ { "code": null, "e": 536, "s": 172, "text": "Graph is a non linear data structure that has nodes and edges. Minimum Spanning Tree is a set of edges in an undirected weighted graph that connects all the vertices with no cycles and minimum total edge weight. For finding the spanning tree, Kruskal’s algorithm is the simplest one. This content is about implementing the algorithm for undirected weighted graph." }, { "code": null, "e": 592, "s": 536, "text": "First step is to create two classes GraphNode and Edge." }, { "code": null, "e": 1144, "s": 592, "text": "class GraphNode { String alias; // it is a label of node Object data; // data that is stored in node GraphNode(String alias, Object data) { this.alias = alias; this.data = data; }}class Edge { GraphNode src; // edge's origin GraphNode dest; // edge's end Integer cost; // cost of the edge Edge(GraphNode src, GraphNode dest, Integer cost) { this.src = src; this.dest = dest; this.cost = cost; }}" }, { "code": null, "e": 1295, "s": 1144, "text": "A class named Graph is created that will have methods and several data structures. For ease, Java’s library guava is used for various Sets operations." }, { "code": null, "e": 1507, "s": 1295, "text": "HashSet<HashSet<String>> universalNodes = new HashSet<>();HashSet<String> subSet1,subSet2;HashSet<HashSet<String>> kUniversal = new HashSet<>();Integer totalCost;ArrayList<Edge> kruskalEdges = new ArrayList<>();" }, { "code": null, "e": 1549, "s": 1507, "text": "Following are the methods in class Graph:" }, { "code": null, "e": 2889, "s": 1549, "text": "public void addEdge(GraphNode src,GraphNode dest,Integer cost) { universalNodes.add(Sets.newHashSet(src.alias)); universalNodes.add(Sets.newHashSet(dest.alias)); kruskalEdges.add(new Edge(src, dest, cost));}public ArrayList<Edge> kruskalMST() { totalCost = 0; kUniversal = new HashSet<>(universalNodes); int edgesLimit = kUniversal.size() - 1; ArrayList<Edge> MSTEdges = new ArrayList<>(); kruskalEdges.sort(Comparator.comparing(edge -> edge.cost)); for(Edge edge: kruskalEdges){ if (MSTEdges.size() == edgesLimit) break; if (isAcyclic(edge.src.alias, edge.dest.alias)) { kUniversal.add(Sets.newHashSet(Sets.union(subSet1, subSet2))) kUniversal.remove(subSet1); kUniversal.remove(subSet2); MSTEdges.add(edge); totalCost += edge.cost; } } return MSTEdges;}public boolean isAcyclic(String srcAlias, String destAlias) { subSet1 = new HashSet<>(); subSet2 = new HashSet<>(); HashSet<HashSet<String>> targetSet; targetSet = kUniversal; for (HashSet<String> subSet : targetSet) { if (subSet.contains(srcAlias)) subSet1 = subSet; if (subSet.contains(destAlias)) subSet2 = subSet; if (subSet1 == subSet2) return false; } return true;}" }, { "code": null, "e": 2923, "s": 2889, "text": "Description of all three methods:" }, { "code": null, "e": 3387, "s": 2923, "text": "A) addEdge(GraphNode src, GraphNode dest, Integer cost):This method has 3 arguments that denotes source, destination and cost of the edge. It adds edge to the list named kruskalEdges. Along with this, when edges are being added, the nodes are appended as Set in a Set called universalNodes. Hereby, kruskalEdges contains list of all the edges that a graph has, whereas universalNodes contains all unique node sets. For an instance, universalNodes would look like:" }, { "code": null, "e": 3566, "s": 3387, "text": "universalNodes = { {node1}, {node2}, {node3}........ {node n}}Here, each node is stored as a Set so that it becomes further easy to check whether the spanning tree forms a cycle." }, { "code": null, "e": 3974, "s": 3566, "text": "B) kruskalMST():Initially, kUniversal set is created that is nothing but a copy of universalNodes, which will be used to find if selected edge forms a cycle if appended to the spanning tree. Variable named edgesLimit is the number of total possible edges. If the graph has n nodes then minimum spanning tree will contain n-1 edges. Next, MSTEdges contains edges that are to be selected in the spanning tree." }, { "code": null, "e": 4185, "s": 3974, "text": "A loop iterates through kruskalEdges but first it checks whether the spanning tree has n-1 edges. If true, then the loop breaks, else it checks if the current edge forms a cycle, using the method isAcyclic(..)." }, { "code": null, "e": 4582, "s": 4185, "text": "If its acyclic then, kUniversal adds a new set which is the union of two subsets. These subsets are set of edges that are selected previously. For example, consider following iterative steps and changes in kruskalEdges.→ {{node1}, {node2}, {node3}, {node 4}, {node 5}}→ {{node1, node3}, {node2}, {node4}, {node5}}→ {{node1, node3}, {node2}, {node4, node5}}→{{node1, node3, node2}, {node4, node5}}" }, { "code": null, "e": 4685, "s": 4582, "text": "After completion of the loop, a list of edges is returned that is considered as Minimum Spanning Tree." }, { "code": null, "e": 5013, "s": 4685, "text": "C) isAcyclic(String srcAlias, String destAlias):Firstly, subSet1 and subSet2 are created. Loop iterates through kUniversal and updates aforementioned two sets when src or dest node is found. If they belong in the same set then that edge is responsible for forming a cycle and hence the method will return false, otherwise true." }, { "code": null, "e": 5073, "s": 5013, "text": "Following lines of code builds a graph mentioned in Fig. 1:" }, { "code": null, "e": 6052, "s": 5073, "text": "// Create object of class GraphGraph testGraph = new Graph();// here second argument is data for node, it is optional and not// required currently for spanning tree. Data can be anything.// String, integer, custom class object, etc.// Create objects of class GraphNodeGraphNode A = new GraphNode(\"A\", \"Data for node A\");GraphNode B = new GraphNode(\"B\", \"Data for node B\");GraphNode C = new GraphNode(\"C\", \"Data for node C\");....GraphNode J = new GraphNode(\"J\", \"Data for node J\");// Add edges to the testGraph, as per the above image (Fig.1)testGraph.addEdge(A, B, 3);testGraph.addEdge(E, A, 9);testGraph.addEdge(A, D, 6);....testGraph.addEdge(E, F, 8);// Print MSTEdges, the list that has all the edges and lastly, total // cost of minimum spanning treefor (Edge edge: testGraph.kruskalMST()) { System.out.println(edge.src.alias + \" - \" + edge.dest.alias + \" : \" + edge.cost);}System.out.println(testGraph.getTotalCost());" }, { "code": null, "e": 6094, "s": 6052, "text": "Final Result with total cost of 38 units:" } ]
Data Exploration on Airbnb Singapore: 01 | by Agratama Arfiano | Towards Data Science
Hi! My name is Agra, I am an architect who is interested in the integration of architecture, urban design, real estate, and technology knowledge. This article is a write-up of my personal data science project while I am learning data science using python programming language for a few weeks. Nowadays, we live in an era where data are produced and circulated in an enormous amount. Those data can be collected and allow us to infer meaningful results and make well-informed decisions. However, as the number of data increases, we need to visualize the data to help us in conducting data analysis. By using visualization tools, we able to deliver a message to our audience and inform them about our findings. The purpose of this article is to explore a publicly open dataset from a technology company, map the result clearly through visualization tools, and give new insight to the public and other relevant parties. To make the topics on each article more focused, this article will be divided into a series of several articles. For the first article, we will explore and visualize the dataset from Airbnb in Singapore using basic exploratory data analysis techniques. We will be finding out the distribution of every Airbnb listing based on their location, including their price range, room type, listing name, and other related factors. What is Exploratory Data Analysis? I’m referring to Terence S, a data scientist, on his explanation of exploratory data analysis. To simplify, exploratory data analysis(EDA), also known as Data Exploration is a step in the Data Analysis process, where several techniques are used to better understand the dataset being used. Some of the techniques are: Extracting important variables and leaving behind useless variables Identifying outliers, missing values, and human error Understanding the data, maximizing our insight on a dataset and minimizing potential error that may occur later in the process By conducting EDA, we can turn an almost useable or unusable dataset into a useable dataset. Main components of Exploratory Data Analysis: Acquire and loading dataCleaning datasetExploring and Visualizing Data Acquire and loading data Cleaning dataset Exploring and Visualizing Data Why Airbnb? Since 2008, guests and hosts have used Airbnb to expand on traveling possibilities and present a more unique, personalized way of experiencing the world. Today, Airbnb became one of a kind service that is used and recognized by the whole world. Data analysis on millions of listings provided through Airbnb is a crucial factor for the company. These millions of listings generate a lot of data — data that can be analyzed. Why Singapore? Airbnb has a long and fairly complex relationship in Singapore. Since five years ago, the Singapore government labeled the short-term rental offered by Airbnb as an illegal service. Although labeled as such, so far only 2 cases found where the hosts fined for violating the rental laws. Moreover, before the pandemic situation hit the global tourism industry. The Airbnb grow rapidly in Singapore and generated a highly comprehensive data within Southeast Asia. For this project, we are using jupyter notebook IDE with a python programming language to write our script. IDE or Integrated Development Environment is a software application used for software development. To get the data, we are using Airbnb data that publicly shared on the internet under the Creative Commons License. Before we are able to load the data into our IDE, first we need to import various external libraries/modules that needed for visualization and analysis. a. Load python libraries Pandas and Numpy library used for data analysis Matplotlib and Seaborn library used for data visualization import pandas as pdimport numpy as npimport matplotlib.pyplot as pltimport matplotlib.image as mpimg%matplotlib inlineimport seaborn as sns b. Load dataset To load the dataset, we use pandas library and function to read the CSV file of Singapore Airbnb 2019–2020 dataset from http://insideairbnb.com/, convert it to the DataFrame and check the top 5 index data. airbnb = pd.read_csv('listings_sum.csv')airbnb.head() c. Understanding data After we load the dataset, we need to understand the dataset by using various techniques. First, we need to look for information on how big is our dataset. By using shape attributes, we get to know our data size from a number of rows which consist of listing index, and the number of columns with the content of every features related to the index. airbnb.shape Then we check all the data type of every column if it already matches our requirement. For instance, we need a numerical data type (integer and float) on the longitude and latitude, for listing names we need to make sure the data is using string/object data type. airbnb.dtypes We found out that our dataset has 7395 listings. The features include listing name, host id, location information, location coordinate, room type, the price per night, and so on. Next, we look up all the unique values of the ‘neighbourhood_group’ that is consists of a list of all the Singapore region airbnb['neighbourhood_group'].unique() From the list above, we see that Singapore has 5 region area. The region area is divided further by the Urban Redevelopment Authority (URA) into 55 areas called planning areas for urban planning purposes. We will use the ‘neighbourhood’ columns to look at which planning area that has the Airbnb listing. airbnb['neighbourhood'].unique() Now, we know that 43 planning areas have the Airbnb listing. We also look up the ‘room_type’ columns for each room type of the listing airbnb['room_type'].unique() From the list above, we see that Airbnb have 4 room type. Based on the information on the Airbnb website, the definition of each room type are: Private room Guests have exclusive access to the bedroom/sleeping area of the listing. Other parts area such as the living room, kitchen, and bathroom are likely open either to the host even to other guests. Entire home/apt Guests have the whole place for themselves. It usually includes a bedroom, bathroom, and kitchen. Shared Room Guest sleep in a bedroom or a common area that could be shared with others. Hotel Room A typical hotel room with its facilities. Since 2018, Airbnb allows some boutique hotels and high rated independent hotel to list their rooms on their site. The next step is cleaning up the data, oftentimes the data we load have various faults, such as typo, missing value, incomplete data, etc. By doing cleaning up, the data quality will have better quality to be used for further analysis. a. Checking column with missing values Let’s check first if there are any missing values within our dataset airbnb.isnull().sum() b. Removing redundant variables In our case, the missing values that are observed do not need too much treatment. Looking into our dataset, we can state columns ‘ name’ and ‘host_name’, ‘last_review’ are irrelevant and unethical for further data exploration analysis. Therefore, we can get rid of those columns. airbnb.drop(['id','host_name','last_review'],axis=1,inplace=True)airbnb.head() c. Replacing all the missing values Next, we need to replace all the missing values in the ‘review_per_month’ column with 0 (zero) to make sure the missing values do not interfere with our analysis airbnb['reviews_per_month'].fillna(0,inplace=True) After we clean up the data, the next step is exploring the data by visualizing and analyzing the values of the features, explaining the process and the results. For our case, we will look up a various listing category consisting of each biggest value, visualize the listing distribution using a map, create a room type proportion for each area, looking for selling value from their listing name, and finding the average price of the most popular listing. a. Top listing counts First, we skip the first column of ‘name’ and begin from the ‘host_id’ column. Then we slice the top 10 hosts in terms of listing count top_host_id = airbnb['host_id'].value_counts().head(10) Next, we set the figure size and setting it up for data visualizations plot using a bar chart sns.set(rc={'figure.figsize':(10,8)})viz_bar = top_host_id.plot(kind='bar')viz_bar.set_title('Hosts with the most listings in Singapore')viz_bar.set_xlabel('Host IDs')viz_bar.set_ylabel('Count of listings')viz_bar.set_xticklabels(viz_bar.get_xticklabels(), rotation=45) From the chart above, we can see the total of top 10 hosts is almost 20%( 1416 listings) of the whole dataset (7395 listings). Even one of the hosts has more than 350 listings! b. Top Region Area Next, we visualize the proportion of the listing count on each region area using the ‘neighbourhood_group’ columns labels = airbnb.neighbourhood_group.value_counts().indexcolors = ['#008fd5','#fc4f30','#e5ae38','#6d904f','#8b8b8b']explode = (0.1,0,0,0,0)shape = airbnb.neighbourhood_group.value_counts().valuesplt.figure(figsize=(12,12))plt.pie(shape, explode = explode, labels=shape, colors= colors, autopct = '%1.1f%%', startangle=90)plt.legend(labels)plt.title('Neighbourhood Group')plt.show() From the chart above, we see the Central Region has the most listings with almost 6000 listings number, covering more than 80% of the total listings. c. Top Planning Areas Next, we look up the top 10 planning areas that have the highest number of listings airbnb.neighbourhood.value_counts().head(10) As we can see, Kallang has the highest number of listings. We also found that 9 out of the top 10 planning areas are located in the Central Region, with Bedok located in East Region as an exception. d. Listing Map To create a map of the listing location, we will use the ‘longitude’ and ‘latitude’ column. But first, we need to check the values within the column coord = airbnb.loc[:,['longitude','latitude']]coord.describe() From the data above, we can see the outer values of longitude and latitude from the min and max index. Next, we visualize the scatter plot map of every listing and group it by color on each different region plt.figure(figsize=(18,12))plt.style.use('fivethirtyeight')BBox = (103.5935, 104.0625, 1.1775, 1.5050)sg_map = plt.imread('map_bnw.png')plt.imshow(sg_map,zorder=0,extent=BBox)ax = plt.gca()groups = airbnb.groupby('neighbourhood_group')for name,group in groups : plt.scatter(group['longitude'],group['latitude'],label=name,alpha=0.5, edgecolors='k')plt.xlabel('Longitude')plt.ylabel('Latitude')plt.legend() Now we can see how the listings are plotted into a map. For a better understanding of the listings density, we can use the folium heat map import foliumfrom folium.plugins import HeatMapmap_folium = folium.Map([1.35255,103.82580],zoom_start=11.4)HeatMap(airbnb[['latitude','longitude']].dropna(),radius=8,gradient={0.2:'blue',0.4:'purple',0.6:'orange',1.0:'red'}).add_to(map_folium)display(map_folium) From the map above, we can see clearly where the densest listing is located, shown by the red color in the southern area of the Central Region. The listing density increasingly declining the more it’s farther away from the Central Region. e. Price Map Before we visualize the price map, we need to update the dataset by removing some of the outlier data as some data prices have value far from the IQR (interquartile range). airbnb_1 = airbnb[airbnb.price < 300] Next, we visualize the scatter plot map of every listing and the difference in price range using longitude and latitude points with a price heat map. plt.figure(figsize=(18,12))sg_map = plt.imread('map_bnw.png')plt.imshow(sg_map,zorder=0,extent=BBox)ax = plt.gca()airbnb_1.plot(kind='scatter',x='longitude',y='latitude',label='Listing Location', c='price', ax=ax, cmap=plt.get_cmap('jet'), colorbar=True, alpha=0.4, zorder=5)plt.legend()plt.show() From the map above, we observe the price relatively going up towards the center part of the Central Region as this region is the CCR Area in Singapore. From the real estate point of view, URA divided Singapore into three main regions, which they call ‘market segments’. The Core Central Region(CCR), indicated by the yellow color is the prime area of Central Region where most high-end and luxury properties can be found. The red color of the Rest of Central Region(RCR) is regarded as the mid-tier market between the mass market condos in the Outside Central Region(OCR) and the high-value properties in the CCR. The last one is the OCR, indicated by the grey color that covers three-quarters of the size of Singapore and basically the area where mass-market condos at the lower range are located. By looking at two maps above, we could argue that the Airbnb listing price is related to the real estate market segments. But to conclude that, we need more data to do further analysis. f. Price Distribution Based on our price heat map observation, we need to visualize the price distribution using a box plot to understand more on the listing price range grouped by the ‘neighbourhood_group’ /region area. plt.style.use('fivethirtyeight')plt.figure(figsize=(14,12))sns.boxplot(y='price',x='neighbourhood_group',data = airbnb_1)plt.title('Neighbourhood Group Price Distribution < S$ 300')plt.show() From the data above, we see the Central Region has the most expensive price per night with a median S$ 130. g. Top listing words Next, we will explore deeper on the property detail by finding out what the most used word in the listing name. The most used word could represent the selling value of their property for the prospective guests. First, we will create a function to collect the words. #Crete empty list where we are going to put the name stringsnames=[]#Getting name string from 'name' column and appending it to the empty listfor name in airbnb.name: names.append(name)#Setting a function to split name strings into seperate wordsdef split_name(name): s = str(name).split() return s#Create empty list where we are going to count the wordsnames_count = []#Getting name string to appending it to the names_count listfor n in names: for word in split_name(n): word = word.lower() names_count.append(word) We need to import counter library to count and generate raw data which contains the top 25 words used by the host from collections import Countertop_25 = Counter(names_count).most_common()top_25 = top_25[:25] Then, we convert the data into DataFrame and visualize our findings word_count_data = pd.DataFrame(top_25)word_count_data.rename(columns={0:'Words',1:'Counts'},inplace=True)viz_count = sns.barplot(x='Words',y='Counts', data = word_count_data)viz_count.set_title('Top 25 used words for listing names')viz_count.set_ylabel('Count of words')viz_count.set_xlabel('Words')viz_count.set_xticklabels(viz_count.get_xticklabels(),rotation = 90) From the chart above, we see the top 25 words used in the listing name. We can use the word cloud visualization method to help us better understand the chart. from wordcloud import WordCloud, ImageColorGeneratortext = ' '.join(str(n).lower() for n in airbnb.name)#Generate wordcloud imagewordcloud = WordCloud(max_words=200, background_color = 'white').generate(text)plt.figure(figsize=(25,20))#Display the imageplt.imshow(wordcloud, interpolation='bilinear')plt.axis('off')plt.show() As we can see, most of the listing selling values are related to the proximity or connection to public facilities such as MRT and center of activities, shown by ‘mrt’, ‘near’, ‘to’, ‘city’ , ‘walk to’ keyword. Interesting to see how the room condition falls behind those values, shown by the ‘spacious’, ‘cosy’, ’cozy’ on the lower rank of the chart. h. Room type details Next, we will visualize all listing’s room type proportions from each region area using Plotly API library for graph visualization import plotly.offline as pyoimport plotly.graph_objs as go#Setting up the color palletecolor_dict = {'Private room': '#cc5a49', 'Entire home/apt' : '#4586ac', 'Shared room' : '#21908d', 'Hotel room' : '#C0C0C0' }#Group the room type using 'neighbourhood_group' as an indexairbnb_types=airbnb.groupby(['neighbourhood_group', 'room_type']).size()#Create function to plot room type proportion on all region areafor region in airbnb.neighbourhood_group.unique(): plt.figure(figsize=(24,12)) airbnb_reg=airbnb_types[region] labels = airbnb_reg.index sizes = airbnb_reg.values colors = [color_dict[x] for x in labels] plot_num = 321 plt.subplot(plot_num) reg_ch = go.Figure(data = [go.Pie(labels = labels, values = sizes, hole = 0.6)]) reg_ch.update_traces(title = reg, marker=dict(colors=colors)) reg_ch.show() plot_num += 1 We can see the Central Region is the only region that dominated by the entire home/apt type, with the rest of the region is dominated by private room type. Overall, the hotel type is the least listing on each region, since Airbnb has only been accepting hotel listing on 2018. i. Top 10 most reviewed listings We will find out the top 10 listings based on their number of reviews to know the most popular Airbnb listings in Singapore. airbnb.nlargest(10, 'number_of_reviews') Voila! Those are the 10 most popular listings. Again, we found out the majority of the most reviewed listing is located in the Central Region, with 7 out of 10 listings. j. Average price per night Lastly, we will calculate the average price per night of the 10 most popular listings price_avg = top_review.price.mean()print('Average price per night: S$ {}'.format(price_avg)) From this output, we can observe that the top 10 most popular listings on Airbnb Singapore have a price average of S$ 99.9 with most of the listings under S$ 90, and 6/10 of them are ‘Private Room’ type, top reviewed listings have a total 3111 reviews. Simply by performing EDA on the dataset, we’ve identified various new insight on how the Airbnb listings distributed on Singapore, we know where are the listings located, found out the Central Region is dominating the listing number and have the highest price range, how the listing price might be related to the surrounding property price and found out the connectivity of the listing to its surrounding becomes one of the common selling value. In the next article, we will explore the dataset using the more detailed version. We will be focusing on the Central Region to understand more on the deeper context, on how the relationship between each listing in the region and their relation with external variables such as the connectivity to the public facility and the impact of property prices on the listing rental prices. Thank you for reading! Feel free to give any feedback!
[ { "code": null, "e": 465, "s": 172, "text": "Hi! My name is Agra, I am an architect who is interested in the integration of architecture, urban design, real estate, and technology knowledge. This article is a write-up of my personal data science project while I am learning data science using python programming language for a few weeks." }, { "code": null, "e": 881, "s": 465, "text": "Nowadays, we live in an era where data are produced and circulated in an enormous amount. Those data can be collected and allow us to infer meaningful results and make well-informed decisions. However, as the number of data increases, we need to visualize the data to help us in conducting data analysis. By using visualization tools, we able to deliver a message to our audience and inform them about our findings." }, { "code": null, "e": 1202, "s": 881, "text": "The purpose of this article is to explore a publicly open dataset from a technology company, map the result clearly through visualization tools, and give new insight to the public and other relevant parties. To make the topics on each article more focused, this article will be divided into a series of several articles." }, { "code": null, "e": 1512, "s": 1202, "text": "For the first article, we will explore and visualize the dataset from Airbnb in Singapore using basic exploratory data analysis techniques. We will be finding out the distribution of every Airbnb listing based on their location, including their price range, room type, listing name, and other related factors." }, { "code": null, "e": 1547, "s": 1512, "text": "What is Exploratory Data Analysis?" }, { "code": null, "e": 1837, "s": 1547, "text": "I’m referring to Terence S, a data scientist, on his explanation of exploratory data analysis. To simplify, exploratory data analysis(EDA), also known as Data Exploration is a step in the Data Analysis process, where several techniques are used to better understand the dataset being used." }, { "code": null, "e": 1865, "s": 1837, "text": "Some of the techniques are:" }, { "code": null, "e": 1933, "s": 1865, "text": "Extracting important variables and leaving behind useless variables" }, { "code": null, "e": 1987, "s": 1933, "text": "Identifying outliers, missing values, and human error" }, { "code": null, "e": 2114, "s": 1987, "text": "Understanding the data, maximizing our insight on a dataset and minimizing potential error that may occur later in the process" }, { "code": null, "e": 2207, "s": 2114, "text": "By conducting EDA, we can turn an almost useable or unusable dataset into a useable dataset." }, { "code": null, "e": 2253, "s": 2207, "text": "Main components of Exploratory Data Analysis:" }, { "code": null, "e": 2324, "s": 2253, "text": "Acquire and loading dataCleaning datasetExploring and Visualizing Data" }, { "code": null, "e": 2349, "s": 2324, "text": "Acquire and loading data" }, { "code": null, "e": 2366, "s": 2349, "text": "Cleaning dataset" }, { "code": null, "e": 2397, "s": 2366, "text": "Exploring and Visualizing Data" }, { "code": null, "e": 2409, "s": 2397, "text": "Why Airbnb?" }, { "code": null, "e": 2832, "s": 2409, "text": "Since 2008, guests and hosts have used Airbnb to expand on traveling possibilities and present a more unique, personalized way of experiencing the world. Today, Airbnb became one of a kind service that is used and recognized by the whole world. Data analysis on millions of listings provided through Airbnb is a crucial factor for the company. These millions of listings generate a lot of data — data that can be analyzed." }, { "code": null, "e": 2847, "s": 2832, "text": "Why Singapore?" }, { "code": null, "e": 3134, "s": 2847, "text": "Airbnb has a long and fairly complex relationship in Singapore. Since five years ago, the Singapore government labeled the short-term rental offered by Airbnb as an illegal service. Although labeled as such, so far only 2 cases found where the hosts fined for violating the rental laws." }, { "code": null, "e": 3309, "s": 3134, "text": "Moreover, before the pandemic situation hit the global tourism industry. The Airbnb grow rapidly in Singapore and generated a highly comprehensive data within Southeast Asia." }, { "code": null, "e": 3516, "s": 3309, "text": "For this project, we are using jupyter notebook IDE with a python programming language to write our script. IDE or Integrated Development Environment is a software application used for software development." }, { "code": null, "e": 3784, "s": 3516, "text": "To get the data, we are using Airbnb data that publicly shared on the internet under the Creative Commons License. Before we are able to load the data into our IDE, first we need to import various external libraries/modules that needed for visualization and analysis." }, { "code": null, "e": 3809, "s": 3784, "text": "a. Load python libraries" }, { "code": null, "e": 3857, "s": 3809, "text": "Pandas and Numpy library used for data analysis" }, { "code": null, "e": 3916, "s": 3857, "text": "Matplotlib and Seaborn library used for data visualization" }, { "code": null, "e": 4056, "s": 3916, "text": "import pandas as pdimport numpy as npimport matplotlib.pyplot as pltimport matplotlib.image as mpimg%matplotlib inlineimport seaborn as sns" }, { "code": null, "e": 4072, "s": 4056, "text": "b. Load dataset" }, { "code": null, "e": 4278, "s": 4072, "text": "To load the dataset, we use pandas library and function to read the CSV file of Singapore Airbnb 2019–2020 dataset from http://insideairbnb.com/, convert it to the DataFrame and check the top 5 index data." }, { "code": null, "e": 4332, "s": 4278, "text": "airbnb = pd.read_csv('listings_sum.csv')airbnb.head()" }, { "code": null, "e": 4354, "s": 4332, "text": "c. Understanding data" }, { "code": null, "e": 4703, "s": 4354, "text": "After we load the dataset, we need to understand the dataset by using various techniques. First, we need to look for information on how big is our dataset. By using shape attributes, we get to know our data size from a number of rows which consist of listing index, and the number of columns with the content of every features related to the index." }, { "code": null, "e": 4716, "s": 4703, "text": "airbnb.shape" }, { "code": null, "e": 4980, "s": 4716, "text": "Then we check all the data type of every column if it already matches our requirement. For instance, we need a numerical data type (integer and float) on the longitude and latitude, for listing names we need to make sure the data is using string/object data type." }, { "code": null, "e": 4994, "s": 4980, "text": "airbnb.dtypes" }, { "code": null, "e": 5173, "s": 4994, "text": "We found out that our dataset has 7395 listings. The features include listing name, host id, location information, location coordinate, room type, the price per night, and so on." }, { "code": null, "e": 5296, "s": 5173, "text": "Next, we look up all the unique values of the ‘neighbourhood_group’ that is consists of a list of all the Singapore region" }, { "code": null, "e": 5335, "s": 5296, "text": "airbnb['neighbourhood_group'].unique()" }, { "code": null, "e": 5397, "s": 5335, "text": "From the list above, we see that Singapore has 5 region area." }, { "code": null, "e": 5640, "s": 5397, "text": "The region area is divided further by the Urban Redevelopment Authority (URA) into 55 areas called planning areas for urban planning purposes. We will use the ‘neighbourhood’ columns to look at which planning area that has the Airbnb listing." }, { "code": null, "e": 5673, "s": 5640, "text": "airbnb['neighbourhood'].unique()" }, { "code": null, "e": 5734, "s": 5673, "text": "Now, we know that 43 planning areas have the Airbnb listing." }, { "code": null, "e": 5808, "s": 5734, "text": "We also look up the ‘room_type’ columns for each room type of the listing" }, { "code": null, "e": 5837, "s": 5808, "text": "airbnb['room_type'].unique()" }, { "code": null, "e": 5981, "s": 5837, "text": "From the list above, we see that Airbnb have 4 room type. Based on the information on the Airbnb website, the definition of each room type are:" }, { "code": null, "e": 5994, "s": 5981, "text": "Private room" }, { "code": null, "e": 6189, "s": 5994, "text": "Guests have exclusive access to the bedroom/sleeping area of the listing. Other parts area such as the living room, kitchen, and bathroom are likely open either to the host even to other guests." }, { "code": null, "e": 6205, "s": 6189, "text": "Entire home/apt" }, { "code": null, "e": 6303, "s": 6205, "text": "Guests have the whole place for themselves. It usually includes a bedroom, bathroom, and kitchen." }, { "code": null, "e": 6315, "s": 6303, "text": "Shared Room" }, { "code": null, "e": 6391, "s": 6315, "text": "Guest sleep in a bedroom or a common area that could be shared with others." }, { "code": null, "e": 6402, "s": 6391, "text": "Hotel Room" }, { "code": null, "e": 6559, "s": 6402, "text": "A typical hotel room with its facilities. Since 2018, Airbnb allows some boutique hotels and high rated independent hotel to list their rooms on their site." }, { "code": null, "e": 6795, "s": 6559, "text": "The next step is cleaning up the data, oftentimes the data we load have various faults, such as typo, missing value, incomplete data, etc. By doing cleaning up, the data quality will have better quality to be used for further analysis." }, { "code": null, "e": 6834, "s": 6795, "text": "a. Checking column with missing values" }, { "code": null, "e": 6903, "s": 6834, "text": "Let’s check first if there are any missing values within our dataset" }, { "code": null, "e": 6925, "s": 6903, "text": "airbnb.isnull().sum()" }, { "code": null, "e": 6957, "s": 6925, "text": "b. Removing redundant variables" }, { "code": null, "e": 7237, "s": 6957, "text": "In our case, the missing values that are observed do not need too much treatment. Looking into our dataset, we can state columns ‘ name’ and ‘host_name’, ‘last_review’ are irrelevant and unethical for further data exploration analysis. Therefore, we can get rid of those columns." }, { "code": null, "e": 7316, "s": 7237, "text": "airbnb.drop(['id','host_name','last_review'],axis=1,inplace=True)airbnb.head()" }, { "code": null, "e": 7352, "s": 7316, "text": "c. Replacing all the missing values" }, { "code": null, "e": 7514, "s": 7352, "text": "Next, we need to replace all the missing values in the ‘review_per_month’ column with 0 (zero) to make sure the missing values do not interfere with our analysis" }, { "code": null, "e": 7565, "s": 7514, "text": "airbnb['reviews_per_month'].fillna(0,inplace=True)" }, { "code": null, "e": 7726, "s": 7565, "text": "After we clean up the data, the next step is exploring the data by visualizing and analyzing the values of the features, explaining the process and the results." }, { "code": null, "e": 8020, "s": 7726, "text": "For our case, we will look up a various listing category consisting of each biggest value, visualize the listing distribution using a map, create a room type proportion for each area, looking for selling value from their listing name, and finding the average price of the most popular listing." }, { "code": null, "e": 8042, "s": 8020, "text": "a. Top listing counts" }, { "code": null, "e": 8178, "s": 8042, "text": "First, we skip the first column of ‘name’ and begin from the ‘host_id’ column. Then we slice the top 10 hosts in terms of listing count" }, { "code": null, "e": 8234, "s": 8178, "text": "top_host_id = airbnb['host_id'].value_counts().head(10)" }, { "code": null, "e": 8328, "s": 8234, "text": "Next, we set the figure size and setting it up for data visualizations plot using a bar chart" }, { "code": null, "e": 8598, "s": 8328, "text": "sns.set(rc={'figure.figsize':(10,8)})viz_bar = top_host_id.plot(kind='bar')viz_bar.set_title('Hosts with the most listings in Singapore')viz_bar.set_xlabel('Host IDs')viz_bar.set_ylabel('Count of listings')viz_bar.set_xticklabels(viz_bar.get_xticklabels(), rotation=45)" }, { "code": null, "e": 8775, "s": 8598, "text": "From the chart above, we can see the total of top 10 hosts is almost 20%( 1416 listings) of the whole dataset (7395 listings). Even one of the hosts has more than 350 listings!" }, { "code": null, "e": 8794, "s": 8775, "text": "b. Top Region Area" }, { "code": null, "e": 8909, "s": 8794, "text": "Next, we visualize the proportion of the listing count on each region area using the ‘neighbourhood_group’ columns" }, { "code": null, "e": 9291, "s": 8909, "text": "labels = airbnb.neighbourhood_group.value_counts().indexcolors = ['#008fd5','#fc4f30','#e5ae38','#6d904f','#8b8b8b']explode = (0.1,0,0,0,0)shape = airbnb.neighbourhood_group.value_counts().valuesplt.figure(figsize=(12,12))plt.pie(shape, explode = explode, labels=shape, colors= colors, autopct = '%1.1f%%', startangle=90)plt.legend(labels)plt.title('Neighbourhood Group')plt.show()" }, { "code": null, "e": 9441, "s": 9291, "text": "From the chart above, we see the Central Region has the most listings with almost 6000 listings number, covering more than 80% of the total listings." }, { "code": null, "e": 9463, "s": 9441, "text": "c. Top Planning Areas" }, { "code": null, "e": 9547, "s": 9463, "text": "Next, we look up the top 10 planning areas that have the highest number of listings" }, { "code": null, "e": 9592, "s": 9547, "text": "airbnb.neighbourhood.value_counts().head(10)" }, { "code": null, "e": 9791, "s": 9592, "text": "As we can see, Kallang has the highest number of listings. We also found that 9 out of the top 10 planning areas are located in the Central Region, with Bedok located in East Region as an exception." }, { "code": null, "e": 9806, "s": 9791, "text": "d. Listing Map" }, { "code": null, "e": 9955, "s": 9806, "text": "To create a map of the listing location, we will use the ‘longitude’ and ‘latitude’ column. But first, we need to check the values within the column" }, { "code": null, "e": 10018, "s": 9955, "text": "coord = airbnb.loc[:,['longitude','latitude']]coord.describe()" }, { "code": null, "e": 10121, "s": 10018, "text": "From the data above, we can see the outer values of longitude and latitude from the min and max index." }, { "code": null, "e": 10225, "s": 10121, "text": "Next, we visualize the scatter plot map of every listing and group it by color on each different region" }, { "code": null, "e": 10634, "s": 10225, "text": "plt.figure(figsize=(18,12))plt.style.use('fivethirtyeight')BBox = (103.5935, 104.0625, 1.1775, 1.5050)sg_map = plt.imread('map_bnw.png')plt.imshow(sg_map,zorder=0,extent=BBox)ax = plt.gca()groups = airbnb.groupby('neighbourhood_group')for name,group in groups : plt.scatter(group['longitude'],group['latitude'],label=name,alpha=0.5, edgecolors='k')plt.xlabel('Longitude')plt.ylabel('Latitude')plt.legend()" }, { "code": null, "e": 10773, "s": 10634, "text": "Now we can see how the listings are plotted into a map. For a better understanding of the listings density, we can use the folium heat map" }, { "code": null, "e": 11036, "s": 10773, "text": "import foliumfrom folium.plugins import HeatMapmap_folium = folium.Map([1.35255,103.82580],zoom_start=11.4)HeatMap(airbnb[['latitude','longitude']].dropna(),radius=8,gradient={0.2:'blue',0.4:'purple',0.6:'orange',1.0:'red'}).add_to(map_folium)display(map_folium)" }, { "code": null, "e": 11275, "s": 11036, "text": "From the map above, we can see clearly where the densest listing is located, shown by the red color in the southern area of the Central Region. The listing density increasingly declining the more it’s farther away from the Central Region." }, { "code": null, "e": 11288, "s": 11275, "text": "e. Price Map" }, { "code": null, "e": 11461, "s": 11288, "text": "Before we visualize the price map, we need to update the dataset by removing some of the outlier data as some data prices have value far from the IQR (interquartile range)." }, { "code": null, "e": 11499, "s": 11461, "text": "airbnb_1 = airbnb[airbnb.price < 300]" }, { "code": null, "e": 11649, "s": 11499, "text": "Next, we visualize the scatter plot map of every listing and the difference in price range using longitude and latitude points with a price heat map." }, { "code": null, "e": 11947, "s": 11649, "text": "plt.figure(figsize=(18,12))sg_map = plt.imread('map_bnw.png')plt.imshow(sg_map,zorder=0,extent=BBox)ax = plt.gca()airbnb_1.plot(kind='scatter',x='longitude',y='latitude',label='Listing Location', c='price', ax=ax, cmap=plt.get_cmap('jet'), colorbar=True, alpha=0.4, zorder=5)plt.legend()plt.show()" }, { "code": null, "e": 12099, "s": 11947, "text": "From the map above, we observe the price relatively going up towards the center part of the Central Region as this region is the CCR Area in Singapore." }, { "code": null, "e": 12746, "s": 12099, "text": "From the real estate point of view, URA divided Singapore into three main regions, which they call ‘market segments’. The Core Central Region(CCR), indicated by the yellow color is the prime area of Central Region where most high-end and luxury properties can be found. The red color of the Rest of Central Region(RCR) is regarded as the mid-tier market between the mass market condos in the Outside Central Region(OCR) and the high-value properties in the CCR. The last one is the OCR, indicated by the grey color that covers three-quarters of the size of Singapore and basically the area where mass-market condos at the lower range are located." }, { "code": null, "e": 12932, "s": 12746, "text": "By looking at two maps above, we could argue that the Airbnb listing price is related to the real estate market segments. But to conclude that, we need more data to do further analysis." }, { "code": null, "e": 12954, "s": 12932, "text": "f. Price Distribution" }, { "code": null, "e": 13153, "s": 12954, "text": "Based on our price heat map observation, we need to visualize the price distribution using a box plot to understand more on the listing price range grouped by the ‘neighbourhood_group’ /region area." }, { "code": null, "e": 13345, "s": 13153, "text": "plt.style.use('fivethirtyeight')plt.figure(figsize=(14,12))sns.boxplot(y='price',x='neighbourhood_group',data = airbnb_1)plt.title('Neighbourhood Group Price Distribution < S$ 300')plt.show()" }, { "code": null, "e": 13453, "s": 13345, "text": "From the data above, we see the Central Region has the most expensive price per night with a median S$ 130." }, { "code": null, "e": 13474, "s": 13453, "text": "g. Top listing words" }, { "code": null, "e": 13740, "s": 13474, "text": "Next, we will explore deeper on the property detail by finding out what the most used word in the listing name. The most used word could represent the selling value of their property for the prospective guests. First, we will create a function to collect the words." }, { "code": null, "e": 14284, "s": 13740, "text": "#Crete empty list where we are going to put the name stringsnames=[]#Getting name string from 'name' column and appending it to the empty listfor name in airbnb.name: names.append(name)#Setting a function to split name strings into seperate wordsdef split_name(name): s = str(name).split() return s#Create empty list where we are going to count the wordsnames_count = []#Getting name string to appending it to the names_count listfor n in names: for word in split_name(n): word = word.lower() names_count.append(word)" }, { "code": null, "e": 14398, "s": 14284, "text": "We need to import counter library to count and generate raw data which contains the top 25 words used by the host" }, { "code": null, "e": 14493, "s": 14398, "text": "from collections import Countertop_25 = Counter(names_count).most_common()top_25 = top_25[:25]" }, { "code": null, "e": 14561, "s": 14493, "text": "Then, we convert the data into DataFrame and visualize our findings" }, { "code": null, "e": 14929, "s": 14561, "text": "word_count_data = pd.DataFrame(top_25)word_count_data.rename(columns={0:'Words',1:'Counts'},inplace=True)viz_count = sns.barplot(x='Words',y='Counts', data = word_count_data)viz_count.set_title('Top 25 used words for listing names')viz_count.set_ylabel('Count of words')viz_count.set_xlabel('Words')viz_count.set_xticklabels(viz_count.get_xticklabels(),rotation = 90)" }, { "code": null, "e": 15088, "s": 14929, "text": "From the chart above, we see the top 25 words used in the listing name. We can use the word cloud visualization method to help us better understand the chart." }, { "code": null, "e": 15414, "s": 15088, "text": "from wordcloud import WordCloud, ImageColorGeneratortext = ' '.join(str(n).lower() for n in airbnb.name)#Generate wordcloud imagewordcloud = WordCloud(max_words=200, background_color = 'white').generate(text)plt.figure(figsize=(25,20))#Display the imageplt.imshow(wordcloud, interpolation='bilinear')plt.axis('off')plt.show()" }, { "code": null, "e": 15765, "s": 15414, "text": "As we can see, most of the listing selling values are related to the proximity or connection to public facilities such as MRT and center of activities, shown by ‘mrt’, ‘near’, ‘to’, ‘city’ , ‘walk to’ keyword. Interesting to see how the room condition falls behind those values, shown by the ‘spacious’, ‘cosy’, ’cozy’ on the lower rank of the chart." }, { "code": null, "e": 15786, "s": 15765, "text": "h. Room type details" }, { "code": null, "e": 15917, "s": 15786, "text": "Next, we will visualize all listing’s room type proportions from each region area using Plotly API library for graph visualization" }, { "code": null, "e": 16800, "s": 15917, "text": "import plotly.offline as pyoimport plotly.graph_objs as go#Setting up the color palletecolor_dict = {'Private room': '#cc5a49', 'Entire home/apt' : '#4586ac', 'Shared room' : '#21908d', 'Hotel room' : '#C0C0C0' }#Group the room type using 'neighbourhood_group' as an indexairbnb_types=airbnb.groupby(['neighbourhood_group', 'room_type']).size()#Create function to plot room type proportion on all region areafor region in airbnb.neighbourhood_group.unique(): plt.figure(figsize=(24,12)) airbnb_reg=airbnb_types[region] labels = airbnb_reg.index sizes = airbnb_reg.values colors = [color_dict[x] for x in labels] plot_num = 321 plt.subplot(plot_num) reg_ch = go.Figure(data = [go.Pie(labels = labels, values = sizes, hole = 0.6)]) reg_ch.update_traces(title = reg, marker=dict(colors=colors)) reg_ch.show() plot_num += 1" }, { "code": null, "e": 17077, "s": 16800, "text": "We can see the Central Region is the only region that dominated by the entire home/apt type, with the rest of the region is dominated by private room type. Overall, the hotel type is the least listing on each region, since Airbnb has only been accepting hotel listing on 2018." }, { "code": null, "e": 17110, "s": 17077, "text": "i. Top 10 most reviewed listings" }, { "code": null, "e": 17235, "s": 17110, "text": "We will find out the top 10 listings based on their number of reviews to know the most popular Airbnb listings in Singapore." }, { "code": null, "e": 17276, "s": 17235, "text": "airbnb.nlargest(10, 'number_of_reviews')" }, { "code": null, "e": 17446, "s": 17276, "text": "Voila! Those are the 10 most popular listings. Again, we found out the majority of the most reviewed listing is located in the Central Region, with 7 out of 10 listings." }, { "code": null, "e": 17473, "s": 17446, "text": "j. Average price per night" }, { "code": null, "e": 17559, "s": 17473, "text": "Lastly, we will calculate the average price per night of the 10 most popular listings" }, { "code": null, "e": 17652, "s": 17559, "text": "price_avg = top_review.price.mean()print('Average price per night: S$ {}'.format(price_avg))" }, { "code": null, "e": 17905, "s": 17652, "text": "From this output, we can observe that the top 10 most popular listings on Airbnb Singapore have a price average of S$ 99.9 with most of the listings under S$ 90, and 6/10 of them are ‘Private Room’ type, top reviewed listings have a total 3111 reviews." }, { "code": null, "e": 18351, "s": 17905, "text": "Simply by performing EDA on the dataset, we’ve identified various new insight on how the Airbnb listings distributed on Singapore, we know where are the listings located, found out the Central Region is dominating the listing number and have the highest price range, how the listing price might be related to the surrounding property price and found out the connectivity of the listing to its surrounding becomes one of the common selling value." }, { "code": null, "e": 18731, "s": 18351, "text": "In the next article, we will explore the dataset using the more detailed version. We will be focusing on the Central Region to understand more on the deeper context, on how the relationship between each listing in the region and their relation with external variables such as the connectivity to the public facility and the impact of property prices on the listing rental prices." } ]
Minimum sum | Practice | GeeksforGeeks
Given an array Arr of size N such that each element is from the range 0 to 9. Find the minimum possible sum of two numbers formed using the elements of the array. All digits in the given array must be used to form the two numbers. Example 1: Input: N = 6 Arr[] = {6, 8, 4, 5, 2, 3} Output: 604 Explanation: The minimum sum is formed by numbers 358 and 246. Example 2: Input: N = 5 Arr[] = {5, 3, 0, 7, 4} Output: 82 Explanation: The minimum sum is formed by numbers 35 and 047. Your Task: You don't need to read input or print anything. Your task is to complete the function solve() which takes arr[] and n as input parameters and returns the minimum possible sum. As the number can be large, return string presentation of the number without leading zeroes. Expected Time Complexity: O(N*logN) Expected Auxiliary Space: O(1) Constraints: 1 ≤ N ≤ 107 0 ≤ Arri ≤ 9 0 suprithsk20014 days ago #easy python sol arr.sort() s1='' s2='' for i in range(n): if i%2==0: s1+=str(arr[i]) else: s2+=str(arr[i]) if(len(s1)==0): return int(s2) elif(len(s2)==0): return int(s1) return int(s1)+int(s2) 0 joyrockok1 week ago class Solution { String solve(int[] arr, int n) { StringBuilder sb = new StringBuilder(); Arrays.sort(arr); String ansStr=""; int a=0, b=0; int olim=0, remain=0; for(int i=n-1; i>=0; i=i-2) { if(i%2 == 0) { a = arr[i]; if(i-1>=0) b = arr[i-1]; else b=0; } else { a = arr[i]; b = arr[i-1]; } int sum=a+b+olim; if(sum>=10) { olim=1; remain = (sum)%10; } else { olim=0; remain = sum; } sb.append(remain); } if(olim==1) sb.append(1); sb.reverse(); int i=0; int c = sb.charAt(i) - '0'; while(sb.charAt(i)-'0' == 0) { i++; } ansStr = sb.substring(i,sb.length()); return ansStr; }} 0 joyrockok This comment was deleted. 0 sudeepgarg6712 weeks ago def solve(self, arr, n): arr1 = sorted(arr) sum1 = 0 sum2 = 0 for i in range(0,n,2): sum1 = sum1*10 + arr1[i] for i in range(1,n,2): sum2 =sum2*10 + arr1[i] return sum1 + sum2 0 hydracody454 weeks ago Upvote if help: cpp EASY OOFN Her my solution: string solve(int arr[], int n) { // code here sort(arr,arr+n); int i=0; string a,b; a="";b=""; while(i<n){ if(arr[i]==0){ i++; continue; } a=(char)(arr[i]+'0')+a; i++; // cout<<(char)(arr[i]+'0'); if(i<n){ b=(char)(arr[i]+'0')+b; i++; } } // cout<<"a="<<a<<"b= "<<b<<endl; int c=0,j=0;i=0; string s=""; while(i<a.length() && j<b.length()){ int x=(int)(a[i]-'0')+(int)(b[i]-'0')+c; s=(char)((x%10)+'0')+s; c=x/10; i++;j++; // cout<<"s="<<s<<endl; } while(i<a.length()){ int x=(int)(a[i]-'0')+c; s=(char)((x%10)+'0')+s; c=x/10; i++; } while(j<b.length()){ int x=(int)(b[j]-'0')+c; s=(char)((x%10)+'0')+s; c=x/10; j++; } if(c!=0){ s=(char)(c+'0')+s; } return s; } 0 jom6655441 month ago def solve(self, arr, n): arr_sort = sorted(arr) if n == 1: return arr[0] return int(''.join(map(str,arr_sort[0:n:2]))) + int(''.join(map(str,arr_sort[1:n:2]))) 0 srivasaurabh791 month ago class Solution: def solve(self, arr, n): # code here if(n == 1): return str(arr[0]) arr.sort() i = 0 s1 = "" s2 = "" while(i < n): s1 += str(arr[i]) i += 2 i = 1 while(i < n): s2 += str(arr[i]) i += 2 ans = int(s1) + int(s2) return str(ans) 0 parthbabbar0011 month ago C++ Solution // { Driver Code Starts //Initial template for C++ #include <bits/stdc++.h> using namespace std; // } Driver Code Ends //User function template for C++ class Solution{ public: string solve(int arr[], int n) { // code here priority_queue<int,vector<int>,greater<int> > pq; for(int i=0;i<n;i++){ if(arr[i]!=0){ pq.push(arr[i]); } } string f; string s; while(!pq.empty()){ int x = pq.top(); pq.pop(); if(!pq.empty()){ int y = pq.top(); pq.pop(); f += to_string(x); s += to_string(y); } else{ f += to_string(x); } } string sum=""; int c=0; int i=f.size()-1; int j=s.size()-1; while(i>=0 and j>=0){ int x=f[i]-'0'; int y=s[j]-'0'; int l=(x+y+c)%10; c=(x+y+c)/10; sum+=to_string(l); i--; j--; } while(i>=0){ int x=f[i]-'0'; int l=(x+c)%10; c=(x+c)/10; sum+=to_string(l); i--; } while(j>=0){ int y=s[j]-'0'; int l=(y+c)%10; c=(y+c)/10; sum+=to_string(l); j--; } if(c!=0){ sum+=to_string(c); } reverse(sum.begin(),sum.end()); return sum; } }; // { Driver Code Starts. int main() { int t; cin >> t; while (t--) { int n; cin >> n; int arr[n]; for (int i = 0; i < n; i++) { cin >> arr[i]; } Solution ob; auto ans = ob.solve(arr, n); cout << ans << "\n"; } return 0; } // } Driver Code Ends +2 patildhiren441 month ago Java String solve(int[] arr, int n) { // code here StringBuilder sb = new StringBuilder(); PriorityQueue<Integer> pq = new PriorityQueue<>(Collections.reverseOrder()); for(int i=0; i<n; i++){ pq.add(arr[i]); } int car = 0; while(!pq.isEmpty()){ int a = pq.remove(); int b = 0; if(!pq.isEmpty()){ b = pq.remove(); } int sum = a + b + car; if(sum>9){ car = 1; }else{ car = 0; } sum = sum %10; sb.append(sum); } if(car == 1){ sb.append(1); } sb.reverse(); while(sb.charAt(0) == '0'){ sb.deleteCharAt(0); } return sb.toString(); } +1 sanketbhagat2 months ago SIMPLE JAVA SOLUTION class Solution { String solve(int[] arr, int n) { // code here PriorityQueue<Integer> pq = new PriorityQueue<>((a,b)->b-a); for(int i: arr) pq.offer(i); StringBuilder sb = new StringBuilder(); int carry = 0; while(!pq.isEmpty()){ int a = pq.poll(); int b = pq.isEmpty()?0:pq.poll(); int sum = a+b+carry; carry = sum>9?1:0; sum %= 10; sb.append(sum); } if(carry==1) sb.append(1); sb.reverse(); while(sb.charAt(0)=='0') sb.deleteCharAt(0); return sb.toString(); } } We strongly recommend solving this problem on your own before viewing its editorial. Do you still want to view the editorial? Login to access your submissions. Problem Contest Reset the IDE using the second button on the top right corner. Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values. Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints. You can access the hints to get an idea about what is expected of you as well as the final solution code. You can view the solutions submitted by other users from the submission tab.
[ { "code": null, "e": 469, "s": 238, "text": "Given an array Arr of size N such that each element is from the range 0 to 9. Find the minimum possible sum of two numbers formed using the elements of the array. All digits in the given array must be used to form the two numbers." }, { "code": null, "e": 481, "s": 469, "text": "\nExample 1:" }, { "code": null, "e": 597, "s": 481, "text": "Input:\nN = 6\nArr[] = {6, 8, 4, 5, 2, 3}\nOutput: 604\nExplanation: The minimum sum is formed \nby numbers 358 and 246." }, { "code": null, "e": 609, "s": 597, "text": "\nExample 2:" }, { "code": null, "e": 720, "s": 609, "text": "Input:\nN = 5\nArr[] = {5, 3, 0, 7, 4}\nOutput: 82\nExplanation: The minimum sum is \nformed by numbers 35 and 047." }, { "code": null, "e": 1003, "s": 720, "text": "\nYour Task:\nYou don't need to read input or print anything. Your task is to complete the function solve() which takes arr[] and n as input parameters and returns the minimum possible sum. As the number can be large, return string presentation of the number without leading zeroes.\n " }, { "code": null, "e": 1070, "s": 1003, "text": "Expected Time Complexity: O(N*logN)\nExpected Auxiliary Space: O(1)" }, { "code": null, "e": 1109, "s": 1070, "text": "\nConstraints:\n1 ≤ N ≤ 107\n0 ≤ Arri ≤ 9" }, { "code": null, "e": 1111, "s": 1109, "text": "0" }, { "code": null, "e": 1135, "s": 1111, "text": "suprithsk20014 days ago" }, { "code": null, "e": 1156, "s": 1135, "text": " #easy python sol " }, { "code": null, "e": 1461, "s": 1156, "text": "arr.sort() s1='' s2='' for i in range(n): if i%2==0: s1+=str(arr[i]) else: s2+=str(arr[i]) if(len(s1)==0): return int(s2) elif(len(s2)==0): return int(s1) return int(s1)+int(s2)" }, { "code": null, "e": 1463, "s": 1461, "text": "0" }, { "code": null, "e": 1483, "s": 1463, "text": "joyrockok1 week ago" }, { "code": null, "e": 2115, "s": 1483, "text": "class Solution { String solve(int[] arr, int n) { StringBuilder sb = new StringBuilder(); Arrays.sort(arr); String ansStr=\"\"; int a=0, b=0; int olim=0, remain=0; for(int i=n-1; i>=0; i=i-2) { if(i%2 == 0) { a = arr[i]; if(i-1>=0) b = arr[i-1]; else b=0; } else { a = arr[i]; b = arr[i-1]; } int sum=a+b+olim; if(sum>=10) { olim=1; remain = (sum)%10; } else { olim=0; remain = sum; } sb.append(remain); } if(olim==1) sb.append(1); sb.reverse(); int i=0; int c = sb.charAt(i) - '0'; while(sb.charAt(i)-'0' == 0) { i++; } ansStr = sb.substring(i,sb.length()); return ansStr;" }, { "code": null, "e": 2121, "s": 2115, "text": " }}" }, { "code": null, "e": 2123, "s": 2121, "text": "0" }, { "code": null, "e": 2133, "s": 2123, "text": "joyrockok" }, { "code": null, "e": 2159, "s": 2133, "text": "This comment was deleted." }, { "code": null, "e": 2161, "s": 2159, "text": "0" }, { "code": null, "e": 2186, "s": 2161, "text": "sudeepgarg6712 weeks ago" }, { "code": null, "e": 2418, "s": 2186, "text": "def solve(self, arr, n): arr1 = sorted(arr) sum1 = 0 sum2 = 0 for i in range(0,n,2): sum1 = sum1*10 + arr1[i] for i in range(1,n,2): sum2 =sum2*10 + arr1[i] return sum1 + sum2" }, { "code": null, "e": 2420, "s": 2418, "text": "0" }, { "code": null, "e": 2443, "s": 2420, "text": "hydracody454 weeks ago" }, { "code": null, "e": 2474, "s": 2443, "text": "Upvote if help: cpp EASY OOFN " }, { "code": null, "e": 2491, "s": 2474, "text": "Her my solution:" }, { "code": null, "e": 3635, "s": 2491, "text": "string solve(int arr[], int n) {\n // code here\n sort(arr,arr+n);\n int i=0;\n string a,b;\n a=\"\";b=\"\";\n while(i<n){\n if(arr[i]==0){\n i++;\n continue;\n }\n a=(char)(arr[i]+'0')+a;\n i++;\n // cout<<(char)(arr[i]+'0');\n if(i<n){\n b=(char)(arr[i]+'0')+b;\n i++;\n }\n\n }\n // cout<<\"a=\"<<a<<\"b= \"<<b<<endl;\n int c=0,j=0;i=0;\n string s=\"\";\n while(i<a.length() && j<b.length()){\n int x=(int)(a[i]-'0')+(int)(b[i]-'0')+c;\n s=(char)((x%10)+'0')+s;\n c=x/10;\n i++;j++;\n // cout<<\"s=\"<<s<<endl;\n }\n\n while(i<a.length()){\n int x=(int)(a[i]-'0')+c;\n s=(char)((x%10)+'0')+s;\n c=x/10;\n i++;\n }\n while(j<b.length()){\n int x=(int)(b[j]-'0')+c;\n s=(char)((x%10)+'0')+s;\n c=x/10;\n j++;\n }\n if(c!=0){\n s=(char)(c+'0')+s;\n }\n \n return s;\n }" }, { "code": null, "e": 3637, "s": 3635, "text": "0" }, { "code": null, "e": 3658, "s": 3637, "text": "jom6655441 month ago" }, { "code": null, "e": 3854, "s": 3658, "text": "def solve(self, arr, n):\n arr_sort = sorted(arr)\n if n == 1:\n return arr[0]\n return int(''.join(map(str,arr_sort[0:n:2]))) + int(''.join(map(str,arr_sort[1:n:2])))" }, { "code": null, "e": 3856, "s": 3854, "text": "0" }, { "code": null, "e": 3882, "s": 3856, "text": "srivasaurabh791 month ago" }, { "code": null, "e": 4300, "s": 3882, "text": "class Solution:\n def solve(self, arr, n):\n # code here\n if(n == 1):\n return str(arr[0])\n arr.sort()\n \n i = 0\n s1 = \"\" \n s2 = \"\"\n \n while(i < n):\n s1 += str(arr[i])\n i += 2\n i = 1 \n \n while(i < n):\n s2 += str(arr[i])\n i += 2\n \n ans = int(s1) + int(s2)\n \n return str(ans)" }, { "code": null, "e": 4302, "s": 4300, "text": "0" }, { "code": null, "e": 4328, "s": 4302, "text": "parthbabbar0011 month ago" }, { "code": null, "e": 4341, "s": 4328, "text": "C++ Solution" }, { "code": null, "e": 6279, "s": 4341, "text": "// { Driver Code Starts\n//Initial template for C++\n\n#include <bits/stdc++.h>\nusing namespace std;\n\n // } Driver Code Ends\n//User function template for C++\n\nclass Solution{ \npublic:\n string solve(int arr[], int n) {\n // code here\n priority_queue<int,vector<int>,greater<int> > pq;\n for(int i=0;i<n;i++){\n if(arr[i]!=0){\n pq.push(arr[i]);\n }\n }\n \n string f;\n string s;\n while(!pq.empty()){\n int x = pq.top();\n pq.pop();\n if(!pq.empty()){\n int y = pq.top();\n pq.pop();\n f += to_string(x);\n s += to_string(y);\n }\n else{\n f += to_string(x);\n }\n }\n \n string sum=\"\";\n int c=0;\n int i=f.size()-1;\n int j=s.size()-1;\n while(i>=0 and j>=0){\n int x=f[i]-'0';\n int y=s[j]-'0';\n int l=(x+y+c)%10;\n c=(x+y+c)/10;\n sum+=to_string(l);\n i--;\n j--;\n }\n while(i>=0){\n int x=f[i]-'0';\n int l=(x+c)%10;\n c=(x+c)/10;\n sum+=to_string(l);\n i--;\n }\n while(j>=0){\n int y=s[j]-'0';\n int l=(y+c)%10;\n c=(y+c)/10;\n sum+=to_string(l);\n j--;\n }\n if(c!=0){\n sum+=to_string(c);\n }\n \n reverse(sum.begin(),sum.end());\n return sum; \n }\n};\n\n// { Driver Code Starts.\nint main() {\n int t;\n cin >> t;\n while (t--) {\n int n;\n cin >> n;\n int arr[n];\n for (int i = 0; i < n; i++) {\n cin >> arr[i];\n }\n Solution ob;\n auto ans = ob.solve(arr, n);\n cout << ans << \"\\n\";\n }\n return 0;\n} // } Driver Code Ends" }, { "code": null, "e": 6282, "s": 6279, "text": "+2" }, { "code": null, "e": 6307, "s": 6282, "text": "patildhiren441 month ago" }, { "code": null, "e": 6312, "s": 6307, "text": "Java" }, { "code": null, "e": 7247, "s": 6312, "text": "String solve(int[] arr, int n) {\n // code here\n StringBuilder sb = new StringBuilder();\n PriorityQueue<Integer> pq = new PriorityQueue<>(Collections.reverseOrder());\n \n for(int i=0; i<n; i++){\n pq.add(arr[i]);\n } \n int car = 0;\n while(!pq.isEmpty()){\n int a = pq.remove();\n int b = 0; \n if(!pq.isEmpty()){\n b = pq.remove();\n } \n int sum = a + b + car; \n if(sum>9){\n car = 1;\n }else{\n car = 0;\n } \n sum = sum %10;\n sb.append(sum);\n }\n \n if(car == 1){\n sb.append(1);\n } \n sb.reverse(); \n while(sb.charAt(0) == '0'){\n sb.deleteCharAt(0);\n } \n return sb.toString();\n }" }, { "code": null, "e": 7250, "s": 7247, "text": "+1" }, { "code": null, "e": 7275, "s": 7250, "text": "sanketbhagat2 months ago" }, { "code": null, "e": 7296, "s": 7275, "text": "SIMPLE JAVA SOLUTION" }, { "code": null, "e": 7928, "s": 7296, "text": "class Solution {\n String solve(int[] arr, int n) {\n // code here\n PriorityQueue<Integer> pq = new PriorityQueue<>((a,b)->b-a);\n for(int i: arr) pq.offer(i);\n StringBuilder sb = new StringBuilder();\n int carry = 0;\n while(!pq.isEmpty()){\n int a = pq.poll();\n int b = pq.isEmpty()?0:pq.poll();\n int sum = a+b+carry;\n carry = sum>9?1:0;\n sum %= 10;\n sb.append(sum);\n }\n if(carry==1) sb.append(1);\n sb.reverse();\n while(sb.charAt(0)=='0') sb.deleteCharAt(0);\n return sb.toString();\n }\n}" }, { "code": null, "e": 8074, "s": 7928, "text": "We strongly recommend solving this problem on your own before viewing its editorial. Do you still\n want to view the editorial?" }, { "code": null, "e": 8110, "s": 8074, "text": " Login to access your submissions. " }, { "code": null, "e": 8120, "s": 8110, "text": "\nProblem\n" }, { "code": null, "e": 8130, "s": 8120, "text": "\nContest\n" }, { "code": null, "e": 8193, "s": 8130, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 8341, "s": 8193, "text": "Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values." }, { "code": null, "e": 8549, "s": 8341, "text": "Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints." }, { "code": null, "e": 8655, "s": 8549, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
Draw a triangle in C++ graphics - GeeksforGeeks
02 Sep, 2020 Prerequisite: graphics.h, How to include graphics.h in CodeBlocks? The task is to write a C program to make a triangle with the line function of graphics. To run the program we have to include the below header file: #include <graphic.h> Approach: The idea is to create a triangle with the help of several lines. We will draw a line in graphics by passing 4 numbers to line() function as: line(a, b, c, d)The above function will draw a line from coordinates (a, b) to (c, d) in the output window. Below is the implementation of the above approach: C++ // C++ program for drawing a triangle#include <graphics.h>#include <iostream> // Driver codeint main(){ // gm is Graphics mode which // is a computer display // mode that generates // image using pixels. // DETECT is a macro // defined in "graphics.h" // header file int gd = DETECT, gm; // initgraph initializes // the graphics system // by loading a graphics // driver from disk initgraph(&gd, &gm, ""); // Triangle // line for x1, y1, x2, y2 line(150, 150, 450, 150); // line for x1, y1, x2, y2 line(150, 150, 300, 300); // line for x1, y1, x2, y2 line(450, 150, 300, 300); // closegraph function closes // the graphics mode and // deallocates all memory // allocated by graphics system getch(); // Close the initialized gdriver closegraph();} Output:Below is the output of the above program: computer-graphics C++ CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Operator Overloading in C++ Iterators in C++ STL Friend class and function in C++ Polymorphism in C++ Sorting a vector in C++ Convert string to char array in C++ List in C++ Standard Template Library (STL) Inline Functions in C++ std::string class in C++ Destructors in C++
[ { "code": null, "e": 24018, "s": 23990, "text": "\n02 Sep, 2020" }, { "code": null, "e": 24085, "s": 24018, "text": "Prerequisite: graphics.h, How to include graphics.h in CodeBlocks?" }, { "code": null, "e": 24173, "s": 24085, "text": "The task is to write a C program to make a triangle with the line function of graphics." }, { "code": null, "e": 24234, "s": 24173, "text": "To run the program we have to include the below header file:" }, { "code": null, "e": 24256, "s": 24234, "text": "#include <graphic.h>\n" }, { "code": null, "e": 24407, "s": 24256, "text": "Approach: The idea is to create a triangle with the help of several lines. We will draw a line in graphics by passing 4 numbers to line() function as:" }, { "code": null, "e": 24516, "s": 24407, "text": "line(a, b, c, d)The above function will draw a line from coordinates (a, b) to (c, d) in the output window. " }, { "code": null, "e": 24567, "s": 24516, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 24571, "s": 24567, "text": "C++" }, { "code": "// C++ program for drawing a triangle#include <graphics.h>#include <iostream> // Driver codeint main(){ // gm is Graphics mode which // is a computer display // mode that generates // image using pixels. // DETECT is a macro // defined in \"graphics.h\" // header file int gd = DETECT, gm; // initgraph initializes // the graphics system // by loading a graphics // driver from disk initgraph(&gd, &gm, \"\"); // Triangle // line for x1, y1, x2, y2 line(150, 150, 450, 150); // line for x1, y1, x2, y2 line(150, 150, 300, 300); // line for x1, y1, x2, y2 line(450, 150, 300, 300); // closegraph function closes // the graphics mode and // deallocates all memory // allocated by graphics system getch(); // Close the initialized gdriver closegraph();}", "e": 25414, "s": 24571, "text": null }, { "code": null, "e": 25463, "s": 25414, "text": "Output:Below is the output of the above program:" }, { "code": null, "e": 25481, "s": 25463, "text": "computer-graphics" }, { "code": null, "e": 25485, "s": 25481, "text": "C++" }, { "code": null, "e": 25489, "s": 25485, "text": "CPP" }, { "code": null, "e": 25587, "s": 25489, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25596, "s": 25587, "text": "Comments" }, { "code": null, "e": 25609, "s": 25596, "text": "Old Comments" }, { "code": null, "e": 25637, "s": 25609, "text": "Operator Overloading in C++" }, { "code": null, "e": 25658, "s": 25637, "text": "Iterators in C++ STL" }, { "code": null, "e": 25691, "s": 25658, "text": "Friend class and function in C++" }, { "code": null, "e": 25711, "s": 25691, "text": "Polymorphism in C++" }, { "code": null, "e": 25735, "s": 25711, "text": "Sorting a vector in C++" }, { "code": null, "e": 25771, "s": 25735, "text": "Convert string to char array in C++" }, { "code": null, "e": 25815, "s": 25771, "text": "List in C++ Standard Template Library (STL)" }, { "code": null, "e": 25839, "s": 25815, "text": "Inline Functions in C++" }, { "code": null, "e": 25864, "s": 25839, "text": "std::string class in C++" } ]
How to Access Twitter’s API using Tweepy | by Paulynn Yu | Towards Data Science
Tweet datasets are an extremely desirable corpus for aspiring (and practicing) data scientists to analyze and perform models on. Tweets are by nature short-form and contain diverse and relevant topics, making it an excellent dataset for sentiment analysis. It is also a great dataset to analyze user engagement since tweet timestamps are available. While there are many existing Twitter datasets out there, they will be predefined for you. I am a believer of first defining the problem you’re interested in, and then figuring out a way to get that data. This is where it is beneficial to access Twitter API — you get the type, volume and ‘newness’ only an API can provide. If it’s any testament, I was able to obtain 70,000 user accounts and their 10 million post which takes close to a full day. It’s slightly longer than proofing your bread dough for homemade sourdough, but really not that much longer. I recommend it more highly than trying to make any bread from scratch (at least once) which believe me, says a lot. The Twitter API exposes dozens of HTTP endpoints that can be used to retrieve, create and delete tweets, retweets and likes. It provides direct access to rich and real-time tweet data, but requires having to deal with a lot of low level details (and very not fun debugging). Tweepy is an open source package that allows you to bypass a lot of those low level details. Twitter’s developer website has great documentation I recommend exploring to get example responses and see the type of data you are able to access. Tweepy’s documentation will furthermore provide code snippets and some basic documentation for the Tweepy module. Twitter API uses OAuth, which is an open authorization protocol to authenticate requests. You will need to create and configure your authentication credentials to access Twitter API. As promised, this is a step-by-step guide so follow along! Step 0: Open a Twitter account. If you already have a Twitter account, skip this step Step 1: Apply for a developer account Go to their developer site and go to apply for access and select “Apply for a developer account”. You will be prompted to log in to your Twitter account. You will then be navigated to a page like this: Select your choice path and fill the details in the next page and fill in some personal details. When you get to intended use, there are a couple of fields with minimum character limit (the one time they have a minimum 😏). This is what I filled up. Be honest, but don’t worry too much about the details and especially not about brevity. In my experience, they have been instantaneous in approvals. There will be further easy questions and steps (be patient!). Once you’ve gone through those steps and accept developer agreement, you now have a developer account! Step 2: Create an Application You might have to wait a hot minute for your developer account to be approved — but once it is, you can start creating your application. Go to your profile tab and select Apps. Create an app and fill in the details. That should take another hot minute. Once you create you app, go to the next step. Step 3: Get your authentication details Go to your apps page where you will see the app you created. Click on details. Once you’re there, click on keys and tokens to get the relevant keys. You will might need to generate your access token and access token secret. You also have the capability to regenerate the key, in case you are needing to write a step-by-step blog post and share your old key (I did). Once you have that, move to to the next step! Replace the CONSUMER_KEY, CONSUMER_SECRET, ACCESS_TOKEN, ACCESS_TOKEN_SECRET in the code below with your own credentials. Run the code below to verify your authentication. I hope it works! import tweepy# Authenticate to Twitterauth = tweepy.OAuthHandler("CONSUMER_KEY", "CONSUMER_SECRET")auth.set_access_token("ACCESS_TOKEN","ACCESS_TOKEN_SECRET")api = tweepy.API(auth)# test authenticationtry: api.verify_credentials() print("Authentication OK")except: print("Error during authentication") Tweepy has a list for methods that will easily help you access Twitter’s end points. There is a method for user timeline, tweets, searches, trends, users and more. Do read documentation for full list, but let me talk about these two methods I used. follower_ids This method allows you to get most recent following of a particular user (use screen_name as parameter). Results are given in groups of 5,000 user IDs and you can use the cursor to navigate through the ‘pages’. api.followers_ids(screen_name=screen_name) For my purposes, I used this as a strategy to get a list of IDs as a parameter to feed into user_timeline method user_timeline The overall rate limit to this method is 100,000 calls during any single 24-hour period. That will translate to 100,000 users and their timeline posts (up to 200 most recent posts). timeline = api.user_timeline(user_id=user_id, count=200) The below is a snippet of the JSON that it will return. Do look through the attributes that are useful for your purposes. For me, the attributes I collected were [‘created_at’, ‘text’, ‘source’, ‘in_reply_to_screen_name’, ‘retweet_count’, ‘favorite_count’, ‘favorited’, ‘retweeted’, ‘is_quote_status’, ‘retweeted_status’, ‘hashtags’, ‘symbols’, ‘user_mentions’] search I did not use this method, but I believe this is useful for most of you seeking Twitter data to get conversations on a particular topic. This method returns a collection of relevant Tweets matching a specified query for all public tweets. The example below returns the 5 most recent tweets about hot pockets Snowden. api.search(q="hot pockets snowden", lang="en", rpp=5) The results you need to parse are: This function will help you get the list of follower IDs for a given Twitter screen name. Each page is has 5000 IDs so the cursor just helps you ‘flip’ through the pages if the particular user has more than 5000 followers. My plan was to call the user timeline for each of this IDs. # define screen_namedef get_ids(screen_name): ''' :argument: screen_name of user :returns: a list_id of the given user's followers ''' # get first list first_list = api.followers_ids(screen_name=screen_name) id_list = first_list['ids'] cursor = first_list['next_cursor'] while cursor != 0 : user_ids = api.followers_ids(screen_name=screen_name, cursor=cursor) id_list.extend(user_ids[0]['ids']) cursor = user_ids[0]['next_cursor'] return id_list The below function is a bit of a handful. But high level, it gets tweets based on attributes I specified. There were some simple manipulations (replace function) I had to perform to help with next line (\n) formatting from the API calls. This is entirely for my operation as my final was a csv file which I move to a postgresql database. If you are capturing this in MongoDB, this might not be needed. def get_tweets(user_id, timeline) : ''' :param user_id: the list_id as recognized by twitter :param timeline: the dictionary that is pulled from user_timeline twitter API :return: all the posts in dictionary format of a specified list_id ''' # attribute lists post_attrs = ['created_at', 'text', 'source', 'in_reply_to_screen_name', 'retweet_count', 'favorite_count', 'favorited', 'retweeted', 'is_quote_status', 'retweeted_status'] entities_attrs = ['hashtags', 'symbols', 'user_mentions'] # creating empty dictionary, and specifying user id post_dict = defaultdict(list) for tweets in timeline : post_dict['user_id'] = user_id for post in list(post_attrs) : if post == 'text' : try : t = tweets[post] t = t.replace('\n','') t = t.replace('\r','') post_dict[post].append(t) except : post_dict[post].append(np.nan) else : try : t = tweets[post] post_dict[post].append(t) except : post_dict[post].append(np.nan) # looping through other post attributes for entity in entities_attrs : try : attr_name = 'len_' + entity post_dict[entity].append(tweets['entities'][entity]) post_dict[attr_name].append(len(tweets['entities'][entity])) except : post_dict[entity].append(np.nan) return post_dict auth = tweepy.OAuthHandler("CONSUMER_KEY", "CONSUMER_SECRET")auth.set_access_token("ACCESS_TOKEN","ACCESS_TOKEN_SECRET")api = tweepy.API(auth, wait_on_rate_limit=True, wait_on_rate_limit_notify=True, parser=tweepy.parsers.JSONParser()) In your API method, do specify wait_on_rate_limit and wait_on_rate_limit_notify which will wait once you’ve reached your rate limit and prints out a message.I found that calling the API from an AWS server (or whatever cloud server) was quicker than using my local machine. This might be purely my own heuristics from observing how quickly printed users IDs were populating as I queried the API. You can try both, especially if speed is important to you.This is probably the biggest tip I can give you and was game-changing in my own data collection. Despite Twitter stating a request limit of 900 per 15 minutes, they will become much much slower (1 call per 7 seconds vs 1 per second) if you’re requesting continually in one batch. By splitting my batches to 5,000 at a time (rather than 20,000 in my first iteration), I was able to get user historical tweets much quicker. What this means is to run your user ID iteration 5000 users at a time then take a break, make another API auth call and call another 5,000 users. Do feel free to test in even smaller batches. In your API method, do specify wait_on_rate_limit and wait_on_rate_limit_notify which will wait once you’ve reached your rate limit and prints out a message. I found that calling the API from an AWS server (or whatever cloud server) was quicker than using my local machine. This might be purely my own heuristics from observing how quickly printed users IDs were populating as I queried the API. You can try both, especially if speed is important to you. This is probably the biggest tip I can give you and was game-changing in my own data collection. Despite Twitter stating a request limit of 900 per 15 minutes, they will become much much slower (1 call per 7 seconds vs 1 per second) if you’re requesting continually in one batch. By splitting my batches to 5,000 at a time (rather than 20,000 in my first iteration), I was able to get user historical tweets much quicker. What this means is to run your user ID iteration 5000 users at a time then take a break, make another API auth call and call another 5,000 users. Do feel free to test in even smaller batches. That’s all for now — please let me know if you have any questions. Happy requesting live fresh data!
[ { "code": null, "e": 520, "s": 171, "text": "Tweet datasets are an extremely desirable corpus for aspiring (and practicing) data scientists to analyze and perform models on. Tweets are by nature short-form and contain diverse and relevant topics, making it an excellent dataset for sentiment analysis. It is also a great dataset to analyze user engagement since tweet timestamps are available." }, { "code": null, "e": 844, "s": 520, "text": "While there are many existing Twitter datasets out there, they will be predefined for you. I am a believer of first defining the problem you’re interested in, and then figuring out a way to get that data. This is where it is beneficial to access Twitter API — you get the type, volume and ‘newness’ only an API can provide." }, { "code": null, "e": 1193, "s": 844, "text": "If it’s any testament, I was able to obtain 70,000 user accounts and their 10 million post which takes close to a full day. It’s slightly longer than proofing your bread dough for homemade sourdough, but really not that much longer. I recommend it more highly than trying to make any bread from scratch (at least once) which believe me, says a lot." }, { "code": null, "e": 1468, "s": 1193, "text": "The Twitter API exposes dozens of HTTP endpoints that can be used to retrieve, create and delete tweets, retweets and likes. It provides direct access to rich and real-time tweet data, but requires having to deal with a lot of low level details (and very not fun debugging)." }, { "code": null, "e": 1823, "s": 1468, "text": "Tweepy is an open source package that allows you to bypass a lot of those low level details. Twitter’s developer website has great documentation I recommend exploring to get example responses and see the type of data you are able to access. Tweepy’s documentation will furthermore provide code snippets and some basic documentation for the Tweepy module." }, { "code": null, "e": 2065, "s": 1823, "text": "Twitter API uses OAuth, which is an open authorization protocol to authenticate requests. You will need to create and configure your authentication credentials to access Twitter API. As promised, this is a step-by-step guide so follow along!" }, { "code": null, "e": 2151, "s": 2065, "text": "Step 0: Open a Twitter account. If you already have a Twitter account, skip this step" }, { "code": null, "e": 2189, "s": 2151, "text": "Step 1: Apply for a developer account" }, { "code": null, "e": 2343, "s": 2189, "text": "Go to their developer site and go to apply for access and select “Apply for a developer account”. You will be prompted to log in to your Twitter account." }, { "code": null, "e": 2391, "s": 2343, "text": "You will then be navigated to a page like this:" }, { "code": null, "e": 2614, "s": 2391, "text": "Select your choice path and fill the details in the next page and fill in some personal details. When you get to intended use, there are a couple of fields with minimum character limit (the one time they have a minimum 😏)." }, { "code": null, "e": 2789, "s": 2614, "text": "This is what I filled up. Be honest, but don’t worry too much about the details and especially not about brevity. In my experience, they have been instantaneous in approvals." }, { "code": null, "e": 2954, "s": 2789, "text": "There will be further easy questions and steps (be patient!). Once you’ve gone through those steps and accept developer agreement, you now have a developer account!" }, { "code": null, "e": 2984, "s": 2954, "text": "Step 2: Create an Application" }, { "code": null, "e": 3121, "s": 2984, "text": "You might have to wait a hot minute for your developer account to be approved — but once it is, you can start creating your application." }, { "code": null, "e": 3237, "s": 3121, "text": "Go to your profile tab and select Apps. Create an app and fill in the details. That should take another hot minute." }, { "code": null, "e": 3283, "s": 3237, "text": "Once you create you app, go to the next step." }, { "code": null, "e": 3323, "s": 3283, "text": "Step 3: Get your authentication details" }, { "code": null, "e": 3402, "s": 3323, "text": "Go to your apps page where you will see the app you created. Click on details." }, { "code": null, "e": 3547, "s": 3402, "text": "Once you’re there, click on keys and tokens to get the relevant keys. You will might need to generate your access token and access token secret." }, { "code": null, "e": 3689, "s": 3547, "text": "You also have the capability to regenerate the key, in case you are needing to write a step-by-step blog post and share your old key (I did)." }, { "code": null, "e": 3735, "s": 3689, "text": "Once you have that, move to to the next step!" }, { "code": null, "e": 3857, "s": 3735, "text": "Replace the CONSUMER_KEY, CONSUMER_SECRET, ACCESS_TOKEN, ACCESS_TOKEN_SECRET in the code below with your own credentials." }, { "code": null, "e": 3924, "s": 3857, "text": "Run the code below to verify your authentication. I hope it works!" }, { "code": null, "e": 4235, "s": 3924, "text": "import tweepy# Authenticate to Twitterauth = tweepy.OAuthHandler(\"CONSUMER_KEY\", \"CONSUMER_SECRET\")auth.set_access_token(\"ACCESS_TOKEN\",\"ACCESS_TOKEN_SECRET\")api = tweepy.API(auth)# test authenticationtry: api.verify_credentials() print(\"Authentication OK\")except: print(\"Error during authentication\")" }, { "code": null, "e": 4484, "s": 4235, "text": "Tweepy has a list for methods that will easily help you access Twitter’s end points. There is a method for user timeline, tweets, searches, trends, users and more. Do read documentation for full list, but let me talk about these two methods I used." }, { "code": null, "e": 4497, "s": 4484, "text": "follower_ids" }, { "code": null, "e": 4708, "s": 4497, "text": "This method allows you to get most recent following of a particular user (use screen_name as parameter). Results are given in groups of 5,000 user IDs and you can use the cursor to navigate through the ‘pages’." }, { "code": null, "e": 4751, "s": 4708, "text": "api.followers_ids(screen_name=screen_name)" }, { "code": null, "e": 4864, "s": 4751, "text": "For my purposes, I used this as a strategy to get a list of IDs as a parameter to feed into user_timeline method" }, { "code": null, "e": 4878, "s": 4864, "text": "user_timeline" }, { "code": null, "e": 5060, "s": 4878, "text": "The overall rate limit to this method is 100,000 calls during any single 24-hour period. That will translate to 100,000 users and their timeline posts (up to 200 most recent posts)." }, { "code": null, "e": 5117, "s": 5060, "text": "timeline = api.user_timeline(user_id=user_id, count=200)" }, { "code": null, "e": 5239, "s": 5117, "text": "The below is a snippet of the JSON that it will return. Do look through the attributes that are useful for your purposes." }, { "code": null, "e": 5479, "s": 5239, "text": "For me, the attributes I collected were [‘created_at’, ‘text’, ‘source’, ‘in_reply_to_screen_name’, ‘retweet_count’, ‘favorite_count’, ‘favorited’, ‘retweeted’, ‘is_quote_status’, ‘retweeted_status’, ‘hashtags’, ‘symbols’, ‘user_mentions’]" }, { "code": null, "e": 5486, "s": 5479, "text": "search" }, { "code": null, "e": 5725, "s": 5486, "text": "I did not use this method, but I believe this is useful for most of you seeking Twitter data to get conversations on a particular topic. This method returns a collection of relevant Tweets matching a specified query for all public tweets." }, { "code": null, "e": 5803, "s": 5725, "text": "The example below returns the 5 most recent tweets about hot pockets Snowden." }, { "code": null, "e": 5857, "s": 5803, "text": "api.search(q=\"hot pockets snowden\", lang=\"en\", rpp=5)" }, { "code": null, "e": 5892, "s": 5857, "text": "The results you need to parse are:" }, { "code": null, "e": 6175, "s": 5892, "text": "This function will help you get the list of follower IDs for a given Twitter screen name. Each page is has 5000 IDs so the cursor just helps you ‘flip’ through the pages if the particular user has more than 5000 followers. My plan was to call the user timeline for each of this IDs." }, { "code": null, "e": 6673, "s": 6175, "text": "# define screen_namedef get_ids(screen_name): ''' :argument: screen_name of user :returns: a list_id of the given user's followers ''' # get first list first_list = api.followers_ids(screen_name=screen_name) id_list = first_list['ids'] cursor = first_list['next_cursor'] while cursor != 0 : user_ids = api.followers_ids(screen_name=screen_name, cursor=cursor) id_list.extend(user_ids[0]['ids']) cursor = user_ids[0]['next_cursor'] return id_list" }, { "code": null, "e": 7011, "s": 6673, "text": "The below function is a bit of a handful. But high level, it gets tweets based on attributes I specified. There were some simple manipulations (replace function) I had to perform to help with next line (\\n) formatting from the API calls. This is entirely for my operation as my final was a csv file which I move to a postgresql database." }, { "code": null, "e": 7075, "s": 7011, "text": "If you are capturing this in MongoDB, this might not be needed." }, { "code": null, "e": 8664, "s": 7075, "text": "def get_tweets(user_id, timeline) : ''' :param user_id: the list_id as recognized by twitter :param timeline: the dictionary that is pulled from user_timeline twitter API :return: all the posts in dictionary format of a specified list_id ''' # attribute lists post_attrs = ['created_at', 'text', 'source', 'in_reply_to_screen_name', 'retweet_count', 'favorite_count', 'favorited', 'retweeted', 'is_quote_status', 'retweeted_status'] entities_attrs = ['hashtags', 'symbols', 'user_mentions'] # creating empty dictionary, and specifying user id post_dict = defaultdict(list) for tweets in timeline : post_dict['user_id'] = user_id for post in list(post_attrs) : if post == 'text' : try : t = tweets[post] t = t.replace('\\n','') t = t.replace('\\r','') post_dict[post].append(t) except : post_dict[post].append(np.nan) else : try : t = tweets[post] post_dict[post].append(t) except : post_dict[post].append(np.nan) # looping through other post attributes for entity in entities_attrs : try : attr_name = 'len_' + entity post_dict[entity].append(tweets['entities'][entity]) post_dict[attr_name].append(len(tweets['entities'][entity])) except : post_dict[entity].append(np.nan) return post_dict" }, { "code": null, "e": 8900, "s": 8664, "text": "auth = tweepy.OAuthHandler(\"CONSUMER_KEY\", \"CONSUMER_SECRET\")auth.set_access_token(\"ACCESS_TOKEN\",\"ACCESS_TOKEN_SECRET\")api = tweepy.API(auth, wait_on_rate_limit=True, wait_on_rate_limit_notify=True, parser=tweepy.parsers.JSONParser())" }, { "code": null, "e": 9967, "s": 8900, "text": "In your API method, do specify wait_on_rate_limit and wait_on_rate_limit_notify which will wait once you’ve reached your rate limit and prints out a message.I found that calling the API from an AWS server (or whatever cloud server) was quicker than using my local machine. This might be purely my own heuristics from observing how quickly printed users IDs were populating as I queried the API. You can try both, especially if speed is important to you.This is probably the biggest tip I can give you and was game-changing in my own data collection. Despite Twitter stating a request limit of 900 per 15 minutes, they will become much much slower (1 call per 7 seconds vs 1 per second) if you’re requesting continually in one batch. By splitting my batches to 5,000 at a time (rather than 20,000 in my first iteration), I was able to get user historical tweets much quicker. What this means is to run your user ID iteration 5000 users at a time then take a break, make another API auth call and call another 5,000 users. Do feel free to test in even smaller batches." }, { "code": null, "e": 10125, "s": 9967, "text": "In your API method, do specify wait_on_rate_limit and wait_on_rate_limit_notify which will wait once you’ve reached your rate limit and prints out a message." }, { "code": null, "e": 10422, "s": 10125, "text": "I found that calling the API from an AWS server (or whatever cloud server) was quicker than using my local machine. This might be purely my own heuristics from observing how quickly printed users IDs were populating as I queried the API. You can try both, especially if speed is important to you." }, { "code": null, "e": 11036, "s": 10422, "text": "This is probably the biggest tip I can give you and was game-changing in my own data collection. Despite Twitter stating a request limit of 900 per 15 minutes, they will become much much slower (1 call per 7 seconds vs 1 per second) if you’re requesting continually in one batch. By splitting my batches to 5,000 at a time (rather than 20,000 in my first iteration), I was able to get user historical tweets much quicker. What this means is to run your user ID iteration 5000 users at a time then take a break, make another API auth call and call another 5,000 users. Do feel free to test in even smaller batches." } ]